diff --git a/packages/paperclip-runner/protocol/manifest.json b/packages/paperclip-runner/protocol/manifest.json index 3ebb45a9cb..8575322f47 100644 --- a/packages/paperclip-runner/protocol/manifest.json +++ b/packages/paperclip-runner/protocol/manifest.json @@ -30,7 +30,7 @@ { "path": "schemas/event.schema.json", "id": "https://paperclip.dev/schemas/prp/v1/event.schema.json", - "sha256": "d69ac4acfd9cd265f9dcb6a6580e949a67a50347093d0a7c12c2000a2da6d482" + "sha256": "e9827a7c31f004ae91388964a96b4ddf6ab40b85f29bf3922683d5dcf64f2559" }, { "path": "schemas/fixture.schema.json", @@ -45,12 +45,12 @@ { "path": "schemas/provider-descriptor.schema.json", "id": "https://paperclip.dev/schemas/prp/v1/provider-descriptor.schema.json", - "sha256": "26e8af9314f1ca49578bfbacdcc111332225b422ea4ff68918a25ddac59129a6" + "sha256": "a56c0c8501171c34bb72f6fba08d3872839a8b45bbc10daa93620afc9dc2b669" }, { "path": "schemas/provider-event.schema.json", "id": "https://paperclip.dev/schemas/prp/v1/provider-event.schema.json", - "sha256": "84521ea87ae782a7c07d1ef68b70f87fc4c436e79951a8076b7ba55e923fa88b" + "sha256": "e0ffb95cbde4afb65783106f471c5154cbcc59055461f96838cd8a5239e5ec56" }, { "path": "schemas/question-adapter-fixture.schema.json", @@ -75,7 +75,7 @@ { "path": "schemas/result.schema.json", "id": "https://paperclip.dev/schemas/prp/v1/result.schema.json", - "sha256": "90f02c0a96e8ab9f75970fd788b61c18ccbd9abbd005bedfba280701729adce0" + "sha256": "86d3b3c4d0f79de34a3e2e37beb183ea08d3bc9f70437a9f6f2b98bdf8faf828" }, { "path": "schemas/semantic-tool.schema.json", @@ -95,7 +95,7 @@ { "path": "schemas/usage.schema.json", "id": "https://paperclip.dev/schemas/prp/v1/usage.schema.json", - "sha256": "28fdbb3202095144649dddc438e6270c66d599c6f7e86838687f58d644726456" + "sha256": "34b1478d2054f898d64b54b62a9bb738670087893bb1e5967da541539d2daf36" }, { "path": "schemas/workspace-diff.schema.json", diff --git a/packages/paperclip-runner/protocol/schemas/event.schema.json b/packages/paperclip-runner/protocol/schemas/event.schema.json index 355e1f6477..9d2b3ed873 100644 --- a/packages/paperclip-runner/protocol/schemas/event.schema.json +++ b/packages/paperclip-runner/protocol/schemas/event.schema.json @@ -28,7 +28,7 @@ "itemId": { "type": "string", "minLength": 1, "maxLength": 160 }, "eventType": { "enum": [ - "runner.connected", "runner.reconnected", "runner.reconciled", "runner.disconnected", "runner.draining", "runner.suspending", "runner.suspended", "runner.stopped", "runner.diagnostic", + "runner.connected", "runner.reconnected", "runner.reconciled", "runner.disconnected", "runner.draining", "runner.backpressure", "runner.suspending", "runner.suspended", "runner.stopped", "runner.diagnostic", "runtime.phase.changed", "sandbox.metric", "workspace.ready", "workspace.change.updated", "workspace.diff.recorded", "workspace.file.referenced", "harness.starting", "harness.ready", "harness.exited", "harness.diagnostic", "plan.updated", @@ -43,7 +43,7 @@ "session.starting", "session.started", "session.resuming", "session.resumed", "session.reconciled", "session.updated", "session.closed", "session.failed", "turn.submitted", "turn.accepted", "turn.started", "turn.completed", "turn.failed", "turn.interrupted", "turn.cancelled", "item.started", "item.delta", "item.completed", "item.failed", "usage.reported", - "semantic_tool.input", "semantic_tool.result", + "semantic_tool.input", "semantic_tool.result", "semantic_tool.reconciled", "mcp_app.discovered", "mcp_app.resource.resolved", "mcp_app.initializing", "mcp_app.ready", "mcp_app.tool_input", "mcp_app.tool_result", "mcp_app.action.requested", "mcp_app.action.resolved", "mcp_app.host_context.changed", "mcp_app.failed", "mcp_app.teardown", "runtime_request.created", "runtime_request.resolved", "runtime_request.expired", "runtime_request.cancelled", "interaction.request.proposed", "interaction.request.materialized", "interaction.request.rejected", "interaction.response.progressed", "interaction.response.resolved", "interaction.response.delivered", @@ -152,6 +152,25 @@ } } }, + { + "if": { "properties": { "eventType": { "const": "semantic_tool.reconciled" } } }, + "then": { + "properties": { + "payload": { + "type": "object", + "properties": { + "semantic_tool": { + "allOf": [ + { "$ref": "https://paperclip.dev/schemas/prp/v1/semantic-tool.schema.json" }, + { "type": "object", "properties": { "phase": { "const": "reconciled" } } } + ] + } + }, + "additionalProperties": true + } + } + } + }, { "if": { "properties": { "eventType": { "const": "run.terminal" } } }, "then": { diff --git a/packages/paperclip-runner/protocol/schemas/provider-descriptor.schema.json b/packages/paperclip-runner/protocol/schemas/provider-descriptor.schema.json index 3bfbb66a06..53c174d983 100644 --- a/packages/paperclip-runner/protocol/schemas/provider-descriptor.schema.json +++ b/packages/paperclip-runner/protocol/schemas/provider-descriptor.schema.json @@ -5,13 +5,96 @@ "type": "object", "required": ["provider", "driver", "model", "executionKind", "providerVersion"], "properties": { - "provider": { "const": "codex" }, - "driver": { "const": "codex_app_server" }, + "provider": { "enum": ["codex", "opencode", "claude_managed", "aws_agentcore", "acpx"] }, + "driver": { "enum": ["codex_app_server", "opencode_server", "claude_managed_agents_api", "aws_agentcore_harness_api", "acpx_runtime"] }, "model": { "type": ["string", "null"], "maxLength": 240 }, - "executionKind": { "const": "local_process" }, + "executionKind": { "enum": ["local_process", "remote_service"] }, "providerVersion": { "type": "string", "minLength": 1, "maxLength": 120 }, + "service": { "enum": ["anthropic_managed_agents", "aws_bedrock_agentcore_harness"] }, "providerSessionId": { "type": ["string", "null"], "maxLength": 240 }, - "processId": { "type": ["integer", "null"], "minimum": 1 } + "processId": { "type": ["integer", "null"], "minimum": 1 }, + "agentProcessId": { "type": ["integer", "null"], "minimum": 1 }, + "endpointArn": { "type": "string", "minLength": 1, "maxLength": 2048 }, + "endpointQualifier": { "type": "string", "minLength": 1, "maxLength": 240 }, + "memoryId": { "type": "string", "minLength": 1, "maxLength": 240 }, + "eventExpiryDays": { "const": 90 }, + "agent": { "enum": ["pi", "claude", "codex"] }, + "requestedModel": { "type": "string", "minLength": 1, "maxLength": 240 }, + "acpProtocolVersion": { "const": 1 }, + "agentServerPackage": { "type": "string", "minLength": 1, "maxLength": 240 }, + "agentServerVersion": { "type": "string", "minLength": 1, "maxLength": 120 }, + "agentRuntimePackage": { "type": ["string", "null"], "maxLength": 240 }, + "agentRuntimeVersion": { "type": ["string", "null"], "maxLength": 120 }, + "acpxRecordId": { "type": ["string", "null"], "maxLength": 240 } }, - "additionalProperties": true + "allOf": [ + { + "oneOf": [ + { + "properties": { + "provider": { "const": "codex" }, + "driver": { "const": "codex_app_server" }, + "executionKind": { "const": "local_process" } + } + }, + { + "properties": { + "provider": { "const": "opencode" }, + "driver": { "const": "opencode_server" }, + "executionKind": { "const": "local_process" } + } + }, + { + "properties": { + "provider": { "const": "claude_managed" }, + "driver": { "const": "claude_managed_agents_api" }, + "executionKind": { "const": "remote_service" } + } + }, + { + "properties": { + "provider": { "const": "aws_agentcore" }, + "driver": { "const": "aws_agentcore_harness_api" }, + "executionKind": { "const": "remote_service" } + } + }, + { + "properties": { + "provider": { "const": "acpx" }, + "driver": { "const": "acpx_runtime" }, + "executionKind": { "const": "local_process" } + } + } + ] + }, + { + "if": { "properties": { "executionKind": { "const": "remote_service" } } }, + "then": { + "required": ["service"], + "properties": { "processId": { "const": null } } + } + }, + { + "if": { "properties": { "executionKind": { "const": "local_process" } } }, + "then": { "properties": { "service": false } } + }, + { + "if": { "properties": { "provider": { "const": "claude_managed" } }, "required": ["provider"] }, + "then": { "properties": { "service": { "const": "anthropic_managed_agents" } }, "required": ["service"] } + }, + { + "if": { "properties": { "provider": { "const": "aws_agentcore" } }, "required": ["provider"] }, + "then": { + "properties": { "service": { "const": "aws_bedrock_agentcore_harness" } }, + "required": ["service", "endpointArn", "endpointQualifier", "memoryId", "eventExpiryDays"] + } + }, + { + "if": { "properties": { "provider": { "const": "acpx" } }, "required": ["provider"] }, + "then": { + "required": ["agent", "requestedModel", "acpProtocolVersion", "agentServerPackage", "agentServerVersion", "acpxRecordId", "agentProcessId"] + } + } + ], + "additionalProperties": false } diff --git a/packages/paperclip-runner/protocol/schemas/provider-event.schema.json b/packages/paperclip-runner/protocol/schemas/provider-event.schema.json index 8af5200ddf..f0275dabf5 100644 --- a/packages/paperclip-runner/protocol/schemas/provider-event.schema.json +++ b/packages/paperclip-runner/protocol/schemas/provider-event.schema.json @@ -28,6 +28,7 @@ "safeUrl": { "type": ["string", "null"], "maxLength": 8192, "pattern": "^https?://" }, "plan": { "type": "object", + "description": "A complete provider-authored within-turn checklist snapshot. Consumers replace the prior snapshot with the same planId in PRP sourceSeq order; this is not Paperclip's durable Plan document.", "required": ["schema", "planId", "revision", "steps", "complete", "syncStatus"], "properties": { "schema": { "const": "paperclip.plan.updated.v1" }, @@ -36,8 +37,8 @@ "explanation": { "$ref": "#/$defs/nullableShortText" }, "steps": { "type": "array", "maxItems": 256, "items": { "type": "object", "required": ["stepId", "body", "status"], "properties": { "stepId": { "$ref": "#/$defs/id" }, "body": { "$ref": "#/$defs/shortText" }, "status": { "enum": ["pending", "in_progress", "completed", "blocked"] } }, "additionalProperties": false } }, "complete": { "type": "boolean" }, - "syncStatus": { "enum": ["streaming", "pending", "synchronized", "conflict", "not_applicable"] }, - "documentRevision": { "type": ["integer", "null"], "minimum": 1 } + "syncStatus": { "description": "Legacy compatibility field. Within-turn checklist snapshots use not_applicable.", "enum": ["streaming", "pending", "synchronized", "conflict", "not_applicable"] }, + "documentRevision": { "description": "Legacy compatibility field. Within-turn checklist snapshots use null.", "type": ["integer", "null"], "minimum": 1 } }, "additionalProperties": false }, diff --git a/packages/paperclip-runner/protocol/schemas/result.schema.json b/packages/paperclip-runner/protocol/schemas/result.schema.json index 62983b280e..95f438d45a 100644 --- a/packages/paperclip-runner/protocol/schemas/result.schema.json +++ b/packages/paperclip-runner/protocol/schemas/result.schema.json @@ -92,7 +92,15 @@ "required": ["reasonCode", "owner", "unblockAction", "scope"], "properties": { "reasonCode": { "type": "string", "minLength": 1 }, - "owner": { "type": "object", "additionalProperties": true }, + "owner": { + "type": "object", + "required": ["kind", "name"], + "properties": { + "kind": { "enum": ["agent", "user", "system", "external"] }, + "name": { "type": "string", "minLength": 1 } + }, + "additionalProperties": true + }, "unblockAction": { "type": "string", "minLength": 1 }, "scope": { "enum": ["current_track", "task_wide"] } }, diff --git a/packages/paperclip-runner/protocol/schemas/usage.schema.json b/packages/paperclip-runner/protocol/schemas/usage.schema.json index 68c912f2dc..c1a57e17bf 100644 --- a/packages/paperclip-runner/protocol/schemas/usage.schema.json +++ b/packages/paperclip-runner/protocol/schemas/usage.schema.json @@ -10,6 +10,7 @@ "providerSessionId": { "type": ["string", "null"], "maxLength": 240 }, "providerRequestId": { "type": ["string", "null"], "maxLength": 240 }, "cumulative": { "$ref": "#/$defs/measurement" }, + "runDeltaAvailable": { "type": "boolean" }, "runDelta": { "$ref": "#/$defs/measurement" } }, "additionalProperties": false, diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs b/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs index f9e7b0d8fe..634f8ddda6 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs @@ -199,8 +199,7 @@ pub fn normalize_codex_notification(method: &str, params: &Value) -> Vec Vec; + }; + constraints: string[]; + expectedResultSchema: "paperclip.run_result.v1"; +} + +export interface CodexModelContextSnapshot { + protocolVersion: typeof CODEX_CODEX_PROTOCOL_VERSION; + codexVersion: string; + clientInfo: { + name: "paperclip-runner"; + title: "Paperclip Runner"; + version: string; + }; + model: string; + modelProvider: string; + workingDirectory: string; + collaborationMode: "default" | "plan"; + sandbox: unknown; + approvalPolicy: unknown; + baseInstructions: string; + instructionSources: string[]; + instructionPolicy: { + skillInstructions: boolean; + appInstructions: false; + collaborationInstructions: boolean; + }; + environmentKeys: string[]; + dynamicToolNames: string[]; + modelInputKinds: ["text"]; + liveConsole?: { + conversationMode?: "task" | "direct"; + runtimeRequestResolution: boolean; + goals: boolean; + threadLineage: boolean; + }; + envelope: CodexTaskEnvelope; +} + +export interface CodexRunMetadata { + schema: "paperclip.runner.codex.metadata.v1"; + fixtureName: string; + identity: { + schema: "paperclip.prp.identity.v1"; + companyId: string; + issueId: string; + runId: string; + environmentLeaseId: string; + runnerInstanceId: string; + normalizedSessionId: string; + driverSessionId?: string; + providerSessionId?: string; + }; + capabilities: PrpCapabilities; +} + +export interface CodexRunTrace { + schema: "paperclip.runner.codex.trace.v1"; + metadata: CodexRunMetadata; + context: CodexModelContextSnapshot; + events: PrpEvent[]; + proposedResult: unknown | null; + result: PrpStructuredRunResult | null; + resultDecision: CodexResultDecision; + liveSnapshot: SessionSnapshot; + replaySnapshot: SessionSnapshot; + diagnostics: string[]; + assertions: { + exactlyOneTerminalResult: boolean; + proposalAccepted: boolean; + liveReplayParity: boolean; + stableIdentity: boolean; + sourceSequenceContinuous: boolean; + stableItemIdentity: boolean; + contextIsSkillless: boolean; + unrelatedSkillsAbsent: boolean; + credentialsAbsent: boolean; + }; +} + +export interface CodexResultValidationIssue { + code: + | "schema_validation" + | "contract_revision_mismatch" + | "unknown_criterion" + | "missing_criterion" + | "duplicate_criterion" + | "invalid_disposition"; + path: string; + message: string; +} + +export type CodexResultDecision = + | { status: "accepted"; result: PrpStructuredRunResult; issues: [] } + | { status: "rejected"; result: null; issues: CodexResultValidationIssue[] }; + +export function createCodexTaskEnvelope(input: { + objective: string; + contractRevision?: string; + criteria?: Array<{ id: string; requirement: string }>; + constraints?: string[]; +}): CodexTaskEnvelope { + return { + schema: CODEX_TASK_ENVELOPE_SCHEMA, + objective: input.objective, + completionContract: { + revision: input.contractRevision ?? "codex-demo-v1", + criteria: + input.criteria ?? [{ id: "objective", requirement: "Complete the objective safely." }], + }, + constraints: input.constraints ?? [ + "Work only inside the supplied working directory.", + "Do not discover or invoke skills.", + "Do not call a control-plane API.", + "Return one semantic completion result.", + ], + expectedResultSchema: "paperclip.run_result.v1", + }; +} + +/** @deprecated Use PRP_COMPLETION_RESULT_OUTPUT_SCHEMA. */ +export const CODEX_RESULT_OUTPUT_SCHEMA = PRP_COMPLETION_RESULT_OUTPUT_SCHEMA; +/** @deprecated Use PRP_BLOCK_RESULT_OUTPUT_SCHEMA. */ +export const CODEX_BLOCK_RESULT_OUTPUT_SCHEMA = PRP_BLOCK_RESULT_OUTPUT_SCHEMA; +export const CODEX_RESULT_PROVIDER_INPUT_SCHEMA = PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA; +export const CODEX_BLOCK_RESULT_PROVIDER_INPUT_SCHEMA = PRP_BLOCK_RESULT_PROVIDER_INPUT_SCHEMA; + +export function isSkilllessCodexContext( + context: CodexModelContextSnapshot, + options: { dynamicTools: boolean } = { dynamicTools: true }, +): boolean { + const serialized = JSON.stringify(context).toLowerCase(); + const expectedTools = options.dynamicTools ? [...CODEX_SEMANTIC_TOOL_NAMES] : []; + return ( + context.instructionSources.length === 0 && + context.baseInstructions === CODEX_SKILLLESS_BASE_INSTRUCTIONS && + context.modelInputKinds.length === 1 && + context.modelInputKinds[0] === "text" && + context.dynamicToolNames.length === expectedTools.length && + context.dynamicToolNames.every((name) => + expectedTools.includes(name as (typeof expectedTools)[number]), + ) && + context.instructionPolicy.skillInstructions === false && + context.instructionPolicy.appInstructions === false && + !serialized.includes("paperclip_api_key") && + !serialized.includes("authorization: bearer") && + !serialized.includes("/api/issues/") && + !serialized.includes('"type":"skill"') + ); +} diff --git a/packages/paperclip-runner/src/contracts/completion-result.test.ts b/packages/paperclip-runner/src/contracts/completion-result.test.ts index 321f0789bb..9ae9b6a76c 100644 --- a/packages/paperclip-runner/src/contracts/completion-result.test.ts +++ b/packages/paperclip-runner/src/contracts/completion-result.test.ts @@ -12,9 +12,7 @@ const baseResult = { completionClaim: { contractRevision: "1", objectiveSatisfied: true, - criteria: [ - { criterionId: "objective", status: "satisfied", evidenceRefs: [] }, - ], + criteria: [{ criterionId: "objective", status: "satisfied", evidenceRefs: [] }], remainingWork: [], }, evidence: [], @@ -24,68 +22,52 @@ const baseResult = { }; describe("provider-neutral completion result schema", () => { - const validate = new Ajv2020({ allErrors: true, strict: false }).compile( - PRP_COMPLETION_RESULT_OUTPUT_SCHEMA, - ); + const validate = new Ajv2020({ allErrors: true, strict: false }) + .compile(PRP_COMPLETION_RESULT_OUTPUT_SCHEMA); it("allows done with no verification and no actionable attention", () => { expect(validate(structuredClone(baseResult))).toBe(true); }); it("allows provider tool callers to omit the constant schema discriminator", () => { - const providerValidate = new Ajv2020({ - allErrors: true, - strict: false, - }).compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA); - const providerResult = structuredClone(baseResult) as Record< - string, - unknown - >; + const providerValidate = new Ajv2020({ allErrors: true, strict: false }) + .compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA); + const providerResult = structuredClone(baseResult) as Record; delete providerResult.schema; expect(providerValidate(providerResult)).toBe(true); }); it("admits known smaller-model aliases at the provider boundary for canonical normalization", () => { - const providerValidate = new Ajv2020({ - allErrors: true, - strict: false, - }).compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA); + const providerValidate = new Ajv2020({ allErrors: true, strict: false }) + .compile(PRP_COMPLETION_RESULT_PROVIDER_INPUT_SCHEMA); const providerResult = structuredClone(baseResult); providerResult.schema = "paperclip_paperclip_finish"; providerResult.reportedWorkDisposition = "completed"; providerResult.completionClaim.criteria[0]!.status = "passed"; - providerResult.verification = [ - { commandOrCheck: "model check", status: "pass" } as never, - ]; + providerResult.verification = [{ commandOrCheck: "model check", status: "pass" } as never]; expect(providerValidate(providerResult)).toBe(true); }); it("requires a reason code for verification that was not run", () => { const result = structuredClone(baseResult); - result.verification = [ - { commandOrCheck: "Run tests", status: "not_run" } as never, - ]; + result.verification = [{ commandOrCheck: "Run tests", status: "not_run" } as never]; expect(validate(result)).toBe(false); - result.verification = [ - { - commandOrCheck: "Run tests", - status: "not_run", - reasonCode: "tool_unavailable", - } as never, - ]; + result.verification = [{ + commandOrCheck: "Run tests", + status: "not_run", + reasonCode: "tool_unavailable", + } as never]; expect(validate(result)).toBe(true); }); it("requires needs_review for actionable attention", () => { const result = structuredClone(baseResult); - result.attentionRequests = [ - { - kind: "review", - summary: "Confirm the external result.", - ownerClass: "human", - } as never, - ]; + result.attentionRequests = [{ + kind: "review", + summary: "Confirm the external result.", + ownerClass: "human", + } as never]; expect(validate(result)).toBe(false); result.reportedWorkDisposition = "needs_review"; @@ -95,13 +77,11 @@ describe("provider-neutral completion result schema", () => { it("requires agent-owned attention to identify its target agent", () => { const result = structuredClone(baseResult); result.reportedWorkDisposition = "needs_review"; - result.attentionRequests = [ - { - kind: "agent_handoff", - summary: "Ask the deployment agent to continue.", - ownerClass: "agent", - } as never, - ]; + result.attentionRequests = [{ + kind: "agent_handoff", + summary: "Ask the deployment agent to continue.", + ownerClass: "agent", + } as never]; expect(validate(result)).toBe(false); }); }); diff --git a/packages/paperclip-runner/src/contracts/completion-result.ts b/packages/paperclip-runner/src/contracts/completion-result.ts index 11be498be4..6c18cdbf47 100644 --- a/packages/paperclip-runner/src/contracts/completion-result.ts +++ b/packages/paperclip-runner/src/contracts/completion-result.ts @@ -36,12 +36,7 @@ export const PRP_ATTENTION_OWNER_CLASSES = [ const completionClaimSchema = { type: "object", additionalProperties: false, - required: [ - "contractRevision", - "objectiveSatisfied", - "criteria", - "remainingWork", - ], + required: ["contractRevision", "objectiveSatisfied", "criteria", "remainingWork"], properties: { contractRevision: { type: "string", minLength: 1 }, objectiveSatisfied: { type: "boolean" }, @@ -100,21 +95,15 @@ const verificationSchema = { }, reasonCode: { enum: [...PRP_VERIFICATION_REASON_CODES], - description: - "Required for not_run; identify why the check had no meaningful verdict.", + description: "Required for not_run; identify why the check had no meaningful verdict.", }, detail: { type: "string" }, artifactRef: { type: "string", minLength: 1 }, }, - allOf: [ - { - if: { - properties: { status: { const: "not_run" } }, - required: ["status"], - }, - then: { required: ["reasonCode"] }, - }, - ], + allOf: [{ + if: { properties: { status: { const: "not_run" } }, required: ["status"] }, + then: { required: ["reasonCode"] }, + }], }, } as const; @@ -130,15 +119,10 @@ const attentionRequestsSchema = { ownerClass: { enum: [...PRP_ATTENTION_OWNER_CLASSES] }, targetAgentId: { type: "string", minLength: 1 }, }, - allOf: [ - { - if: { - properties: { ownerClass: { const: "agent" } }, - required: ["ownerClass"], - }, - then: { required: ["targetAgentId"] }, - }, - ], + allOf: [{ + if: { properties: { ownerClass: { const: "agent" } }, required: ["ownerClass"] }, + then: { required: ["targetAgentId"] }, + }], }, } as const; @@ -183,17 +167,11 @@ export const PRP_COMPLETION_RESULT_OUTPUT_SCHEMA = { }, allOf: [ { - if: { - properties: { reportedWorkDisposition: { const: "done" } }, - required: ["reportedWorkDisposition"], - }, + if: { properties: { reportedWorkDisposition: { const: "done" } }, required: ["reportedWorkDisposition"] }, then: { properties: { attentionRequests: { maxItems: 0 } } }, }, { - if: { - properties: { reportedWorkDisposition: { const: "needs_review" } }, - required: ["reportedWorkDisposition"], - }, + if: { properties: { reportedWorkDisposition: { const: "needs_review" } }, required: ["reportedWorkDisposition"] }, then: { properties: { attentionRequests: { minItems: 1 } } }, }, ], @@ -215,11 +193,7 @@ export const PRP_BLOCK_RESULT_OUTPUT_SCHEMA = { properties: { ...commonResultProperties, reportedWorkDisposition: { type: "string", const: "blocked" }, - attentionRequests: { - type: "array", - maxItems: 0, - items: attentionRequestsSchema.items, - }, + attentionRequests: { type: "array", maxItems: 0, items: attentionRequestsSchema.items }, blocker: { type: "object", additionalProperties: false, @@ -254,24 +228,13 @@ const providerVerificationCompatibilitySchema = { commandOrCheck: { type: "string", minLength: 1 }, command: { type: "string", minLength: 1 }, status: { - enum: [ - "passed", - "failed", - "not_run", - "blocked", - "skipped", - "pass", - "success", - "succeeded", - "fail", - ], + enum: ["passed", "failed", "not_run", "blocked", "skipped", "pass", "success", "succeeded", "fail"], description: "passed: the check ran and succeeded. failed: the check ran to a meaningful verdict and found the work incorrect. not_run: no meaningful verdict because the check was not attempted or could not complete. Prefer not_run over legacy blocked/skipped, and include reasonCode for any unavailable check.", }, reasonCode: { enum: [...PRP_VERIFICATION_REASON_CODES], - description: - "Required for not_run; identify why the check had no meaningful verdict.", + description: "Required for not_run; identify why the check had no meaningful verdict.", }, detail: { type: "string" }, result: { type: "string" }, diff --git a/packages/paperclip-runner/src/contracts/durable-recovery.ts b/packages/paperclip-runner/src/contracts/durable-recovery.ts new file mode 100644 index 0000000000..5cd271b687 --- /dev/null +++ b/packages/paperclip-runner/src/contracts/durable-recovery.ts @@ -0,0 +1,160 @@ +export const DURABLE_RECOVERY_FAULTS = [ + "none", + "socket-drop", + "lost-ack", + "duplicate-command", + "runner-restart", + "harness-restart", + "malformed-input", + "lease-expiry", + "storage-pressure", + "drain", + "revoke", +] as const; + +export type DurableRecoveryFault = (typeof DURABLE_RECOVERY_FAULTS)[number]; + +export interface DurableRecoveryIdentity { + runnerInstanceId: string; + environmentLeaseId: string; + runId: string; + normalizedSessionId: string; + turnId: string; + itemId: string; +} + +export interface DurableRecoveryStoredEvent { + sourceSeq: number; + sourceEventId: string; + priority: 0 | 1 | 2; + eventType: string; + itemId?: string; + envelope: Record; + byteSize: number; +} + +export interface DurableRecoveryProcessedCommand { + commandId: string; + controllerSeq: number; + commandDigest: string; + status: "completed" | "failed" | "rejected"; + logicalEffectCount: number; + result: Record; +} + +export interface DurableRecoveryRunnerState extends DurableRecoveryIdentity { + schema: "paperclip.runner.durable.state.v1"; + lifecycle: + | "connecting" + | "ready" + | "terminal" + | "backpressure" + | "draining" + | "revoked" + | "stopped" + | "recoverable_failure" + | "unrecoverable"; + nextSourceSeq: number; + ackedSourceSeq: number; + lastControllerCommandSeq: number; + reconnectCount: number; + maxOutboxBytes: number; + peakOutboxBytes: number; + outbox: DurableRecoveryStoredEvent[]; + processedCommands: Record; + compactedCommandFilter: string; + compactedCommandCount: number; + diagnostics: string[]; + backpressure: boolean; + recoverableFailure: string | null; + unrecoverableOutcome: string | null; + harnessGeneration: number; + stopAfterFlush: boolean; +} + +export interface DurableRecoveryCoreCommand { + schema: "paperclip.prp.command.v1"; + commandId: string; + controllerSeq: number; + type: string; + issuedAt: string; + payload: Record; + status: "pending" | "completed" | "failed" | "rejected"; + result: Record | null; +} + +export interface DurableRecoveryCommittedEvent { + sourceSeq: number; + sourceEventId: string; + eventType: string; + priority: 0 | 1 | 2; + envelope: Record; + deliveryCount: number; + logicalEffectCount: number; +} + +export interface DurableRecoveryDiagnostics { + schema: "paperclip.runner.durable.diagnostics.v1"; + fault: DurableRecoveryFault; + connection: { + state: string; + connectionCount: number; + reconnectCount: number; + leaseId: string | null; + leaseExpiresAt: string | null; + }; + identity: DurableRecoveryIdentity; + cursors: { + runnerAckedSourceSeq: number; + runnerNextSourceSeq: number; + coreAckedSourceSeq: number; + highestCommittedSourceSeq: number; + }; + outbox: { + events: number; + bytes: number; + peakBytes: number; + maxBytes: number; + backpressure: boolean; + p0Committed: number; + p0Lost: number; + }; + commands: { + issued: number; + completed: number; + rejected: number; + logicalEffects: number; + duplicateDeliveries: number; + }; + recovery: { + replayDeliveries: number; + runnerRestarts: number; + harnessRestarts: number; + malformedFrames: number; + freshBootstraps: number; + outcome: "recovered" | "drained" | "revoked" | "unrecoverable"; + reason: string; + }; + security: { + bootstrapTicketPersisted: boolean; + connectionLeaseTokenPersisted: boolean; + secretLeakCount: number; + }; + committedEvents: DurableRecoveryCommittedEvent[]; +} + +export interface DurableRecoveryRunTrace { + schema: "paperclip.runner.durable.trace.v1"; + diagnostics: DurableRecoveryDiagnostics; + runnerState: DurableRecoveryRunnerState; + commands: DurableRecoveryCoreCommand[]; + assertions: { + stableIdentity: boolean; + sourceCursorContinuous: boolean; + oneLogicalEffectPerAcceptedCommand: boolean; + noDuplicateLogicalEvents: boolean; + p0Preserved: boolean; + boundedStorage: boolean; + secretsRedacted: boolean; + }; +} diff --git a/packages/paperclip-runner/src/contracts/local-runner.ts b/packages/paperclip-runner/src/contracts/local-runner.ts new file mode 100644 index 0000000000..ae878c2827 --- /dev/null +++ b/packages/paperclip-runner/src/contracts/local-runner.ts @@ -0,0 +1,51 @@ +import type { + PrpCapabilities, + PrpCommand, + PrpEvent, + PrpIdentity, + PrpRequest, + PrpStructuredRunResult, +} from "../protocol/replay-contract.js"; + +export const LOCAL_RUNNER_SCENARIOS = [ + "happy-path", + "permission-input", + "interrupted", + "error", + "duplicate-terminal", +] as const; + +export type LocalRunnerScenario = (typeof LOCAL_RUNNER_SCENARIOS)[number]; + +export interface LocalRunnerCommandReceipt { + commandId: string; + controllerSeq: number; + status: "accepted" | "duplicate" | "rejected"; + detail: string; +} + +export interface LocalRunnerProcessExitFact { + exitCode: number | null; + success: boolean; + signal: number | null; +} + +export interface LocalRunnerRunMetadata { + schema: "paperclip.runner.local-runner.metadata.v1"; + scenario: LocalRunnerScenario; + fixtureName: string; + identity: PrpIdentity; + capabilities: PrpCapabilities; +} + +export interface LocalRunnerRunTrace extends Omit { + schema: "paperclip.runner.local-runner.trace.v1"; + commands: PrpCommand[]; + commandReceipts: LocalRunnerCommandReceipt[]; + events: PrpEvent[]; + requests: PrpRequest[]; + result: PrpStructuredRunResult | null; + harnessProcessExit: LocalRunnerProcessExitFact | null; + runnerProcessExit: { code: number | null; signal: string | null }; + runnerDiagnostics: string[]; +} diff --git a/packages/paperclip-runner/src/contracts/native-execution.test.ts b/packages/paperclip-runner/src/contracts/native-execution.test.ts new file mode 100644 index 0000000000..980ae6e3a9 --- /dev/null +++ b/packages/paperclip-runner/src/contracts/native-execution.test.ts @@ -0,0 +1,414 @@ +import { describe, expect, it } from "vitest"; + +import { buildNativeModelEnvelope, parseNativeExecutionInput, type NativeExecutionInputV1 } from "./native-execution.js"; +import { + NATIVE_RUNTIME_ASSET_SCHEMA, + PAPERCLIP_EXECUTION_PROMPT, + PAPERCLIP_EXECUTION_PROMPT_REVISION, + canonicalNativeRuntimeContextDigest, + composeNativeSystemInstructions, + nativeRuntimePromptDigest, +} from "./runtime-context.js"; + +const input: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", + binding: { + companyId: "company-1", + runId: "run-1", + issueId: "issue-1", + agentId: "agent-1", + executionWorkspaceId: "workspace-1", + }, + task: { + identifier: "PAP-1", + title: "Safe task", + description: null, + prompt: "# PAP-1: Safe task\n\nPlease address the latest comment.", + workMode: "standard", + }, + workspace: { cwd: "/safe/workspace", repoUrl: null, repoRef: null, branchName: null }, + session: { + normalizedSessionId: null, + driverKind: "codex_app_server", + protocolVersion: 1, + lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, + }, + provider: { kind: "codex", model: null }, + completionContract: { + id: "contract-1", + sha256: "abc123", + schemaVersion: "paperclip.completion-contract.v1", + contract: { + revision: "1", + objective: "Complete the safe task.", + criteria: [{ id: "objective", requirement: "The task is complete." }], + }, + }, + interactionResponses: [], + credentialBindings: [{ + bindingId: "opaque-binding", + service: "github", + destination: "github.com", + expiresAt: null, + displayName: "GitHub", + }], +}; + +describe("NativeExecutionInputV1", () => { + it("parses v3 immutable runtime context without changing the model task envelope", () => { + const digest = "0".repeat(64); + const context = { + prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() }, + instructions: { + entryPath: "AGENTS.md", + bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: "/runtime/instructions", fileCount: 2, totalBytes: 42 }, + }, + skills: [{ + key: "company/research", + runtimeName: "research", + versionId: "version-1", + bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: "/runtime/skills/research", fileCount: 2, totalBytes: 42 }, + }], + mcp: { assignmentSetId: "sha256:test", digest, bindingId: "native-mcp:run-1" }, + } as const; + const parsed = parseNativeExecutionInput({ + ...input, + schema: "paperclip.native-execution-input.v3", + executionMode: "default", + planningContext: null, + runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) }, + }); + expect(parsed.schema).toBe("paperclip.native-execution-input.v3"); + const envelope = buildNativeModelEnvelope(parsed); + expect(envelope.task).toEqual(buildNativeModelEnvelope(input).task); + expect(envelope.completionContract).toEqual(buildNativeModelEnvelope(input).completionContract); + expect(JSON.stringify(envelope)).not.toContain("runtimeContext"); + expect(JSON.stringify(envelope)).not.toContain(PAPERCLIP_EXECUTION_PROMPT); + expect(composeNativeSystemInstructions(parsed.runtimeContext, "Follow sibling.md")).toBe( + `${PAPERCLIP_EXECUTION_PROMPT}\n\nFollow sibling.md\n\nRead-only instruction sibling root: /runtime/instructions`, + ); + expect(canonicalNativeRuntimeContextDigest({ + ...context, + mcp: { ...context.mcp, bindingId: "native-mcp:run-2" }, + })).toBe(parsed.runtimeContext.aggregateDigest); + const current = parseNativeExecutionInput({ + ...parsed, + schema: "paperclip.native-execution-input.v4", + provider: { kind: "codex", model: null, approvalPolicy: "on-request" }, + }); + expect(current).toMatchObject({ + schema: "paperclip.native-execution-input.v4", + provider: { kind: "codex", approvalPolicy: "on-request" }, + }); + expect(() => parseNativeExecutionInput({ + ...parsed, + schema: "paperclip.native-execution-input.v4", + provider: { kind: "codex", model: null, approvalPolicy: "sometimes" }, + })).toThrow("approvalPolicy"); + }); + + it("rejects runtime-context traversal and aggregate digest drift", () => { + const digest = "0".repeat(64); + const context = { + prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() }, + instructions: { + entryPath: "../AGENTS.md", + bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: "/runtime/instructions", fileCount: 1, totalBytes: 1 }, + }, + skills: [], + mcp: { assignmentSetId: "none", digest, bindingId: null }, + aggregateDigest: digest, + } as const; + expect(() => parseNativeExecutionInput({ ...input, schema: "paperclip.native-execution-input.v3", executionMode: "default", planningContext: null, runtimeContext: context })).toThrow("bundle root"); + expect(() => parseNativeExecutionInput({ + ...input, + schema: "paperclip.native-execution-input.v3", + executionMode: "default", + planningContext: null, + runtimeContext: { ...context, instructions: { ...context.instructions, entryPath: "AGENTS.md" } }, + })).toThrow("aggregateDigest"); + }); + + it("builds a model envelope without authority or credential bindings", () => { + const parsed = parseNativeExecutionInput(input); + const model = buildNativeModelEnvelope(parsed); + const serialized = JSON.stringify(model); + expect(serialized).not.toContain("company-1"); + expect(serialized).not.toContain("run-1"); + expect(serialized).not.toContain("opaque-binding"); + expect(model.task.title).toBe("Safe task"); + expect(model.task.prompt).toContain("latest comment"); + }); + + it("rejects unknown context or environment escape hatches", () => { + expect(() => parseNativeExecutionInput({ ...input, context: { secret: "canary" } })).toThrow( + "unknown field context", + ); + expect(() => parseNativeExecutionInput({ + ...input, + workspace: { ...input.workspace, env: { PAPERCLIP_API_KEY: "canary" } }, + })).toThrow("unknown field env"); + }); + + it("accepts a persisted OpenCode driver/model pair and rejects mismatches", () => { + const opencode = parseNativeExecutionInput({ + ...input, + session: { ...input.session, driverKind: "opencode_server" }, + provider: { kind: "opencode", model: "openrouter/deepseek/deepseek-v4-flash-0731" }, + }); + expect(opencode.provider).toEqual({ + kind: "opencode", + model: "openrouter/deepseek/deepseek-v4-flash-0731", + }); + expect(parseNativeExecutionInput(opencode)).toEqual(opencode); + expect(() => parseNativeExecutionInput({ + ...input, + session: { ...input.session, driverKind: "opencode_server" }, + provider: { kind: "codex", model: null }, + })).toThrow("does not match"); + }); + + it("deserializes pre-provider Codex state as Codex", () => { + const legacy = structuredClone(input) as Record; + delete legacy.provider; + expect(parseNativeExecutionInput(legacy).provider).toEqual({ + kind: "codex", + model: null, + }); + expect(parseNativeExecutionInput(parseNativeExecutionInput(legacy))).toEqual( + parseNativeExecutionInput(legacy), + ); + }); + + it("accepts an immutable Claude Managed Agent profile and rejects driver or beta drift", () => { + const claudeManaged = { + ...input, + session: { ...input.session, driverKind: "claude_managed_agents_api" }, + provider: { + kind: "claude_managed", + model: "claude-sonnet-5", + managedProfile: { + profileId: "managed-profile-1", + anthropicAgentId: "agent_01", + agentVersion: "3", + environmentId: "environment_01", + betaVersion: "managed-agents-2026-04-01", + }, + maxSessionListCostUsd: 1, + }, + } as const; + const parsed = parseNativeExecutionInput(claudeManaged); + expect(parsed.provider).toEqual(claudeManaged.provider); + expect(buildNativeModelEnvelope(parsed).workspace).toBeNull(); + expect(() => parseNativeExecutionInput({ + ...claudeManaged, + session: { ...claudeManaged.session, driverKind: "codex_app_server" }, + })).toThrow("does not match"); + expect(() => parseNativeExecutionInput({ + ...claudeManaged, + provider: { + ...claudeManaged.provider, + managedProfile: { ...claudeManaged.provider.managedProfile, betaVersion: "future-beta" }, + }, + })).toThrow("betaVersion"); + }); + + it("accepts a closed AWS AgentCore Harness snapshot and rejects drift or unsafe limits", () => { + const awsAgentCore = { + ...input, + session: { ...input.session, driverKind: "aws_agentcore_harness_api" }, + provider: { + kind: "aws_agentcore", + model: "global.anthropic.claude-sonnet-4-6", + agentCoreProfile: { + profileId: "agentcore-development", + region: "us-east-1", + accountId: "123456789012", + harnessArn: "arn:aws:bedrock-agentcore:us-east-1:123456789012:harness/harness-1", + harnessVersion: "3", + endpointArn: "arn:aws:bedrock-agentcore:us-east-1:123456789012:harness-endpoint/harness-1/paperclip", + endpointQualifier: "paperclip", + agentRuntimeArn: "arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/runtime-1", + memoryArn: "arn:aws:bedrock-agentcore:us-east-1:123456789012:memory/memory-1", + memoryId: "memory-1", + invocationRoleArn: "arn:aws:iam::123456789012:role/paperclip-agentcore-runner", + contextBucket: "paperclip-agentcore-context", + contextPrefix: "paperclip/runtime", + contextKmsKeyArn: "arn:aws:kms:us-east-1:123456789012:key/test", + qualificationRevision: "aws-agentcore-harness-v1", + eventExpiryDays: 90, + }, + maxEstimatedSessionCostUsd: 1, + invocationLimits: { maxIterations: 8, maxOutputTokens: 4096, timeoutSeconds: 300 }, + }, + } as const; + const parsed = parseNativeExecutionInput(awsAgentCore); + expect(parsed.provider).toEqual(awsAgentCore.provider); + expect(buildNativeModelEnvelope(parsed).workspace).toBeNull(); + expect(JSON.stringify(parsed)).not.toContain("AWS_SECRET_ACCESS_KEY"); + expect(() => parseNativeExecutionInput({ + ...awsAgentCore, + session: { ...awsAgentCore.session, driverKind: "codex_app_server" }, + })).toThrow("does not match"); + expect(() => parseNativeExecutionInput({ + ...awsAgentCore, + provider: { ...awsAgentCore.provider, invocationLimits: { ...awsAgentCore.provider.invocationLimits, maxIterations: 9 } }, + })).toThrow("maxIterations"); + expect(() => parseNativeExecutionInput({ + ...awsAgentCore, + provider: { ...awsAgentCore.provider, agentCoreProfile: { ...awsAgentCore.provider.agentCoreProfile, eventExpiryDays: 30 } }, + })).toThrow("eventExpiryDays"); + }); + + it("accepts only a closed ACPX profile matching the driver and agent", () => { + const provider = { + kind: "acpx", + agent: "pi", + model: "openrouter/deepseek/deepseek-v4-flash-0731", + permissionPolicy: "interactive", + profile: { + driverKind: "acpx_runtime", + protocolVersion: 1, + acpxVersion: "0.13.1", + agent: "pi", + agentProfileVersion: 1, + agentServerPackage: "pi-acp", + agentServerVersion: "0.0.33", + agentRuntimePackage: "@earendil-works/pi-coding-agent", + agentRuntimeVersion: "0.84.2", + commandDigest: "sha256:24ff73fda6e3c76ddce2d359a79f5c4b8f292eb290e4d2ab85aac94676b2c2dc", + }, + } as const; + const parsed = parseNativeExecutionInput({ + ...input, + session: { ...input.session, driverKind: "acpx_runtime" }, + provider, + }); + expect(parsed.provider).toEqual({ + kind: "acpx", + agent: "pi", + model: "openrouter/deepseek/deepseek-v4-flash-0731", + permissionPolicy: "interactive", + profile: provider.profile, + }); + expect(parseNativeExecutionInput(parsed)).toEqual(parsed); + expect(buildNativeModelEnvelope(parsed).workspace).toEqual({ cwd: "/safe/workspace" }); + expect(() => parseNativeExecutionInput({ + ...input, + session: { ...input.session, driverKind: "acpx_runtime" }, + provider: { ...provider, profile: { ...provider.profile, agent: "claude" } }, + })).toThrow("qualified ACPX v1 profile"); + expect(() => parseNativeExecutionInput({ + ...input, + session: { ...input.session, driverKind: "opencode_server" }, + provider, + })).toThrow("does not match"); + }); + + it("defaults legacy lifecycle state to per-turn and validates warm timeouts", () => { + const legacy = structuredClone(input) as Record; + delete (legacy.session as Record).lifecyclePolicy; + expect(parseNativeExecutionInput(legacy).session.lifecyclePolicy).toEqual({ + mode: "per_turn", + idleTimeoutMs: null, + }); + expect(parseNativeExecutionInput({ + ...input, + session: { + ...input.session, + lifecyclePolicy: { mode: "warm", idleTimeoutMs: 300_000 }, + }, + }).session.lifecyclePolicy).toEqual({ mode: "warm", idleTimeoutMs: 300_000 }); + expect(() => parseNativeExecutionInput({ + ...input, + session: { + ...input.session, + lifecyclePolicy: { mode: "warm", idleTimeoutMs: 0 }, + }, + })).toThrow("positive integer"); + }); +}); + +describe("NativeExecutionInputV2 planning", () => { + const planning = { + ...input, + schema: "paperclip.native-execution-input.v2", + executionMode: "plan", + task: { ...input.task, workMode: "planning" }, + planningContext: { + documentId: "document-1", + baseRevisionId: "revision-3", + baseRevisionNumber: 3, + markdown: "# Existing plan", + sha256: "plan-digest", + reviewContext: { threads: [{ id: "annotation-1" }] }, + }, + } as const; + + it("round-trips native plan mode and its pinned canonical revision into model context", () => { + const parsed = parseNativeExecutionInput(planning); + expect(parsed).toMatchObject({ schema: "paperclip.native-execution-input.v2", executionMode: "plan" }); + expect(buildNativeModelEnvelope(parsed)).toMatchObject({ + schema: "paperclip.native-model-envelope.v2", + executionMode: "plan", + planningContext: { baseRevisionId: "revision-3", baseRevisionNumber: 3 }, + }); + }); + + it("fails closed when plan mode omits its pinned Paperclip context", () => { + expect(() => parseNativeExecutionInput({ ...planning, planningContext: null })) + .toThrow("planningContext is required"); + expect(() => parseNativeExecutionInput({ + ...planning, + task: { ...planning.task, workMode: "standard" }, + })).toThrow("requires planning work mode"); + }); + + it("allows an accepted planning issue to continue in fresh default execution mode", () => { + expect(parseNativeExecutionInput({ + ...planning, + executionMode: "default", + planningContext: null, + })).toMatchObject({ task: { workMode: "planning" }, executionMode: "default" }); + }); +}); + +describe("NativeExecutionInputV2 ask mode", () => { + it("round-trips ask mode as a default execution without planning context", () => { + const parsed = parseNativeExecutionInput({ + ...input, + schema: "paperclip.native-execution-input.v2", + executionMode: "default", + task: { ...input.task, workMode: "ask" }, + planningContext: null, + }); + expect(parsed).toMatchObject({ + schema: "paperclip.native-execution-input.v2", + executionMode: "default", + task: { workMode: "ask" }, + }); + expect(buildNativeModelEnvelope(parsed)).toMatchObject({ + schema: "paperclip.native-model-envelope.v2", + task: { workMode: "ask" }, + executionMode: "default", + planningContext: null, + }); + }); + + it("rejects plan execution for ask mode", () => { + expect(() => parseNativeExecutionInput({ + ...input, + schema: "paperclip.native-execution-input.v2", + executionMode: "plan", + task: { ...input.task, workMode: "ask" }, + planningContext: { + documentId: null, + baseRevisionId: null, + baseRevisionNumber: 0, + markdown: "", + sha256: "digest", + reviewContext: {}, + }, + })).toThrow("plan execution mode requires planning work mode"); + }); +}); diff --git a/packages/paperclip-runner/src/contracts/native-execution.ts b/packages/paperclip-runner/src/contracts/native-execution.ts new file mode 100644 index 0000000000..9e51fbcc71 --- /dev/null +++ b/packages/paperclip-runner/src/contracts/native-execution.ts @@ -0,0 +1,732 @@ +import type { PrpStructuredRunResult, PrpTerminalState } from "../protocol/replay-contract.js"; +import { parseNativeRuntimeContext, type NativeRuntimeContextSnapshot } from "./runtime-context.js"; + +export const NATIVE_EXECUTION_INPUT_SCHEMA_V1 = "paperclip.native-execution-input.v1" as const; +export const NATIVE_EXECUTION_INPUT_SCHEMA_V2 = "paperclip.native-execution-input.v2" as const; +export const NATIVE_EXECUTION_INPUT_SCHEMA_V3 = "paperclip.native-execution-input.v3" as const; +export const NATIVE_EXECUTION_INPUT_SCHEMA = "paperclip.native-execution-input.v4" as const; +export const NATIVE_MODEL_ENVELOPE_SCHEMA_V1 = "paperclip.native-model-envelope.v1" as const; +export const NATIVE_MODEL_ENVELOPE_SCHEMA = "paperclip.native-model-envelope.v2" as const; + +export type NativeExecutionMode = "default" | "plan"; + +export interface NativePlanningContext { + documentId: string | null; + baseRevisionId: string | null; + baseRevisionNumber: number; + markdown: string; + sha256: string; + reviewContext: Record; +} + +export interface StrictCompletionContractInput { + revision: string; + objective: string; + criteria: Array<{ id: string; requirement: string }>; +} + +export interface NativeInteractionResponseEnvelope { + interactionId: string; + kind: + | "suggest_tasks" + | "ask_user_questions" + | "request_confirmation" + | "request_checkbox_confirmation" + | "request_item_verdicts"; + response: Record; +} + +export interface NativeCredentialBindingRef { + bindingId: string; + service: string; + destination: string; + expiresAt: string | null; + displayName: string | null; +} + +export type NativeSessionLifecyclePolicy = + | { mode: "per_turn"; idleTimeoutMs: null } + | { mode: "warm"; idleTimeoutMs: number }; + +export interface NativeManagedAgentProfileSnapshot { + profileId: string; + anthropicAgentId: string; + agentVersion: string; + environmentId: string; + betaVersion: "managed-agents-2026-04-01"; +} + +export interface NativeAwsAgentCoreProfileSnapshot { + profileId: string; + region: string; + accountId: string; + harnessArn: string; + harnessVersion: string; + endpointArn: string; + endpointQualifier: string; + agentRuntimeArn: string; + memoryArn: string; + memoryId: string; + invocationRoleArn: string; + contextBucket: string; + contextPrefix: string; + contextKmsKeyArn: string; + qualificationRevision: string; + eventExpiryDays: 90; +} + +export type NativeAcpxAgent = "pi" | "claude" | "codex"; +export type NativeCodexApprovalPolicy = "never" | "on-request" | "untrusted"; +export type NativeOpenCodePermissionMode = "allow" | "ask" | "deny"; +export type NativeAcpxPermissionMode = "approve-all" | "approve-reads" | "deny-all"; + +export interface NativeAcpxProfileSnapshot { + driverKind: "acpx_runtime"; + protocolVersion: 1; + acpxVersion: "0.13.1"; + agent: NativeAcpxAgent; + agentProfileVersion: 1; + agentServerPackage: string; + agentServerVersion: string; + agentRuntimePackage: string | null; + agentRuntimeVersion: string | null; + commandDigest: string; +} + +export type NativeProviderConfig = + | { kind: "codex"; model: string | null; approvalPolicy?: NativeCodexApprovalPolicy } + | { kind: "opencode"; model: string; permissionMode?: NativeOpenCodePermissionMode } + | { + kind: "claude_managed"; + model: string; + managedProfile: NativeManagedAgentProfileSnapshot; + maxSessionListCostUsd: number; + } + | { + kind: "aws_agentcore"; + model: string; + agentCoreProfile: NativeAwsAgentCoreProfileSnapshot; + maxEstimatedSessionCostUsd: number; + invocationLimits: { + maxIterations: number; + maxOutputTokens: number; + timeoutSeconds: number; + }; + } + | { + kind: "acpx"; + agent: NativeAcpxAgent; + model: string; + permissionMode?: NativeAcpxPermissionMode; + /** Present only in persisted v1-v3 inputs. */ + permissionPolicy?: "interactive"; + profile: NativeAcpxProfileSnapshot; + }; + +export type NativeProviderConfigV4 = + | { kind: "codex"; model: string | null; approvalPolicy: NativeCodexApprovalPolicy } + | { kind: "opencode"; model: string; permissionMode: NativeOpenCodePermissionMode } + | Extract + | { + kind: "acpx"; + agent: NativeAcpxAgent; + model: string; + permissionMode: NativeAcpxPermissionMode; + profile: NativeAcpxProfileSnapshot; + }; + +export interface NativeExecutionInputV1 { + schema: typeof NATIVE_EXECUTION_INPUT_SCHEMA_V1; + binding: { + companyId: string; + runId: string; + issueId: string; + agentId: string; + executionWorkspaceId: string; + }; + task: { + identifier: string; + title: string; + description: string | null; + /** Redacted, server-authored task markdown including the current wake comment. */ + prompt: string; + workMode: "standard"; + }; + workspace: { + cwd: string; + repoUrl: string | null; + repoRef: string | null; + branchName: string | null; + }; + session: { + normalizedSessionId: string | null; + driverKind: "codex_app_server" | "opencode_server" | "claude_managed_agents_api" | "aws_agentcore_harness_api" | "acpx_runtime"; + protocolVersion: 1; + lifecyclePolicy: NativeSessionLifecyclePolicy; + }; + provider: NativeProviderConfig; + completionContract: { + id: string; + sha256: string; + schemaVersion: string; + contract: StrictCompletionContractInput; + }; + interactionResponses: NativeInteractionResponseEnvelope[]; + credentialBindings: NativeCredentialBindingRef[]; +} + +export interface NativeExecutionInputV2 extends Omit { + schema: typeof NATIVE_EXECUTION_INPUT_SCHEMA_V2; + executionMode: NativeExecutionMode; + task: Omit & { + workMode: "standard" | "planning" | "ask"; + }; + planningContext: NativePlanningContext | null; +} + +export interface NativeExecutionInputV3 extends Omit { + schema: typeof NATIVE_EXECUTION_INPUT_SCHEMA_V3; + runtimeContext: NativeRuntimeContextSnapshot; +} + +export interface NativeExecutionInputV4 extends Omit { + schema: typeof NATIVE_EXECUTION_INPUT_SCHEMA; + provider: NativeProviderConfigV4; +} + +export type NativeExecutionInput = NativeExecutionInputV1 | NativeExecutionInputV2 | NativeExecutionInputV3 | NativeExecutionInputV4; + +/** The only task data that may enter provider-visible model input. */ +export interface NativeModelEnvelopeV1 { + schema: typeof NATIVE_MODEL_ENVELOPE_SCHEMA_V1; + task: NativeExecutionInputV1["task"]; + /** Remote providers have no Paperclip workspace mounted in their service. */ + workspace: Pick | null; + completionContract: StrictCompletionContractInput; + interactionResponses: NativeInteractionResponseEnvelope[]; +} + +export interface NativeModelEnvelopeV2 { + schema: typeof NATIVE_MODEL_ENVELOPE_SCHEMA; + task: NativeExecutionInputV2["task"]; + executionMode: NativeExecutionMode; + planningContext: NativePlanningContext | null; + workspace: Pick | null; + completionContract: StrictCompletionContractInput; + interactionResponses: NativeInteractionResponseEnvelope[]; +} + +export interface NativeSessionExecutionResult { + result: PrpStructuredRunResult; + terminal: PrpTerminalState; + turnId: string | null; + normalizedSessionId: string; + providerSessionId: string | null; + driverKind: string; + driverVersion: string; + nativeEventCount: number; + highestContiguousSourceSeq: number; + usage: Record | null; +} + +export class NativeExecutionInputError extends Error { + readonly code = "native_execution_input_invalid" as const; + + constructor(message: string) { + super(message); + this.name = "NativeExecutionInputError"; + } +} + +function record(value: unknown, path: string): Record { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new NativeExecutionInputError(`${path} must be an object`); + } + return value as Record; +} + +function exactKeys(value: Record, keys: readonly string[], path: string): void { + const allowed = new Set(keys); + const unknown = Object.keys(value).filter((key) => !allowed.has(key)); + if (unknown.length > 0) { + throw new NativeExecutionInputError(`${path} contains unknown field ${unknown[0]}`); + } +} + +function text(value: unknown, path: string): string { + if (typeof value !== "string" || value.trim().length === 0) { + throw new NativeExecutionInputError(`${path} must be a non-empty string`); + } + return value; +} + +function nullableText(value: unknown, path: string): string | null { + return value === null ? null : text(value, path); +} + +/** + * Strictly validates the closed Paperclip-to-runner launch contract. This is + * intentionally not an extensible metadata bag: new fields require a contract + * revision and an explicit security review. + */ +export function parseNativeExecutionInput(value: unknown): NativeExecutionInput { + const input = record(value, "input"); + const isV4 = input.schema === NATIVE_EXECUTION_INPUT_SCHEMA; + const isV3 = isV4 || input.schema === NATIVE_EXECUTION_INPUT_SCHEMA_V3; + const isV2 = isV3 || input.schema === NATIVE_EXECUTION_INPUT_SCHEMA_V2; + exactKeys(input, [ + "schema", + "binding", + "task", + "workspace", + "session", + "provider", + "completionContract", + "interactionResponses", + "credentialBindings", + ...(isV2 ? ["executionMode", "planningContext"] : []), + ...(isV3 ? ["runtimeContext"] : []), + ], "input"); + if (!isV2 && input.schema !== NATIVE_EXECUTION_INPUT_SCHEMA_V1) { + throw new NativeExecutionInputError( + `input.schema must be ${NATIVE_EXECUTION_INPUT_SCHEMA_V1}, ${NATIVE_EXECUTION_INPUT_SCHEMA_V2}, ${NATIVE_EXECUTION_INPUT_SCHEMA_V3}, or ${NATIVE_EXECUTION_INPUT_SCHEMA}`, + ); + } + + const binding = record(input.binding, "input.binding"); + exactKeys(binding, ["companyId", "runId", "issueId", "agentId", "executionWorkspaceId"], "input.binding"); + const task = record(input.task, "input.task"); + exactKeys(task, ["identifier", "title", "description", "prompt", "workMode"], "input.task"); + const workspace = record(input.workspace, "input.workspace"); + exactKeys(workspace, ["cwd", "repoUrl", "repoRef", "branchName"], "input.workspace"); + const session = record(input.session, "input.session"); + exactKeys(session, ["normalizedSessionId", "driverKind", "protocolVersion", "lifecyclePolicy"], "input.session"); + const completionContract = record(input.completionContract, "input.completionContract"); + exactKeys(completionContract, ["id", "sha256", "schemaVersion", "contract"], "input.completionContract"); + const contract = record(completionContract.contract, "input.completionContract.contract"); + exactKeys(contract, ["revision", "objective", "criteria"], "input.completionContract.contract"); + + if (task.workMode !== "standard" && (!isV2 || task.workMode !== "planning" && task.workMode !== "ask")) { + throw new NativeExecutionInputError("input.task.workMode must be standard, planning, or ask"); + } + const executionMode: NativeExecutionMode = isV2 && input.executionMode === "plan" ? "plan" : "default"; + if (isV2 && input.executionMode !== "default" && input.executionMode !== "plan") { + throw new NativeExecutionInputError("input.executionMode must be default or plan"); + } + if (isV2 && task.workMode !== "planning" && executionMode === "plan") { + throw new NativeExecutionInputError("plan execution mode requires planning work mode"); + } + let planningContext: NativePlanningContext | null = null; + if (isV2 && input.planningContext !== null) { + const context = record(input.planningContext, "input.planningContext"); + exactKeys(context, [ + "documentId", "baseRevisionId", "baseRevisionNumber", "markdown", "sha256", "reviewContext", + ], "input.planningContext"); + if (!Number.isSafeInteger(context.baseRevisionNumber) || Number(context.baseRevisionNumber) < 0) { + throw new NativeExecutionInputError("input.planningContext.baseRevisionNumber must be a non-negative integer"); + } + planningContext = { + documentId: context.documentId === null ? null : text(context.documentId, "input.planningContext.documentId"), + baseRevisionId: context.baseRevisionId === null + ? null + : text(context.baseRevisionId, "input.planningContext.baseRevisionId"), + baseRevisionNumber: Number(context.baseRevisionNumber), + markdown: typeof context.markdown === "string" + ? context.markdown + : (() => { throw new NativeExecutionInputError("input.planningContext.markdown must be a string"); })(), + sha256: text(context.sha256, "input.planningContext.sha256"), + reviewContext: structuredClone(record(context.reviewContext, "input.planningContext.reviewContext")), + }; + } + if (isV2 && executionMode === "plan" && planningContext === null) { + throw new NativeExecutionInputError("input.planningContext is required in plan execution mode"); + } + if (isV2 && executionMode === "default" && input.planningContext !== null) { + throw new NativeExecutionInputError("input.planningContext is only valid in plan execution mode"); + } + if ( + ( + session.driverKind !== "codex_app_server" + && session.driverKind !== "opencode_server" + && session.driverKind !== "claude_managed_agents_api" + && session.driverKind !== "aws_agentcore_harness_api" + && session.driverKind !== "acpx_runtime" + ) + || session.protocolVersion !== 1 + ) { + throw new NativeExecutionInputError("input.session must select a supported protocol version 1 driver"); + } + const driverKind = session.driverKind as NativeExecutionInputV1["session"]["driverKind"]; + const lifecyclePolicyValue = session.lifecyclePolicy === undefined + ? { mode: "per_turn", idleTimeoutMs: null } + : record(session.lifecyclePolicy, "input.session.lifecyclePolicy"); + exactKeys(lifecyclePolicyValue, ["mode", "idleTimeoutMs"], "input.session.lifecyclePolicy"); + let lifecyclePolicy: NativeSessionLifecyclePolicy; + if (lifecyclePolicyValue.mode === "per_turn") { + if (lifecyclePolicyValue.idleTimeoutMs !== null) { + throw new NativeExecutionInputError("input.session.lifecyclePolicy.idleTimeoutMs must be null for per_turn"); + } + lifecyclePolicy = { mode: "per_turn", idleTimeoutMs: null }; + } else if (lifecyclePolicyValue.mode === "warm") { + if (!Number.isSafeInteger(lifecyclePolicyValue.idleTimeoutMs) || Number(lifecyclePolicyValue.idleTimeoutMs) <= 0) { + throw new NativeExecutionInputError("input.session.lifecyclePolicy.idleTimeoutMs must be a positive integer for warm"); + } + lifecyclePolicy = { mode: "warm", idleTimeoutMs: Number(lifecyclePolicyValue.idleTimeoutMs) }; + } else { + throw new NativeExecutionInputError("input.session.lifecyclePolicy.mode must be per_turn or warm"); + } + const provider = input.provider === undefined + ? { kind: "codex", model: null } + : record(input.provider, "input.provider"); + if ( + provider.kind !== "codex" + && provider.kind !== "opencode" + && provider.kind !== "claude_managed" + && provider.kind !== "aws_agentcore" + && provider.kind !== "acpx" + ) { + throw new NativeExecutionInputError("input.provider.kind must be codex, opencode, claude_managed, aws_agentcore, or acpx"); + } + exactKeys( + provider, + provider.kind === "claude_managed" + ? ["kind", "model", "managedProfile", "maxSessionListCostUsd"] + : provider.kind === "aws_agentcore" + ? ["kind", "model", "agentCoreProfile", "maxEstimatedSessionCostUsd", "invocationLimits"] + : provider.kind === "acpx" + ? ["kind", "agent", "model", isV4 ? "permissionMode" : "permissionPolicy", "profile"] + : provider.kind === "codex" && isV4 + ? ["kind", "model", "approvalPolicy"] + : provider.kind === "opencode" && isV4 + ? ["kind", "model", "permissionMode"] + : ["kind", "model"], + "input.provider", + ); + if ( + (provider.kind === "codex" && session.driverKind !== "codex_app_server") + || (provider.kind === "opencode" && session.driverKind !== "opencode_server") + || (provider.kind === "claude_managed" && session.driverKind !== "claude_managed_agents_api") + || (provider.kind === "aws_agentcore" && session.driverKind !== "aws_agentcore_harness_api") + || (provider.kind === "acpx" && session.driverKind !== "acpx_runtime") + ) { + throw new NativeExecutionInputError("input.provider.kind does not match input.session.driverKind"); + } + const providerModel = provider.model === null || provider.model === undefined + ? null + : text(provider.model, "input.provider.model"); + if (provider.kind === "opencode" && (providerModel === null || !providerModel.includes("/"))) { + throw new NativeExecutionInputError("input.provider.model is required for opencode in provider/model form"); + } + let parsedProvider: NativeProviderConfig; + if (provider.kind === "claude_managed") { + if (providerModel === null) { + throw new NativeExecutionInputError("input.provider.model is required for claude_managed"); + } + const managedProfile = record(provider.managedProfile, "input.provider.managedProfile"); + exactKeys( + managedProfile, + ["profileId", "anthropicAgentId", "agentVersion", "environmentId", "betaVersion"], + "input.provider.managedProfile", + ); + if (managedProfile.betaVersion !== "managed-agents-2026-04-01") { + throw new NativeExecutionInputError( + "input.provider.managedProfile.betaVersion must be managed-agents-2026-04-01", + ); + } + if ( + typeof provider.maxSessionListCostUsd !== "number" + || !Number.isFinite(provider.maxSessionListCostUsd) + || provider.maxSessionListCostUsd <= 0 + ) { + throw new NativeExecutionInputError("input.provider.maxSessionListCostUsd must be a positive finite number"); + } + parsedProvider = { + kind: "claude_managed", + model: providerModel, + managedProfile: { + profileId: text(managedProfile.profileId, "input.provider.managedProfile.profileId"), + anthropicAgentId: text( + managedProfile.anthropicAgentId, + "input.provider.managedProfile.anthropicAgentId", + ), + agentVersion: text(managedProfile.agentVersion, "input.provider.managedProfile.agentVersion"), + environmentId: text(managedProfile.environmentId, "input.provider.managedProfile.environmentId"), + betaVersion: "managed-agents-2026-04-01", + }, + maxSessionListCostUsd: provider.maxSessionListCostUsd, + }; + } else if (provider.kind === "aws_agentcore") { + if (providerModel === null) { + throw new NativeExecutionInputError("input.provider.model is required for aws_agentcore"); + } + const profile = record(provider.agentCoreProfile, "input.provider.agentCoreProfile"); + exactKeys(profile, [ + "profileId", "region", "accountId", "harnessArn", "harnessVersion", "endpointArn", + "endpointQualifier", "agentRuntimeArn", "memoryArn", "memoryId", "invocationRoleArn", + "contextBucket", "contextPrefix", "contextKmsKeyArn", "qualificationRevision", "eventExpiryDays", + ], "input.provider.agentCoreProfile"); + if (profile.eventExpiryDays !== 90) { + throw new NativeExecutionInputError("input.provider.agentCoreProfile.eventExpiryDays must be 90"); + } + if ( + typeof provider.maxEstimatedSessionCostUsd !== "number" + || !Number.isFinite(provider.maxEstimatedSessionCostUsd) + || provider.maxEstimatedSessionCostUsd <= 0 + ) { + throw new NativeExecutionInputError("input.provider.maxEstimatedSessionCostUsd must be a positive finite number"); + } + const limits = record(provider.invocationLimits, "input.provider.invocationLimits"); + exactKeys(limits, ["maxIterations", "maxOutputTokens", "timeoutSeconds"], "input.provider.invocationLimits"); + const positiveInteger = (value: unknown, path: string): number => { + if (!Number.isSafeInteger(value) || Number(value) <= 0) { + throw new NativeExecutionInputError(`${path} must be a positive integer`); + } + return Number(value); + }; + const maxIterations = positiveInteger(limits.maxIterations, "input.provider.invocationLimits.maxIterations"); + const maxOutputTokens = positiveInteger(limits.maxOutputTokens, "input.provider.invocationLimits.maxOutputTokens"); + const timeoutSeconds = positiveInteger(limits.timeoutSeconds, "input.provider.invocationLimits.timeoutSeconds"); + if (maxIterations > 8) throw new NativeExecutionInputError("input.provider.invocationLimits.maxIterations exceeds 8"); + if (maxOutputTokens > 4096) throw new NativeExecutionInputError("input.provider.invocationLimits.maxOutputTokens exceeds 4096"); + if (timeoutSeconds > 300) throw new NativeExecutionInputError("input.provider.invocationLimits.timeoutSeconds exceeds 300"); + parsedProvider = { + kind: "aws_agentcore", + model: providerModel, + agentCoreProfile: { + profileId: text(profile.profileId, "input.provider.agentCoreProfile.profileId"), + region: text(profile.region, "input.provider.agentCoreProfile.region"), + accountId: text(profile.accountId, "input.provider.agentCoreProfile.accountId"), + harnessArn: text(profile.harnessArn, "input.provider.agentCoreProfile.harnessArn"), + harnessVersion: text(profile.harnessVersion, "input.provider.agentCoreProfile.harnessVersion"), + endpointArn: text(profile.endpointArn, "input.provider.agentCoreProfile.endpointArn"), + endpointQualifier: text(profile.endpointQualifier, "input.provider.agentCoreProfile.endpointQualifier"), + agentRuntimeArn: text(profile.agentRuntimeArn, "input.provider.agentCoreProfile.agentRuntimeArn"), + memoryArn: text(profile.memoryArn, "input.provider.agentCoreProfile.memoryArn"), + memoryId: text(profile.memoryId, "input.provider.agentCoreProfile.memoryId"), + invocationRoleArn: text(profile.invocationRoleArn, "input.provider.agentCoreProfile.invocationRoleArn"), + contextBucket: text(profile.contextBucket, "input.provider.agentCoreProfile.contextBucket"), + contextPrefix: text(profile.contextPrefix, "input.provider.agentCoreProfile.contextPrefix"), + contextKmsKeyArn: text(profile.contextKmsKeyArn, "input.provider.agentCoreProfile.contextKmsKeyArn"), + qualificationRevision: text(profile.qualificationRevision, "input.provider.agentCoreProfile.qualificationRevision"), + eventExpiryDays: 90, + }, + maxEstimatedSessionCostUsd: provider.maxEstimatedSessionCostUsd, + invocationLimits: { maxIterations, maxOutputTokens, timeoutSeconds }, + }; + } else if (provider.kind === "acpx") { + if (providerModel === null) { + throw new NativeExecutionInputError("input.provider.model is required for acpx"); + } + if (provider.agent !== "pi" && provider.agent !== "claude" && provider.agent !== "codex") { + throw new NativeExecutionInputError("input.provider.agent must be pi, claude, or codex"); + } + if (isV4) { + if (provider.permissionMode !== "approve-all" && provider.permissionMode !== "approve-reads" && provider.permissionMode !== "deny-all") { + throw new NativeExecutionInputError("input.provider.permissionMode must be approve-all, approve-reads, or deny-all"); + } + } else if (provider.permissionPolicy !== "interactive") { + throw new NativeExecutionInputError("input.provider.permissionPolicy must be interactive"); + } + const profile = record(provider.profile, "input.provider.profile"); + exactKeys(profile, [ + "driverKind", + "protocolVersion", + "acpxVersion", + "agent", + "agentProfileVersion", + "agentServerPackage", + "agentServerVersion", + "agentRuntimePackage", + "agentRuntimeVersion", + "commandDigest", + ], "input.provider.profile"); + if ( + profile.driverKind !== "acpx_runtime" + || profile.protocolVersion !== 1 + || profile.acpxVersion !== "0.13.1" + || profile.agent !== provider.agent + || profile.agentProfileVersion !== 1 + ) { + throw new NativeExecutionInputError("input.provider.profile does not match the qualified ACPX v1 profile"); + } + const runtimePackage = nullableText(profile.agentRuntimePackage, "input.provider.profile.agentRuntimePackage"); + const runtimeVersion = nullableText(profile.agentRuntimeVersion, "input.provider.profile.agentRuntimeVersion"); + if ((runtimePackage === null) !== (runtimeVersion === null)) { + throw new NativeExecutionInputError("input.provider.profile agent runtime package and version must both be present or null"); + } + parsedProvider = { + kind: "acpx", + agent: provider.agent, + model: providerModel, + ...(isV4 + ? { permissionMode: provider.permissionMode as NativeAcpxPermissionMode } + : { permissionPolicy: "interactive" as const }), + profile: { + driverKind: "acpx_runtime", + protocolVersion: 1, + acpxVersion: "0.13.1", + agent: provider.agent, + agentProfileVersion: 1, + agentServerPackage: text(profile.agentServerPackage, "input.provider.profile.agentServerPackage"), + agentServerVersion: text(profile.agentServerVersion, "input.provider.profile.agentServerVersion"), + agentRuntimePackage: runtimePackage, + agentRuntimeVersion: runtimeVersion, + commandDigest: text(profile.commandDigest, "input.provider.profile.commandDigest"), + }, + }; + } else if (provider.kind === "opencode") { + if (isV4 && provider.permissionMode !== "allow" && provider.permissionMode !== "ask" && provider.permissionMode !== "deny") { + throw new NativeExecutionInputError("input.provider.permissionMode must be allow, ask, or deny"); + } + parsedProvider = { + kind: "opencode", + model: providerModel!, + ...(isV4 + ? { permissionMode: provider.permissionMode as NativeOpenCodePermissionMode } + : {}), + }; + } else { + if (isV4 && provider.approvalPolicy !== "never" && provider.approvalPolicy !== "on-request" && provider.approvalPolicy !== "untrusted") { + throw new NativeExecutionInputError("input.provider.approvalPolicy must be never, on-request, or untrusted"); + } + parsedProvider = { + kind: "codex", + model: providerModel, + ...(isV4 + ? { approvalPolicy: provider.approvalPolicy as NativeCodexApprovalPolicy } + : {}), + }; + } + if (!Array.isArray(contract.criteria) || contract.criteria.length === 0) { + throw new NativeExecutionInputError("input.completionContract.contract.criteria must not be empty"); + } + const criteria = contract.criteria.map((entry, index) => { + const criterion = record(entry, `input.completionContract.contract.criteria[${index}]`); + exactKeys(criterion, ["id", "requirement"], `input.completionContract.contract.criteria[${index}]`); + return { id: text(criterion.id, `criteria[${index}].id`), requirement: text(criterion.requirement, `criteria[${index}].requirement`) }; + }); + + if (!Array.isArray(input.interactionResponses) || !Array.isArray(input.credentialBindings)) { + throw new NativeExecutionInputError("interactionResponses and credentialBindings must be arrays"); + } + const interactionResponses = input.interactionResponses.map((entry, index) => { + const response = record(entry, `input.interactionResponses[${index}]`); + exactKeys(response, ["interactionId", "kind", "response"], `input.interactionResponses[${index}]`); + if (![ + "suggest_tasks", + "ask_user_questions", + "request_confirmation", + "request_checkbox_confirmation", + "request_item_verdicts", + ].includes(String(response.kind))) { + throw new NativeExecutionInputError(`input.interactionResponses[${index}].kind is unsupported`); + } + const kind = response.kind as NativeInteractionResponseEnvelope["kind"]; + return { + interactionId: text(response.interactionId, `input.interactionResponses[${index}].interactionId`), + kind, + response: structuredClone(record(response.response, `input.interactionResponses[${index}].response`)), + }; + }); + const credentialBindings = input.credentialBindings.map((entry, index) => { + const bindingRef = record(entry, `input.credentialBindings[${index}]`); + exactKeys(bindingRef, ["bindingId", "service", "destination", "expiresAt", "displayName"], `input.credentialBindings[${index}]`); + return { + bindingId: text(bindingRef.bindingId, `credentialBindings[${index}].bindingId`), + service: text(bindingRef.service, `credentialBindings[${index}].service`), + destination: text(bindingRef.destination, `credentialBindings[${index}].destination`), + expiresAt: nullableText(bindingRef.expiresAt, `credentialBindings[${index}].expiresAt`), + displayName: nullableText(bindingRef.displayName, `credentialBindings[${index}].displayName`), + }; + }); + + const common = { + binding: { + companyId: text(binding.companyId, "input.binding.companyId"), + runId: text(binding.runId, "input.binding.runId"), + issueId: text(binding.issueId, "input.binding.issueId"), + agentId: text(binding.agentId, "input.binding.agentId"), + executionWorkspaceId: text(binding.executionWorkspaceId, "input.binding.executionWorkspaceId"), + }, + task: { + identifier: text(task.identifier, "input.task.identifier"), + title: text(task.title, "input.task.title"), + description: nullableText(task.description, "input.task.description"), + // `prompt` was added after native run inputs were already persisted. + // Recovery must retain those runs, so derive the same bounded model + // prompt from their task fields instead of making them unrecoverable. + prompt: text(task.prompt ?? task.description ?? task.title, "input.task.prompt"), + workMode: task.workMode as "standard" | "planning" | "ask", + }, + workspace: { + cwd: text(workspace.cwd, "input.workspace.cwd"), + repoUrl: nullableText(workspace.repoUrl, "input.workspace.repoUrl"), + repoRef: nullableText(workspace.repoRef, "input.workspace.repoRef"), + branchName: nullableText(workspace.branchName, "input.workspace.branchName"), + }, + session: { + normalizedSessionId: nullableText(session.normalizedSessionId, "input.session.normalizedSessionId"), + driverKind, + protocolVersion: 1 as const, + lifecyclePolicy, + }, + provider: parsedProvider, + completionContract: { + id: text(completionContract.id, "input.completionContract.id"), + sha256: text(completionContract.sha256, "input.completionContract.sha256"), + schemaVersion: text(completionContract.schemaVersion, "input.completionContract.schemaVersion"), + contract: { + revision: text(contract.revision, "input.completionContract.contract.revision"), + objective: text(contract.objective, "input.completionContract.contract.objective"), + criteria, + }, + }, + interactionResponses, + credentialBindings, + }; + if (!isV2) { + return { + ...common, + schema: NATIVE_EXECUTION_INPUT_SCHEMA_V1, + task: { ...common.task, workMode: "standard" }, + }; + } + const current = { + ...common, + executionMode, + planningContext, + }; + if (!isV3) return { ...current, schema: NATIVE_EXECUTION_INPUT_SCHEMA_V2 }; + const withRuntimeContext = { ...current, runtimeContext: parseNativeRuntimeContext(input.runtimeContext) }; + if (!isV4) return { ...withRuntimeContext, schema: NATIVE_EXECUTION_INPUT_SCHEMA_V3 }; + return { + ...withRuntimeContext, + schema: NATIVE_EXECUTION_INPUT_SCHEMA, + provider: parsedProvider as NativeProviderConfigV4, + }; +} + +export function buildNativeModelEnvelope(input: NativeExecutionInput): NativeModelEnvelopeV1 | NativeModelEnvelopeV2 { + if (input.schema === NATIVE_EXECUTION_INPUT_SCHEMA_V1) { + return { + schema: NATIVE_MODEL_ENVELOPE_SCHEMA_V1, + task: structuredClone(input.task), + workspace: input.provider.kind === "claude_managed" || input.provider.kind === "aws_agentcore" + ? null + : { cwd: input.workspace.cwd }, + completionContract: structuredClone(input.completionContract.contract), + interactionResponses: structuredClone(input.interactionResponses), + }; + } + return { + schema: NATIVE_MODEL_ENVELOPE_SCHEMA, + task: structuredClone(input.task), + executionMode: input.executionMode, + planningContext: structuredClone(input.planningContext), + workspace: input.provider.kind === "claude_managed" || input.provider.kind === "aws_agentcore" + ? null + : { cwd: input.workspace.cwd }, + completionContract: structuredClone(input.completionContract.contract), + interactionResponses: structuredClone(input.interactionResponses), + }; +} diff --git a/packages/paperclip-runner/src/contracts/question-set.test.ts b/packages/paperclip-runner/src/contracts/question-set.test.ts index 04644da0aa..7cd873afe3 100644 --- a/packages/paperclip-runner/src/contracts/question-set.test.ts +++ b/packages/paperclip-runner/src/contracts/question-set.test.ts @@ -18,7 +18,7 @@ const questionSet: PaperclipQuestionSet = { required: true, answerMode: "single_select", options: [ - { id: "staging", label: "Staging" }, + { id: "staging", label: "Staging", recommended: true }, { id: "production", label: "Production" }, ], customAnswer: { enabled: true, label: "Other" }, @@ -36,15 +36,13 @@ const questionSet: PaperclipQuestionSet = { describe("Paperclip question-set contract", () => { it("round-trips the portable presentation model", () => { expect(parsePaperclipQuestionSet(questionSet)).toEqual(questionSet); - expect( - parsePaperclipQuestionResponse(questionSet, { - schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, - answers: { - environment: { selectedOptionIds: ["staging"] }, - replicas: { text: "3" }, - }, - }), - ).toEqual({ + expect(parsePaperclipQuestionResponse(questionSet, { + schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, + answers: { + environment: { selectedOptionIds: ["staging"] }, + replicas: { text: "3" }, + }, + })).toEqual({ schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, answers: { environment: { selectedOptionIds: ["staging"] }, @@ -54,55 +52,40 @@ describe("Paperclip question-set contract", () => { }); it("rejects missing, unknown, and provider-shaped answers", () => { - expect(() => - parsePaperclipQuestionResponse(questionSet, { - schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, - answers: { - environment: { selectedOptionIds: ["unknown"] }, - replicas: { text: "3" }, - }, - }), - ).toThrow(/unknown option/); - expect(() => - parsePaperclipQuestionResponse(questionSet, { - schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, - answers: { environment: { selectedOptionIds: ["staging"] } }, - }), - ).toThrow(/replicas.*required/); - expect(() => - parsePaperclipQuestionResponse(questionSet, { - answers: { environment: { answers: ["Staging"] } }, - }), - ).toThrow(/paperclip.question_response.v1/); - expect(() => - parsePaperclipQuestionResponse(questionSet, { - schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, - answers: { - environment: { answers: ["Staging"] }, - replicas: { text: "3" }, - }, - }), - ).toThrow(/canonical response contract/); + expect(() => parsePaperclipQuestionResponse(questionSet, { + schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, + answers: { environment: { selectedOptionIds: ["unknown"] }, replicas: { text: "3" } }, + })).toThrow(/unknown option/); + expect(() => parsePaperclipQuestionResponse(questionSet, { + schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, + answers: { environment: { selectedOptionIds: ["staging"] } }, + })).toThrow(/replicas.*required/); + expect(() => parsePaperclipQuestionResponse(questionSet, { + answers: { environment: { answers: ["Staging"] } }, + })).toThrow(/paperclip.question_response.v1/); + expect(() => parsePaperclipQuestionResponse(questionSet, { + schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, + answers: { + environment: { answers: ["Staging"] }, + replicas: { text: "3" }, + }, + })).toThrow(/canonical response contract/); }); it("applies typed numeric validation before an adapter sees the answer", () => { - expect(() => - parsePaperclipQuestionResponse(questionSet, { - schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, - answers: { - environment: { customText: "Canary" }, - replicas: { text: "3.5" }, - }, - }), - ).toThrow(/valid integer/); - expect(() => - parsePaperclipQuestionResponse(questionSet, { - schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, - answers: { - environment: { customText: "Canary" }, - replicas: { text: "21" }, - }, - }), - ).toThrow(/at most 20/); + expect(() => parsePaperclipQuestionResponse(questionSet, { + schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, + answers: { + environment: { customText: "Canary" }, + replicas: { text: "3.5" }, + }, + })).toThrow(/valid integer/); + expect(() => parsePaperclipQuestionResponse(questionSet, { + schema: PAPERCLIP_QUESTION_RESPONSE_SCHEMA, + answers: { + environment: { customText: "Canary" }, + replicas: { text: "21" }, + }, + })).toThrow(/at most 20/); }); }); diff --git a/packages/paperclip-runner/src/contracts/question-set.ts b/packages/paperclip-runner/src/contracts/question-set.ts index a0a0323fea..34156a87cf 100644 --- a/packages/paperclip-runner/src/contracts/question-set.ts +++ b/packages/paperclip-runner/src/contracts/question-set.ts @@ -1,17 +1,14 @@ -export const PAPERCLIP_QUESTION_SET_SCHEMA = - "paperclip.question_set.v1" as const; -export const PAPERCLIP_QUESTION_RESPONSE_SCHEMA = - "paperclip.question_response.v1" as const; -export const PAPERCLIP_RUNTIME_REQUEST_SCHEMA_V2 = - "paperclip.runtime_request.v2" as const; +export const PAPERCLIP_QUESTION_SET_SCHEMA = "paperclip.question_set.v1" as const; +export const PAPERCLIP_QUESTION_RESPONSE_SCHEMA = "paperclip.question_response.v1" as const; +export const PAPERCLIP_RUNTIME_REQUEST_SCHEMA_V2 = "paperclip.runtime_request.v2" as const; -export type PaperclipQuestionAnswerMode = - "single_select" | "multi_select" | "text"; +export type PaperclipQuestionAnswerMode = "single_select" | "multi_select" | "text"; export interface PaperclipQuestionOption { id: string; label: string; description?: string; + recommended?: boolean; } export interface PaperclipQuestionCustomAnswer { @@ -104,46 +101,26 @@ function rejectUnknownKeys( const allowedKeys = new Set(allowed); const unknown = Object.keys(value).find((key) => !allowedKeys.has(key)); if (unknown !== undefined) { - throw new PaperclipQuestionValidationError( - `${path}/${unknown}`, - "is not part of the canonical response contract", - ); + throw new PaperclipQuestionValidationError(`${path}/${unknown}`, "is not part of the canonical response contract"); } } function requiredText(value: unknown, path: string, maxLength = 4_000): string { - if ( - typeof value !== "string" || - value.length === 0 || - value.length > maxLength - ) { - throw new PaperclipQuestionValidationError( - path, - `must be a non-empty string of at most ${maxLength} characters`, - ); + if (typeof value !== "string" || value.length === 0 || value.length > maxLength) { + throw new PaperclipQuestionValidationError(path, `must be a non-empty string of at most ${maxLength} characters`); } return value; } -function optionalText( - value: unknown, - path: string, - maxLength = 4_000, -): string | undefined { +function optionalText(value: unknown, path: string, maxLength = 4_000): string | undefined { if (value === undefined) return undefined; if (typeof value !== "string" || value.length > maxLength) { - throw new PaperclipQuestionValidationError( - path, - `must be a string of at most ${maxLength} characters`, - ); + throw new PaperclipQuestionValidationError(path, `must be a string of at most ${maxLength} characters`); } return value; } -function optionalFiniteNumber( - value: unknown, - path: string, -): number | undefined { +function optionalFiniteNumber(value: unknown, path: string): number | undefined { if (value === undefined) return undefined; if (typeof value !== "number" || !Number.isFinite(value)) { throw new PaperclipQuestionValidationError(path, "must be a finite number"); @@ -152,321 +129,151 @@ function optionalFiniteNumber( } /** Parse and sanitize the provider-neutral presentation contract at an adapter boundary. */ -export function parsePaperclipQuestionSet( - value: unknown, -): PaperclipQuestionSet { +export function parsePaperclipQuestionSet(value: unknown): PaperclipQuestionSet { const candidate = record(value); - if ( - candidate === null || - candidate.schema !== PAPERCLIP_QUESTION_SET_SCHEMA - ) { - throw new PaperclipQuestionValidationError( - "/input", - `must use ${PAPERCLIP_QUESTION_SET_SCHEMA}`, - ); + if (candidate === null || candidate.schema !== PAPERCLIP_QUESTION_SET_SCHEMA) { + throw new PaperclipQuestionValidationError("/input", `must use ${PAPERCLIP_QUESTION_SET_SCHEMA}`); } - if ( - !Array.isArray(candidate.questions) || - candidate.questions.length === 0 || - candidate.questions.length > 64 - ) { - throw new PaperclipQuestionValidationError( - "/input/questions", - "must contain between 1 and 64 questions", - ); + if (!Array.isArray(candidate.questions) || candidate.questions.length === 0 || candidate.questions.length > 64) { + throw new PaperclipQuestionValidationError("/input/questions", "must contain between 1 and 64 questions"); } const questionIds = new Set(); - const questions = candidate.questions.map( - (rawQuestion, questionIndex): PaperclipQuestion => { - const path = `/input/questions/${questionIndex}`; - const question = record(rawQuestion); - if (question === null) - throw new PaperclipQuestionValidationError(path, "must be an object"); - const id = requiredText(question.id, `${path}/id`, 160); - if (questionIds.has(id)) - throw new PaperclipQuestionValidationError( - `${path}/id`, - "must be unique", - ); - questionIds.add(id); - const answerMode = question.answerMode; - if ( - answerMode !== "single_select" && - answerMode !== "multi_select" && - answerMode !== "text" - ) { - throw new PaperclipQuestionValidationError( - `${path}/answerMode`, - "must be single_select, multi_select, or text", - ); - } - if (typeof question.required !== "boolean") { - throw new PaperclipQuestionValidationError( - `${path}/required`, - "must be boolean", - ); - } - if (Array.isArray(question.options) && question.options.length > 128) { - throw new PaperclipQuestionValidationError( - `${path}/options`, - "cannot contain more than 128 options", - ); - } - const options: PaperclipQuestionOption[] | undefined = Array.isArray( - question.options, - ) - ? question.options.map((rawOption, optionIndex) => { - const optionPath = `${path}/options/${optionIndex}`; - const option = record(rawOption); - if (option === null) - throw new PaperclipQuestionValidationError( - optionPath, - "must be an object", - ); - return { - id: requiredText(option.id, `${optionPath}/id`, 160), - label: requiredText(option.label, `${optionPath}/label`, 1_000), - ...(optionalText( - option.description, - `${optionPath}/description`, - ) !== undefined - ? { - description: optionalText( - option.description, - `${optionPath}/description`, - ), - } - : {}), - }; - }) - : undefined; - if ( - options !== undefined && - new Set(options.map((option) => option.id)).size !== options.length - ) { - throw new PaperclipQuestionValidationError( - `${path}/options`, - "option IDs must be unique within a question", - ); - } - if (answerMode !== "text" && (!options || options.length === 0)) { - throw new PaperclipQuestionValidationError( - `${path}/options`, - "select questions require at least one option", - ); - } - if ( - answerMode === "text" && - options !== undefined && - options.length > 0 - ) { - throw new PaperclipQuestionValidationError( - `${path}/options`, - "text questions cannot define options", - ); - } - const custom = record(question.customAnswer); - const customAnswer = - custom === null - ? undefined - : { - enabled: true as const, - ...(optionalText( - custom.label, - `${path}/customAnswer/label`, - 1_000, - ) !== undefined - ? { - label: optionalText( - custom.label, - `${path}/customAnswer/label`, - 1_000, - ), - } - : {}), - ...(optionalText( - custom.placeholder, - `${path}/customAnswer/placeholder`, - 1_000, - ) !== undefined - ? { - placeholder: optionalText( - custom.placeholder, - `${path}/customAnswer/placeholder`, - 1_000, - ), - } - : {}), - }; - if (custom !== null && custom.enabled !== true) { - throw new PaperclipQuestionValidationError( - `${path}/customAnswer/enabled`, - "must be true when customAnswer is present", - ); - } - if (answerMode === "text" && customAnswer !== undefined) { - throw new PaperclipQuestionValidationError( - `${path}/customAnswer`, - "text questions do not use a separate custom answer", - ); - } - const validation = record(question.textValidation); - const textValidation: PaperclipQuestionTextValidation | undefined = - validation === null - ? undefined - : { - ...(typeof validation.minLength === "number" - ? { minLength: validation.minLength } - : {}), - ...(typeof validation.maxLength === "number" - ? { maxLength: validation.maxLength } - : {}), - ...(optionalText( - validation.pattern, - `${path}/textValidation/pattern`, - 1_000, - ) !== undefined - ? { - pattern: optionalText( - validation.pattern, - `${path}/textValidation/pattern`, - 1_000, - ), - } - : {}), - ...(validation.inputType === "number" || - validation.inputType === "integer" || - validation.inputType === "text" - ? { inputType: validation.inputType } - : {}), - ...(optionalFiniteNumber( - validation.minimum, - `${path}/textValidation/minimum`, - ) !== undefined - ? { - minimum: optionalFiniteNumber( - validation.minimum, - `${path}/textValidation/minimum`, - ), - } - : {}), - ...(optionalFiniteNumber( - validation.maximum, - `${path}/textValidation/maximum`, - ) !== undefined - ? { - maximum: optionalFiniteNumber( - validation.maximum, - `${path}/textValidation/maximum`, - ), - } - : {}), - }; - if (validation !== null) { - for (const key of ["minLength", "maxLength"] as const) { - const raw = validation[key]; - if ( - raw !== undefined && - (!Number.isSafeInteger(raw) || - (raw as number) < 0 || - (raw as number) > 100_000) - ) { - throw new PaperclipQuestionValidationError( - `${path}/textValidation/${key}`, - "must be an integer from 0 through 100000", - ); - } - } - if ( - validation.inputType !== undefined && - !["text", "number", "integer"].includes(String(validation.inputType)) - ) { - throw new PaperclipQuestionValidationError( - `${path}/textValidation/inputType`, - "must be text, number, or integer", - ); - } - if ( - textValidation?.minLength !== undefined && - textValidation.maxLength !== undefined && - textValidation.minLength > textValidation.maxLength - ) { - throw new PaperclipQuestionValidationError( - `${path}/textValidation`, - "minLength cannot exceed maxLength", - ); - } - if ( - textValidation?.minimum !== undefined && - textValidation.maximum !== undefined && - textValidation.minimum > textValidation.maximum - ) { - throw new PaperclipQuestionValidationError( - `${path}/textValidation`, - "minimum cannot exceed maximum", - ); - } - if (textValidation?.pattern !== undefined) { - try { - new RegExp(textValidation.pattern); - } catch { - throw new PaperclipQuestionValidationError( - `${path}/textValidation/pattern`, - "must be a valid regular expression", - ); + const questions = candidate.questions.map((rawQuestion, questionIndex): PaperclipQuestion => { + const path = `/input/questions/${questionIndex}`; + const question = record(rawQuestion); + if (question === null) throw new PaperclipQuestionValidationError(path, "must be an object"); + const id = requiredText(question.id, `${path}/id`, 160); + if (questionIds.has(id)) throw new PaperclipQuestionValidationError(`${path}/id`, "must be unique"); + questionIds.add(id); + const answerMode = question.answerMode; + if (answerMode !== "single_select" && answerMode !== "multi_select" && answerMode !== "text") { + throw new PaperclipQuestionValidationError(`${path}/answerMode`, "must be single_select, multi_select, or text"); + } + if (typeof question.required !== "boolean") { + throw new PaperclipQuestionValidationError(`${path}/required`, "must be boolean"); + } + if (Array.isArray(question.options) && question.options.length > 128) { + throw new PaperclipQuestionValidationError(`${path}/options`, "cannot contain more than 128 options"); + } + const options: PaperclipQuestionOption[] | undefined = Array.isArray(question.options) + ? question.options.map((rawOption, optionIndex) => { + const optionPath = `${path}/options/${optionIndex}`; + const option = record(rawOption); + if (option === null) throw new PaperclipQuestionValidationError(optionPath, "must be an object"); + if (option.recommended !== undefined && typeof option.recommended !== "boolean") { + throw new PaperclipQuestionValidationError(`${optionPath}/recommended`, "must be boolean"); } + return { + id: requiredText(option.id, `${optionPath}/id`, 160), + label: requiredText(option.label, `${optionPath}/label`, 1_000), + ...(optionalText(option.description, `${optionPath}/description`) !== undefined + ? { description: optionalText(option.description, `${optionPath}/description`) } + : {}), + ...(option.recommended !== undefined ? { recommended: option.recommended } : {}), + }; + }) + : undefined; + if (options !== undefined && new Set(options.map((option) => option.id)).size !== options.length) { + throw new PaperclipQuestionValidationError(`${path}/options`, "option IDs must be unique within a question"); + } + if (answerMode !== "text" && (!options || options.length === 0)) { + throw new PaperclipQuestionValidationError(`${path}/options`, "select questions require at least one option"); + } + if (answerMode === "text" && options !== undefined && options.length > 0) { + throw new PaperclipQuestionValidationError(`${path}/options`, "text questions cannot define options"); + } + const custom = record(question.customAnswer); + const customAnswer = custom === null + ? undefined + : { + enabled: true as const, + ...(optionalText(custom.label, `${path}/customAnswer/label`, 1_000) !== undefined + ? { label: optionalText(custom.label, `${path}/customAnswer/label`, 1_000) } + : {}), + ...(optionalText(custom.placeholder, `${path}/customAnswer/placeholder`, 1_000) !== undefined + ? { placeholder: optionalText(custom.placeholder, `${path}/customAnswer/placeholder`, 1_000) } + : {}), + }; + if (custom !== null && custom.enabled !== true) { + throw new PaperclipQuestionValidationError(`${path}/customAnswer/enabled`, "must be true when customAnswer is present"); + } + if (answerMode === "text" && customAnswer !== undefined) { + throw new PaperclipQuestionValidationError(`${path}/customAnswer`, "text questions do not use a separate custom answer"); + } + const validation = record(question.textValidation); + const textValidation: PaperclipQuestionTextValidation | undefined = validation === null + ? undefined + : { + ...(typeof validation.minLength === "number" ? { minLength: validation.minLength } : {}), + ...(typeof validation.maxLength === "number" ? { maxLength: validation.maxLength } : {}), + ...(optionalText(validation.pattern, `${path}/textValidation/pattern`, 1_000) !== undefined + ? { pattern: optionalText(validation.pattern, `${path}/textValidation/pattern`, 1_000) } + : {}), + ...(validation.inputType === "number" || validation.inputType === "integer" || validation.inputType === "text" + ? { inputType: validation.inputType } + : {}), + ...(optionalFiniteNumber(validation.minimum, `${path}/textValidation/minimum`) !== undefined + ? { minimum: optionalFiniteNumber(validation.minimum, `${path}/textValidation/minimum`) } + : {}), + ...(optionalFiniteNumber(validation.maximum, `${path}/textValidation/maximum`) !== undefined + ? { maximum: optionalFiniteNumber(validation.maximum, `${path}/textValidation/maximum`) } + : {}), + }; + if (validation !== null) { + for (const key of ["minLength", "maxLength"] as const) { + const raw = validation[key]; + if (raw !== undefined && (!Number.isSafeInteger(raw) || (raw as number) < 0 || (raw as number) > 100_000)) { + throw new PaperclipQuestionValidationError(`${path}/textValidation/${key}`, "must be an integer from 0 through 100000"); } } - return { - id, - ...(optionalText(question.header, `${path}/header`, 1_000) !== undefined - ? { header: optionalText(question.header, `${path}/header`, 1_000) } - : {}), - prompt: requiredText(question.prompt, `${path}/prompt`), - ...(optionalText(question.helpText, `${path}/helpText`) !== undefined - ? { helpText: optionalText(question.helpText, `${path}/helpText`) } - : {}), - required: question.required, - answerMode, - ...(options !== undefined ? { options } : {}), - ...(customAnswer !== undefined ? { customAnswer } : {}), - ...(textValidation !== undefined ? { textValidation } : {}), - }; - }, - ); + if (validation.inputType !== undefined && !["text", "number", "integer"].includes(String(validation.inputType))) { + throw new PaperclipQuestionValidationError(`${path}/textValidation/inputType`, "must be text, number, or integer"); + } + if (textValidation?.minLength !== undefined && textValidation.maxLength !== undefined && textValidation.minLength > textValidation.maxLength) { + throw new PaperclipQuestionValidationError(`${path}/textValidation`, "minLength cannot exceed maxLength"); + } + if (textValidation?.minimum !== undefined && textValidation.maximum !== undefined && textValidation.minimum > textValidation.maximum) { + throw new PaperclipQuestionValidationError(`${path}/textValidation`, "minimum cannot exceed maximum"); + } + if (textValidation?.pattern !== undefined) { + try { new RegExp(textValidation.pattern); } catch { + throw new PaperclipQuestionValidationError(`${path}/textValidation/pattern`, "must be a valid regular expression"); + } + } + } + return { + id, + ...(optionalText(question.header, `${path}/header`, 1_000) !== undefined + ? { header: optionalText(question.header, `${path}/header`, 1_000) } + : {}), + prompt: requiredText(question.prompt, `${path}/prompt`), + ...(optionalText(question.helpText, `${path}/helpText`) !== undefined + ? { helpText: optionalText(question.helpText, `${path}/helpText`) } + : {}), + required: question.required, + answerMode, + ...(options !== undefined ? { options } : {}), + ...(customAnswer !== undefined ? { customAnswer } : {}), + ...(textValidation !== undefined ? { textValidation } : {}), + }; + }); return { schema: PAPERCLIP_QUESTION_SET_SCHEMA, ...(optionalText(candidate.title, "/input/title", 1_000) !== undefined ? { title: optionalText(candidate.title, "/input/title", 1_000) } : {}), ...(optionalText(candidate.description, "/input/description") !== undefined - ? { - description: optionalText( - candidate.description, - "/input/description", - ), - } + ? { description: optionalText(candidate.description, "/input/description") } : {}), - ...(optionalText(candidate.submitLabel, "/input/submitLabel", 200) !== - undefined - ? { - submitLabel: optionalText( - candidate.submitLabel, - "/input/submitLabel", - 200, - ), - } + ...(optionalText(candidate.submitLabel, "/input/submitLabel", 200) !== undefined + ? { submitLabel: optionalText(candidate.submitLabel, "/input/submitLabel", 200) } : {}), questions, }; } function answerHasValue(answer: PaperclipQuestionAnswer): boolean { - return Boolean( - answer.text?.trim() || - answer.customText?.trim() || - answer.selectedOptionIds?.length, - ); + return Boolean(answer.text?.trim() || answer.customText?.trim() || answer.selectedOptionIds?.length); } /** Revalidate untrusted UI input against the persisted question set. */ @@ -476,122 +283,54 @@ export function parsePaperclipQuestionResponse( ): PaperclipQuestionResponse { const questionSet = parsePaperclipQuestionSet(questionSetValue); const response = record(responseValue); - if ( - response === null || - response.schema !== PAPERCLIP_QUESTION_RESPONSE_SCHEMA - ) { - throw new PaperclipQuestionValidationError( - "/response", - `must use ${PAPERCLIP_QUESTION_RESPONSE_SCHEMA}`, - ); + if (response === null || response.schema !== PAPERCLIP_QUESTION_RESPONSE_SCHEMA) { + throw new PaperclipQuestionValidationError("/response", `must use ${PAPERCLIP_QUESTION_RESPONSE_SCHEMA}`); } rejectUnknownKeys(response, ["schema", "answers"], "/response"); const rawAnswers = record(response.answers); - if (rawAnswers === null) - throw new PaperclipQuestionValidationError( - "/response/answers", - "must be an object keyed by question ID", - ); - const questions = new Map( - questionSet.questions.map((question) => [question.id, question]), - ); + if (rawAnswers === null) throw new PaperclipQuestionValidationError("/response/answers", "must be an object keyed by question ID"); + const questions = new Map(questionSet.questions.map((question) => [question.id, question])); for (const questionId of Object.keys(rawAnswers)) { - if (!questions.has(questionId)) - throw new PaperclipQuestionValidationError( - `/response/answers/${questionId}`, - "does not match a question in the persisted set", - ); + if (!questions.has(questionId)) throw new PaperclipQuestionValidationError(`/response/answers/${questionId}`, "does not match a question in the persisted set"); } const answers: Record = {}; for (const question of questionSet.questions) { const path = `/response/answers/${question.id}`; const raw = rawAnswers[question.id]; if (raw === undefined) { - if (question.required) - throw new PaperclipQuestionValidationError(path, "is required"); + if (question.required) throw new PaperclipQuestionValidationError(path, "is required"); continue; } const answer = record(raw); - if (answer === null) - throw new PaperclipQuestionValidationError(path, "must be an object"); - rejectUnknownKeys( - answer, - ["selectedOptionIds", "text", "customText"], - path, - ); - const selectedOptionIds = - answer.selectedOptionIds === undefined - ? undefined - : Array.isArray(answer.selectedOptionIds) && - answer.selectedOptionIds.every((entry) => typeof entry === "string") - ? [...answer.selectedOptionIds] - : null; - if (selectedOptionIds === null) - throw new PaperclipQuestionValidationError( - `${path}/selectedOptionIds`, - "must be an array of strings", - ); - if ( - selectedOptionIds !== undefined && - new Set(selectedOptionIds).size !== selectedOptionIds.length - ) { - throw new PaperclipQuestionValidationError( - `${path}/selectedOptionIds`, - "cannot contain duplicates", - ); + if (answer === null) throw new PaperclipQuestionValidationError(path, "must be an object"); + rejectUnknownKeys(answer, ["selectedOptionIds", "text", "customText"], path); + const selectedOptionIds = answer.selectedOptionIds === undefined + ? undefined + : Array.isArray(answer.selectedOptionIds) && answer.selectedOptionIds.every((entry) => typeof entry === "string") + ? [...answer.selectedOptionIds] + : null; + if (selectedOptionIds === null) throw new PaperclipQuestionValidationError(`${path}/selectedOptionIds`, "must be an array of strings"); + if (selectedOptionIds !== undefined && new Set(selectedOptionIds).size !== selectedOptionIds.length) { + throw new PaperclipQuestionValidationError(`${path}/selectedOptionIds`, "cannot contain duplicates"); } const textValue = optionalText(answer.text, `${path}/text`, 100_000); - const customText = optionalText( - answer.customText, - `${path}/customText`, - 100_000, - ); + const customText = optionalText(answer.customText, `${path}/customText`, 100_000); if (question.answerMode === "text") { - if (selectedOptionIds?.length || customText !== undefined) - throw new PaperclipQuestionValidationError( - path, - "text answers only carry text", - ); + if (selectedOptionIds?.length || customText !== undefined) throw new PaperclipQuestionValidationError(path, "text answers only carry text"); } else { - if (textValue !== undefined) - throw new PaperclipQuestionValidationError( - path, - "select answers do not carry text", - ); - const allowed = new Set( - (question.options ?? []).map((option) => option.id), - ); + if (textValue !== undefined) throw new PaperclipQuestionValidationError(path, "select answers do not carry text"); + const allowed = new Set((question.options ?? []).map((option) => option.id)); for (const optionId of selectedOptionIds ?? []) { - if (!allowed.has(optionId)) - throw new PaperclipQuestionValidationError( - `${path}/selectedOptionIds`, - `contains unknown option ${optionId}`, - ); + if (!allowed.has(optionId)) throw new PaperclipQuestionValidationError(`${path}/selectedOptionIds`, `contains unknown option ${optionId}`); } - if ( - question.answerMode === "single_select" && - (selectedOptionIds?.length ?? 0) > 1 - ) { - throw new PaperclipQuestionValidationError( - `${path}/selectedOptionIds`, - "single-select answers choose at most one option", - ); + if (question.answerMode === "single_select" && (selectedOptionIds?.length ?? 0) > 1) { + throw new PaperclipQuestionValidationError(`${path}/selectedOptionIds`, "single-select answers choose at most one option"); } if (customText !== undefined && question.customAnswer?.enabled !== true) { - throw new PaperclipQuestionValidationError( - `${path}/customText`, - "custom answers are not enabled for this question", - ); + throw new PaperclipQuestionValidationError(`${path}/customText`, "custom answers are not enabled for this question"); } - if ( - customText?.trim() && - (selectedOptionIds?.length ?? 0) > 0 && - question.answerMode === "single_select" - ) { - throw new PaperclipQuestionValidationError( - path, - "single-select answers cannot select an option and a custom answer", - ); + if (customText?.trim() && (selectedOptionIds?.length ?? 0) > 0 && question.answerMode === "single_select") { + throw new PaperclipQuestionValidationError(path, "single-select answers cannot select an option and a custom answer"); } } const parsed: PaperclipQuestionAnswer = { @@ -599,63 +338,26 @@ export function parsePaperclipQuestionResponse( ...(textValue !== undefined ? { text: textValue } : {}), ...(customText !== undefined ? { customText } : {}), }; - if (question.required && !answerHasValue(parsed)) - throw new PaperclipQuestionValidationError(path, "is required"); - const boundedText = - question.answerMode === "text" ? parsed.text : parsed.customText; + if (question.required && !answerHasValue(parsed)) throw new PaperclipQuestionValidationError(path, "is required"); + const boundedText = question.answerMode === "text" ? parsed.text : parsed.customText; if (boundedText !== undefined) { const validation = question.textValidation; - if ( - validation?.minLength !== undefined && - boundedText.length < validation.minLength - ) { - throw new PaperclipQuestionValidationError( - path, - `must contain at least ${validation.minLength} characters`, - ); + if (validation?.minLength !== undefined && boundedText.length < validation.minLength) { + throw new PaperclipQuestionValidationError(path, `must contain at least ${validation.minLength} characters`); } - if ( - validation?.maxLength !== undefined && - boundedText.length > validation.maxLength - ) { - throw new PaperclipQuestionValidationError( - path, - `must contain at most ${validation.maxLength} characters`, - ); + if (validation?.maxLength !== undefined && boundedText.length > validation.maxLength) { + throw new PaperclipQuestionValidationError(path, `must contain at most ${validation.maxLength} characters`); } - if ( - validation?.pattern !== undefined && - !new RegExp(validation.pattern).test(boundedText) - ) { - throw new PaperclipQuestionValidationError( - path, - "does not match the required format", - ); + if (validation?.pattern !== undefined && !new RegExp(validation.pattern).test(boundedText)) { + throw new PaperclipQuestionValidationError(path, "does not match the required format"); } - if ( - validation?.inputType === "number" || - validation?.inputType === "integer" - ) { + if (validation?.inputType === "number" || validation?.inputType === "integer") { const numeric = Number(boundedText); - if ( - !Number.isFinite(numeric) || - (validation.inputType === "integer" && !Number.isInteger(numeric)) - ) { - throw new PaperclipQuestionValidationError( - path, - `must be a valid ${validation.inputType}`, - ); + if (!Number.isFinite(numeric) || (validation.inputType === "integer" && !Number.isInteger(numeric))) { + throw new PaperclipQuestionValidationError(path, `must be a valid ${validation.inputType}`); } - if (validation.minimum !== undefined && numeric < validation.minimum) - throw new PaperclipQuestionValidationError( - path, - `must be at least ${validation.minimum}`, - ); - if (validation.maximum !== undefined && numeric > validation.maximum) - throw new PaperclipQuestionValidationError( - path, - `must be at most ${validation.maximum}`, - ); + if (validation.minimum !== undefined && numeric < validation.minimum) throw new PaperclipQuestionValidationError(path, `must be at least ${validation.minimum}`); + if (validation.maximum !== undefined && numeric > validation.maximum) throw new PaperclipQuestionValidationError(path, `must be at most ${validation.maximum}`); } } if (answerHasValue(parsed)) answers[question.id] = parsed; diff --git a/packages/paperclip-runner/src/contracts/runtime-context.ts b/packages/paperclip-runner/src/contracts/runtime-context.ts new file mode 100644 index 0000000000..8832457945 --- /dev/null +++ b/packages/paperclip-runner/src/contracts/runtime-context.ts @@ -0,0 +1,146 @@ +import { createHash } from "node:crypto"; + +export const NATIVE_RUNTIME_ASSET_SCHEMA = "paperclip.runtime-asset.v1" as const; +export const PAPERCLIP_EXECUTION_PROMPT_REVISION = "paperclip-execution.v1" as const; +export const PAPERCLIP_EXECUTION_PROMPT = "You are running as a Paperclip agent. Complete the assigned task in the provided execution environment. Follow the attached agent instructions and use assigned skills and tools when relevant. Use Paperclip tools for coordination. Finish exactly once with `paperclip_finish` or `paperclip_block`." as const; + +export interface NativeRuntimeAssetReference { + schema: typeof NATIVE_RUNTIME_ASSET_SCHEMA; + digest: string; + manifestDigest: string; + rootPath: string; + fileCount: number; + totalBytes: number; +} + +export interface NativeRuntimeContextSnapshot { + prompt: { revision: typeof PAPERCLIP_EXECUTION_PROMPT_REVISION; text: typeof PAPERCLIP_EXECUTION_PROMPT; digest: string }; + instructions: { entryPath: string; bundle: NativeRuntimeAssetReference }; + skills: Array<{ key: string; runtimeName: string; versionId: string | null; bundle: NativeRuntimeAssetReference }>; + mcp: { assignmentSetId: string; digest: string; bindingId: string | null }; + aggregateDigest: string; +} + +export class NativeRuntimeContextError extends Error { + readonly code = "native_runtime_context_invalid" as const; + constructor(message: string) { super(message); this.name = "NativeRuntimeContextError"; } +} + +const sha256 = (value: string) => createHash("sha256").update(value).digest("hex"); +const object = (value: unknown, path: string): Record => { + if (!value || typeof value !== "object" || Array.isArray(value)) throw new NativeRuntimeContextError(`${path} must be an object`); + return value as Record; +}; +const exact = (value: Record, keys: string[], path: string) => { + const allowed = new Set(keys); + const unknown = Object.keys(value).find((key) => !allowed.has(key)); + if (unknown) throw new NativeRuntimeContextError(`${path} contains unknown field ${unknown}`); +}; +const text = (value: unknown, path: string) => { + if (typeof value !== "string" || !value.trim()) throw new NativeRuntimeContextError(`${path} must be a non-empty string`); + return value; +}; +const digest = (value: unknown, path: string) => { + const result = text(value, path); + if (!/^[a-f0-9]{64}$/.test(result)) throw new NativeRuntimeContextError(`${path} must be a sha256 digest`); + return result; +}; +const integer = (value: unknown, path: string) => { + if (!Number.isSafeInteger(value) || Number(value) < 0) throw new NativeRuntimeContextError(`${path} must be a non-negative integer`); + return Number(value); +}; +const safeRelativePath = (value: unknown, path: string) => { + const result = text(value, path).replaceAll("\\", "/"); + if (result.startsWith("/") || result.includes("\0") || result.split("/").some((part) => !part || part === "." || part === "..")) { + throw new NativeRuntimeContextError(`${path} must stay within its bundle root`); + } + return result; +}; + +function parseAsset(value: unknown, path: string): NativeRuntimeAssetReference { + const asset = object(value, path); + exact(asset, ["schema", "digest", "manifestDigest", "rootPath", "fileCount", "totalBytes"], path); + if (asset.schema !== NATIVE_RUNTIME_ASSET_SCHEMA) throw new NativeRuntimeContextError(`${path}.schema is unsupported`); + return { + schema: NATIVE_RUNTIME_ASSET_SCHEMA, + digest: digest(asset.digest, `${path}.digest`), + manifestDigest: digest(asset.manifestDigest, `${path}.manifestDigest`), + rootPath: text(asset.rootPath, `${path}.rootPath`), + fileCount: integer(asset.fileCount, `${path}.fileCount`), + totalBytes: integer(asset.totalBytes, `${path}.totalBytes`), + }; +} + +function aggregatePayload(value: Omit) { + return { + prompt: value.prompt, + instructions: { entryPath: value.instructions.entryPath, bundleDigest: value.instructions.bundle.digest }, + skills: [...value.skills].sort((a, b) => a.key.localeCompare(b.key)).map((skill) => ({ + key: skill.key, runtimeName: skill.runtimeName, versionId: skill.versionId, bundleDigest: skill.bundle.digest, + })), + // The binding is deliberately run-scoped. Compatibility is determined by the + // assigned access set so a fresh capability can be rebound without forcing a + // provider-session rotation when policy has not changed. + mcp: { assignmentSetId: value.mcp.assignmentSetId, digest: value.mcp.digest }, + }; +} + +export function canonicalNativeRuntimeContextDigest(value: Omit): string { + return sha256(JSON.stringify(aggregatePayload(value))); +} + +export function nativeRuntimePromptDigest(): string { return sha256(PAPERCLIP_EXECUTION_PROMPT); } + +export function parseNativeRuntimeContext(value: unknown): NativeRuntimeContextSnapshot { + const context = object(value, "input.runtimeContext"); + exact(context, ["prompt", "instructions", "skills", "mcp", "aggregateDigest"], "input.runtimeContext"); + const prompt = object(context.prompt, "input.runtimeContext.prompt"); + exact(prompt, ["revision", "text", "digest"], "input.runtimeContext.prompt"); + if (prompt.revision !== PAPERCLIP_EXECUTION_PROMPT_REVISION || prompt.text !== PAPERCLIP_EXECUTION_PROMPT) { + throw new NativeRuntimeContextError("input.runtimeContext.prompt must match the fixed Paperclip prompt revision"); + } + if (digest(prompt.digest, "input.runtimeContext.prompt.digest") !== nativeRuntimePromptDigest()) { + throw new NativeRuntimeContextError("input.runtimeContext.prompt.digest does not match prompt text"); + } + const instructions = object(context.instructions, "input.runtimeContext.instructions"); + exact(instructions, ["entryPath", "bundle"], "input.runtimeContext.instructions"); + if (!Array.isArray(context.skills)) throw new NativeRuntimeContextError("input.runtimeContext.skills must be an array"); + const skills = context.skills.map((value, index) => { + const skill = object(value, `input.runtimeContext.skills[${index}]`); + exact(skill, ["key", "runtimeName", "versionId", "bundle"], `input.runtimeContext.skills[${index}]`); + return { + key: text(skill.key, `input.runtimeContext.skills[${index}].key`), + runtimeName: safeRelativePath(skill.runtimeName, `input.runtimeContext.skills[${index}].runtimeName`), + versionId: skill.versionId === null ? null : text(skill.versionId, `input.runtimeContext.skills[${index}].versionId`), + bundle: parseAsset(skill.bundle, `input.runtimeContext.skills[${index}].bundle`), + }; + }); + if (new Set(skills.flatMap((skill) => [skill.key, `runtime:${skill.runtimeName}`])).size !== skills.length * 2) { + throw new NativeRuntimeContextError("input.runtimeContext.skills contains duplicate identities"); + } + const mcp = object(context.mcp, "input.runtimeContext.mcp"); + exact(mcp, ["assignmentSetId", "digest", "bindingId"], "input.runtimeContext.mcp"); + const parsed = { + prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() }, + instructions: { entryPath: safeRelativePath(instructions.entryPath, "input.runtimeContext.instructions.entryPath"), bundle: parseAsset(instructions.bundle, "input.runtimeContext.instructions.bundle") }, + skills, + mcp: { + assignmentSetId: text(mcp.assignmentSetId, "input.runtimeContext.mcp.assignmentSetId"), + digest: digest(mcp.digest, "input.runtimeContext.mcp.digest"), + bindingId: mcp.bindingId === null ? null : text(mcp.bindingId, "input.runtimeContext.mcp.bindingId"), + }, + } satisfies Omit; + const aggregateDigest = digest(context.aggregateDigest, "input.runtimeContext.aggregateDigest"); + if (aggregateDigest !== canonicalNativeRuntimeContextDigest(parsed)) { + throw new NativeRuntimeContextError("input.runtimeContext.aggregateDigest does not match the canonical context"); + } + return { ...parsed, aggregateDigest }; +} + +export function composeNativeSystemInstructions(context: NativeRuntimeContextSnapshot, entryContent: string): string { + return [ + context.prompt.text, + entryContent.trim(), + `Read-only instruction sibling root: ${context.instructions.bundle.rootPath}`, + ].filter(Boolean).join("\n\n"); +} diff --git a/packages/paperclip-runner/src/contracts/types.ts b/packages/paperclip-runner/src/contracts/types.ts new file mode 100644 index 0000000000..811e922aa1 --- /dev/null +++ b/packages/paperclip-runner/src/contracts/types.ts @@ -0,0 +1,49 @@ +export interface NativeRunIdentity { + runId: string; + sessionId: string; + companyId: string; + issueId: string; + agentId: string; +} + +export type NativeRunEventType = "run.started" | "run.completed"; + +export interface NativeRunEvent { + eventId: string; + runId: string; + sequence: number; + type: NativeRunEventType; +} + +export type NativeRunStatus = "succeeded" | "failed" | "cancelled"; + +export interface NativeRunResult { + runId: string; + status: NativeRunStatus; + summary: string; +} + +export interface NativeSessionCapabilities { + resume: boolean; + typedEvents: boolean; + typedEventFamilies?: TypedEventFamilyCapability[]; + steering: boolean; + interruption: boolean; + structuredResult: boolean; + read?: boolean; + reconciliation?: boolean; + usage?: boolean; + dynamicTools?: boolean; + runtimeRequestResolution?: boolean; + runtimeRequestHandoff?: boolean; + goals?: boolean; + threadLineage?: boolean; + collaborationModes?: Array<"default" | "plan">; + unsupported?: string[]; +} + +export interface NativeUserMessage { + role: "user"; + text: string; +} +import type { TypedEventFamilyCapability } from "../provider-events.js"; diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.ts index 8c8f4d86db..02210787d2 100644 --- a/packages/paperclip-runner/src/index.ts +++ b/packages/paperclip-runner/src/index.ts @@ -1,6 +1,12 @@ export * from "./catalog/index.js"; export * from "./contracts/completion-result.js"; +export * from "./contracts/codex.js"; +export * from "./contracts/durable-recovery.js"; +export * from "./contracts/local-runner.js"; +export * from "./contracts/native-execution.js"; export * from "./contracts/question-set.js"; +export * from "./contracts/runtime-context.js"; +export * from "./contracts/types.js"; export { DurablePrpControlPlane, type DurablePrpControlPlaneOptions, @@ -8,6 +14,7 @@ export { export type { DurableRecoveryIdentity } from "./control-plane/prp-transport-types.js"; export * from "./protocol/replay-contract.js"; export * from "./protocol/result-normalization.js"; +export * from "./provider-events.js"; export * from "./reducer/session-reducer.js"; export * from "./semantic-tools/index.js"; export * from "./tracer/replay.js"; diff --git a/packages/paperclip-runner/src/protocol/generated/schema-bundle.ts b/packages/paperclip-runner/src/protocol/generated/schema-bundle.ts index 37368bec6e..d6b096a2db 100644 --- a/packages/paperclip-runner/src/protocol/generated/schema-bundle.ts +++ b/packages/paperclip-runner/src/protocol/generated/schema-bundle.ts @@ -344,10 +344,22 @@ export const providerDescriptorSchema = { ], "properties": { "provider": { - "const": "codex" + "enum": [ + "codex", + "opencode", + "claude_managed", + "aws_agentcore", + "acpx" + ] }, "driver": { - "const": "codex_app_server" + "enum": [ + "codex_app_server", + "opencode_server", + "claude_managed_agents_api", + "aws_agentcore_harness_api", + "acpx_runtime" + ] }, "model": { "type": [ @@ -357,13 +369,22 @@ export const providerDescriptorSchema = { "maxLength": 240 }, "executionKind": { - "const": "local_process" + "enum": [ + "local_process", + "remote_service" + ] }, "providerVersion": { "type": "string", "minLength": 1, "maxLength": 120 }, + "service": { + "enum": [ + "anthropic_managed_agents", + "aws_bedrock_agentcore_harness" + ] + }, "providerSessionId": { "type": [ "string", @@ -377,9 +398,255 @@ export const providerDescriptorSchema = { "null" ], "minimum": 1 + }, + "agentProcessId": { + "type": [ + "integer", + "null" + ], + "minimum": 1 + }, + "endpointArn": { + "type": "string", + "minLength": 1, + "maxLength": 2048 + }, + "endpointQualifier": { + "type": "string", + "minLength": 1, + "maxLength": 240 + }, + "memoryId": { + "type": "string", + "minLength": 1, + "maxLength": 240 + }, + "eventExpiryDays": { + "const": 90 + }, + "agent": { + "enum": [ + "pi", + "claude", + "codex" + ] + }, + "requestedModel": { + "type": "string", + "minLength": 1, + "maxLength": 240 + }, + "acpProtocolVersion": { + "const": 1 + }, + "agentServerPackage": { + "type": "string", + "minLength": 1, + "maxLength": 240 + }, + "agentServerVersion": { + "type": "string", + "minLength": 1, + "maxLength": 120 + }, + "agentRuntimePackage": { + "type": [ + "string", + "null" + ], + "maxLength": 240 + }, + "agentRuntimeVersion": { + "type": [ + "string", + "null" + ], + "maxLength": 120 + }, + "acpxRecordId": { + "type": [ + "string", + "null" + ], + "maxLength": 240 } }, - "additionalProperties": true + "allOf": [ + { + "oneOf": [ + { + "properties": { + "provider": { + "const": "codex" + }, + "driver": { + "const": "codex_app_server" + }, + "executionKind": { + "const": "local_process" + } + } + }, + { + "properties": { + "provider": { + "const": "opencode" + }, + "driver": { + "const": "opencode_server" + }, + "executionKind": { + "const": "local_process" + } + } + }, + { + "properties": { + "provider": { + "const": "claude_managed" + }, + "driver": { + "const": "claude_managed_agents_api" + }, + "executionKind": { + "const": "remote_service" + } + } + }, + { + "properties": { + "provider": { + "const": "aws_agentcore" + }, + "driver": { + "const": "aws_agentcore_harness_api" + }, + "executionKind": { + "const": "remote_service" + } + } + }, + { + "properties": { + "provider": { + "const": "acpx" + }, + "driver": { + "const": "acpx_runtime" + }, + "executionKind": { + "const": "local_process" + } + } + } + ] + }, + { + "if": { + "properties": { + "executionKind": { + "const": "remote_service" + } + } + }, + "then": { + "required": [ + "service" + ], + "properties": { + "processId": { + "const": null + } + } + } + }, + { + "if": { + "properties": { + "executionKind": { + "const": "local_process" + } + } + }, + "then": { + "properties": { + "service": false + } + } + }, + { + "if": { + "properties": { + "provider": { + "const": "claude_managed" + } + }, + "required": [ + "provider" + ] + }, + "then": { + "properties": { + "service": { + "const": "anthropic_managed_agents" + } + }, + "required": [ + "service" + ] + } + }, + { + "if": { + "properties": { + "provider": { + "const": "aws_agentcore" + } + }, + "required": [ + "provider" + ] + }, + "then": { + "properties": { + "service": { + "const": "aws_bedrock_agentcore_harness" + } + }, + "required": [ + "service", + "endpointArn", + "endpointQualifier", + "memoryId", + "eventExpiryDays" + ] + } + }, + { + "if": { + "properties": { + "provider": { + "const": "acpx" + } + }, + "required": [ + "provider" + ] + }, + "then": { + "required": [ + "agent", + "requestedModel", + "acpProtocolVersion", + "agentServerPackage", + "agentServerVersion", + "acpxRecordId", + "agentProcessId" + ] + } + } + ], + "additionalProperties": false } as const; export const providerEventSchema = { @@ -472,6 +739,7 @@ export const providerEventSchema = { }, "plan": { "type": "object", + "description": "A complete provider-authored within-turn checklist snapshot. Consumers replace the prior snapshot with the same planId in PRP sourceSeq order; this is not Paperclip's durable Plan document.", "required": [ "schema", "planId", @@ -527,6 +795,7 @@ export const providerEventSchema = { "type": "boolean" }, "syncStatus": { + "description": "Legacy compatibility field. Within-turn checklist snapshots use not_applicable.", "enum": [ "streaming", "pending", @@ -536,6 +805,7 @@ export const providerEventSchema = { ] }, "documentRevision": { + "description": "Legacy compatibility field. Within-turn checklist snapshots use null.", "type": [ "integer", "null" @@ -1893,6 +2163,9 @@ export const usageSchema = { "cumulative": { "$ref": "#/$defs/measurement" }, + "runDeltaAvailable": { + "type": "boolean" + }, "runDelta": { "$ref": "#/$defs/measurement" } @@ -2772,6 +3045,24 @@ export const resultSchema = { }, "owner": { "type": "object", + "required": [ + "kind", + "name" + ], + "properties": { + "kind": { + "enum": [ + "agent", + "user", + "system", + "external" + ] + }, + "name": { + "type": "string", + "minLength": 1 + } + }, "additionalProperties": true }, "unblockAction": { @@ -2971,6 +3262,7 @@ export const eventSchema = { "runner.reconciled", "runner.disconnected", "runner.draining", + "runner.backpressure", "runner.suspending", "runner.suspended", "runner.stopped", @@ -3032,6 +3324,7 @@ export const eventSchema = { "usage.reported", "semantic_tool.input", "semantic_tool.result", + "semantic_tool.reconciled", "mcp_app.discovered", "mcp_app.resource.resolved", "mcp_app.initializing", @@ -3530,6 +3823,40 @@ export const eventSchema = { } } }, + { + "if": { + "properties": { + "eventType": { + "const": "semantic_tool.reconciled" + } + } + }, + "then": { + "properties": { + "payload": { + "type": "object", + "properties": { + "semantic_tool": { + "allOf": [ + { + "$ref": "https://paperclip.dev/schemas/prp/v1/semantic-tool.schema.json" + }, + { + "type": "object", + "properties": { + "phase": { + "const": "reconciled" + } + } + } + ] + } + }, + "additionalProperties": true + } + } + } + }, { "if": { "properties": { diff --git a/packages/paperclip-runner/src/protocol/result-normalization.test.ts b/packages/paperclip-runner/src/protocol/result-normalization.test.ts index cf68d2977d..2473b821fe 100644 --- a/packages/paperclip-runner/src/protocol/result-normalization.test.ts +++ b/packages/paperclip-runner/src/protocol/result-normalization.test.ts @@ -69,6 +69,44 @@ describe("normalizePrpResultSignals", () => { }); }); + it("requires an identified owner for blocked results", () => { + const blockedResult = { + reportedWorkDisposition: "blocked", + summary: "External input is required.", + completionClaim: { + contractRevision: "1", + objectiveSatisfied: false, + criteria: [ + { criterionId: "objective", status: "not_satisfied", evidenceRefs: [] }, + ], + remainingWork: [ + { description: "Wait for external input.", blocksCompletion: true }, + ], + }, + evidence: [], + verification: [], + blocker: { + reasonCode: "external_input_required", + owner: {}, + unblockAction: "Provide the required input.", + scope: "current_track", + }, + }; + + expect(validatePrpStructuredRunResult(blockedResult)).toMatchObject({ + ok: false, + }); + expect( + validatePrpStructuredRunResult({ + ...blockedResult, + blocker: { + ...blockedResult.blocker, + owner: { kind: "external", name: "External input" }, + }, + }), + ).toMatchObject({ ok: true }); + }); + it("normalizes unambiguous completion aliases emitted by smaller tool callers", () => { const toolShaped = { schema: "paperclip_paperclip_finish", diff --git a/packages/paperclip-runner/src/provider-events.test.ts b/packages/paperclip-runner/src/provider-events.test.ts new file mode 100644 index 0000000000..887ad58d32 --- /dev/null +++ b/packages/paperclip-runner/src/provider-events.test.ts @@ -0,0 +1,409 @@ +import { describe, expect, it } from "vitest"; + +import { + CODEX_THREAD_ITEM_CLASSIFICATION, + PROVIDER_EVENT_FAMILIES, + canonicalProviderEventsFromAcpxRuntimeEvent, + canonicalProviderEventsFromCodex, + canonicalProviderEventsFromOpenCodePart, + createAcpxToolEventNormalizer, + providerFamilyCapabilities, +} from "./provider-events.js"; +import { validatePrpEvent } from "./protocol/replay-contract.js"; + +function envelope(event: ReturnType[number]) { + return { + schema: "paperclip.prp.event.v1", sourceEventId: `source:${event.itemId}`, sourceSeq: 1, + sourceInstanceId: "runner-1", sourceKind: "runner", runId: "run-1", + normalizedSessionId: "session-1", turnId: "turn-1", itemId: event.itemId, + eventType: event.eventType, schemaVersion: 1, priority: 1, + emittedAt: "2026-08-21T12:00:00.000Z", payload: event.payload, + }; +} + +describe("provider-neutral events", () => { + it("classifies the complete qualified 18-variant Codex ThreadItem inventory", () => { + expect(Object.keys(CODEX_THREAD_ITEM_CLASSIFICATION)).toEqual([ + "userMessage", "hookPrompt", "agentMessage", "plan", "reasoning", + "commandExecution", "fileChange", "mcpToolCall", "dynamicToolCall", + "collabAgentToolCall", "subAgentActivity", "webSearch", "imageView", + "sleep", "imageGeneration", "enteredReviewMode", "exitedReviewMode", + "contextCompaction", + ]); + expect(Object.values(CODEX_THREAD_ITEM_CLASSIFICATION)).not.toContain("unclassified"); + expect(CODEX_THREAD_ITEM_CLASSIFICATION.plan).toBe("existing_transcript"); + }); + + it("negotiates every declared family and preserves explicit unsupported states", () => { + const capabilities = providerFamilyCapabilities({ plan: "available", artifact: "policy_disabled" }); + expect(capabilities).toHaveLength(PROVIDER_EVENT_FAMILIES.length); + expect(capabilities.find((entry) => entry.family === "plan")?.detailLevel).toBe("structured"); + expect(capabilities.find((entry) => entry.family === "artifact")?.availability).toBe("policy_disabled"); + expect(capabilities.find((entry) => entry.family === "memory")?.availability).toBe("unsupported"); + }); + + it("maps representative Codex variants across every canonical family to valid PRP", () => { + const cases: Array<[string, Record]> = [ + ["turn/plan/updated", { turnId: "turn-1", plan: [{ step: "Ship it", status: "inProgress" }] }], + ["item/completed", { item: { id: "exec-1", type: "commandExecution", status: "completed", output: "ok" } }], + ["item/completed", { item: { id: "web-1", type: "webSearch", action: { type: "search", query: "PRP" }, results: [{ ref_id: "source-1", title: "Protocol notes", url: "https://example.com/prp", snippet: "Canonical event details" }] } }], + ["item/completed", { item: { id: "child-1", type: "collabAgentToolCall", tool: "spawnAgent" } }], + ["model/rerouted", { turnId: "turn-1", fromModel: "gpt-5", toModel: "gpt-5.1", reason: "capacity" }], + ["thread/compacted", { itemId: "compact-1" }], + ["item/completed", { item: { id: "image-1", type: "imageView", path: "artifacts/a.png" } }], + ["item/completed", { item: { id: "review-1", type: "enteredReviewMode" } }], + ["hook/completed", { run: { id: "hook-1", eventName: "post-tool", scope: "workspace", status: "completed" } }], + ["item/completed", { item: { id: "message-1", type: "agentMessage", memoryCitation: { entries: [{ label: "Decision" }] } } }], + ["item/autoApprovalReview/completed", { reviewId: "safety-1", targetItemId: "exec-1" }], + ["item/commandExecution/terminalInteraction", { itemId: "exec-1", stdin: "secret input" }], + ["item/completed", { item: { id: "wait-1", type: "sleep", durationMs: 1000 } }], + ["warning", { message: "Update the provider configuration" }], + ]; + const mapped = cases.flatMap(([method, params]) => canonicalProviderEventsFromCodex(method, params)); + expect(mapped).toHaveLength(cases.length); + for (const event of mapped) expect(validatePrpEvent(envelope(event))).toEqual({ ok: true, event: expect.any(Object), issues: [] }); + expect(JSON.stringify(mapped.find((entry) => entry.eventType === "terminal.input.sent"))).not.toContain("secret input"); + expect(mapped.find((entry) => entry.eventType === "research.completed")?.payload.sources).toEqual([{ + sourceId: "source-1", + title: "Protocol notes", + url: "https://example.com/prp", + snippet: "Canonical event details", + }]); + }); + + it("bounds and filters Codex research sources before they enter PRP", () => { + const event = canonicalProviderEventsFromCodex("item/completed", { + item: { + id: "web-1", + type: "webSearch", + results: [ + { ref_id: "good", title: "Good", url: "https://example.com/good", snippet: "x".repeat(5000) }, + { ref_id: "unsafe", title: "Unsafe", url: "file:///etc/passwd" }, + ], + }, + })[0]!; + expect(event.payload.sources).toEqual([expect.objectContaining({ sourceId: "good", url: "https://example.com/good", snippet: "x".repeat(4000) })]); + expect(validatePrpEvent(envelope(event))).toEqual({ ok: true, event: expect.any(Object), issues: [] }); + }); + + it("bounds Codex plan explanations before they enter PRP", () => { + const event = canonicalProviderEventsFromCodex("turn/plan/updated", { + turnId: "turn-1", + explanation: "x".repeat(5000), + plan: [{ step: "Ship it", status: "inProgress" }], + })[0]!; + expect(event.payload.explanation).toBe("x".repeat(4000)); + expect(validatePrpEvent(envelope(event))).toEqual({ ok: true, event: expect.any(Object), issues: [] }); + }); + + it("normalizes malformed or non-positive Codex plan revisions", () => { + for (const revision of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + const event = canonicalProviderEventsFromCodex("turn/plan/updated", { + turnId: "turn-revision", + revision, + plan: [{ step: "Ship it", status: "inProgress" }], + })[0]!; + expect(event.payload.revision).toBe(1); + expect(validatePrpEvent(envelope(event))).toEqual({ + ok: true, + event: expect.any(Object), + issues: [], + }); + } + expect(canonicalProviderEventsFromCodex("turn/plan/updated", { + turnId: "turn-revision", + revision: 7, + plan: [], + })[0]?.payload.revision).toBe(7); + }); + + it("marks a turn plan complete when every native step is complete", () => { + const event = canonicalProviderEventsFromCodex("turn/plan/updated", { + turnId: "turn-1", + plan: [ + { step: "Inspect", status: "completed" }, + { step: "Implement", status: "completed" }, + ], + })[0]!; + expect(event).toMatchObject({ + itemId: "turn-1", + eventType: "plan.updated", + payload: { + planId: "turn-1", + complete: true, + syncStatus: "not_applicable", + documentRevision: null, + }, + }); + }); + + it("treats Codex proposed-plan text as transcript content, not a checklist", () => { + expect(canonicalProviderEventsFromCodex("item/completed", { + item: { id: "proposed-plan-1", type: "plan", text: "# Proposed implementation\n\nShip it." }, + })).toEqual([]); + }); + + it("uses an empty native plan as a stable clearing snapshot", () => { + const event = canonicalProviderEventsFromCodex("turn/plan/updated", { + turnId: "turn-1", + plan: [], + })[0]!; + expect(event).toMatchObject({ + itemId: "turn-1", + payload: { planId: "turn-1", steps: [], complete: false }, + }); + }); + + it("normalizes provider plan statuses without accepting malformed steps", () => { + const event = canonicalProviderEventsFromCodex("turn/plan/updated", { + turnId: "turn-statuses", + plan: [ + { step: "Active", status: "inProgress" }, + { step: "Blocked", status: "failed" }, + { step: "Later", status: "unexpected" }, + { step: " ", status: "completed" }, + ], + })[0]!; + expect(event.payload.steps).toEqual([ + { stepId: "step-1", body: "Active", status: "in_progress" }, + { stepId: "step-2", body: "Blocked", status: "blocked" }, + { stepId: "step-3", body: "Later", status: "pending" }, + ]); + expect(event.payload.complete).toBe(false); + }); + + it("preserves every structured ACPX plan entry in a stable turn snapshot", () => { + const event = canonicalProviderEventsFromAcpxRuntimeEvent({ + type: "plan", + tag: "plan", + entries: [ + { content: "Inspect", status: "completed", priority: "high" }, + { content: "Implement", status: "in_progress", priority: "medium" }, + { content: "Verify", status: "pending", priority: "low" }, + ], + } as never, "fallback", "turn-acp")[0]!; + + expect(event).toMatchObject({ + itemId: "turn-acp", + eventType: "plan.updated", + payload: { + planId: "turn-acp", + complete: false, + syncStatus: "not_applicable", + steps: [ + { body: "Inspect", status: "completed" }, + { body: "Implement", status: "in_progress" }, + { body: "Verify", status: "pending" }, + ], + }, + }); + expect(validatePrpEvent(envelope(event))).toEqual({ ok: true, event: expect.any(Object), issues: [] }); + }); + + it("does not infer an ACPX checklist from legacy status text", () => { + const events = canonicalProviderEventsFromAcpxRuntimeEvent({ + type: "status", + tag: "plan", + text: "Implement (in progress)", + } as never, "fallback", "turn-acp"); + expect(events.some((event) => event.eventType === "plan.updated")).toBe(false); + }); + + it("bounds and sanitizes structured ACPX plan snapshots", () => { + const entries = Array.from({ length: 300 }, (_, index) => ({ + content: index === 3 ? " " : `Step ${index} ${"x".repeat(5_000)}`, + status: index === 0 ? "completed" : "pending", + })); + const event = canonicalProviderEventsFromAcpxRuntimeEvent({ + type: "plan", + tag: "plan", + entries, + } as never, "fallback", "turn-bounded")[0]!; + const steps = event.payload.steps as Array<{ body: string }>; + expect(steps).toHaveLength(255); + expect(steps.every((step) => step.body.length <= 4_000)).toBe(true); + expect(validatePrpEvent(envelope(event))).toEqual({ ok: true, event: expect.any(Object), issues: [] }); + }); + + it("classifies only structured OpenCode parts and never assistant prose", () => { + expect(canonicalProviderEventsFromOpenCodePart({ id: "tool-1", type: "tool", tool: "read", state: { status: "completed", output: "done" } })[0]?.eventType).toBe("tool.execution.completed"); + expect(canonicalProviderEventsFromOpenCodePart({ id: "text-1", type: "text", text: "I ran a command and delegated work" })).toEqual([]); + }); + + it("maps OpenCode pending dynamic tools to a valid builtin execution start", () => { + const event = canonicalProviderEventsFromOpenCodePart({ + id: "prt_02c35c313001X42cqyvQrpXOFv", + type: "tool", + tool: "paperclip_report_progress", + callID: "call_6cd0302e681d44c2aba3c164", + state: { status: "pending", input: {}, raw: "" }, + })[0]!; + expect(event).toMatchObject({ + eventType: "tool.execution.started", + payload: { + schema: "paperclip.tool.execution.v1", + transport: "builtin", + status: "running", + name: "paperclip_report_progress", + }, + }); + expect(validatePrpEvent(envelope(event))).toEqual({ ok: true, event: expect.any(Object), issues: [] }); + }); + + it("preserves ACPX identity across title-less progress and completion updates", () => { + const normalize = createAcpxToolEventNormalizer(); + const started = normalize({ + type: "tool_call", + tag: "tool_call", + toolCallId: "tool-1", + title: "mcp__paperclip__search_tasks", + kind: "other", + status: "pending", + text: "mcp__paperclip__search_tasks (pending)", + locations: [{ path: "doc/plan.md", line: 4 }], + } as never); + const progressed = normalize({ + type: "tool_call", + tag: "tool_call_update", + toolCallId: "tool-1", + title: "tool call", + status: "in_progress", + text: "Searching the task index", + } as never); + const completed = normalize({ + type: "tool_call", + tag: "tool_call_update", + toolCallId: "tool-1", + title: "tool call", + status: "completed", + text: "tool call (completed)", + rawOutput: { ok: true }, + } as never); + + expect(progressed).toMatchObject({ + title: "mcp__paperclip__search_tasks", + kind: "other", + text: "Searching the task index", + locations: [{ path: "doc/plan.md", line: 4 }], + }); + expect(completed).toMatchObject({ + title: "mcp__paperclip__search_tasks", + kind: "other", + locations: [{ path: "doc/plan.md", line: 4 }], + }); + + const mapped = [started, progressed, completed].flatMap((event, index) => + canonicalProviderEventsFromAcpxRuntimeEvent(event, `fallback-${index}`)); + expect(mapped.at(-1)).toMatchObject({ + eventType: "tool.execution.completed", + payload: { + transport: "mcp", + namespace: "paperclip", + name: "search_tasks", + operation: "search", + target: "doc/plan.md", + status: "completed", + }, + }); + for (const event of mapped) { + expect(validatePrpEvent(envelope(event))).toEqual({ ok: true, event: expect.any(Object), issues: [] }); + } + }); + + it("treats provider status metacharacters as literal progress text", () => { + const normalize = createAcpxToolEventNormalizer(); + expect(() => normalize({ + type: "tool_call", + tag: "tool_call", + toolCallId: "tool-hostile-status", + title: "Read", + kind: "read", + status: "[", + text: "Read ([)", + } as never)).not.toThrow(); + expect(normalize({ + type: "tool_call", + tag: "tool_call_update", + toolCallId: "tool-hostile-status", + title: "Read", + status: "(", + text: "Meaningful progress", + } as never)).toMatchObject({ text: "Meaningful progress" }); + }); + + it("normalizes dotted MCP names, ToolSearch, and truly unnamed calls", () => { + const dotted = canonicalProviderEventsFromAcpxRuntimeEvent({ + type: "tool_call", tag: "tool_call", toolCallId: "mcp-1", title: "mcp.paperclip.get_task_context", + kind: "other", status: "pending", text: "Starting", + } as never, "fallback")[0]!; + const toolSearch = canonicalProviderEventsFromAcpxRuntimeEvent({ + type: "tool_call", tag: "tool_call", toolCallId: "search-1", title: "ToolSearch", + kind: "other", status: "pending", text: "Starting", + } as never, "fallback")[0]!; + const unnamed = canonicalProviderEventsFromAcpxRuntimeEvent({ + type: "tool_call", tag: "tool_call", toolCallId: "unknown-1", title: "tool call", + kind: "other", status: "pending", text: "tool call (pending)", + } as never, "fallback")[0]!; + + expect(dotted.payload).toMatchObject({ transport: "mcp", namespace: "paperclip", name: "get_task_context", operation: "read" }); + expect(toolSearch.payload).toMatchObject({ transport: "builtin", namespace: null, name: "ToolSearch", operation: "search" }); + expect(unnamed.payload).toMatchObject({ name: null, operation: "unknown" }); + }); + + it("presents OpenCode's server-qualified semantic tool with its canonical name", () => { + const event = canonicalProviderEventsFromOpenCodePart({ + id: "finish-1", + type: "tool", + tool: "paperclip_paperclip_finish", + state: { status: "running", input: {} }, + })[0]!; + expect(event.payload).toMatchObject({ name: "paperclip_finish", transport: "builtin" }); + expect(validatePrpEvent(envelope(event))).toEqual({ ok: true, event: expect.any(Object), issues: [] }); + }); + + it("recovers an interrupted OpenCode function label and error from its structured call id", () => { + const event = canonicalProviderEventsFromOpenCodePart({ + id: "prt_interrupted", + type: "tool", + tool: "unknown", + callID: "functions.todowrite:0", + state: { + status: "error", + input: {}, + error: "Tool execution aborted", + metadata: { interrupted: true }, + }, + })[0]!; + expect(event).toMatchObject({ + eventType: "tool.execution.completed", + payload: { + name: "todowrite", + status: "failed", + output: "Tool execution aborted", + outputBytes: 22, + }, + }); + expect(validatePrpEvent(envelope(event))).toEqual({ ok: true, event: expect.any(Object), issues: [] }); + }); + + it("does not infer a tool label from an opaque provider call id", () => { + const event = canonicalProviderEventsFromOpenCodePart({ + id: "prt_unknown", + type: "tool", + tool: "unknown", + callID: "call_f3d79e", + state: { status: "error", error: "Unavailable" }, + })[0]!; + expect(event.payload).toMatchObject({ name: "unknown", output: "Unavailable" }); + }); + + it("rejects a canonical event whose payload belongs to another family", () => { + const plan = canonicalProviderEventsFromCodex("item/completed", { + item: { id: "plan-1", type: "plan", text: "Ship it" }, + })[0]!; + expect(validatePrpEvent(envelope({ + ...plan, + eventType: "tool.execution.completed", + }))).toMatchObject({ ok: false }); + }); +}); diff --git a/packages/paperclip-runner/src/provider-events.ts b/packages/paperclip-runner/src/provider-events.ts new file mode 100644 index 0000000000..65bedc04ca --- /dev/null +++ b/packages/paperclip-runner/src/provider-events.ts @@ -0,0 +1,592 @@ +import { createHash } from "node:crypto"; + +/** + * Structural subset of an ACP runtime event consumed by the canonical event + * mapper. Keeping the protocol layer vendor-neutral avoids making ACPX a + * runtime dependency merely to describe events; the ACPX provider can pass + * its richer event objects directly because they satisfy this shape. + */ +export interface AcpRuntimeEventShape { + type: string; + toolCallId?: string; + title?: string; + kind?: string; + locations?: unknown[]; + text?: string; + status?: string; + rawOutput?: unknown; + tag?: string; + entries?: Array<{ content: string; status?: string }>; + [key: string]: unknown; +} + +export const PROVIDER_EVENT_FAMILIES = [ + "plan", "tool_execution", "research", "delegation", "model_identity", + "context", "artifact", "review", "hook", "memory", "safety", "terminal", + "wait", "provider_notice", +] as const; + +export type ProviderEventFamily = (typeof PROVIDER_EVENT_FAMILIES)[number]; +export type ProviderEventAvailability = "available" | "unsupported" | "policy_disabled"; + +/** + * Exhaustive inventory from the qualified Codex app-server ThreadItem schema. + * Keeping this closed makes a provider upgrade fail visibly in the inventory + * test instead of silently dropping a new native item shape. + */ +export const CODEX_THREAD_ITEM_CLASSIFICATION = { + userMessage: "existing_transcript", + hookPrompt: "hook", + agentMessage: "existing_transcript", + // Codex's `plan` ThreadItem is proposed-plan document text. The live + // execution checklist is a separate `turn/plan/updated` notification. + plan: "existing_transcript", + reasoning: "existing_reasoning", + commandExecution: "tool_execution", + fileChange: "existing_workspace_change", + mcpToolCall: "tool_execution", + dynamicToolCall: "tool_execution", + collabAgentToolCall: "delegation", + subAgentActivity: "delegation", + webSearch: "research", + imageView: "artifact", + sleep: "wait", + imageGeneration: "artifact", + enteredReviewMode: "review", + exitedReviewMode: "review", + contextCompaction: "context", +} as const satisfies Record; + +export interface TypedEventFamilyCapability { + family: ProviderEventFamily; + version: 1; + availability: ProviderEventAvailability; + detailLevel: "summary" | "structured"; +} + +export type CanonicalProviderEventType = + | "plan.updated" + | "tool.execution.started" | "tool.execution.progressed" | "tool.execution.completed" + | "research.started" | "research.progressed" | "research.completed" + | "delegation.started" | "delegation.updated" | "delegation.completed" + | "model.route.changed" | "model.verification.updated" | "context.compacted" + | "artifact.viewed" | "artifact.generated" | "review.mode.changed" + | "hook.started" | "hook.completed" | "memory.citation.referenced" + | "safety.review.started" | "safety.review.completed" | "terminal.input.sent" + | "wait.started" | "wait.completed" | "provider.notice.recorded"; + +export interface CanonicalProviderEvent { + eventType: CanonicalProviderEventType; + payload: Record; + itemId: string; +} + +const MAX_OUTPUT = 64 * 1024; + +function record(value: unknown): Record { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? value as Record + : {}; +} + +function text(value: unknown, fallback = ""): string { + return typeof value === "string" ? value : fallback; +} + +function integer(value: unknown): number | null { + return Number.isSafeInteger(value) ? Number(value) : null; +} + +function safeId(value: string, fallback: string): string { + const candidate = value.replace(/[^A-Za-z0-9._:-]/g, "-").slice(0, 160); + return /^[A-Za-z0-9]/.test(candidate) ? candidate : fallback; +} + +const GENERIC_ACP_TOOL_NAMES = new Set(["tool", "tool call", "tool_call", "acp_tool"]); + +function normalizedToolWords(value: string): string[] { + return value + .replace(/^mcp__(.+?)__/, "") + .replace(/^mcp\.[^.]+\./, "") + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/[^A-Za-z0-9]+/g, " ") + .trim() + .toLowerCase() + .split(/\s+/) + .filter(Boolean); +} + +function isGenericAcpToolName(value: unknown): boolean { + const name = text(value) + .trim() + .toLowerCase() + .replace(/\s*\((?:pending|in[_ -]?progress|completed|failed|cancelled|canceled)\)$/, ""); + return !name || GENERIC_ACP_TOOL_NAMES.has(name); +} + +function meaningfulAcpToolProgress(value: string, title: string | undefined, status: string | undefined): boolean { + const progress = value.trim(); + if (!progress || /^tool(?:\s+|_)call\b/i.test(progress)) return false; + const statusPattern = (status ?? "") + .replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + .replaceAll("_", "[ _-]?"); + if (!title || !statusPattern) return true; + const escapedTitle = title.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return !new RegExp(`^${escapedTitle}\\s*\\(${statusPattern}\\)\\s*$`, "i").test(progress); +} + +interface AcpxToolLifecycleIdentity { + title?: string; + kind?: string; + locations?: unknown[]; + progress?: string; +} + +/** + * ACP tool updates are deltas: a later update may omit the title, kind, and + * locations that were present on the opening event. ACPX represents a missing + * title as the literal `tool call`, so consumers must restore lifecycle + * identity before translating the event into a durable protocol record. + */ +export function createAcpxToolEventNormalizer(): (event: T) => T { + const lifecycle = new Map(); + return (event) => { + if (event.type !== "tool_call" || !event.toolCallId) return event; + const previous = lifecycle.get(event.toolCallId) ?? {}; + const incomingTitle = isGenericAcpToolName(event.title) ? undefined : event.title?.trim(); + const title = previous.title ?? incomingTitle; + const kind = previous.kind && previous.kind !== "other" + ? previous.kind + : event.kind ?? previous.kind; + const locations = event.locations?.length ? event.locations : previous.locations; + const eventText = text(event.text); + const progress = meaningfulAcpToolProgress(eventText, incomingTitle, event.status) + ? eventText + : previous.progress; + lifecycle.set(event.toolCallId, { title, kind, locations, progress }); + return { + ...event, + title, + kind, + locations, + ...(progress && canonicalStatus(event.status, "running") === "running" ? { text: progress } : {}), + } as T; + }; +} + +function acpxMcpToolIdentity(value: string): { namespace: string; name: string } | null { + const doubleUnderscore = value.match(/^mcp__(.+?)__(.+)$/i); + if (doubleUnderscore) return { namespace: doubleUnderscore[1], name: doubleUnderscore[2] }; + const dotted = value.match(/^mcp\.([^.]+)\.(.+)$/i); + return dotted ? { namespace: dotted[1], name: dotted[2] } : null; +} + +function acpxToolOperation( + kindValue: unknown, + name: string, +): "read" | "search" | "list" | "execute" | "edit" | "unknown" { + const kind = text(kindValue).toLowerCase(); + if (kind === "read") return "read"; + if (kind === "search" || kind === "fetch") return "search"; + if (["edit", "delete", "move"].includes(kind)) return "edit"; + if (kind === "execute") return "execute"; + + const words = normalizedToolWords(name); + const first = words[0] ?? ""; + const compact = words.join(""); + if (["get", "read", "inspect", "view"].includes(first)) return "read"; + if (["list", "glob"].includes(first)) return "list"; + if (["toolsearch", "websearch"].includes(compact) || ["find", "search", "grep", "query", "lookup", "fetch", "open", "browse"].includes(first)) return "search"; + if (["write", "edit", "update", "set", "patch", "upsert", "sync", "create", "add", "register", "upload", "delete", "remove", "move", "rename", "report", "answer", "request", "decide", "comment", "finish", "complete", "block"].includes(first)) return "edit"; + if (["run", "execute", "bash", "shell", "command", "start", "spawn", "delegate", "send", "message", "stop", "cancel", "interrupt", "wait", "sleep", "poll"].includes(first)) return "execute"; + return "unknown"; +} + +function digest(value: string): string { + return `sha256:${createHash("sha256").update(value).digest("hex")}`; +} + +function boundedOutput(value: string): Pick, "output" | "outputBytes" | "outputTruncated" | "outputDigest"> { + const bytes = Buffer.byteLength(value); + const output = Buffer.from(value).subarray(Math.max(0, bytes - MAX_OUTPUT)).toString("utf8"); + return { output, outputBytes: bytes, outputTruncated: bytes > MAX_OUTPUT, outputDigest: digest(value) }; +} + +function canonicalStatus(value: unknown, fallback: "running" | "completed" | "failed" | "cancelled" | "interrupted"): "running" | "completed" | "failed" | "cancelled" | "interrupted" { + const status = text(value).toLowerCase().replaceAll("_", "-"); + if (status === "completed" || status === "success") return "completed"; + if (status === "failed" || status === "error") return "failed"; + if (status === "cancelled" || status === "canceled") return "cancelled"; + if (status === "interrupted" || status === "aborted") return "interrupted"; + if (status === "running" || status === "pending" || status === "in-progress") return "running"; + return fallback; +} + +function planStepStatus(value: unknown): "pending" | "in_progress" | "completed" | "blocked" { + const status = text(value) + .replace(/([a-z])([A-Z])/g, "$1_$2") + .toLowerCase() + .replaceAll("-", "_"); + if (status === "in_progress" || status === "completed" || status === "blocked") return status; + if (status === "failed" || status === "error") return "blocked"; + return "pending"; +} + +function operationFromActions(item: Record): "read" | "search" | "list" | "execute" | "edit" | "unknown" { + const action = record(Array.isArray(item.commandActions) ? item.commandActions[0] : undefined); + const kind = text(action.type).toLowerCase(); + if (kind === "read") return "read"; + if (kind === "search") return "search"; + if (kind === "listfiles") return "list"; + return text(item.command) ? "execute" : "unknown"; +} + +function executionPayload(item: Record, status: string): Record { + const id = safeId(text(item.id), "execution"); + const output = text(item.aggregatedOutput, text(item.output)); + const action = record(Array.isArray(item.commandActions) ? item.commandActions[0] : undefined); + const target = text(action.path) || null; + return { + schema: "paperclip.tool.execution.v1", + executionId: id, + transport: text(item.type) === "mcpToolCall" ? "mcp" : text(item.type) === "dynamicToolCall" ? "dynamic" : "process", + operation: text(item.type).includes("ToolCall") ? "unknown" : operationFromActions(item), + name: text(item.tool, text(item.command)) || null, + target: target?.startsWith("/") || target?.split("/").includes("..") ? null : target, + namespace: text(item.server, text(item.namespace)) || null, + readOnly: typeof item.readOnlyHint === "boolean" ? item.readOnlyHint : null, + status, + durationMs: integer(item.durationMs), + exitCode: integer(item.exitCode), + progress: null, + ...boundedOutput(output), + }; +} + +function turnPlanPayload(params: Record): Record { + const plan = Array.isArray(params.plan) ? params.plan : []; + const steps = plan.slice(0, 256).flatMap((entry, index) => { + const step = record(entry); + const body = text(step.step).trim().slice(0, 4000); + return body + ? [{ stepId: `step-${index + 1}`, body, status: planStepStatus(step.status) }] + : []; + }); + const planComplete = steps.length > 0 && steps.every((step) => step.status === "completed"); + const planId = safeId(text(params.turnId), "turn-plan"); + const revision = Number(params.revision); + return { + schema: "paperclip.plan.updated.v1", + planId, + revision: Number.isSafeInteger(revision) && revision > 0 ? revision : 1, + explanation: text(params.explanation).slice(0, 4000) || null, + steps, + complete: planComplete, + syncStatus: "not_applicable", + documentRevision: null, + }; +} + +function researchSources(item: Record, researchId: string): Array> { + if (!Array.isArray(item.results)) return []; + return item.results.slice(0, 64).flatMap((value, index) => { + const result = record(value); + const url = text(result.url).slice(0, 8192); + if (!url.startsWith("http://") && !url.startsWith("https://")) return []; + const fallbackId = `${researchId}:source:${index + 1}`; + return [{ + sourceId: safeId(text(result.ref_id, text(result.refId, fallbackId)), fallbackId), + title: text(result.title, url).slice(0, 4000), + url, + snippet: text(result.snippet).slice(0, 4000) || null, + }]; + }); +} + +/** Maps qualified Codex app-server notifications to bounded canonical PRP events. */ +export function canonicalProviderEventsFromCodex(method: string, paramsValue: unknown): CanonicalProviderEvent[] { + const params = record(paramsValue); + const item = record(params.item); + const type = text(item.type); + const itemId = safeId(text(item.id, text(params.itemId)), "provider-item"); + const completed = method === "item/completed"; + if (method === "turn/plan/updated") { + const turnPlanId = safeId(text(params.turnId), "turn-plan"); + return [{ eventType: "plan.updated", payload: turnPlanPayload(params), itemId: turnPlanId }]; + } + if ((method === "item/started" || completed) && ["commandExecution", "mcpToolCall", "dynamicToolCall"].includes(type)) { + return [{ eventType: completed ? "tool.execution.completed" : "tool.execution.started", payload: executionPayload(item, completed ? canonicalStatus(item.status, "completed") : "running"), itemId }]; + } + if (method === "item/commandExecution/outputDelta" || method === "item/mcpToolCall/progress") { + const delta = text(params.delta, text(params.message)); + return [{ eventType: "tool.execution.progressed", payload: { ...executionPayload({ ...item, id: itemId, output: delta }, "running"), progress: delta.slice(0, 4000) || null }, itemId }]; + } + if ((method === "item/started" || completed) && type === "webSearch") { + const action = record(item.action); + const actionType = text(action.type, "other").replace("openPage", "open_page").replace("findInPage", "find_in_page"); + const url = text(action.url) || null; + return [{ eventType: completed ? "research.completed" : "research.started", payload: { schema: "paperclip.research.v1", researchId: itemId, action: actionType, status: completed ? "completed" : "running", query: text(item.query, text(action.query)) || null, url: url?.startsWith("http://") || url?.startsWith("https://") ? url : null, pattern: text(action.pattern) || null, sources: completed ? researchSources(item, itemId) : [] }, itemId }]; + } + if ((method === "item/started" || completed) && (type === "collabAgentToolCall" || type === "subAgentActivity")) { + return [{ eventType: completed ? "delegation.completed" : "delegation.started", payload: { schema: "paperclip.delegation.v1", delegationId: itemId, action: text(item.tool, "spawnAgent").replace("spawnAgent", "spawn").replace("sendInput", "message").replace("resumeAgent", "resume").replace("closeAgent", "close"), status: completed ? "completed" : "running", children: [] }, itemId }]; + } + if (method === "model/rerouted") { + return [{ eventType: "model.route.changed", payload: { schema: "paperclip.model.route_changed.v1", routeId: safeId(text(params.turnId), "model-route"), provider: "openai", requestedModel: text(params.fromModel, "unknown"), fromModel: text(params.fromModel) || null, effectiveModel: text(params.toModel, "unknown"), reason: text(params.reason, "provider reroute").slice(0, 4000) }, itemId }]; + } + if (method === "model/verification" || method === "model/safetyBuffering/updated") { + return [{ eventType: "model.verification.updated", payload: { schema: "paperclip.model.verification.v1", verificationId: safeId(text(params.turnId), "model-verification"), status: params.showBufferingUi === true ? "running" : "completed", classes: Array.isArray(params.verifications) ? params.verifications.slice(0, 32) : [], buffering: params.showBufferingUi === true, summary: Array.isArray(params.reasons) ? params.reasons.join("; ").slice(0, 4000) : null }, itemId }]; + } + if (method === "thread/compacted" || ((method === "item/completed" || method === "item/started") && type === "contextCompaction")) { + return [{ eventType: "context.compacted", payload: { schema: "paperclip.context.compacted.v1", compactionId: itemId, reason: "provider", preTokens: null, postTokens: null, sameSession: true }, itemId }]; + } + if ((method === "item/started" || completed) && type === "imageView") { + const path = text(item.path).replaceAll("\\", "/"); + return [{ eventType: "artifact.viewed", payload: { schema: "paperclip.artifact.viewed.v1", artifactId: itemId, reference: path.startsWith("/") || path.split("/").includes("..") ? null : path, mediaType: "image/*", title: null }, itemId }]; + } + if ((method === "item/started" || completed) && type === "imageGeneration") { + const path = text(item.savedPath).replaceAll("\\", "/"); + return [{ eventType: "artifact.generated", payload: { schema: "paperclip.artifact.generated.v1", artifactId: itemId, status: completed ? text(item.status, "completed") : "running", reference: path.startsWith("/") || path.split("/").includes("..") ? null : path || null, mediaType: "image/*", registered: false, transparentBackground: typeof item.transparentBackground === "boolean" ? item.transparentBackground : null, failure: text(record(item.failure).message) || null }, itemId }]; + } + if ((method === "item/started" || completed) && (type === "enteredReviewMode" || type === "exitedReviewMode")) { + return [{ eventType: "review.mode.changed", payload: { schema: "paperclip.review.mode_changed.v1", reviewId: itemId, state: type === "enteredReviewMode" ? "entered" : "exited", scope: text(item.review) || null }, itemId }]; + } + if (method === "hook/started" || method === "hook/completed") { + const run = record(params.run); + return [{ eventType: method === "hook/started" ? "hook.started" : "hook.completed", payload: { schema: "paperclip.hook.v1", hookId: safeId(text(run.id), "hook"), event: text(run.eventName, "unknown"), scope: text(run.scope, "provider"), status: method === "hook/started" ? "running" : text(run.status, "completed"), blocking: run.executionMode === "blocking", durationMs: integer(run.durationMs), summary: text(run.statusMessage) || null }, itemId: safeId(text(run.id), "hook") }]; + } + if (completed && type === "agentMessage" && item.memoryCitation) { + const citation = record(item.memoryCitation); + const entries = Array.isArray(citation.entries) ? citation.entries : []; + return entries.slice(0, 64).map((entry, index) => ({ eventType: "memory.citation.referenced" as const, payload: { schema: "paperclip.memory.citation.v1", citationId: `${itemId}:citation:${index + 1}`, messageItemId: itemId, label: text(record(entry).label, `Memory source ${index + 1}`).slice(0, 4000), available: false, reference: null }, itemId: `${itemId}:citation:${index + 1}` })); + } + if (method === "item/autoApprovalReview/started" || method === "item/autoApprovalReview/completed") { + return [{ eventType: method.endsWith("started") ? "safety.review.started" : "safety.review.completed", payload: { schema: "paperclip.safety.review.v1", reviewId: safeId(text(params.reviewId), "safety-review"), targetExecutionId: text(params.targetItemId) || null, status: method.endsWith("started") ? "running" : "completed", decision: method.endsWith("started") ? "pending" : "unknown", summary: null }, itemId: safeId(text(params.reviewId), "safety-review") }]; + } + if (method === "item/commandExecution/terminalInteraction") { + return [{ eventType: "terminal.input.sent", payload: { schema: "paperclip.terminal.input_sent.v1", executionId: safeId(text(params.itemId), "execution"), origin: "agent", inputClass: "text", byteCount: Buffer.byteLength(text(params.stdin)) }, itemId: safeId(text(params.itemId), "execution") }]; + } + if ((method === "item/started" || completed) && type === "sleep") { + return [{ eventType: completed ? "wait.completed" : "wait.started", payload: { schema: "paperclip.wait.v1", waitId: itemId, reason: "timer", status: completed ? "completed" : "running", plannedDurationMs: integer(item.durationMs), elapsedDurationMs: completed ? integer(item.durationMs) : null }, itemId }]; + } + if (["error", "warning", "guardianWarning", "deprecationNotice", "configWarning", "windows/worldWritableWarning"].includes(method)) { + return [{ eventType: "provider.notice.recorded", payload: { schema: "paperclip.provider.notice.v1", noticeId: safeId(`${method}:${text(params.code, "notice")}`, "provider-notice"), severity: method === "error" ? "error" : "warning", category: method.replaceAll("/", "_").slice(0, 160), scope: method.includes("config") || method.includes("windows") ? "environment" : "turn", recoverable: method !== "error", userActionable: method === "error" || method === "warning", summary: text(params.message, "Provider notice").slice(0, 4000) }, itemId }]; + } + return []; +} + +/** Maps documented OpenCode structured message parts. Unrecognized parts are deliberately unsupported. */ +export function canonicalProviderEventsFromOpenCodePart(partValue: unknown): CanonicalProviderEvent[] { + const part = record(partValue); + const type = text(part.type).toLowerCase(); + const itemId = safeId(text(part.id, text(part.callID, text(part.callId))), "opencode-part"); + const state = record(part.state); + const nativeStatus = text(state.status).toLowerCase().replaceAll("_", "-"); + const status = canonicalStatus(state.status, "running"); + if (["tool", "tool-call", "tool_call", "bash", "command"].includes(type)) { + const tool = canonicalOpenCodeDisplayToolName( + text(part.tool, text(part.name, type)), + text(part.callID, text(part.callId)), + ); + // OpenCode places terminal tool failures in `state.error`, not `output`. + // Preserve the bounded provider message so a failed row is actionable. + const output = text(state.output, text(part.output, text(state.error))); + const payload = { + schema: "paperclip.tool.execution.v1", + executionId: itemId, + transport: type === "tool" || type.includes("tool") ? "builtin" : "process", + operation: /read/i.test(tool) ? "read" : /search|grep|find/i.test(tool) ? "search" : /list|glob/i.test(tool) ? "list" : /edit|write|patch/i.test(tool) ? "edit" : "execute", + name: tool || null, + target: null, + namespace: null, + readOnly: /read|search|grep|find|list|glob/i.test(tool), + status, + durationMs: integer(state.time), + exitCode: integer(state.exit), + progress: status === "running" ? text(state.title).slice(0, 4000) || null : null, + ...boundedOutput(output), + }; + const eventType = nativeStatus === "pending" + ? "tool.execution.started" + : status === "running" + ? "tool.execution.progressed" + : "tool.execution.completed"; + return [{ eventType, payload, itemId }]; + } + if (["websearch", "web_search"].includes(type)) { + return [{ eventType: status === "running" ? "research.progressed" : "research.completed", payload: { schema: "paperclip.research.v1", researchId: itemId, action: "search", status: status === "interrupted" ? "cancelled" : status, query: text(part.query) || null, url: null, pattern: null, sources: [] }, itemId }]; + } + if (["subtask", "task"].includes(type)) { + return [{ eventType: status === "running" ? "delegation.updated" : "delegation.completed", payload: { schema: "paperclip.delegation.v1", delegationId: itemId, action: "spawn", status: status === "cancelled" ? "interrupted" : status, children: [] }, itemId }]; + } + if (["compaction", "context-compaction"].includes(type)) { + return [{ eventType: "context.compacted", payload: { schema: "paperclip.context.compacted.v1", compactionId: itemId, reason: "provider", preTokens: null, postTokens: null, sameSession: true }, itemId }]; + } + return []; +} + +/** Maps ACPX's bounded public runtime events; raw ACP JSON-RPC never enters PRP. */ +export function canonicalProviderEventsFromAcpxRuntimeEvent( + event: AcpRuntimeEventShape, + fallbackItemId: string, + turnId?: string, +): CanonicalProviderEvent[] { + const runtimeType = text(record(event).type); + if (!["text_delta", "status", "tool_call", "plan", "error", "done"].includes(runtimeType)) { + return [{ + eventType: "provider.notice.recorded", + payload: { + schema: "paperclip.provider.notice.v1", + noticeId: safeId(`${fallbackItemId}:${runtimeType || "unknown"}`, "acpx-unclassified-update"), + severity: "warning", + category: `unclassified_acp_${runtimeType || "unknown"}`.slice(0, 160), + scope: "turn", + recoverable: true, + userActionable: false, + summary: "The qualified ACP agent emitted an unclassified runtime update.", + }, + itemId: fallbackItemId, + }]; + } + const itemId = safeId( + event.type === "tool_call" + ? text(event.toolCallId, fallbackItemId) + : event.type === "plan" + ? text(turnId, fallbackItemId) + : fallbackItemId, + "acpx-item", + ); + if (event.type === "plan") { + const steps = (event.entries ?? []).slice(0, 256).flatMap((entry, index) => { + const body = entry.content.trim().slice(0, 4000); + return body + ? [{ + stepId: `step-${index + 1}`, + body, + status: planStepStatus(entry.status), + }] + : []; + }); + const complete = steps.length > 0 && steps.every((step) => step.status === "completed"); + return [{ + eventType: "plan.updated", + payload: { + schema: "paperclip.plan.updated.v1", + planId: safeId(text(turnId, fallbackItemId), "turn-plan"), + revision: 1, + explanation: null, + steps, + complete, + syncStatus: "not_applicable", + documentRevision: null, + }, + itemId, + }]; + } + if (event.type === "tool_call") { + const status = canonicalStatus(event.status, "running"); + const output = typeof event.rawOutput === "string" + ? event.rawOutput + : event.rawOutput === undefined + ? "" + : JSON.stringify(event.rawOutput); + const title = isGenericAcpToolName(event.title) ? "" : text(event.title).trim(); + const mcp = acpxMcpToolIdentity(title); + const name = mcp?.name ?? title; + const operation = acpxToolOperation(event.kind, name); + const payload = { + schema: "paperclip.tool.execution.v1", + executionId: itemId, + transport: mcp ? "mcp" : "builtin", + operation, + name: name || null, + target: safeAcpLocation(event.locations?.[0]), + namespace: mcp?.namespace ?? null, + readOnly: ["read", "search", "list"].includes(operation), + status, + durationMs: null, + exitCode: null, + progress: status === "running" ? text(event.text).slice(0, 4000) || null : null, + ...boundedOutput(output), + }; + const terminal = status !== "running"; + return [{ + eventType: terminal ? "tool.execution.completed" : event.tag === "tool_call" ? "tool.execution.started" : "tool.execution.progressed", + payload, + itemId, + }]; + } + if (event.type === "status" && event.tag === "current_mode_update") { + const statusText = text(event.text); + const state = /review|plan/i.test(statusText) ? "entered" : "exited"; + return [{ + eventType: "review.mode.changed", + payload: { + schema: "paperclip.review.mode_changed.v1", + reviewId: itemId, + state, + scope: statusText.slice(0, 4000) || null, + }, + itemId, + }]; + } + if (event.type === "status" && event.tag && ![ + "usage_update", + "available_commands_update", + "config_option_update", + "session_info_update", + ].includes(event.tag)) { + return [{ + eventType: "provider.notice.recorded", + payload: { + schema: "paperclip.provider.notice.v1", + noticeId: itemId, + severity: "info", + category: `acp_${event.tag}`.slice(0, 160), + scope: "turn", + recoverable: true, + userActionable: false, + summary: text(event.text).slice(0, 4000) || "ACP provider update", + }, + itemId, + }]; + } + return []; +} + +export function canonicalOpenCodeDisplayToolName(value: string, callId = ""): string { + let name = value.trim(); + // Some OpenRouter models ask OpenCode for a function using a qualified + // `callID` while OpenCode reports the display tool as `unknown`. Recover + // only this documented, structured prefix; opaque provider call IDs remain + // opaque and continue to display as unknown. + if (!name || name === "unknown" || name === "tool") { + const qualified = /^functions[./:_-]([^:/.]+)(?::\d+)?$/i.exec(callId.trim()); + if (qualified?.[1]) name = qualified[1]; + } + // OpenCode exposes MCP tools as `_`. Paperclip's semantic + // tools already carry the paperclip prefix, producing names such as + // `paperclip_paperclip_finish` in native events. Keep the transport-native + // name in the raw trace, while presenting the stable protocol operation. + while (name.startsWith("paperclip_paperclip_")) { + name = name.slice("paperclip_".length); + } + return name; +} + +function safeAcpLocation(value: unknown): string | null { + const location = record(value); + const raw = text(location.path, text(location.uri)).replaceAll("\\", "/"); + if (!raw || raw.startsWith("/") || raw.split("/").includes("..") || /^[a-z]+:\/\//i.test(raw)) return null; + return raw.slice(0, 4000); +} + +export function providerFamilyCapabilities( + availability: Partial>, +): TypedEventFamilyCapability[] { + return PROVIDER_EVENT_FAMILIES.map((family) => ({ + family, + version: 1, + availability: availability[family] ?? "unsupported", + detailLevel: availability[family] === "available" ? "structured" : "summary", + })); +} diff --git a/packages/paperclip-runner/test/protocol-contract.test.mjs b/packages/paperclip-runner/test/protocol-contract.test.mjs index 523b79f5ac..fb63206d6a 100644 --- a/packages/paperclip-runner/test/protocol-contract.test.mjs +++ b/packages/paperclip-runner/test/protocol-contract.test.mjs @@ -85,6 +85,27 @@ test("accepted fixtures satisfy the complete JSON Schemas", async () => { assert.doesNotThrow(() => assertSchemaInstance(validators.fixture, unsupported, "required-v2", false)); }); +test("provider descriptors require coherent provider, driver, and execution combinations", async () => { + const schemas = await loadSchemaCatalog(resolve(protocolRoot, "schemas")); + const validators = compileProtocolValidators(schemas); + const codex = { + provider: "codex", + driver: "codex_app_server", + model: "gpt-5.3-codex", + executionKind: "local_process", + providerVersion: "1", + }; + assert.doesNotThrow(() => assertSchemaInstance(validators.providerDescriptor, codex, "codex-provider")); + assert.throws( + () => assertSchemaInstance( + validators.providerDescriptor, + { ...codex, driver: "opencode_server" }, + "mismatched-provider", + ), + /schema_validation_failed: mismatched-provider must be accepted/, + ); +}); + test("the Codex question fixture uses stable provider-neutral IDs", async () => { const value = await fixture("questions/codex.json"); assert.doesNotThrow(() => assertCodexQuestionFixture(value)); diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index e8d3879455..fdbb037b33 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1938,6 +1938,7 @@ export { suggestTasksResultSchema, askUserQuestionsQuestionOptionSchema, askUserQuestionsQuestionSchema, + paperclipQuestionSetPayloadSchema, askUserQuestionsPayloadSchema, askUserQuestionsAnswerSchema, askUserQuestionsResultSchema, diff --git a/packages/shared/src/issue-thread-interactions.test.ts b/packages/shared/src/issue-thread-interactions.test.ts index 37ce228ba0..fed1aa714c 100644 --- a/packages/shared/src/issue-thread-interactions.test.ts +++ b/packages/shared/src/issue-thread-interactions.test.ts @@ -9,6 +9,7 @@ import { acceptIssueThreadInteractionSchema, askUserQuestionsResultSchema, createIssueThreadInteractionSchema, + paperclipQuestionSetPayloadSchema, requestConfirmationPayloadSchema, requestConfirmationResultSchema, requestItemVerdictsResultSchema, @@ -258,6 +259,44 @@ describe("issue thread interaction schemas", () => { }); }); + it("retains canonical runner question sets without narrowing their public bounds", () => { + const questionSet = { + schema: "paperclip.question_set.v1" as const, + title: "Runner input", + questions: [{ + id: "deployment-color", + prompt: "Which deployment color should the runner use?", + required: true, + answerMode: "single_select" as const, + options: [{ id: "blue", label: "Blue" }], + }], + }; + const parsed = createIssueThreadInteractionSchema.parse({ + kind: "ask_user_questions", + continuationPolicy: "none", + resolverPolicy: "human_only", + payload: { + version: 1, + questions: [{ + id: "deployment-color", + prompt: "Which deployment color should the runner use?", + selectionMode: "single", + allowOther: false, + options: [{ id: "blue", label: "Blue" }], + }], + questionSet, + }, + }); + expect(parsed.kind).toBe("ask_user_questions"); + if (parsed.kind !== "ask_user_questions") return; + expect(parsed.payload.questionSet).toEqual(questionSet); + + expect(() => paperclipQuestionSetPayloadSchema.parse({ + ...questionSet, + questions: [{ ...questionSet.questions[0], answerMode: "text", options: questionSet.questions[0].options }], + })).toThrow("text questions cannot define options"); + }); + it("rejects unsafe request_confirmation target hrefs", () => { const base = { kind: "request_confirmation", diff --git a/packages/shared/src/types/issue.ts b/packages/shared/src/types/issue.ts index 5456b89fc6..d6a9eff602 100644 --- a/packages/shared/src/types/issue.ts +++ b/packages/shared/src/types/issue.ts @@ -1109,6 +1109,8 @@ export interface AskUserQuestionsQuestion { helpText?: string | null; selectionMode: "single" | "multi"; required?: boolean; + /** False suppresses the legacy free-form fallback for closed select sets. */ + allowOther?: boolean; options: AskUserQuestionsQuestionOption[]; } diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index e76bb8cd2d..cc72371b30 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -460,6 +460,7 @@ export { suggestTasksResultSchema, askUserQuestionsQuestionOptionSchema, askUserQuestionsQuestionSchema, + paperclipQuestionSetPayloadSchema, askUserQuestionsPayloadSchema, askUserQuestionsAnswerSchema, askUserQuestionsResultSchema, diff --git a/packages/shared/src/validators/issue.ts b/packages/shared/src/validators/issue.ts index b40175e000..4e219b597a 100644 --- a/packages/shared/src/validators/issue.ts +++ b/packages/shared/src/validators/issue.ts @@ -876,9 +876,9 @@ export const suggestTasksResultSchema = z.object({ }); export const askUserQuestionsQuestionOptionSchema = z.object({ - id: z.string().trim().min(1).max(120), - label: z.string().trim().min(1).max(120), - description: z.string().trim().max(500).nullable().optional(), + id: z.string().trim().min(1).max(160), + label: z.string().trim().min(1).max(1000), + description: z.string().trim().max(4000).nullable().optional(), freeText: z .boolean() .optional() @@ -888,12 +888,13 @@ export const askUserQuestionsQuestionOptionSchema = z.object({ }); export const askUserQuestionsQuestionSchema = z.object({ - id: z.string().trim().min(1).max(120), - prompt: z.string().trim().min(1).max(500), - helpText: z.string().trim().max(1000).nullable().optional(), + id: z.string().trim().min(1).max(160), + prompt: z.string().trim().min(1).max(4000), + helpText: z.string().trim().max(4000).nullable().optional(), selectionMode: z.enum(["single", "multi"]), required: z.boolean().optional(), - options: z.array(askUserQuestionsQuestionOptionSchema).min(1).max(10), + allowOther: z.boolean().optional(), + options: z.array(askUserQuestionsQuestionOptionSchema).min(1).max(129), }); const paperclipQuestionOptionSchema = z.object({ @@ -924,14 +925,54 @@ const paperclipQuestionSchema = z.object({ minimum: z.number().finite().optional(), maximum: z.number().finite().optional(), }).optional(), +}).superRefine((value, ctx) => { + if (value.answerMode === "text" && value.options && value.options.length > 0) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "text questions cannot define options", path: ["options"] }); + } + if (value.answerMode !== "text" && (!value.options || value.options.length === 0)) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "select questions require options", path: ["options"] }); + } + if (value.answerMode === "text" && value.customAnswer) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "text questions cannot define customAnswer", path: ["customAnswer"] }); + } + if ( + value.textValidation?.minLength !== undefined + && value.textValidation.maxLength !== undefined + && value.textValidation.minLength > value.textValidation.maxLength + ) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "minLength cannot exceed maxLength", path: ["textValidation"] }); + } + if ( + value.textValidation?.minimum !== undefined + && value.textValidation.maximum !== undefined + && value.textValidation.minimum > value.textValidation.maximum + ) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "minimum cannot exceed maximum", path: ["textValidation"] }); + } + if (value.textValidation?.pattern !== undefined) { + try { + new RegExp(value.textValidation.pattern); + } catch { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "pattern must be a valid regular expression", path: ["textValidation", "pattern"] }); + } + } + const optionIds = value.options?.map((option) => option.id) ?? []; + if (new Set(optionIds).size !== optionIds.length) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "option ids must be unique", path: ["options"] }); + } }); -const paperclipQuestionSetSchema = z.object({ +export const paperclipQuestionSetPayloadSchema = z.object({ schema: z.literal("paperclip.question_set.v1"), title: z.string().max(1000).optional(), description: z.string().max(4000).optional(), submitLabel: z.string().max(200).optional(), questions: z.array(paperclipQuestionSchema).min(1).max(64), +}).superRefine((value, ctx) => { + const questionIds = value.questions.map((question) => question.id); + if (new Set(questionIds).size !== questionIds.length) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "question ids must be unique", path: ["questions"] }); + } }); export const askUserQuestionsPayloadSchema = z.object({ @@ -939,9 +980,9 @@ export const askUserQuestionsPayloadSchema = z.object({ title: z.string().trim().max(240).nullable().optional(), submitLabel: z.string().trim().max(120).nullable().optional(), supersedeOnUserComment: z.boolean().optional(), - questions: z.array(askUserQuestionsQuestionSchema).min(1).max(10), + questions: z.array(askUserQuestionsQuestionSchema).min(1).max(64), /** Exact canonical presentation retained for a recovered harness request. */ - questionSet: paperclipQuestionSetSchema.optional(), + questionSet: paperclipQuestionSetPayloadSchema.optional(), /** Stable correlation for draft handoff from a live runtime request. */ runtimeRequestId: z.string().trim().min(1).max(255).nullable().optional(), }).superRefine((value, ctx) => { @@ -982,16 +1023,16 @@ export const askUserQuestionsPayloadSchema = z.object({ }); export const askUserQuestionsAnswerSchema = z.object({ - questionId: z.string().trim().min(1).max(120), - optionIds: z.array(z.string().trim().min(1).max(120)).max(20), - otherText: multilineTextSchema.pipe(z.string().trim().max(4000)).nullable().optional(), + questionId: z.string().trim().min(1).max(160), + optionIds: z.array(z.string().trim().min(1).max(160)).max(129), + otherText: multilineTextSchema.pipe(z.string().trim().max(100000)).nullable().optional(), }); export const askUserQuestionsResultSchema = z.object({ version: z.literal(1), outcome: z.enum(["withdrawn", "issue_closed", "addressee_deleted"]).optional(), reason: z.string().trim().max(4000).nullable().optional(), - answers: z.array(askUserQuestionsAnswerSchema).max(20), + answers: z.array(askUserQuestionsAnswerSchema).max(64), cancelled: z.literal(true).optional(), cancellationReason: z.string().trim().max(4000).nullable().optional(), expirationReason: z.enum(["superseded_by_comment", "superseded_by_newer_interaction"]).optional(), diff --git a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts index 1db628e3f9..2a19a6fc65 100644 --- a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts +++ b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts @@ -1003,6 +1003,8 @@ describe("agent issue mutation checkout ownership", () => { issueId, expect.objectContaining({ status: "done" }), expect.anything(), + undefined, + expect.any(Array), ); }); diff --git a/server/src/__tests__/issue-comment-reopen-routes.test.ts b/server/src/__tests__/issue-comment-reopen-routes.test.ts index b63c7056a6..078a1ffda3 100644 --- a/server/src/__tests__/issue-comment-reopen-routes.test.ts +++ b/server/src/__tests__/issue-comment-reopen-routes.test.ts @@ -2450,6 +2450,7 @@ describe.sequential("issue comment reopen routes", () => { }), mockTx, expect.any(Array), + expect.any(Array), ); const updatePatch = mockIssueService.update.mock.calls[0]?.[1] as Record; const decisionId = updatePatch.executionState.lastDecisionId; @@ -2545,6 +2546,8 @@ describe.sequential("issue comment reopen routes", () => { }), }), mockTx, + undefined, + expect.any(Array), ); }); @@ -2630,6 +2633,8 @@ describe.sequential("issue comment reopen routes", () => { }), }), mockTx, + undefined, + expect.any(Array), ); }); @@ -3239,6 +3244,8 @@ describe.sequential("issue comment reopen routes", () => { "11111111-1111-4111-8111-111111111111", expect.objectContaining({ status: "done" }), mockTx, + undefined, + expect.any(Array), ); expect(mockLogActivity).toHaveBeenCalledWith( expect.anything(), diff --git a/server/src/__tests__/issue-execution-policy-routes.test.ts b/server/src/__tests__/issue-execution-policy-routes.test.ts index bd5d9a72c5..cfd98a9ac6 100644 --- a/server/src/__tests__/issue-execution-policy-routes.test.ts +++ b/server/src/__tests__/issue-execution-policy-routes.test.ts @@ -792,6 +792,8 @@ describe("issue execution policy routes", () => { actorUserId: "local-board", }), expect.anything(), + undefined, + expect.any(Array), ); expect(mockHeartbeatService.cancelRun).not.toHaveBeenCalled(); }); @@ -849,6 +851,8 @@ describe("issue execution policy routes", () => { actorUserId: "local-board", }), expect.anything(), + undefined, + expect.any(Array), ); const updatePatch = mockIssueService.update.mock.calls[0]?.[1] as Record; expect(updatePatch.status).toBe("cancelled"); diff --git a/server/src/__tests__/issue-thread-interaction-routes.test.ts b/server/src/__tests__/issue-thread-interaction-routes.test.ts index d8bce7b3e0..e13e5a4f78 100644 --- a/server/src/__tests__/issue-thread-interaction-routes.test.ts +++ b/server/src/__tests__/issue-thread-interaction-routes.test.ts @@ -46,6 +46,16 @@ const mockInteractionService = vi.hoisted(() => ({ const mockHeartbeatService = vi.hoisted(() => ({ wakeup: vi.fn(async () => undefined), + cancelRun: vi.fn(async () => null), +})); +const mockRequestNativeQuestionRunCancellation = vi.hoisted(() => + vi.fn(async () => null as string | null) +); + +vi.mock("../services/native-runtime/native-question-bridge.js", () => ({ + deliverNativeQuestionResponse: vi.fn(async () => "not_native"), + requestNativeQuestionRunCancellation: mockRequestNativeQuestionRunCancellation, + validateNativeQuestionResponseInput: vi.fn(), })); const mockQuestionResponseDeliveries = vi.hoisted(() => ({ deliver: vi.fn(async () => null), @@ -279,6 +289,20 @@ async function createApp(actor: Record = { return app; } +async function resolveMockInteraction( + args: unknown[], + interaction: Record, +) { + const mutationOptions = args[4] as { + afterResolveInTransaction?: ( + tx: Record, + resolved: Record, + ) => Promise; + } | undefined; + await mutationOptions?.afterResolveInTransaction?.({}, interaction); + return interaction; +} + describe.sequential("issue thread interaction routes", () => { beforeEach(() => { vi.resetModules(); @@ -290,6 +314,7 @@ describe.sequential("issue thread interaction routes", () => { vi.clearAllMocks(); mockInteractionService.getForIssue.mockReset(); mockQuestionResponseDeliveries.deliver.mockResolvedValue(null); + mockRequestNativeQuestionRunCancellation.mockResolvedValue(null); mockResolveTaskWatchdogMutationScope.mockReset(); mockResolveCoreTrustPreset.mockReset(); mockAccessDecide.mockReset(); @@ -317,7 +342,7 @@ describe.sequential("issue thread interaction routes", () => { status: "pending", payload: { version: 1, questions: [] }, }); - mockInteractionService.withdrawInteraction.mockResolvedValue({ + mockInteractionService.withdrawInteraction.mockImplementation((...args) => resolveMockInteraction(args, { id: "interaction-withdraw", companyId: "company-1", issueId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", @@ -327,7 +352,7 @@ describe.sequential("issue thread interaction routes", () => { continuationPolicy: "wake_assignee", payload: { version: 1, prompt: "Proceed?" }, result: { version: 1, outcome: "withdrawn", reason: "Replanning" }, - }); + })); mockInteractionService.recordSecretProposalExecutionResult.mockImplementation( async (_issue, _interactionId, _proposalId, execution) => ({ ...(await mockInteractionService.acceptInteraction.mock.results.at(-1)?.value)?.interaction, @@ -490,7 +515,7 @@ describe.sequential("issue thread interaction routes", () => { }, newlyResolvedItemIds: ["docs"], }); - mockInteractionService.cancelQuestions.mockResolvedValue({ + mockInteractionService.cancelQuestions.mockImplementation((...args) => resolveMockInteraction(args, { id: "interaction-2", companyId: "company-1", issueId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", @@ -519,7 +544,7 @@ describe.sequential("issue thread interaction routes", () => { createdAt: "2026-04-20T12:00:00.000Z", updatedAt: "2026-04-20T12:05:00.000Z", resolvedAt: "2026-04-20T12:05:00.000Z", - }); + })); mockDbSelect.mockImplementation(() => ({ from: mockDbSelectFrom })); mockDbSelectFrom.mockImplementation(() => ({ where: mockDbSelectWhere })); mockDbSelectWhere.mockImplementation(() => ({ @@ -853,6 +878,7 @@ describe.sequential("issue thread interaction routes", () => { "interaction-withdraw", { reason: "Replanning" }, expect.objectContaining({ userId: "local-board" }), + expect.objectContaining({ afterResolveInTransaction: expect.any(Function) }), ); expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(ASSIGNEE_AGENT_ID, expect.objectContaining({ payload: expect.objectContaining({ interactionStatus: "cancelled" }), @@ -862,6 +888,71 @@ describe.sequential("issue thread interaction routes", () => { })); }); + it("cancels the bound native run when its question is withdrawn", async () => { + mockInteractionService.withdrawInteraction.mockImplementationOnce((...args) => resolveMockInteraction(args, { + id: "interaction-withdraw", + companyId: "company-1", + issueId: ISSUE_ID, + kind: "ask_user_questions", + createdByAgentId: CREATED_AGENT_ID, + sourceRunId: RUN_1, + status: "cancelled", + continuationPolicy: "none", + payload: { version: 1, questions: [] }, + result: { version: 1, answers: [], cancelled: true }, + })); + mockRequestNativeQuestionRunCancellation.mockResolvedValueOnce(RUN_1); + + const res = await request(await createApp()) + .post(`/api/issues/${ISSUE_ID}/interactions/interaction-withdraw/withdraw`) + .send({ reason: "No longer needed" }); + + expect(res.status).toBe(200); + expect(mockRequestNativeQuestionRunCancellation).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ id: "interaction-withdraw", sourceRunId: RUN_1 }), + { kind: "interaction_withdrawn", interactionId: "interaction-withdraw" }, + ); + expect(mockHeartbeatService.cancelRun).toHaveBeenCalledWith( + RUN_1, + "Question withdrawn while waiting for operator input", + expect.objectContaining({ + resultJson: expect.objectContaining({ + withdrawnInteractionId: "interaction-withdraw", + withdrawnByActorType: "user", + }), + }), + ); + }); + + it("keeps a durable withdrawal intent when immediate native cancellation fails", async () => { + mockInteractionService.withdrawInteraction.mockImplementationOnce((...args) => resolveMockInteraction(args, { + id: "interaction-withdraw", + companyId: "company-1", + issueId: ISSUE_ID, + kind: "ask_user_questions", + createdByAgentId: CREATED_AGENT_ID, + sourceRunId: RUN_1, + status: "cancelled", + continuationPolicy: "none", + payload: { version: 1, questions: [] }, + result: { version: 1, answers: [], cancelled: true }, + })); + mockRequestNativeQuestionRunCancellation.mockResolvedValueOnce(RUN_1); + mockHeartbeatService.cancelRun.mockRejectedValueOnce(new Error("process unavailable")); + + const res = await request(await createApp()) + .post(`/api/issues/${ISSUE_ID}/interactions/interaction-withdraw/withdraw`) + .send({ reason: "No longer needed" }); + + expect(res.status).toBe(200); + expect(mockRequestNativeQuestionRunCancellation).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ id: "interaction-withdraw" }), + { kind: "interaction_withdrawn", interactionId: "interaction-withdraw" }, + ); + }); + it("allows the creator agent to withdraw and wakes a different assignee", async () => { mockIssueService.getById.mockResolvedValueOnce(createIssue({ status: "in_review", reviewPolicy: null })); mockInteractionService.getForIssue.mockResolvedValueOnce({ @@ -919,6 +1010,7 @@ describe.sequential("issue thread interaction routes", () => { "interaction-withdraw", {}, expect.objectContaining({ agentId: ASSIGNEE_AGENT_ID, runId: RUN_WATCHDOG }), + expect.objectContaining({ afterResolveInTransaction: expect.any(Function) }), ); expect(res.status).toBe(200); }); @@ -948,6 +1040,7 @@ describe.sequential("issue thread interaction routes", () => { "interaction-2", {}, expect.objectContaining({ userId: "local-board" }), + expect.objectContaining({ afterResolveInTransaction: expect.any(Function) }), ); expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith( ASSIGNEE_AGENT_ID, @@ -970,6 +1063,28 @@ describe.sequential("issue thread interaction routes", () => { ); }); + it("durably marks a board-cancelled native question before cancelling its run", async () => { + mockRequestNativeQuestionRunCancellation.mockResolvedValueOnce(RUN_2); + + const res = await request(await createApp()) + .post(`/api/issues/${ISSUE_ID}/interactions/interaction-2/cancel`) + .send({}); + + expect(res.status).toBe(200); + expect(mockRequestNativeQuestionRunCancellation).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ id: "interaction-2", sourceRunId: RUN_2 }), + { kind: "interaction_cancelled", interactionId: "interaction-2" }, + ); + expect(mockHeartbeatService.cancelRun).toHaveBeenCalledWith( + RUN_2, + "Cancelled while waiting for operator input", + expect.objectContaining({ + resultJson: expect.objectContaining({ cancelledInteractionId: "interaction-2" }), + }), + ); + }); + it("accepts request confirmations and wakes the current assignee when configured for accept-only wakeups", async () => { mockInteractionService.acceptInteraction.mockResolvedValueOnce({ interaction: { diff --git a/server/src/__tests__/issue-tree-control-service.test.ts b/server/src/__tests__/issue-tree-control-service.test.ts index afb23add9e..43c620053a 100644 --- a/server/src/__tests__/issue-tree-control-service.test.ts +++ b/server/src/__tests__/issue-tree-control-service.test.ts @@ -2,12 +2,14 @@ import { randomUUID } from "node:crypto"; import { eq, inArray } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { + activityLog, agents, agentWakeupRequests, companies, createDb, heartbeatRuns, issueComments, + issueThreadInteractions, issueTreeHoldMembers, issueTreeHolds, issues, @@ -38,6 +40,8 @@ describeEmbeddedPostgres("issueTreeControlService", () => { }, 20_000); afterEach(async () => { + await db.delete(issueThreadInteractions); + await db.delete(activityLog); await db.delete(issueTreeHoldMembers); await db.delete(issueTreeHolds); await db.delete(issueComments); @@ -137,7 +141,6 @@ describeEmbeddedPostgres("issueTreeControlService", () => { createdAt: new Date("2026-04-21T10:03:00.000Z"), }, ]); - const svc = issueTreeControlService(db); const preview = await svc.preview(companyId, rootIssueId, { mode: "pause" }); @@ -314,6 +317,14 @@ describeEmbeddedPostgres("issueTreeControlService", () => { createdAt: new Date("2026-04-21T10:03:00.000Z"), }, ]); + const [pendingInteraction] = await db.insert(issueThreadInteractions).values({ + companyId, + issueId: runningChildId, + kind: "request_confirmation", + status: "pending", + continuationPolicy: "none", + payload: { version: 1, prompt: "Continue?" }, + }).returning(); const svc = issueTreeControlService(db); const cancel = await svc.createHold(companyId, rootIssueId, { @@ -340,6 +351,11 @@ describeEmbeddedPostgres("issueTreeControlService", () => { [todoChildId]: "cancelled", [doneChildId]: "done", }); + const [expiredInteraction] = await db + .select({ status: issueThreadInteractions.status }) + .from(issueThreadInteractions) + .where(eq(issueThreadInteractions.id, pendingInteraction!.id)); + expect(expiredInteraction?.status).toBe("expired"); await db .update(issues) diff --git a/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts b/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts index 23651af684..419c52739a 100644 --- a/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts +++ b/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts @@ -33,6 +33,12 @@ const mockIssueThreadInteractionService = vi.hoisted(() => ({ expireStaleRequestConfirmationsForIssueDocument: vi.fn(async () => []), })); +vi.mock("../services/native-runtime/native-question-bridge.js", () => ({ + deliverNativeQuestionResponse: vi.fn(async () => "not_native"), + nativeQuestionRunToCancel: vi.fn(async () => null), + validateNativeQuestionResponseInput: vi.fn(), +})); + vi.mock("../services/index.js", () => ({ companyService: () => ({ getById: vi.fn(async () => ({ id: "company-1" })), @@ -485,41 +491,6 @@ describe("issue update comment wakeups", () => { ); }); - it("does not wake the assignee when a closure comment marks the issue done", async () => { - const existing = makeIssue({ - assigneeAgentId: ASSIGNEE_AGENT_ID, - assigneeUserId: null, - status: "in_progress", - }); - const updated = { - ...existing, - status: "done", - completedAt: new Date("2026-06-26T16:30:00.000Z"), - }; - mockIssueService.getById.mockResolvedValue(existing); - mockIssueService.update.mockResolvedValue(updated); - mockIssueService.addComment.mockResolvedValue({ - id: "comment-close-1", - issueId: existing.id, - companyId: existing.companyId, - body: "Closing this out.", - }); - - const res = await request(await createApp()) - .patch(`/api/issues/${existing.id}`) - .send({ - status: "done", - comment: "Closing this out.", - }); - - expect(res.status).toBe(200); - await new Promise((resolve) => setImmediate(resolve)); - const issueCommentedWakeCalls = mockHeartbeatService.wakeup.mock.calls.filter( - ([, wakeup]: [string, { reason?: string }]) => wakeup?.reason === "issue_commented", - ); - expect(issueCommentedWakeCalls).toEqual([]); - }); - it("wakes the assignee on top-level board issue comments", async () => { const existing = makeIssue({ assigneeAgentId: ASSIGNEE_AGENT_ID, diff --git a/server/src/__tests__/pipelines-service.test.ts b/server/src/__tests__/pipelines-service.test.ts index bd63341402..3ffda9d205 100644 --- a/server/src/__tests__/pipelines-service.test.ts +++ b/server/src/__tests__/pipelines-service.test.ts @@ -10,6 +10,7 @@ import { heartbeatRuns, instanceSettings, issueComments, + issueThreadInteractions, issues, pipelineAutomationExecutions, pipelineCaseBlockers, @@ -68,6 +69,7 @@ describeEmbeddedPostgres("pipelineService", () => { await db.delete(pipelineTransitions); await db.delete(pipelineStages); await db.delete(pipelines); + await db.delete(issueThreadInteractions); await db.delete(issueComments); await db.delete(activityLog); await db.delete(routineRuns); @@ -1707,6 +1709,27 @@ describeEmbeddedPostgres("pipelineService", () => { status: "failed", error: "boom", }).returning(); + const [automationIssue] = await db.insert(issues).values({ + companyId: company.id, + title: "Retry-owned automation issue", + status: "in_progress", + priority: "medium", + }).returning(); + await db.insert(pipelineCaseIssueLinks).values({ + companyId: company.id, + caseId: parent.case.id, + issueId: automationIssue!.id, + role: "automation", + automationAttemptId: attempt!.id, + }); + const [pendingInteraction] = await db.insert(issueThreadInteractions).values({ + companyId: company.id, + issueId: automationIssue!.id, + kind: "request_confirmation", + status: "pending", + continuationPolicy: "none", + payload: { version: 1, prompt: "Continue automation?" }, + }).returning(); const child = await svc.ingestCase({ companyId: company.id, pipelineId: pipeline.id, @@ -1777,6 +1800,16 @@ describeEmbeddedPostgres("pipelineService", () => { expect(freshParent!.stageKey).toBe("review"); expect(freshChild!.terminalKind).toBe("cancelled"); expect(freshChild!.retiredReason).toBe("automation_retry"); + const [cancelledAutomationIssue] = await db + .select({ status: issues.status }) + .from(issues) + .where(eq(issues.id, automationIssue!.id)); + expect(cancelledAutomationIssue?.status).toBe("cancelled"); + const [expiredInteraction] = await db + .select({ status: issueThreadInteractions.status }) + .from(issueThreadInteractions) + .where(eq(issueThreadInteractions.id, pendingInteraction!.id)); + expect(expiredInteraction?.status).toBe("expired"); const events = await svc.listCaseEvents(company.id, parent.case.id); expect(events.filter((pipelineEvent) => pipelineEvent.type === "children_terminal")).toHaveLength(2); }); diff --git a/server/src/__tests__/question-response-delivery.test.ts b/server/src/__tests__/question-response-delivery.test.ts index 9619c0bfcd..dbeddfa395 100644 --- a/server/src/__tests__/question-response-delivery.test.ts +++ b/server/src/__tests__/question-response-delivery.test.ts @@ -241,6 +241,56 @@ describeEmbeddedPostgres("question response delivery", () => { expect(JSON.stringify(deliveryEvents[0]?.details)).not.toContain("Node.js"); }); + it("resolves an in-flight native input request before creating a continuation", async () => { + const seeded = await seed({ + adapterType: "paperclip_runner", + runtimeMode: "native", + sourceStatus: "running", + }); + const wakeup = vi.fn(); + const resolveNativeQuestion = vi.fn().mockResolvedValue("queued" as const); + + const outcome = await questionResponseDeliveryService(db, { + heartbeat: { wakeup } as never, + resolveNativeQuestion, + }).deliver(seeded.interaction.id); + + expect(outcome).toMatchObject({ + status: "delivered", + mode: "steered", + targetRunId: seeded.sourceRunId, + }); + expect(resolveNativeQuestion).toHaveBeenCalledWith(expect.objectContaining({ + id: seeded.interaction.id, + status: "answered", + })); + expect(wakeup).not.toHaveBeenCalled(); + }); + + it("keeps native input delivery pending while its PRP session is unavailable", async () => { + const seeded = await seed({ + adapterType: "paperclip_runner", + runtimeMode: "native", + sourceStatus: "running", + }); + const wakeup = vi.fn(); + + const outcome = await questionResponseDeliveryService(db, { + heartbeat: { wakeup } as never, + resolveNativeQuestion: vi.fn().mockResolvedValue("pending" as const), + }).deliver(seeded.interaction.id); + + expect(outcome).toBeNull(); + expect(wakeup).not.toHaveBeenCalled(); + const [delivery] = await db.select().from(issueQuestionResponseDeliveries); + expect(delivery).toMatchObject({ + status: "pending", + attemptCount: 1, + errorCount: 0, + lastErrorCode: "native_question_session_unavailable", + }); + }); + it("coalesces into a queued successor without creating another wake", async () => { const seeded = await seed({ successorStatus: "queued" }); const successor = await db.select().from(heartbeatRuns) diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index 791df7154b..015faec1c3 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -326,6 +326,13 @@ vi.mock("../services/question-response-delivery.js", () => ({ })), })); +vi.mock("../services/native-runtime/native-question-bridge.js", () => ({ + deliverNativeQuestionResponse: vi.fn(async () => "not_native"), + nativeQuestionCancellationIdentity: vi.fn(() => null), + nativeQuestionRunToCancel: vi.fn(async () => null), + validateNativeQuestionResponseInput: vi.fn(), +})); + vi.mock("../services/secret-proposals.js", () => ({ createSecretProposalsService: vi.fn(() => ({ sweepExpired: vi.fn(async () => 0), diff --git a/server/src/index.ts b/server/src/index.ts index 09a66a0d91..6d85140dbd 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -69,6 +69,7 @@ import { workspaceOperationService, } from "./services/index.js"; import { questionResponseDeliveryService } from "./services/question-response-delivery.js"; +import { deliverNativeQuestionResponse } from "./services/native-runtime/native-question-bridge.js"; import { queueIssueAssignmentWakeup } from "./services/issue-assignment-wakeup.js"; import { createSecretProposalsService } from "./services/secret-proposals.js"; import { environmentRuntimeService } from "./services/environment-runtime.js"; @@ -1084,6 +1085,7 @@ export async function startServer(): Promise { heartbeat ?? heartbeatService(db as any, { pluginWorkerManager }); const questionResponseDeliveries = questionResponseDeliveryService(db as any, { heartbeat: environmentLeaseCleanupHeartbeat, + resolveNativeQuestion: (interaction) => deliverNativeQuestionResponse(db as any, interaction), }); const runEnvironmentLeaseCleanupSweep = (backoffMs: number) => environmentLeaseCleanupHeartbeat diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 89960672bc..028e868e54 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -5298,6 +5298,7 @@ export function agentRoutes( const columns = { id: heartbeatRuns.id, + runtimeMode: heartbeatRuns.runtimeMode, companyId: heartbeatRuns.companyId, status: heartbeatRuns.status, invocationSource: heartbeatRuns.invocationSource, @@ -5523,6 +5524,7 @@ export function agentRoutes( const liveRuns = await db .select({ id: heartbeatRuns.id, + runtimeMode: heartbeatRuns.runtimeMode, status: heartbeatRuns.status, invocationSource: heartbeatRuns.invocationSource, triggerDetail: heartbeatRuns.triggerDetail, diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index ab07d8c789..1bff0fbc14 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -202,6 +202,7 @@ import { ISSUE_WAKE_DIAGNOSTICS_MAX_ACTIVITY_RECORDS, ISSUE_WAKE_DIAGNOSTICS_MAX_WAKE_REQUESTS, readAcceptedPlanConfirmationTarget, + type IssuePostCommitAction, } from "../services/issues.js"; import { authorizationDeniedDetails } from "../services/authorization.js"; import { stalledReviewDecisionService } from "../services/stalled-review-decisions.js"; @@ -209,6 +210,11 @@ import { environmentService } from "../services/environments.js"; import { environmentRuntimeService } from "../services/environment-runtime.js"; import { redactSensitiveText } from "../redaction.js"; import { createRunSecretRedactionRegistry } from "../services/run-secret-redaction.js"; +import { + deliverNativeQuestionResponse, + requestNativeQuestionRunCancellation, + validateNativeQuestionResponseInput, +} from "../services/native-runtime/native-question-bridge.js"; import { createCompanySearchRateLimiter, type CompanySearchRateLimiter, @@ -2855,7 +2861,14 @@ export function issueRoutes( const issueThreadInteractionsSvc = issueThreadInteractionService(db); const questionResponseDeliveries = questionResponseDeliveryService(db, { heartbeat, + resolveNativeQuestion: (interaction) => deliverNativeQuestionResponse(db, interaction), }); + const flushIssuePostCommitActions = async (actions: readonly IssuePostCommitAction[]) => { + if (actions.length === 0) return; + const { executeIssuePostCommitActions } = await import("../services/issues.js"); + await executeIssuePostCommitActions(db, actions); + }; + const memoizeIssueRead = createRequestPromiseMemo>>({ shouldCache: (issue) => issue !== null, }); @@ -6876,6 +6889,7 @@ export function issueRoutes( const actor = getActorInfo(req); const actionStatus = outcome === "cancelled" ? "cancelled" : "resolved"; const postCommitActivityPublications: ActivityPublication[] = []; + const postCommitIssueActions: IssuePostCommitAction[] = []; const result = await db.transaction(async (tx) => { const lockedIssue = await tx .select() @@ -6996,16 +7010,20 @@ export function issueRoutes( } } - const updatedIssue = await svc.update( - id, - { - ...updateFields, - actorAgentId: actor.agentId ?? null, - actorUserId: actor.actorType === "user" ? actor.actorId : null, - }, - tx, - postCommitActivityPublications, - ); + const issueUpdate = { + ...updateFields, + actorAgentId: actor.agentId ?? null, + actorUserId: actor.actorType === "user" ? actor.actorId : null, + }; + const updatedIssue = sourceIssueStatus === "done" || sourceIssueStatus === "cancelled" + ? await svc.update( + id, + issueUpdate, + tx, + postCommitActivityPublications, + postCommitIssueActions, + ) + : await svc.update(id, issueUpdate, tx, postCommitActivityPublications); if (!updatedIssue) throw notFound("Issue not found"); issue = updatedIssue; } @@ -7035,6 +7053,7 @@ export function issueRoutes( return { issue, recoveryAction }; }); for (const publication of postCommitActivityPublications) publishActivity(publication); + await flushIssuePostCommitActions(postCommitIssueActions); await routinesSvc.syncRunStatusForIssue(result.issue.id); @@ -9852,6 +9871,7 @@ export function issueRoutes( value: Awaited>; } = { value: null }; const postCommitActivityPublications: ActivityPublication[] = []; + const postCommitIssueActions: IssuePostCommitAction[] = []; const issueUpdateData = { ...updateFields, actorAgentId: actor.agentId ?? null, @@ -9859,10 +9879,15 @@ export function issueRoutes( }; const shouldCollectCompletionPublication = actor.actorType === "user" && existing.status !== "done" && updateFields.status === "done"; + const shouldCollectTerminalIssueActions = + updateFields.status === "done" || updateFields.status === "cancelled"; const updateIssue = (tx?: Parameters[2]) => { if (tx) { - return shouldCollectCompletionPublication - ? svc.update(id, issueUpdateData, tx, postCommitActivityPublications) + if (shouldCollectCompletionPublication) { + return svc.update(id, issueUpdateData, tx, postCommitActivityPublications, postCommitIssueActions); + } + return shouldCollectTerminalIssueActions + ? svc.update(id, issueUpdateData, tx, undefined, postCommitIssueActions) : svc.update(id, issueUpdateData, tx); } return shouldCollectCompletionPublication @@ -10033,6 +10058,7 @@ export function issueRoutes( return; } for (const publication of postCommitActivityPublications) publishActivity(publication); + await flushIssuePostCommitActions(postCommitIssueActions); if (enteringBlocked) { const blockedIssue = issue; @@ -11682,9 +11708,12 @@ export function issueRoutes( interactionId, ); if (!authorizedResolution) return; - const { interactionSvc, resolutionAuthorization } = authorizedResolution; + const { interactionSvc, current, resolutionAuthorization } = authorizedResolution; const actor = getActorInfo(req); + if (current.kind === "ask_user_questions") { + validateNativeQuestionResponseInput(current, req.body); + } const interaction = await interactionSvc.answerQuestions(issue, interactionId, req.body, { agentId: actor.agentId, runId: actor.runId, @@ -11829,11 +11858,42 @@ export function issueRoutes( await assertPendingReviewInteractionVerdictAllowed(req, issue, current); const actor = getActorInfo(req); - const interaction = await interactionSvc.withdrawInteraction(issue, interactionId, req.body, { - agentId: actor.agentId, - runId: actor.runId, - userId: actor.actorType === "user" ? actor.actorId : null, - }); + let nativeRunId: string | null = null; + const interaction = await interactionSvc.withdrawInteraction( + issue, + interactionId, + req.body, + { + agentId: actor.agentId, + runId: actor.runId, + userId: actor.actorType === "user" ? actor.actorId : null, + }, + { + afterResolveInTransaction: async (tx, resolved) => { + if (resolved.kind !== "ask_user_questions") return; + nativeRunId = await requestNativeQuestionRunCancellation(tx, resolved, { + kind: "interaction_withdrawn", + interactionId: resolved.id, + }); + }, + }, + ); + if (nativeRunId) { + try { + await heartbeat.cancelRun(nativeRunId, "Question withdrawn while waiting for operator input", { + resultJson: { + withdrawnInteractionId: interaction.id, + withdrawnByActorType: actor.actorType, + withdrawnByActorId: actor.actorId, + }, + }); + } catch (err) { + logger.warn( + { err, runId: nativeRunId, interactionId: interaction.id }, + "native question withdrawal cancellation deferred to recovery sweep", + ); + } + } await logActivity(db, { companyId: issue.companyId, actorType: actor.actorType, @@ -11881,10 +11941,25 @@ export function issueRoutes( assertBoard(req); const actor = getActorInfo(req); - const interaction = await issueThreadInteractionService(db).cancelQuestions(issue, interactionId, req.body, { - agentId: actor.agentId, - userId: actor.actorType === "user" ? actor.actorId : null, - }); + let nativeRunId: string | null = null; + const interaction = await issueThreadInteractionService(db).cancelQuestions( + issue, + interactionId, + req.body, + { + agentId: actor.agentId, + userId: actor.actorType === "user" ? actor.actorId : null, + }, + { + afterResolveInTransaction: async (tx, resolved) => { + if (resolved.kind !== "ask_user_questions") return; + nativeRunId = await requestNativeQuestionRunCancellation(tx, resolved, { + kind: "interaction_cancelled", + interactionId: resolved.id, + }); + }, + }, + ); await logActivity(db, { companyId: issue.companyId, @@ -11907,6 +11982,23 @@ export function issueRoutes( }, }); + if (nativeRunId) { + try { + await heartbeat.cancelRun(nativeRunId, "Cancelled while waiting for operator input", { + resultJson: { + cancelledByActorType: "user", + cancelledByUserId: req.actor.userId ?? null, + cancelledInteractionId: interaction.id, + }, + }); + } catch (err) { + logger.warn( + { err, runId: nativeRunId, interactionId: interaction.id }, + "native question board cancellation deferred to recovery sweep", + ); + } + } + await queueResolvedInteractionContinuationWakeup({ db, heartbeat, @@ -12444,6 +12536,7 @@ export function issueRoutes( }; let txResult: { comment: Awaited>; issue: NonNullable>> }; const postCommitActivityPublications: ActivityPublication[] = []; + const postCommitIssueActions: IssuePostCommitAction[] = []; try { txResult = await db.transaction(async (tx) => { const insertedComment = await svc.addComment( @@ -12459,8 +12552,8 @@ export function issueRoutes( tx, ); const updated = actor.actorType === "user" && currentIssue.status !== "done" - ? await svc.update(id, updatePatch, tx, postCommitActivityPublications) - : await svc.update(id, updatePatch, tx); + ? await svc.update(id, updatePatch, tx, postCommitActivityPublications, postCommitIssueActions) + : await svc.update(id, updatePatch, tx, undefined, postCommitIssueActions); // Throw (not return null) so drizzle rolls back the inserted comment when the issue // has been concurrently deleted between the initial fetch and the in-transaction update. if (!updated) throw new AutoApprovalIssueMissingError(); @@ -12490,6 +12583,7 @@ export function issueRoutes( throw err; } for (const publication of postCommitActivityPublications) publishActivity(publication); + await flushIssuePostCommitActions(postCommitIssueActions); comment = txResult.comment; currentIssue = txResult.issue; // Mirror the normal status-change audit trail: every other in_review -> done path diff --git a/server/src/services/activity.ts b/server/src/services/activity.ts index a9c6f592dd..5cc2cc625a 100644 --- a/server/src/services/activity.ts +++ b/server/src/services/activity.ts @@ -381,6 +381,7 @@ export function activityService(db: Db) { const runs = await db .select({ runId: heartbeatRuns.id, + runtimeMode: heartbeatRuns.runtimeMode, status: heartbeatRuns.status, agentId: heartbeatRuns.agentId, adapterType: agents.adapterType, diff --git a/server/src/services/decisions.ts b/server/src/services/decisions.ts index 704a713ae4..c9a5706354 100644 --- a/server/src/services/decisions.ts +++ b/server/src/services/decisions.ts @@ -8,7 +8,10 @@ import { conflict, forbidden, notFound, tooManyRequests, unprocessable } from ". import { authorizationService, type AuthorizationActor } from "./authorization.js"; import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; import { signDecisionSpec, verifyDecisionSpec } from "./decision-signing.js"; -import { issueService } from "./issues.js"; +import { + issueService, + type IssuePostCommitAction, +} from "./issues.js"; import { decisionRetentionService, hashAttentionArchiveManifest } from "./decision-retention.js"; type Snapshot = { status: string; assigneeAgentId: string | null; assigneeUserId: string | null; updatedAt: string; @@ -406,6 +409,7 @@ export function decisionService(db: Db, options: DecisionServiceOptions) { try { const postCommitActivityPublications: ActivityPublication[] = []; + const postCommitIssueActions: IssuePostCommitAction[] = []; const executionResult = await db.transaction(async (tx) => { await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`); let execution = await tx.select().from(decisionEffectExecutions).where(and(eq(decisionEffectExecutions.decisionId, decision.id), eq(decisionEffectExecutions.effectIndex, effectIndex))) @@ -472,6 +476,7 @@ export function decisionService(db: Db, options: DecisionServiceOptions) { { status: effect.status, actorUserId: decidedByUserId }, tx, postCommitActivityPublications, + postCommitIssueActions, ); if (effect.comment) await svc.addComment(target.id, interpolate(effect.comment, values), { userId: decidedByUserId }, undefined, tx); result = { issueId: updated?.id, status: updated?.status }; @@ -485,6 +490,7 @@ export function decisionService(db: Db, options: DecisionServiceOptions) { }, tx, postCommitActivityPublications, + postCommitIssueActions, ); if (effect.comment) await svc.addComment(target.id, interpolate(effect.comment, values), { userId: decidedByUserId }, undefined, tx); result = { issueId: updated?.id }; @@ -498,6 +504,7 @@ export function decisionService(db: Db, options: DecisionServiceOptions) { }, tx, postCommitActivityPublications, + postCommitIssueActions, ); result = { removedBlockedByIssueIds: effect.removeBlockedByIssueIds }; } else if (effect.type === "create_issue") { @@ -515,6 +522,7 @@ export function decisionService(db: Db, options: DecisionServiceOptions) { { status: "cancelled", actorUserId: decidedByUserId }, tx, postCommitActivityPublications, + postCommitIssueActions, ); } await svc.addComment(target.id, interpolate(effect.reasonComment, values), { userId: decidedByUserId }, undefined, tx); @@ -525,6 +533,10 @@ export function decisionService(db: Db, options: DecisionServiceOptions) { return row; }); for (const publication of postCommitActivityPublications) publishActivity(publication); + if (postCommitIssueActions.length > 0) { + const { executeIssuePostCommitActions } = await import("./issues.js"); + await executeIssuePostCommitActions(db, postCommitIssueActions); + } return executionResult; } catch (error) { const message = error instanceof Error ? error.message : "Decision effect execution failed"; diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index b62e59fb78..3c4c63282c 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -463,6 +463,7 @@ const MAX_AGENT_SESSION_MESSAGE_CHARS = 12_000; const execFile = promisify(execFileCallback); const EXECUTION_PATH_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_retry"] as const; const CANCELLABLE_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_retry"] as const; +const NATIVE_QUESTION_CANCELLATION_CONTEXT_KEY = "nativeQuestionCancellation"; const HEARTBEAT_RUN_TERMINAL_STATUSES = ["succeeded", "interrupted", "failed", "cancelled", "timed_out"] as const; const UNSUCCESSFUL_HEARTBEAT_RUN_TERMINAL_STATUSES = ["failed", "cancelled", "timed_out"] as const; const TIMER_ACTIONABLE_ISSUE_STATUSES = ["todo", "in_progress"] as const; @@ -2571,6 +2572,7 @@ const heartbeatRunLogAccessColumns = { const heartbeatRunIssueSummaryColumns = { id: heartbeatRuns.id, + runtimeMode: heartbeatRuns.runtimeMode, status: heartbeatRuns.status, invocationSource: heartbeatRuns.invocationSource, triggerDetail: heartbeatRuns.triggerDetail, @@ -14024,6 +14026,56 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {}) const staleThresholdMs = opts?.staleThresholdMs ?? 0; const now = new Date(); + // A terminal issue transition writes this intent in the same transaction + // that expires the native question. Consume it before generic orphan + // recovery so a restart preserves the requested cancellation outcome. + const cancellationRequests = await db + .select({ + id: heartbeatRuns.id, + contextSnapshot: heartbeatRuns.contextSnapshot, + }) + .from(heartbeatRuns) + .where(and( + inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]), + sql`${heartbeatRuns.contextSnapshot} -> ${NATIVE_QUESTION_CANCELLATION_CONTEXT_KEY} is not null`, + )); + for (const request of cancellationRequests) { + const marker = parseObject( + parseObject(request.contextSnapshot)[NATIVE_QUESTION_CANCELLATION_CONTEXT_KEY], + ); + const issueId = readNonEmptyString(marker.issueId); + const issueStatus = readNonEmptyString(marker.issueStatus); + const interactionId = readNonEmptyString(marker.interactionId); + const kind = readNonEmptyString(marker.kind); + const reason = kind === "interaction_withdrawn" + ? "Question withdrawn while waiting for operator input" + : kind === "interaction_cancelled" + ? "Cancelled while waiting for operator input" + : "Task closed while waiting for operator input"; + try { + await cancelRunInternal(request.id, reason, { + resultJson: { + ...(kind === "interaction_withdrawn" && interactionId + ? { withdrawnInteractionId: interactionId } + : {}), + ...(kind === "interaction_cancelled" && interactionId + ? { cancelledInteractionId: interactionId } + : {}), + ...((!kind || kind === "issue_terminal") && issueStatus + ? { cancelledByIssueStatus: issueStatus } + : {}), + ...(issueId ? { cancelledIssueId: issueId } : {}), + }, + }); + } catch (err) { + // Keep the marker intact for the next startup/periodic sweep. + logger.warn( + { err, runId: request.id }, + "native question cancellation recovery attempt failed", + ); + } + } + // Find all runs stuck in "running" state (queued runs are legitimately waiting; resumeQueuedRuns handles them) const activeRuns = await db .select({ diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index 118e075e85..ccca8310de 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -107,6 +107,11 @@ type InteractionActor = { resolutionDetails?: Record; }; +type CreateInteractionOptions = { + /** Keep independently owned pending cards actionable. Internal runtime bridges use this. */ + supersedePendingSiblingInteractions?: boolean; +}; + type InteractionWakeup = (agentId: string, options: { source: "automation"; triggerDetail: "system"; @@ -128,6 +133,14 @@ export type IssueThreadInteractionServiceOptions = { now?: () => Date; }; +type DbTransaction = Parameters[0]>[0]; +type InteractionResolutionMutationOptions = { + afterResolveInTransaction?: ( + tx: DbTransaction, + interaction: IssueThreadInteraction, + ) => Promise; +}; + const GITHUB_PULL_REQUEST_URL_PATTERN = /https:\/\/(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/([1-9][0-9]*)/gi; const GITHUB_PULL_REQUEST_SHORTHAND_PATTERN = /(^|[^A-Za-z0-9_.-])([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#([1-9][0-9]*)\b/g; const MERGE_CONFIRMATION_INTENT_PATTERN = /^(?:please\s+)?(?:confirm(?:\s+that)?\s+.{0,80}\s+)?(?:merge|merged)\b|\bready\s+to\s+merge\b/i; @@ -2469,6 +2482,7 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti issue: { id: string; companyId: string }, input: CreateIssueThreadInteraction, actor: InteractionActor, + options: CreateInteractionOptions = {}, ) => { const data = normalizeCreateInteractionInput(createIssueThreadInteractionSchema.parse(input)); const usedDeprecatedResolverPolicyAlias = @@ -2634,10 +2648,13 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti // result shape. Scoped strictly to the same agent + issue + kind, so // other agents' or other kinds' pending cards are untouched. const canSupersedeSiblingCards = - (data.kind === "request_confirmation" - && data.payload.toolAction === undefined - && data.payload.secretProposal === undefined) - || data.kind === "ask_user_questions"; + options.supersedePendingSiblingInteractions !== false + && ( + (data.kind === "request_confirmation" + && data.payload.toolAction === undefined + && data.payload.secretProposal === undefined) + || data.kind === "ask_user_questions" + ); if (!actor.agentId || !canSupersedeSiblingCards) { return { row, supersededRows: [] }; } @@ -3481,6 +3498,7 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti interactionId: string, input: WithdrawIssueThreadInteraction, actor: InteractionActor, + mutationOptions: InteractionResolutionMutationOptions = {}, ) => { assertIssueOpenForInteractionResolution(issue); const data = withdrawIssueThreadInteractionSchema.parse(input); @@ -3546,6 +3564,7 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti )) .returning(); if (!row) throw interactionAlreadyResolvedError(); + await mutationOptions.afterResolveInTransaction?.(tx, hydrateInteraction(row)); return row; }); @@ -3628,6 +3647,7 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti interactionId: string, input: CancelIssueThreadInteraction, actor: InteractionActor, + mutationOptions: InteractionResolutionMutationOptions = {}, ) => { assertIssueOpenForInteractionResolution(issue); const data = cancelIssueThreadInteractionSchema.parse(input); @@ -3649,32 +3669,35 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti } const reason = data.reason?.trim() || null; - const [updated] = await db - .update(issueThreadInteractions) - .set({ - status: "cancelled", - result: { - version: 1, - answers: [], - cancelled: true, - cancellationReason: reason, - summaryMarkdown: null, - }, - resolvedByAgentId: actor.agentId ?? null, - resolvedByRunId: actor.runId ?? null, - resolvedByUserId: actor.userId ?? null, - resolvedAt: new Date(), - updatedAt: new Date(), - }) - .where(and( - eq(issueThreadInteractions.id, interactionId), - eq(issueThreadInteractions.status, "pending"), - )) - .returning(); + const updated = await db.transaction(async (tx) => { + const resolvedAt = new Date(); + const [row] = await tx + .update(issueThreadInteractions) + .set({ + status: "cancelled", + result: { + version: 1, + answers: [], + cancelled: true, + cancellationReason: reason, + summaryMarkdown: null, + }, + resolvedByAgentId: actor.agentId ?? null, + resolvedByRunId: actor.runId ?? null, + resolvedByUserId: actor.userId ?? null, + resolvedAt, + updatedAt: resolvedAt, + }) + .where(and( + eq(issueThreadInteractions.id, interactionId), + eq(issueThreadInteractions.status, "pending"), + )) + .returning(); - if (!updated) { - throw interactionAlreadyResolvedError(); - } + if (!row) throw interactionAlreadyResolvedError(); + await mutationOptions.afterResolveInTransaction?.(tx, hydrateInteraction(row)); + return row; + }); await touchIssue(db, issue.id); const cancelled = hydrateInteraction(updated); diff --git a/server/src/services/issue-tree-control.ts b/server/src/services/issue-tree-control.ts index 8ab640c865..afce7b6e75 100644 --- a/server/src/services/issue-tree-control.ts +++ b/server/src/services/issue-tree-control.ts @@ -22,7 +22,7 @@ import { type IssueTreePreviewWarning, } from "@paperclipai/shared"; import { conflict, notFound, unprocessable } from "../errors.js"; -import { finalizeSummarySlotsForTerminalIssue } from "./summary-slot-finalization.js"; +import type { IssuePostCommitAction } from "./issues.js"; type IssueRow = typeof issues.$inferSelect; type HoldRow = typeof issueTreeHolds.$inferSelect; @@ -886,43 +886,40 @@ export function issueTreeControlService(db: Db) { if (issueIds.length === 0) return { updatedIssueIds: [], updatedIssues: [] }; const now = new Date(); + const postCommitIssueActions: IssuePostCommitAction[] = []; + const { executeIssuePostCommitActions, issueService } = await import("./issues.js"); + const svc = issueService(db); const updated = await db.transaction(async (tx) => { - const rows = await tx - .update(issues) - .set({ - status: "cancelled", - cancelledAt: now, - completedAt: null, - checkoutRunId: null, - executionRunId: null, - executionAgentNameKey: null, - executionLockedAt: null, - updatedAt: now, - }) + const eligibleIssues = await tx + .select({ id: issues.id }) + .from(issues) .where( and( eq(issues.companyId, companyId), inArray(issues.id, issueIds), notInArray(issues.status, ["done", "cancelled"]), ), - ) - .returning({ - id: issues.id, - companyId: issues.companyId, - identifier: issues.identifier, - title: issues.title, - status: issues.status, - assigneeAgentId: issues.assigneeAgentId, - }); + ); - for (const issue of rows) { - await finalizeSummarySlotsForTerminalIssue(tx, { - ...issue, - status: coerceIssueStatus(issue.status), - }); + const rows = []; + for (const issue of eligibleIssues) { + const updatedIssue = await svc.update( + issue.id, + { + status: "cancelled", + cancelledAt: now, + actorAgentId: hold.createdByAgentId, + actorUserId: hold.createdByUserId, + }, + tx, + undefined, + postCommitIssueActions, + ); + if (updatedIssue) rows.push(updatedIssue); } return rows; }); + await executeIssuePostCommitActions(db, postCommitIssueActions); return { updatedIssueIds: updated.map((issue) => issue.id), diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index 640ece5d7b..b3c8557201 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -164,6 +164,44 @@ const ISSUE_CREATE_IDEMPOTENCY_KEY_CLEANUP_BATCH_SIZE = 500; const DELETED_ISSUE_COMMENT_BODY = ""; const ISSUE_WAKE_DIAGNOSTICS_ACTIVITY_ACTIONS = ["issue.tree_hold_wakeup_deferred"] as const; +export type IssuePostCommitAction = { + type: "cancel_native_question_run"; + runId: string; + issueId: string; + issueStatus: string; +}; + +/** Execute side effects that must never run before the issue transaction commits. */ +export async function executeIssuePostCommitActions( + db: Db, + actions: readonly IssuePostCommitAction[], +): Promise { + if (actions.length === 0) return; + const { heartbeatService } = await import("./heartbeat.js"); + const heartbeat = heartbeatService(db); + const cancelledRunIds = new Set(); + for (const action of actions) { + if (cancelledRunIds.has(action.runId)) continue; + cancelledRunIds.add(action.runId); + try { + await heartbeat.cancelRun(action.runId, "Task closed while waiting for operator input", { + resultJson: { + cancelledByIssueStatus: action.issueStatus, + cancelledIssueId: action.issueId, + }, + }); + } catch (err) { + // The durable marker written by the issue transaction remains available + // to startup and periodic recovery. Do not report a post-commit failure + // as though the already-committed issue transition had rolled back. + logger.warn( + { err, runId: action.runId, issueId: action.issueId }, + "native question cancellation deferred to recovery sweep", + ); + } + } +} + function wakeRequestTargetsIssue(issueId: string) { return sql`( ${agentWakeupRequests.payload} ->> 'issueId' = ${issueId} @@ -7711,9 +7749,12 @@ export function issueService(db: Db) { }, dbOrTx: any = db, postCommitActivityPublications?: ActivityPublication[], + postCommitActions?: IssuePostCommitAction[], ) => { const ownedActivityPublications: ActivityPublication[] = []; const activityPublications = postCommitActivityPublications ?? ownedActivityPublications; + const ownedPostCommitActions: IssuePostCommitAction[] = []; + const queuedPostCommitActions = postCommitActions ?? ownedPostCommitActions; const existing = await dbOrTx .select() .from(issues) @@ -7960,7 +8001,36 @@ export function issueService(db: Db) { updated, { agentId: actorAgentId ?? null, userId: actorUserId ?? null }, ); + const { + nativeQuestionCancellationIdentity, + requestNativeQuestionRunCancellation, + } = await import( + "./native-runtime/native-question-bridge.js" + ); for (const interaction of expiredInteractions) { + if (interaction.kind === "ask_user_questions") { + const nativeQuestion = nativeQuestionCancellationIdentity(interaction); + if (nativeQuestion) { + if (dbOrTx !== db && !postCommitActions) { + throw new Error( + "Terminal native question updates in an external transaction require a post-commit action queue", + ); + } + const runId = await requestNativeQuestionRunCancellation( + tx, + nativeQuestion, + { kind: "issue_terminal", issueStatus: updated.status }, + ); + if (runId) { + queuedPostCommitActions.push({ + type: "cancel_native_question_run", + runId, + issueId: updated.id, + issueStatus: updated.status, + }); + } + } + } await logActivity(tx as unknown as Db, { companyId: updated.companyId, actorType: actorAgentId ? "agent" : actorUserId ? "user" : "system", @@ -8122,6 +8192,9 @@ export function issueService(db: Db) { if (dbOrTx === db && !postCommitActivityPublications) { for (const publication of ownedActivityPublications) publishActivity(publication); } + if (dbOrTx === db && !postCommitActions) { + await executeIssuePostCommitActions(db, ownedPostCommitActions); + } return result; }, diff --git a/server/src/services/native-runtime/native-question-bridge.test.ts b/server/src/services/native-runtime/native-question-bridge.test.ts new file mode 100644 index 0000000000..3c04925ebf --- /dev/null +++ b/server/src/services/native-runtime/native-question-bridge.test.ts @@ -0,0 +1,490 @@ +import { randomUUID } from "node:crypto"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { eq, sql } from "drizzle-orm"; + +import { + activityLog, + agents, + companies, + createDb, + heartbeatRuns, + issueQuestionResponseDeliveries, + issueThreadInteractions, + issues, +} from "@paperclipai/db"; +import type { PrpEvent } from "@paperclipai/paperclip-runner"; + +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "../../__tests__/helpers/embedded-postgres.js"; +import { issueThreadInteractionService } from "../issue-thread-interactions.js"; +import { + deliverNativeQuestionResponse, + flushNativeQuestionResponses, + nativeQuestionBridgeInternals, + nativeQuestionRunToCancel, + projectNativeRuntimeRequest, + registerNativeQuestionCommandTarget, + requestNativeQuestionRunCancellation, + validateNativeQuestionResponseInput, +} from "./native-question-bridge.js"; +import { + executeIssuePostCommitActions, + issueService, + type IssuePostCommitAction, +} from "../issues.js"; +import { heartbeatService } from "../heartbeat.js"; + +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; + +if (!embeddedPostgresSupport.supported) { + console.warn( + `Skipping native question bridge tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`, + ); +} + +describeEmbeddedPostgres("native question bridge", () => { + let temporary: Awaited> | null = null; + let db: ReturnType; + let companyId: string; + let issueId: string; + let agentId: string; + let runId: string; + let sessionId: string; + let runnerInstanceId: string; + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("paperclip-native-question-"); + db = createDb(temporary.connectionString); + }, 20_000); + + afterEach(async () => { + nativeQuestionBridgeInternals.resetForTests(); + await db.execute(sql.raw(` + TRUNCATE TABLE + "activity_log", + "issue_thread_interactions", + "heartbeat_runs", + "agent_wakeup_requests", + "issues", + "agents", + "companies" + RESTART IDENTITY CASCADE + `)); + }); + + afterAll(async () => temporary?.cleanup()); + + async function seed() { + companyId = randomUUID(); + issueId = randomUUID(); + agentId = randomUUID(); + runId = randomUUID(); + sessionId = randomUUID(); + runnerInstanceId = randomUUID(); + await db.insert(companies).values({ + id: companyId, + name: "Native questions", + issuePrefix: `NQ${companyId.replaceAll("-", "").slice(0, 6).toUpperCase()}`, + requireBoardApprovalForNewAgents: false, + }); + await db.insert(agents).values({ + id: agentId, + companyId, + name: "Native Codex", + adapterType: "paperclip_runner", + status: "running", + adapterConfig: { provider: "codex" }, + runtimeConfig: {}, + }); + await db.insert(issues).values({ + id: issueId, + companyId, + title: "Answer a native question", + status: "in_progress", + assigneeAgentId: agentId, + }); + await db.insert(heartbeatRuns).values({ + id: runId, + companyId, + agentId, + status: "running", + runtimeMode: "native", + runtimeModeResolvedAt: new Date(), + nativeIssueId: issueId, + nativeSessionId: sessionId, + runnerInstanceId, + driverKind: "codex", + contextSnapshot: { issueId }, + }); + } + + function runtimeRequestEvent(): PrpEvent { + return { + schema: "paperclip.prp.event.v1", + sourceEventId: "runtime-question-1", + sourceSeq: 1, + sourceInstanceId: runnerInstanceId, + sourceKind: "runner", + runId, + normalizedSessionId: sessionId, + turnId: "turn-1", + itemId: "item-1", + eventType: "runtime_request.created", + schemaVersion: 1, + priority: 0, + emittedAt: "2026-08-25T18:00:00.000Z", + payload: { + request: { + schema: "paperclip.runtime_request.v2", + requestKind: "runtime", + requestId: "request-1", + type: "input", + status: "pending", + prompt: "Choose a deployment color", + input: { + schema: "paperclip.question_set.v1", + title: "Deployment", + questions: [{ + id: "color", + prompt: "Which color?", + required: true, + answerMode: "single_select", + options: [ + { id: "blue", label: "Blue" }, + { id: "green", label: "Green" }, + ], + }], + }, + }, + }, + }; + } + + function binding() { + return { + companyId, + issueId, + runId, + agentId, + normalizedSessionId: sessionId, + runnerSourceInstanceId: runnerInstanceId, + completionContractId: randomUUID(), + completionContractSha256: `sha256:${"a".repeat(64)}`, + completionContractRevision: "1", + completionContractCriterionIds: [], + }; + } + + it("materializes, validates, and durably resumes a provider-neutral question response", async () => { + await seed(); + const interaction = await projectNativeRuntimeRequest({ + db, + binding: binding(), + event: runtimeRequestEvent(), + }); + + expect(interaction).toMatchObject({ + kind: "ask_user_questions", + status: "pending", + sourceRunId: runId, + continuationPolicy: "none", + effectiveResolverPolicy: "human_only", + payload: { + runtimeRequestId: "request-1", + supersedeOnUserComment: false, + questionSet: { schema: "paperclip.question_set.v1" }, + questions: [{ + id: "color", + selectionMode: "single", + allowOther: false, + options: [{ id: "blue", label: "Blue" }, { id: "green", label: "Green" }], + }], + }, + }); + expect(await db.select().from(activityLog)).toHaveLength(1); + + const answer = { answers: [{ questionId: "color", optionIds: ["blue"] }] }; + validateNativeQuestionResponseInput(interaction!, answer); + expect(() => validateNativeQuestionResponseInput(interaction!, { + answers: [{ questionId: "color", optionIds: ["red"] }], + })).toThrow(/unknown option red/); + + const answered = await issueThreadInteractionService(db).answerQuestions( + { id: issueId, companyId, status: "in_progress" }, + interaction!.id, + answer, + { userId: "operator-1" }, + ); + const queueCommand = vi.fn(() => ({ commandId: "question", controllerSeq: 1 })); + const release = registerNativeQuestionCommandTarget({ + binding: { companyId, issueId, runId, agentId }, + queueCommand, + }); + + await flushNativeQuestionResponses(db, runId); + expect(queueCommand).toHaveBeenCalledWith( + "request.resolve", + { + requestId: "request-1", + response: { + schema: "paperclip.question_response.v1", + answers: { color: { selectedOptionIds: ["blue"] } }, + }, + }, + `question_${interaction!.id}`, + ); + expect(queueCommand).toHaveBeenCalledTimes(1); + const [delivery] = await db.select().from(issueQuestionResponseDeliveries); + expect(delivery).toMatchObject({ + interactionId: interaction!.id, + status: "delivered", + deliveryMode: "steered", + targetRunId: runId, + }); + expect(answered.kind).toBe("ask_user_questions"); + if (answered.kind !== "ask_user_questions") throw new Error("expected question interaction"); + await expect(nativeQuestionRunToCancel(db, answered)).resolves.toBe(runId); + release(); + }); + + it("binds projection to the persisted native run and ignores legacy delivery", async () => { + await seed(); + const mismatched = runtimeRequestEvent(); + mismatched.runId = randomUUID(); + await expect(projectNativeRuntimeRequest({ db, binding: binding(), event: mismatched })) + .rejects.toThrow("native_runtime_request_binding_mismatch"); + + const interaction = await projectNativeRuntimeRequest({ + db, + binding: binding(), + event: runtimeRequestEvent(), + }); + const answered = await issueThreadInteractionService(db).answerQuestions( + { id: issueId, companyId, status: "in_progress" }, + interaction!.id, + { answers: [{ questionId: "color", optionIds: ["green"] }] }, + { userId: "operator-1" }, + ); + await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, runId)); + expect(answered.kind).toBe("ask_user_questions"); + if (answered.kind !== "ask_user_questions") throw new Error("expected question interaction"); + await expect(deliverNativeQuestionResponse(db, answered)).resolves.toBe("not_native"); + await expect(nativeQuestionRunToCancel(db, answered)).resolves.toBeNull(); + }); + + it("does not duplicate the task card when the runner replays a request", async () => { + await seed(); + const first = await projectNativeRuntimeRequest({ db, binding: binding(), event: runtimeRequestEvent() }); + const second = await projectNativeRuntimeRequest({ db, binding: binding(), event: runtimeRequestEvent() }); + expect(second?.id).toBe(first?.id); + expect(await db.select().from(issueThreadInteractions)).toHaveLength(1); + expect(await db.select().from(activityLog)).toHaveLength(1); + }); + + it("cancels the active native run when the shared issue service expires its question", async () => { + await seed(); + const interaction = await projectNativeRuntimeRequest({ + db, + binding: binding(), + event: runtimeRequestEvent(), + }); + await issueService(db).update(issueId, { status: "cancelled" }); + + const [persistedInteraction] = await db.select({ status: issueThreadInteractions.status }) + .from(issueThreadInteractions) + .where(eq(issueThreadInteractions.id, interaction!.id)); + const [persistedRun] = await db.select({ + status: heartbeatRuns.status, + resultJson: heartbeatRuns.resultJson, + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(persistedInteraction?.status).toBe("expired"); + expect(persistedRun).toMatchObject({ + status: "cancelled", + resultJson: { + cancelledByIssueStatus: "cancelled", + cancelledIssueId: issueId, + }, + }); + }); + + it("defers native cancellation until an external issue transaction commits", async () => { + await seed(); + await projectNativeRuntimeRequest({ + db, + binding: binding(), + event: runtimeRequestEvent(), + }); + const postCommitActions: IssuePostCommitAction[] = []; + await db.transaction(async (tx) => { + await issueService(db).update( + issueId, + { status: "done" }, + tx, + undefined, + postCommitActions, + ); + const [runInsideTransaction] = await tx.select({ status: heartbeatRuns.status }) + .from(heartbeatRuns) + .where(eq(heartbeatRuns.id, runId)); + expect(runInsideTransaction?.status).toBe("running"); + }); + + expect(postCommitActions).toHaveLength(1); + await executeIssuePostCommitActions(db, postCommitActions); + const [persistedRun] = await db.select({ status: heartbeatRuns.status }) + .from(heartbeatRuns) + .where(eq(heartbeatRuns.id, runId)); + expect(persistedRun?.status).toBe("cancelled"); + }); + + it("recovers a durable native cancellation when the post-commit process exits", async () => { + await seed(); + await projectNativeRuntimeRequest({ + db, + binding: binding(), + event: runtimeRequestEvent(), + }); + const postCommitActions: IssuePostCommitAction[] = []; + await db.transaction(async (tx) => { + await issueService(db).update( + issueId, + { status: "done" }, + tx, + undefined, + postCommitActions, + ); + }); + + const [markedRun] = await db.select({ + status: heartbeatRuns.status, + contextSnapshot: heartbeatRuns.contextSnapshot, + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(markedRun).toMatchObject({ + status: "running", + contextSnapshot: { + nativeQuestionCancellation: { + version: 1, + issueId, + issueStatus: "done", + }, + }, + }); + + // Simulate process exit before executeIssuePostCommitActions can run. + await heartbeatService(db).reapOrphanedRuns(); + + const [persistedRun] = await db.select({ + status: heartbeatRuns.status, + resultJson: heartbeatRuns.resultJson, + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(persistedRun).toMatchObject({ + status: "cancelled", + resultJson: { + cancelledByIssueStatus: "done", + cancelledIssueId: issueId, + }, + }); + }); + + it("recovers an explicit question withdrawal committed with its cancellation intent", async () => { + await seed(); + const interaction = await projectNativeRuntimeRequest({ + db, + binding: binding(), + event: runtimeRequestEvent(), + }); + await issueThreadInteractionService(db).withdrawInteraction( + { id: issueId, companyId }, + interaction!.id, + { reason: "No longer needed" }, + { userId: "operator-1" }, + { + afterResolveInTransaction: async (tx, withdrawn) => { + await expect(requestNativeQuestionRunCancellation(tx, withdrawn, { + kind: "interaction_withdrawn", + interactionId: withdrawn.id, + })).resolves.toBe(runId); + }, + }, + ); + + const [markedRun] = await db.select({ contextSnapshot: heartbeatRuns.contextSnapshot }) + .from(heartbeatRuns) + .where(eq(heartbeatRuns.id, runId)); + expect(markedRun?.contextSnapshot).toMatchObject({ + nativeQuestionCancellation: { + version: 1, + kind: "interaction_withdrawn", + interactionId: interaction!.id, + issueId, + }, + }); + + await heartbeatService(db).reapOrphanedRuns(); + + const [cancelledRun] = await db.select({ + status: heartbeatRuns.status, + resultJson: heartbeatRuns.resultJson, + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(cancelledRun).toMatchObject({ + status: "cancelled", + resultJson: { + withdrawnInteractionId: interaction!.id, + cancelledIssueId: issueId, + }, + }); + }); + + it("removes the UI-only marker from a canonical custom response", async () => { + await seed(); + const event = runtimeRequestEvent(); + const request = event.payload.request as Record; + const input = request.input as Record; + input.questions = [{ + id: "color", + prompt: "Which color?", + required: true, + answerMode: "single_select", + options: [{ id: "blue", label: "Blue" }], + customAnswer: { enabled: true, label: "Another color" }, + }]; + const interaction = await projectNativeRuntimeRequest({ db, binding: binding(), event }); + const answer = { + answers: [{ + questionId: "color", + optionIds: ["paperclip_custom_answer"], + otherText: "purple", + }], + }; + validateNativeQuestionResponseInput(interaction!, answer); + const answered = await issueThreadInteractionService(db).answerQuestions( + { id: issueId, companyId, status: "in_progress" }, + interaction!.id, + answer, + { userId: "operator-1" }, + ); + expect(answered.kind).toBe("ask_user_questions"); + if (answered.kind !== "ask_user_questions") throw new Error("expected question interaction"); + + const queueCommand = vi.fn(() => ({ commandId: "question", controllerSeq: 1 })); + registerNativeQuestionCommandTarget({ + binding: { companyId, issueId, runId, agentId }, + queueCommand, + }); + await expect(deliverNativeQuestionResponse(db, answered)).resolves.toBe("queued"); + expect(queueCommand).toHaveBeenCalledWith( + "request.resolve", + { + requestId: "request-1", + response: { + schema: "paperclip.question_response.v1", + answers: { color: { selectedOptionIds: [], customText: "purple" } }, + }, + }, + `question_${interaction!.id}`, + ); + }); +}); diff --git a/server/src/services/native-runtime/native-question-bridge.ts b/server/src/services/native-runtime/native-question-bridge.ts new file mode 100644 index 0000000000..391320d4e8 --- /dev/null +++ b/server/src/services/native-runtime/native-question-bridge.ts @@ -0,0 +1,444 @@ +import { and, eq, inArray, sql } from "drizzle-orm"; + +import type { Db } from "@paperclipai/db"; +import { heartbeatRuns, issueThreadInteractions } from "@paperclipai/db"; +import type { + AskUserQuestionsAnswer, + AskUserQuestionsInteraction, + AskUserQuestionsQuestionOption, + PaperclipQuestionSetPayload, + RespondIssueThreadInteraction, +} from "@paperclipai/shared"; + +import type { PrpEvent } from "../../vendor/paperclip-runner/index.js"; +import { + parsePaperclipQuestionResponse, + parsePaperclipQuestionSet, + type PaperclipQuestionResponse, + type PaperclipQuestionSet, +} from "../../vendor/paperclip-runner/index.js"; +import { logger } from "../../middleware/logger.js"; +import { unprocessable } from "../../errors.js"; +import { logActivity } from "../activity-log.js"; +import { issueThreadInteractionService } from "../issue-thread-interactions.js"; +import { questionResponseDeliveryService } from "../question-response-delivery.js"; +import type { NativeRunStoreBinding } from "./native-run-coordinator-store.js"; + +const QUESTION_KEY_PREFIX = "paperclip-runner-question:"; +const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/; +const TEXT_ANSWER_OPTION_ID = "paperclip_text_answer"; +const CUSTOM_ANSWER_OPTION_ID = "paperclip_custom_answer"; +export const NATIVE_QUESTION_CANCELLATION_CONTEXT_KEY = "nativeQuestionCancellation"; + +type QueueCommand = ( + type: string, + payload?: Record, + commandId?: string, +) => { readonly commandId: string; readonly controllerSeq: number }; + +interface NativeQuestionCommandTarget { + binding: Pick; + queueCommand: QueueCommand; +} + +const activeTargets = new Map(); + +interface NativeQuestionIdentity { + idempotencyKey?: string | null; + sourceRunId?: string | null; + payload: unknown; +} + +export interface NativeQuestionAuthorizationIdentity extends NativeQuestionIdentity { + companyId: string; + issueId: string; +} + +export type NativeQuestionCancellationCause = + | { kind: "issue_terminal"; issueStatus: string } + | { kind: "interaction_withdrawn"; interactionId: string } + | { kind: "interaction_cancelled"; interactionId: string }; + +type DbTransaction = Parameters[0]>[0]; +type NativeQuestionMutationDb = Pick; + +function record(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) + ? value as Record + : null; +} + +function requestIdForInteraction( + interaction: NativeQuestionIdentity, +): string | null { + const payload = record(interaction.payload); + if (!interaction.sourceRunId || !payload?.questionSet) return null; + const key = interaction.idempotencyKey; + const expectedPrefix = `${QUESTION_KEY_PREFIX}${interaction.sourceRunId}:`; + if (!key?.startsWith(expectedPrefix)) return null; + const requestId = key.slice(expectedPrefix.length); + if (!REQUEST_ID_PATTERN.test(requestId)) return null; + return typeof payload.runtimeRequestId === "string" && payload.runtimeRequestId !== requestId + ? null + : requestId; +} + +function uniqueSyntheticOptionId(existing: readonly string[], preferred: string): string { + const ids = new Set(existing); + if (!ids.has(preferred)) return preferred; + for (let suffix = 2; suffix < 10_000; suffix += 1) { + const candidate = `${preferred}_${suffix}`; + if (!ids.has(candidate)) return candidate; + } + throw new Error("native_question_synthetic_option_exhausted"); +} + +function toInteractionPayload(questionSet: PaperclipQuestionSet, runtimeRequestId: string) { + return { + version: 1 as const, + ...(questionSet.title ? { title: questionSet.title.slice(0, 240) } : {}), + ...(questionSet.submitLabel ? { submitLabel: questionSet.submitLabel.slice(0, 120) } : {}), + questions: questionSet.questions.map((question) => { + const canonicalOptions = question.options ?? []; + const options: AskUserQuestionsQuestionOption[] = canonicalOptions.map((option) => ({ + id: option.id, + label: option.label, + ...(option.description ? { description: option.description } : {}), + })); + if (question.answerMode === "text") { + options.push({ + id: uniqueSyntheticOptionId([], TEXT_ANSWER_OPTION_ID), + label: question.header ?? "Type an answer", + ...(question.textValidation?.inputType + ? { description: `Expected ${question.textValidation.inputType} input` } + : {}), + freeText: true, + }); + } else if (question.customAnswer?.enabled) { + options.push({ + id: uniqueSyntheticOptionId(canonicalOptions.map((option) => option.id), CUSTOM_ANSWER_OPTION_ID), + label: question.customAnswer.label ?? "Other", + ...(question.customAnswer.placeholder ? { description: question.customAnswer.placeholder } : {}), + freeText: true, + }); + } + return { + id: question.id, + prompt: question.prompt, + ...((question.helpText || question.header) + ? { helpText: question.helpText ?? question.header } + : {}), + selectionMode: question.answerMode === "multi_select" ? "multi" as const : "single" as const, + required: question.required, + allowOther: question.answerMode === "text" || question.customAnswer?.enabled === true, + options, + }; + }), + questionSet: questionSet as PaperclipQuestionSetPayload, + runtimeRequestId, + // A generic task comment cannot satisfy this provider request. Keep the + // card actionable until a validated answer or an explicit terminal action. + supersedeOnUserComment: false, + }; +} + +function canonicalResponse( + questionSet: PaperclipQuestionSetPayload, + answers: readonly AskUserQuestionsAnswer[], +): PaperclipQuestionResponse { + const answerByQuestionId = new Map(answers.map((answer) => [answer.questionId, answer])); + const response: PaperclipQuestionResponse = { + schema: "paperclip.question_response.v1", + answers: {}, + }; + for (const question of questionSet.questions) { + const answer = answerByQuestionId.get(question.id); + if (!answer) continue; + if (question.answerMode === "text") { + response.answers[question.id] = { + ...(answer.otherText !== undefined && answer.otherText !== null + ? { text: answer.otherText } + : {}), + }; + } else { + const customOptionId = question.customAnswer?.enabled + ? uniqueSyntheticOptionId( + (question.options ?? []).map((option) => option.id), + CUSTOM_ANSWER_OPTION_ID, + ) + : null; + response.answers[question.id] = { + selectedOptionIds: answer.optionIds.filter((optionId) => optionId !== customOptionId), + ...(answer.otherText !== undefined && answer.otherText !== null + ? { customText: answer.otherText } + : {}), + }; + } + } + return parsePaperclipQuestionResponse(questionSet, response); +} + +async function authorizedNativeRun( + db: Pick, + interaction: NativeQuestionAuthorizationIdentity, +) { + const requestId = requestIdForInteraction(interaction); + if (!requestId || !interaction.sourceRunId) return null; + const run = await db.select({ + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + issueId: heartbeatRuns.nativeIssueId, + agentId: heartbeatRuns.agentId, + runtimeMode: heartbeatRuns.runtimeMode, + status: heartbeatRuns.status, + }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, interaction.sourceRunId), + eq(heartbeatRuns.companyId, interaction.companyId), + eq(heartbeatRuns.nativeIssueId, interaction.issueId), + eq(heartbeatRuns.runtimeMode, "native"), + )).limit(1).then((rows) => rows[0] ?? null); + return run ? { ...run, requestId } : null; +} + +/** Materialize a canonical runtime input request as the existing task-thread card. */ +export async function projectNativeRuntimeRequest(input: { + db: Db; + binding: NativeRunStoreBinding; + event: PrpEvent; +}): Promise { + if (input.event.eventType !== "runtime_request.created") return null; + if ( + input.event.runId !== input.binding.runId + || input.event.normalizedSessionId !== input.binding.normalizedSessionId + || input.event.sourceInstanceId !== input.binding.runnerSourceInstanceId + ) { + throw new Error("native_runtime_request_binding_mismatch"); + } + const request = record(record(input.event.payload)?.request); + if ( + !request + || request.schema !== "paperclip.runtime_request.v2" + || request.requestKind !== "runtime" + || request.type !== "input" + || request.status !== "pending" + || typeof request.requestId !== "string" + || !REQUEST_ID_PATTERN.test(request.requestId) + ) { + throw new Error("native_runtime_request_invalid"); + } + const questionSet = parsePaperclipQuestionSet(request.input); + if (questionSet.questions.some((question) => question.textValidation?.pattern !== undefined)) { + // JavaScript regular expressions have no execution budget. Provider-authored + // patterns therefore stay fail-closed until the runner contract supplies a + // bounded regex dialect rather than exposing the server to catastrophic backtracking. + throw new Error("native_runtime_question_pattern_unsupported"); + } + const idempotencyKey = `${QUESTION_KEY_PREFIX}${input.binding.runId}:${request.requestId}`; + const existing = await input.db.select({ id: issueThreadInteractions.id }) + .from(issueThreadInteractions) + .where(and( + eq(issueThreadInteractions.companyId, input.binding.companyId), + eq(issueThreadInteractions.issueId, input.binding.issueId), + eq(issueThreadInteractions.idempotencyKey, idempotencyKey), + )) + .limit(1) + .then((rows) => rows[0] ?? null); + const interaction = await issueThreadInteractionService(input.db).create( + { id: input.binding.issueId, companyId: input.binding.companyId }, + { + kind: "ask_user_questions", + idempotencyKey, + sourceRunId: input.binding.runId, + resolverPolicy: "human_only", + continuationPolicy: "none", + ...(questionSet.title ? { title: questionSet.title.slice(0, 240) } : {}), + ...(typeof request.prompt === "string" ? { summary: request.prompt.slice(0, 1000) } : {}), + payload: toInteractionPayload(questionSet, request.requestId), + }, + { agentId: input.binding.agentId, runId: input.binding.runId }, + { supersedePendingSiblingInteractions: false }, + ) as AskUserQuestionsInteraction; + if (!existing) { + await logActivity(input.db, { + companyId: input.binding.companyId, + actorType: "agent", + actorId: input.binding.agentId, + agentId: input.binding.agentId, + runId: input.binding.runId, + action: "issue.thread_interaction_created", + entityType: "issue", + entityId: input.binding.issueId, + details: { + interactionId: interaction.id, + interactionKind: interaction.kind, + interactionStatus: interaction.status, + runtimeMode: "native", + }, + }); + } + if (interaction.status === "answered") { + await deliverNativeQuestionResponseDurably(input.db, interaction); + } + return interaction; +} + +/** Validate untrusted board input before the existing interaction service persists it. */ +export function validateNativeQuestionResponseInput( + interaction: AskUserQuestionsInteraction, + input: RespondIssueThreadInteraction, +): void { + if (!requestIdForInteraction(interaction) || !interaction.payload.questionSet) return; + try { + canonicalResponse(interaction.payload.questionSet, input.answers); + } catch (error) { + throw unprocessable( + error instanceof Error ? error.message : "Invalid native question response", + { code: "invalid_question_response" }, + ); + } +} + +/** Queue an answered interaction into the active durable PRP command stream. */ +export async function deliverNativeQuestionResponse( + db: Db, + interaction: AskUserQuestionsInteraction, +): Promise<"not_native" | "pending" | "queued"> { + if (interaction.status !== "answered" || !interaction.result || !interaction.payload.questionSet) { + return "not_native"; + } + const run = await authorizedNativeRun(db, interaction); + if (!run) return "not_native"; + const response = canonicalResponse(interaction.payload.questionSet, interaction.result.answers); + const target = activeTargets.get(run.id); + if ( + !target + || target.binding.companyId !== run.companyId + || target.binding.issueId !== run.issueId + || target.binding.agentId !== run.agentId + ) { + return "pending"; + } + try { + target.queueCommand( + "request.resolve", + { requestId: run.requestId, response: response as unknown as Record }, + `question_${interaction.id}`, + ); + return "queued"; + } catch (error) { + logger.warn( + { err: error, runId: run.id, interactionId: interaction.id }, + "native question response remains durable for session recovery", + ); + return "pending"; + } +} + +async function deliverNativeQuestionResponseDurably( + db: Db, + interaction: AskUserQuestionsInteraction, +): Promise { + await questionResponseDeliveryService(db, { + heartbeat: { + wakeup: async () => { + throw new Error("native_question_wake_unreachable"); + }, + } as never, + resolveNativeQuestion: (candidate) => deliverNativeQuestionResponse(db, candidate), + }).deliver(interaction.id); +} + +export async function flushNativeQuestionResponses( + db: Db, + runId: string, +): Promise { + const target = activeTargets.get(runId); + if (!target) return; + const interactions = await issueThreadInteractionService(db).listForIssue(target.binding.issueId); + for (const interaction of interactions) { + if ( + interaction.kind === "ask_user_questions" + && interaction.sourceRunId === runId + && interaction.status === "answered" + ) { + await deliverNativeQuestionResponseDurably(db, interaction); + } + } +} + +export function registerNativeQuestionCommandTarget(target: NativeQuestionCommandTarget): () => void { + const existing = activeTargets.get(target.binding.runId); + if (existing) throw new Error("native_question_command_target_conflict"); + activeTargets.set(target.binding.runId, target); + return () => { + if (activeTargets.get(target.binding.runId) === target) { + activeTargets.delete(target.binding.runId); + } + }; +} + +export async function nativeQuestionRunToCancel( + db: Db, + interaction: NativeQuestionAuthorizationIdentity, +): Promise { + const run = await authorizedNativeRun(db, interaction); + return run && ["queued", "running"].includes(run.status) ? run.id : null; +} + +/** + * Persist cancellation intent in the same transaction that closes the issue. + * The post-commit fast path and the heartbeat recovery sweep both consume this + * marker, so process exit or a transient process-termination failure cannot + * strand a native run after its question has expired. + */ +export async function requestNativeQuestionRunCancellation( + db: NativeQuestionMutationDb, + interaction: NativeQuestionAuthorizationIdentity, + cause: NativeQuestionCancellationCause, +): Promise { + const run = await authorizedNativeRun(db, interaction); + if (!run || !["queued", "running"].includes(run.status)) return null; + const marker = JSON.stringify({ + version: 1, + issueId: interaction.issueId, + ...cause, + requestedAt: new Date().toISOString(), + }); + return db.update(heartbeatRuns).set({ + contextSnapshot: sql`jsonb_set( + case + when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then ${heartbeatRuns.contextSnapshot} + else '{}'::jsonb + end, + array[${NATIVE_QUESTION_CANCELLATION_CONTEXT_KEY}], + ${marker}::jsonb, + true + )`, + updatedAt: new Date(), + }).where(and( + eq(heartbeatRuns.id, run.id), + eq(heartbeatRuns.companyId, interaction.companyId), + eq(heartbeatRuns.nativeIssueId, interaction.issueId), + eq(heartbeatRuns.runtimeMode, "native"), + inArray(heartbeatRuns.status, ["queued", "running"]), + )).returning({ id: heartbeatRuns.id }).then((rows) => rows[0]?.id ?? null); +} + +/** Capture the minimum bound identity needed to cancel after the issue transaction commits. */ +export function nativeQuestionCancellationIdentity( + interaction: NativeQuestionAuthorizationIdentity, +): NativeQuestionAuthorizationIdentity | null { + if (!requestIdForInteraction(interaction)) return null; + return { + companyId: interaction.companyId, + issueId: interaction.issueId, + sourceRunId: interaction.sourceRunId, + payload: interaction.payload, + idempotencyKey: interaction.idempotencyKey, + }; +} + +export const nativeQuestionBridgeInternals = { + resetForTests: () => activeTargets.clear(), +}; diff --git a/server/src/services/native-runtime/runner-prp-coordinator.ts b/server/src/services/native-runtime/runner-prp-coordinator.ts index 9d9d9f2f91..067e77903f 100644 --- a/server/src/services/native-runtime/runner-prp-coordinator.ts +++ b/server/src/services/native-runtime/runner-prp-coordinator.ts @@ -13,6 +13,11 @@ import { import { registerRunnerPrpAuthority } from "../../realtime/runner-prp-ws.js"; import { NativeRunCoordinatorStore } from "./native-run-coordinator-store.js"; +import { + flushNativeQuestionResponses, + projectNativeRuntimeRequest, + registerNativeQuestionCommandTarget, +} from "./native-question-bridge.js"; import { PaperclipRunnerSemanticAuthority } from "./runner-semantic-authority.js"; const UUID_PATTERN = @@ -214,7 +219,7 @@ export function runnerPrpCoordinator( agentId: input.agentId, }); const semanticTools = await semanticAuthority.listAlwaysAvailableTools(); - const nativeStore = new NativeRunCoordinatorStore(db, { + const storeBinding = { companyId: input.companyId, issueId: input.issueId, runId: input.runId, @@ -225,7 +230,8 @@ export function runnerPrpCoordinator( completionContractSha256: binding.run.completionContractSha256, completionContractRevision: String(binding.completionContract.revision), completionContractCriterionIds: criterionIds, - }); + } as const; + const nativeStore = new NativeRunCoordinatorStore(db, storeBinding); type StoredCompletedRun = NonNullable>>; type CompletedRun = StoredCompletedRun & { readonly providerSessionId?: string }; const withProviderSession = async (stored: StoredCompletedRun): Promise => { @@ -255,6 +261,9 @@ export function runnerPrpCoordinator( connectionLeaseTtlMs, onCommittedEvent: async (event) => { await nativeStore.appendEvent(event); + if (event.eventType === "runtime_request.created") { + await projectNativeRuntimeRequest({ db, binding: storeBinding, event }); + } await nativeStore.reconcileTerminalEvent(event); if (event.eventType === "run.terminal") { const stored = await nativeStore.readCompletedRun(); @@ -274,15 +283,38 @@ export function runnerPrpCoordinator( }, }); - const registration = await registerRunnerPrpAuthority({ - companyId: input.companyId, - runId: input.runId, - authority, - }); + let registration: Awaited>; + try { + registration = await registerRunnerPrpAuthority({ + companyId: input.companyId, + runId: input.runId, + authority, + }); + } catch (error) { + authority.disconnectActiveRunner(); + throw error; + } + let releaseQuestionTarget = () => {}; + try { + releaseQuestionTarget = registerNativeQuestionCommandTarget({ + binding: storeBinding, + queueCommand: (type, payload = {}, commandId) => { + const command = authority.queueCommand(type, payload, commandId, true); + return { commandId: command.commandId, controllerSeq: command.controllerSeq }; + }, + }); + await flushNativeQuestionResponses(db, input.runId); + } catch (error) { + releaseQuestionTarget(); + authority.disconnectActiveRunner(); + await registration.release(); + throw error; + } let bootstrapTicket: string; try { bootstrapTicket = authority.issueBootstrapTicket(bootstrapTtlMs); } catch (error) { + releaseQuestionTarget(); authority.disconnectActiveRunner(); await registration.release(); throw error; @@ -339,6 +371,7 @@ export function runnerPrpCoordinator( release: async () => { if (released) return; released = true; + releaseQuestionTarget(); authority.disconnectActiveRunner(); await registration.release(); }, diff --git a/server/src/services/pipelines.ts b/server/src/services/pipelines.ts index dfe2bb43f4..90e55dbaf5 100644 --- a/server/src/services/pipelines.ts +++ b/server/src/services/pipelines.ts @@ -50,7 +50,7 @@ import { logActivity } from "./activity-log.js"; import { assertAssignableAgent } from "./agent-assignability.js"; import { authorizationService } from "./authorization.js"; import { visibleIssueCondition } from "./issue-visibility.js"; -import { finalizeSummarySlotsForTerminalIssue } from "./summary-slot-finalization.js"; +import type { IssuePostCommitAction } from "./issues.js"; import { formatPipelineCaseOutputContextMarkdown, pipelineCaseOutputsService, @@ -4503,6 +4503,9 @@ export function pipelineService(db: Db, deps: { heartbeat?: IssueAssignmentWakeu cleanup: PipelineAutomationRetryCleanupOptions; actor: PipelineActor; }) { + const postCommitIssueActions: IssuePostCommitAction[] = []; + const { executeIssuePostCommitActions, issueService } = await import("./issues.js"); + const issueSvc = issueService(db); const result = await db.transaction(async (tx) => { const detail = await getCaseWithStageForUpdateOrThrow(tx, input.companyId, input.caseId); if (detail.case.version !== input.expectedVersion) { @@ -4613,26 +4616,26 @@ export function pipelineService(db: Db, deps: { heartbeat?: IssueAssignmentWakeu ? effects.linkedAutomationIssueIds : []; if (issueIdsToCancel.length > 0) { - const cancelledIssues = await tx - .update(issues) - .set({ status: "cancelled", updatedAt: now }) + const cancellableIssues = await tx + .select({ id: issues.id }) + .from(issues) .where(and( eq(issues.companyId, input.companyId), inArray(issues.id, issueIdsToCancel), ne(issues.status, "done"), - )) - .returning({ - id: issues.id, - companyId: issues.companyId, - identifier: issues.identifier, - title: issues.title, - status: issues.status, - }); - for (const issue of cancelledIssues) { - await finalizeSummarySlotsForTerminalIssue(tx, { - ...issue, - status: "cancelled", - }); + )); + for (const issue of cancellableIssues) { + await issueSvc.update( + issue.id, + { + status: "cancelled", + actorAgentId: input.actor.type === "agent" ? input.actor.agentId : null, + actorUserId: input.actor.type === "user" ? input.actor.userId : null, + }, + tx, + undefined, + postCommitIssueActions, + ); } await tx .update(pipelineCaseIssueLinks) @@ -4717,6 +4720,7 @@ export function pipelineService(db: Db, deps: { heartbeat?: IssueAssignmentWakeu }, }; }); + await executeIssuePostCommitActions(db, postCommitIssueActions); const automationExecution = await executeAutomationLedger(result.ledger.id, input.actor); const { targetStageRow: _targetStageRow, automationRoutineId: _automationRoutineId, ...plan } = result.plan; return { diff --git a/server/src/services/question-response-delivery.ts b/server/src/services/question-response-delivery.ts index 0820b82faa..aaca08029d 100644 --- a/server/src/services/question-response-delivery.ts +++ b/server/src/services/question-response-delivery.ts @@ -55,6 +55,9 @@ type QuestionResponseSteer = (input: { message: string; correlationId: string; }) => Promise<{ turnId?: string | null }>; +type NativeQuestionResponseResolver = ( + interaction: AskUserQuestionsInteraction, +) => Promise<"not_native" | "pending" | "queued">; export interface QuestionResponseDeliveryEnvelope { schema: "paperclip.question_response_delivery.v1"; @@ -77,6 +80,8 @@ export interface QuestionResponseDeliveryServiceOptions { heartbeat: Heartbeat; /** Optional native steering seam. Direct adapters use the durable wake fallback. */ steer?: QuestionResponseSteer; + /** Resolve the original in-flight native input request before considering a continuation run. */ + resolveNativeQuestion?: NativeQuestionResponseResolver; now?: () => Date; /** Test-only lease timings. Production callers use the bounded defaults. */ claimStaleMs?: number; @@ -260,6 +265,7 @@ export function questionResponseDeliveryService( options: QuestionResponseDeliveryServiceOptions, ) { const steer = options.steer; + const resolveNativeQuestion = options.resolveNativeQuestion; const now = options.now ?? (() => new Date()); const claimStaleMs = Math.max(2, options.claimStaleMs ?? DELIVERY_CLAIM_STALE_MS); const claimRefreshMs = Math.max( @@ -568,7 +574,8 @@ export function questionResponseDeliveryService( const queuedSuccessor = issueRuns.find((run) => (run.status === "queued" || run.status === "scheduled_retry") && run.id !== interaction.sourceRunId, ) ?? null; - const envelope = buildQuestionResponseDeliveryEnvelope(hydrateQuestionInteraction(interaction)); + const hydratedInteraction = hydrateQuestionInteraction(interaction); + const envelope = buildQuestionResponseDeliveryEnvelope(hydratedInteraction); if (nativeSha256(envelope) !== claimed.payloadSha256) { return recordTerminal({ delivery: claimed, @@ -581,6 +588,53 @@ export function questionResponseDeliveryService( }); } + if (resolveNativeQuestion) { + try { + const nativeDisposition = await withClaimLease( + claimed, + () => resolveNativeQuestion(hydratedInteraction), + ); + if (nativeDisposition === "queued") { + return recordTerminal({ + delivery: claimed, + interaction, + status: "delivered", + mode: "steered", + targetRunId: interaction.sourceRunId, + adapter, + }); + } + if (nativeDisposition === "pending") { + await releaseForRetry(claimed, "native_question_session_unavailable", { bounded: false }); + return null; + } + } catch (error) { + if (error instanceof DeliveryClaimUnavailableError) return terminalOutcome(interactionId); + const errorCode = error instanceof Error && compactLine(error.message) + ? compactLine(error.message)!.slice(0, 160) + : "native_question_delivery_failed"; + const exhausted = await releaseForRetry(claimed, errorCode); + logger.warn({ + err: error, + deliveryId: claimed.id, + interactionId, + attemptCount: claimed.attemptCount, + errorCount: claimed.errorCount + 1, + exhausted, + }, "native question response delivery will retry"); + if (!exhausted) return null; + return recordTerminal({ + delivery: claimed, + interaction, + status: "failed", + mode: null, + targetRunId: interaction.sourceRunId, + adapter, + errorCode, + }); + } + } + let steeringErrorCode: string | null = null; if (successorRunning?.runtimeMode === "native" && steer) { try { diff --git a/server/src/services/stalled-review-decisions.ts b/server/src/services/stalled-review-decisions.ts index 86847864b6..acaf324b6c 100644 --- a/server/src/services/stalled-review-decisions.ts +++ b/server/src/services/stalled-review-decisions.ts @@ -2,9 +2,17 @@ import { and, eq } from "drizzle-orm"; import { issues, type Db } from "@paperclipai/db"; import type { StalledReviewDecisionAction } from "@paperclipai/shared"; import { conflict, notFound } from "../errors.js"; -import { logActivity } from "./activity-log.js"; +import { + logActivity, + publishActivity, + type ActivityPublication, +} from "./activity-log.js"; import { visibleIssueCondition } from "./issue-visibility.js"; -import { issueService } from "./issues.js"; +import { + executeIssuePostCommitActions, + issueService, + type IssuePostCommitAction, +} from "./issues.js"; export interface StalledReviewDecisionActor { userId: string; @@ -20,92 +28,105 @@ export interface DecideStalledReviewInput { } export function stalledReviewDecisionService(db: Db) { + const svc = issueService(db); return { - decide: async (input: DecideStalledReviewInput) => db.transaction(async (tx) => { - const txDb = tx as unknown as Db; - const lockedIssue = await tx - .select() - .from(issues) - .where(and( - eq(issues.id, input.issueId), - eq(issues.companyId, input.companyId), - visibleIssueCondition(), - )) - .for("update") - .then((rows) => rows[0] ?? null); + decide: async (input: DecideStalledReviewInput) => { + const postCommitActivityPublications: ActivityPublication[] = []; + const postCommitIssueActions: IssuePostCommitAction[] = []; + const result = await db.transaction(async (tx) => { + const txDb = tx as unknown as Db; + const lockedIssue = await tx + .select() + .from(issues) + .where(and( + eq(issues.id, input.issueId), + eq(issues.companyId, input.companyId), + visibleIssueCondition(), + )) + .for("update") + .then((rows) => rows[0] ?? null); - if (!lockedIssue) throw notFound("Issue not found"); - if (lockedIssue.status !== "in_review") { - throw conflict("Issue is no longer a stalled review", { - issueId: lockedIssue.id, - currentStatus: lockedIssue.status, - }); - } + if (!lockedIssue) throw notFound("Issue not found"); + if (lockedIssue.status !== "in_review") { + throw conflict("Issue is no longer a stalled review", { + issueId: lockedIssue.id, + currentStatus: lockedIssue.status, + }); + } - const svc = issueService(txDb); - const reviewAttention = await svc - .listReviewAttention(lockedIssue.companyId, [lockedIssue]) - .then((rows) => rows.get(lockedIssue.id)); - if (reviewAttention?.state !== "stalled") { - throw conflict("Issue is no longer a stalled review", { - issueId: lockedIssue.id, - reviewAttentionState: reviewAttention?.state ?? "none", - }); - } + const reviewAttention = await svc + .listReviewAttention(lockedIssue.companyId, [lockedIssue], tx) + .then((rows) => rows.get(lockedIssue.id)); + if (reviewAttention?.state !== "stalled") { + throw conflict("Issue is no longer a stalled review", { + issueId: lockedIssue.id, + reviewAttentionState: reviewAttention?.state ?? "none", + }); + } - const comment = input.note - ? await svc.addComment( - lockedIssue.id, - input.note, - { userId: input.actor.userId, runId: input.actor.runId ?? null }, - { authorType: "user" }, - tx, - ) - : null; - const status = input.action === "approve" ? "done" : "todo"; - const updated = await svc.update(lockedIssue.id, { - status, - actorUserId: input.actor.userId, - }, tx); - if (!updated) throw notFound("Issue not found"); + const comment = input.note + ? await svc.addComment( + lockedIssue.id, + input.note, + { userId: input.actor.userId, runId: input.actor.runId ?? null }, + { authorType: "user" }, + tx, + ) + : null; + const status = input.action === "approve" ? "done" : "todo"; + const updated = await svc.update( + lockedIssue.id, + { + status, + actorUserId: input.actor.userId, + }, + tx, + postCommitActivityPublications, + postCommitIssueActions, + ); + if (!updated) throw notFound("Issue not found"); - if (comment) { + if (comment) { + await logActivity(txDb, { + companyId: updated.companyId, + actorType: "user", + actorId: input.actor.userId, + runId: input.actor.runId ?? null, + action: "issue.comment_added", + entityType: "issue", + entityId: updated.id, + issueId: updated.id, + details: { + commentId: comment.id, + authorUserId: input.actor.userId, + source: "stalled_review_decision", + }, + }); + } await logActivity(txDb, { companyId: updated.companyId, actorType: "user", actorId: input.actor.userId, runId: input.actor.runId ?? null, - action: "issue.comment_added", + action: "issue.stalled_review_decided", entityType: "issue", entityId: updated.id, issueId: updated.id, details: { - commentId: comment.id, - authorUserId: input.actor.userId, - source: "stalled_review_decision", + action: input.action, + status, + identifier: updated.identifier, + commentId: comment?.id ?? null, + authorUserId: comment ? input.actor.userId : null, + _previous: { status: lockedIssue.status }, }, }); - } - await logActivity(txDb, { - companyId: updated.companyId, - actorType: "user", - actorId: input.actor.userId, - runId: input.actor.runId ?? null, - action: "issue.stalled_review_decided", - entityType: "issue", - entityId: updated.id, - issueId: updated.id, - details: { - action: input.action, - status, - identifier: updated.identifier, - commentId: comment?.id ?? null, - authorUserId: comment ? input.actor.userId : null, - _previous: { status: lockedIssue.status }, - }, - }); - return { issue: updated, comment }; - }), + return { issue: updated, comment }; + }); + for (const publication of postCommitActivityPublications) publishActivity(publication); + await executeIssuePostCommitActions(db, postCommitIssueActions); + return result; + }, }; } diff --git a/server/src/vendor/paperclip-runner/index.ts b/server/src/vendor/paperclip-runner/index.ts index 03c4346e8c..3fb08b0758 100644 --- a/server/src/vendor/paperclip-runner/index.ts +++ b/server/src/vendor/paperclip-runner/index.ts @@ -19,6 +19,8 @@ export type { PaperclipSemanticToolCall, PaperclipSemanticToolDefinition, PaperclipSemanticToolResult, + PaperclipQuestionSet, + PaperclipRuntimeInputRequest, PrpEvent, PrpStructuredRunResult, PrpTerminalState, @@ -36,6 +38,8 @@ const runner = await import(sourceUrl.href) as RunnerModule; export const DurablePrpControlPlane = runner.DurablePrpControlPlane; export const PaperclipSemanticDispatcher = runner.PaperclipSemanticDispatcher; +export const parsePaperclipQuestionSet = runner.parsePaperclipQuestionSet; +export const parsePaperclipQuestionResponse = runner.parsePaperclipQuestionResponse; export const validatePrpEvent = runner.validatePrpEvent; export const validatePrpStructuredRunResult = runner.validatePrpStructuredRunResult; diff --git a/ui/src/api/activity.ts b/ui/src/api/activity.ts index 30698b12ff..b4d9d2baf8 100644 --- a/ui/src/api/activity.ts +++ b/ui/src/api/activity.ts @@ -5,6 +5,7 @@ export type { RunLivenessState } from "@paperclipai/shared"; export interface RunForIssue { runId: string; + runtimeMode?: "legacy" | "native"; status: string; agentId: string; adapterType: string; diff --git a/ui/src/api/heartbeats.ts b/ui/src/api/heartbeats.ts index c9f4312c5c..80b4fcb429 100644 --- a/ui/src/api/heartbeats.ts +++ b/ui/src/api/heartbeats.ts @@ -15,6 +15,7 @@ export interface RunLivenessFields { export interface ActiveRunForIssue { id: string; + runtimeMode?: "legacy" | "native"; status: string; invocationSource: string; triggerDetail: string | null; @@ -44,6 +45,7 @@ export interface ActiveRunForIssue { export interface LiveRunForIssue { id: string; + runtimeMode?: "legacy" | "native"; status: string; invocationSource: string; triggerDetail: string | null; diff --git a/ui/src/components/IssueThreadInteractionCard.test.tsx b/ui/src/components/IssueThreadInteractionCard.test.tsx index fff0a67dd3..9ccde6b047 100644 --- a/ui/src/components/IssueThreadInteractionCard.test.tsx +++ b/ui/src/components/IssueThreadInteractionCard.test.tsx @@ -354,6 +354,32 @@ describe("IssueThreadInteractionCard", () => { expect(host.querySelectorAll('[role="radio"]').length).toBeGreaterThan(0); }); + it("keeps a closed native select set closed while preserving direct-question defaults", () => { + const closed = { + ...pendingAskUserQuestionsInteraction, + payload: { + ...pendingAskUserQuestionsInteraction.payload, + questions: pendingAskUserQuestionsInteraction.payload.questions.map((question) => ({ + ...question, + allowOther: false, + })), + }, + }; + const host = renderCard({ interaction: closed, onSubmitInteractionAnswers: vi.fn() }); + expect(Array.from(host.querySelectorAll("button")).some((button) => button.textContent === "Other")) + .toBe(false); + + act(() => root?.unmount()); + host.remove(); + root = null; + const legacy = renderCard({ + interaction: pendingAskUserQuestionsInteraction, + onSubmitInteractionAnswers: vi.fn(), + }); + expect(Array.from(legacy.querySelectorAll("button")).some((button) => button.textContent === "Other")) + .toBe(true); + }); + it("only shows question cancellation when a cancel handler is wired", () => { const withoutHandler = renderCard({ interaction: pendingAskUserQuestionsInteraction, diff --git a/ui/src/components/IssueThreadInteractionCard.tsx b/ui/src/components/IssueThreadInteractionCard.tsx index 1578f29a67..44c6a57db1 100644 --- a/ui/src/components/IssueThreadInteractionCard.tsx +++ b/ui/src/components/IssueThreadInteractionCard.tsx @@ -1310,7 +1310,7 @@ function AskUserQuestionsCard({ * free-text option so the card never shows two ways to type an * answer (PAP-419). */} - {hasFreeTextOption ? null : ( + {hasFreeTextOption || question.allowOther === false ? null : ( <>