Refresh the SSH account branch from master

Keep the SSH base current so the stacked Tailscale migrations can follow the
latest upstream schema sequence. The merge preserves managed SSH account
selection, host-auth compatibility, and the PATH-only ACP prerequisite check.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip committed 2026-11-13 09:03:27 -08:00
commit e8a0316483
262 files changed
+13201 -1135

No files matched your search

@@ -2305,6 +2305,8 @@ export function renderPaperclipWakePrompt(
renderPaperclipWakePromptBody(value, options),
instructions ? `## Assigned connector skills\n\n${instructions}` : "",
asString(parseObject(parseObject(value).connectionInstructions).text, "").trim(),
// Server-rendered and labelled untrusted: what MCP Apps widgets in the task reported.
asString(parseObject(value).mcpAppContext, "").trim(),
]);
}
@@ -0,0 +1,3 @@
ALTER TABLE "tool_catalog_entries" ADD COLUMN "icons" jsonb;--> statement-breakpoint
ALTER TABLE "tool_mcp_app_views" ADD COLUMN "model_context" jsonb;--> statement-breakpoint
ALTER TABLE "tool_mcp_app_views" ADD COLUMN "model_context_updated_at" timestamp with time zone;
@@ -0,0 +1,49 @@
CREATE TABLE "tool_mcp_tasks" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"company_id" uuid NOT NULL,
"invocation_id" uuid NOT NULL,
"connection_id" uuid NOT NULL,
"grant_id" uuid NOT NULL,
"agent_id" uuid,
"issue_id" uuid,
"run_id" uuid,
"actor_type" text NOT NULL,
"actor_id" text,
"responsible_user_id" text,
"identity_context_id" uuid,
"catalog_tool_name" text NOT NULL,
"request_hash" text NOT NULL,
"endpoint_hash" text NOT NULL,
"sealed_caller_headers" text,
"protocol_version" text NOT NULL,
"sealed_provider_task_id" text NOT NULL,
"provider_task_id_hash" text NOT NULL,
"status" text NOT NULL,
"poll_interval_ms" integer,
"ttl_ms" integer,
"expires_at" timestamp with time zone NOT NULL,
"next_poll_at" timestamp with time zone,
"last_polled_at" timestamp with time zone,
"poll_failures" integer DEFAULT 0 NOT NULL,
"lease_expires_at" timestamp with time zone,
"lease_owner" text,
"arguments_identity" text NOT NULL,
"answered_input_keys" jsonb DEFAULT '[]'::jsonb NOT NULL,
"surfaced_input_keys" jsonb DEFAULT '[]'::jsonb NOT NULL,
"input_wake_count" integer DEFAULT 0 NOT NULL,
"input_wake_at" timestamp with time zone,
"error_code" text,
"wake_requested_at" timestamp with time zone,
"delivered_at" timestamp with time zone,
"last_invocation_id" uuid,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "tool_mcp_tasks" ADD CONSTRAINT "tool_mcp_tasks_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "tool_mcp_tasks" ADD CONSTRAINT "tool_mcp_tasks_invocation_id_tool_invocations_id_fk" FOREIGN KEY ("invocation_id") REFERENCES "public"."tool_invocations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "tool_mcp_tasks" ADD CONSTRAINT "tool_mcp_tasks_connection_id_tool_connections_id_fk" FOREIGN KEY ("connection_id") REFERENCES "public"."tool_connections"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "tool_mcp_tasks_provider_task_uq" ON "tool_mcp_tasks" USING btree ("company_id","connection_id","provider_task_id_hash");--> statement-breakpoint
CREATE INDEX "tool_mcp_tasks_attach_idx" ON "tool_mcp_tasks" USING btree ("company_id","connection_id","request_hash");--> statement-breakpoint
CREATE INDEX "tool_mcp_tasks_invocation_idx" ON "tool_mcp_tasks" USING btree ("company_id","invocation_id");--> statement-breakpoint
CREATE INDEX "tool_mcp_tasks_next_poll_idx" ON "tool_mcp_tasks" USING btree ("next_poll_at") WHERE "tool_mcp_tasks"."next_poll_at" is not null;
@@ -1,6 +1,6 @@
{
"id": "f14430e8-1ebf-414a-8c89-93c32740c4e6",
"prevId": "77704cfc-2cbe-41de-9d2c-5225b8466646",
"id": "d5d69127-12de-4281-9816-c20e013bfeb7",
"prevId": "82dcdc57-0796-4162-9451-8ea08a72199e",
"version": "7",
"dialect": "postgresql",
"tables": {
@@ -3954,6 +3954,28 @@
"method": "btree",
"with": {}
},
"agent_wakeup_requests_company_run_idx": {
"name": "agent_wakeup_requests_company_run_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "run_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"agent_wakeup_requests\".\"run_id\" IS NOT NULL",
"concurrently": true,
"method": "btree",
"with": {}
},
"agent_wakeup_requests_review_path_recovery_idempotency_uq": {
"name": "agent_wakeup_requests_review_path_recovery_idempotency_uq",
"columns": [
@@ -53942,6 +53964,7 @@
}
],
"isUnique": true,
"where": "\"sandbox_creation_operations\".\"state\" <> 'resolved'",
"concurrently": false,
"method": "btree",
"with": {}
@@ -57541,6 +57564,12 @@
"primaryKey": false,
"notNull": false
},
"icons": {
"name": "icons",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"risk_level": {
"name": "risk_level",
"type": "text",
@@ -59762,6 +59791,18 @@
"primaryKey": false,
"notNull": true
},
"model_context": {
"name": "model_context",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"model_context_updated_at": {
"name": "model_context_updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
@@ -60627,6 +60668,334 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_mcp_skill_files": {
"name": "tool_mcp_skill_files",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"company_id": {
"name": "company_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"connection_id": {
"name": "connection_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"file_uri": {
"name": "file_uri",
"type": "text",
"primaryKey": false,
"notNull": true
},
"digest": {
"name": "digest",
"type": "text",
"primaryKey": false,
"notNull": true
},
"size": {
"name": "size",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"content_base64": {
"name": "content_base64",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"tool_mcp_skill_files_digest_idx": {
"name": "tool_mcp_skill_files_digest_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "connection_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "file_uri",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "digest",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"tool_mcp_skill_files_company_id_companies_id_fk": {
"name": "tool_mcp_skill_files_company_id_companies_id_fk",
"tableFrom": "tool_mcp_skill_files",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tool_mcp_skill_files_connection_id_tool_connections_id_fk": {
"name": "tool_mcp_skill_files_connection_id_tool_connections_id_fk",
"tableFrom": "tool_mcp_skill_files",
"tableTo": "tool_connections",
"columnsFrom": [
"connection_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_mcp_skills": {
"name": "tool_mcp_skills",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"company_id": {
"name": "company_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"connection_id": {
"name": "connection_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"skill_uri": {
"name": "skill_uri",
"type": "text",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "''"
},
"frontmatter": {
"name": "frontmatter",
"type": "jsonb",
"primaryKey": false,
"notNull": true
},
"manifest": {
"name": "manifest",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"manifest_digest": {
"name": "manifest_digest",
"type": "text",
"primaryKey": false,
"notNull": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'pending_review'"
},
"status_reason": {
"name": "status_reason",
"type": "text",
"primaryKey": false,
"notNull": false
},
"approved_manifest_digest": {
"name": "approved_manifest_digest",
"type": "text",
"primaryKey": false,
"notNull": false
},
"allowed_tools_approved": {
"name": "allowed_tools_approved",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"reviewed_at": {
"name": "reviewed_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"reviewed_by_user_id": {
"name": "reviewed_by_user_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"last_seen_at": {
"name": "last_seen_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"tool_mcp_skills_connection_uri_idx": {
"name": "tool_mcp_skills_connection_uri_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "connection_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "skill_uri",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
},
"tool_mcp_skills_company_status_idx": {
"name": "tool_mcp_skills_company_status_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "status",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"tool_mcp_skills_company_id_companies_id_fk": {
"name": "tool_mcp_skills_company_id_companies_id_fk",
"tableFrom": "tool_mcp_skills",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"tool_mcp_skills_connection_id_tool_connections_id_fk": {
"name": "tool_mcp_skills_connection_id_tool_connections_id_fk",
"tableFrom": "tool_mcp_skills",
"tableTo": "tool_connections",
"columnsFrom": [
"connection_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.tool_oauth_states": {
"name": "tool_oauth_states",
"schema": "",
+14
View File
@@ -3326,6 +3326,20 @@
"when": 1794553127740,
"tag": "0476_wakeup_request_run_index",
"breakpoints": true
},
{
"idx": 477,
"version": "7",
"when": 1794554569782,
"tag": "0477_friendly_toro",
"breakpoints": true
},
{
"idx": 478,
"version": "7",
"when": 1794577652781,
"tag": "0478_jazzy_vertigo",
"breakpoints": true
}
]
}
+1
View File
@@ -193,6 +193,7 @@ export {
toolMcpAppViews,
toolMcpSkills,
toolMcpSkillFiles,
toolMcpTasks,
toolActionRequests,
toolCallEvents,
toolRateLimitCounters,
+83
View File
@@ -19,7 +19,9 @@ import type {
ConnectionAgentInstructions,
ConnectionTokenIssuanceOutcome,
ConnectionTokenIssuancePath,
McpAppModelContext,
McpAppToolUi,
McpIcon,
McpConnectionCredentialRef,
ToolActionRequestStatus,
ToolApplicationStatus,
@@ -385,6 +387,8 @@ export const toolCatalogEntries = pgTable(
annotations: jsonb("annotations").$type<Record<string, unknown>>().notNull().default({}),
/** Normalized MCP Apps `_meta.ui` declaration (`ui://` view), when the tool has one. */
uiMeta: jsonb("ui_meta").$type<McpAppToolUi>(),
/** Sanitized MCP `icons` (SEP-973) the provider declared for the tool. Not part of the version hash. */
icons: jsonb("icons").$type<McpIcon[]>(),
riskLevel: text("risk_level").$type<ToolRiskLevel>().notNull().default("read"),
isReadOnly: boolean("is_read_only").notNull().default(true),
isWrite: boolean("is_write").notNull().default(false),
@@ -835,6 +839,9 @@ export const toolMcpAppViews = pgTable(
resourceUri: text("resource_uri").notNull(),
toolInput: jsonb("tool_input").$type<Record<string, unknown>>().notNull().default({}),
toolResult: jsonb("tool_result").$type<Record<string, unknown>>().notNull(),
/** The view's latest `ui/update-model-context`, bounded. Delivered to the task's next run as untrusted app data. */
modelContext: jsonb("model_context").$type<McpAppModelContext>(),
modelContextUpdatedAt: timestamp("model_context_updated_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
@@ -883,6 +890,82 @@ export const toolMcpSkills = pgTable(
],
);
/**
* A provider task (MCP Tasks extension) that a `tools/call` returned in place
* of its result. The row is the durable handle: polling resumes from it after
* a restart, and a repeated call with the same request identity, grant, and
* agent attaches to it instead of starting the work again. No provider result
* is stored here; the result is read from the provider when it is delivered.
*/
export const toolMcpTasks = pgTable(
"tool_mcp_tasks",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
/** The call that created the task. */
invocationId: uuid("invocation_id").notNull().references(() => toolInvocations.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id").notNull().references(() => toolConnections.id, { onDelete: "cascade" }),
/** The grant whose credentials created the task; only that grant may read it. */
grantId: uuid("grant_id").notNull(),
agentId: uuid("agent_id"),
issueId: uuid("issue_id"),
/** The latest run that waited on the task. */
runId: uuid("run_id"),
actorType: text("actor_type").notNull(),
actorId: text("actor_id"),
/** The person whose grant applied, and the run identity, so background checks see the same caller. */
responsibleUserId: text("responsible_user_id"),
identityContextId: uuid("identity_context_id"),
catalogToolName: text("catalog_tool_name").notNull(),
/** Endpoint, tool, and full arguments; a call attaches only on an exact match. */
requestHash: text("request_hash").notNull(),
endpointHash: text("endpoint_hash").notNull(),
/** Forwarded caller headers the connection allows (such as a tenant), sealed; background polls send them too. */
sealedCallerHeaders: text("sealed_caller_headers"),
protocolVersion: text("protocol_version").notNull(),
/** The provider's task ID, sealed: it may act as a bearer token. */
sealedProviderTaskId: text("sealed_provider_task_id").notNull(),
/** Keyed hash of the provider's task ID, for uniqueness without the ID. */
providerTaskIdHash: text("provider_task_id_hash").notNull(),
/** working | input_required | completed | failed | cancelled | expired */
status: text("status").notNull(),
pollIntervalMs: integer("poll_interval_ms"),
ttlMs: integer("ttl_ms"),
/** When Paperclip stops tracking the task (the provider's TTL, capped). */
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
/** Next background check; null when nothing is left to do. */
nextPollAt: timestamp("next_poll_at", { withTimezone: true }),
lastPolledAt: timestamp("last_polled_at", { withTimezone: true }),
pollFailures: integer("poll_failures").notNull().default(0),
/** A live call or the background worker holds the task until then. */
leaseExpiresAt: timestamp("lease_expires_at", { withTimezone: true }),
/** Who holds the lease; writes under a lease require it. */
leaseOwner: text("lease_owner"),
/** The gateway's keyed identity of the full arguments, for keyed retries. */
argumentsIdentity: text("arguments_identity").notNull(),
/** Input request keys already answered with `tasks/update`. */
answeredInputKeys: jsonb("answered_input_keys").$type<string[]>().notNull().default([]),
/** Input request keys already shown to the agent (a link or a question card). */
surfacedInputKeys: jsonb("surfaced_input_keys").$type<string[]>().notNull().default([]),
/** Wakes requested for new input requests; capped, so a provider cannot wake an agent without end. */
inputWakeCount: integer("input_wake_count").notNull().default(0),
inputWakeAt: timestamp("input_wake_at", { withTimezone: true }),
errorCode: text("error_code"),
wakeRequestedAt: timestamp("wake_requested_at", { withTimezone: true }),
deliveredAt: timestamp("delivered_at", { withTimezone: true }),
/** The latest call that waited on the task (a retry with its key attaches again). */
lastInvocationId: uuid("last_invocation_id"),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
uniqueIndex("tool_mcp_tasks_provider_task_uq").on(table.companyId, table.connectionId, table.providerTaskIdHash),
index("tool_mcp_tasks_attach_idx").on(table.companyId, table.connectionId, table.requestHash),
index("tool_mcp_tasks_invocation_idx").on(table.companyId, table.invocationId),
index("tool_mcp_tasks_next_poll_idx").on(table.nextPollAt).where(sql`${table.nextPollAt} is not null`),
],
);
/**
* Verified skill files, written only by the server after a size and SHA-256
* check and never changed in place. Rows are keyed by connection and digest,
@@ -5,7 +5,7 @@ import { expect, it, vi } from "vitest";
import { OpenCodeServerDriver } from "./opencode-server-driver.js";
import type { PrpEvent } from "../../protocol/replay-contract.js";
it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow-native-tool", "idle-stall", "tool-idle-stall", "empty-again", "request-fails", "normal", "foreign-idle", "queued-tool", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches"] as const)("handles an empty OpenCode response: %s", async mode => {
it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow-native-tool", "idle-stall", "tool-idle-stall", "empty-again", "request-fails", "normal", "foreign-idle", "queued-tool", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches", "tool-call-markup", "tool-work-text", "tool-work-empty", "stale-tool-work"] as const)("handles an empty OpenCode response: %s", async mode => {
const root = await mkdtemp(join(tmpdir(), "opencode-empty-response-"));
const command = join(root, "fake-opencode.mjs");
await copyFile(resolve("test/fixtures/fake-opencode-server.mjs"), command);
@@ -15,6 +15,7 @@ it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow
// through OpenRouter): the step's reasoning, then the same text again as an
// ordinary text part, and no completion call.
const recordedReasoning = "Task created and already executing (status in_progress, run dafb...). Good. Reply with link. Use finish. Keep concise.\n\nCompletion contract revision 1, criterion \"objective\". I should call paperclip_finish with done. Include evidence refs maybe task link. Let's do.";
const recordedMarkup = "\n\n<|DSML| calls>\n<|DSML| invoke name=\"paperclip_paperclip_finish\">\n<|DSML| parameter name=\"reportedWorkDisposition\" string=\"true\">done</|DSML| parameter>\n<|DSML| parameter name=\"summary\" string=\"true\">Created `website-fixture.txt` in the task workspace.</|DSML| parameter>\n</|DSML| invoke>\n</|DSML| calls>";
let toolTimer: ReturnType<typeof setTimeout> | undefined;
let stream: ReadableStreamDefaultController<Uint8Array> | undefined;
let streamOpened!: () => void;
@@ -55,6 +56,17 @@ it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow
return;
}
}
// Recorded from chat-eval cohort 11 (documents-artifacts.write-plan):
// the turn saved a document with a tool, then the step and its
// correction both came back with no text and no completion call.
// A late tool update from the first turn arrives while the second
// turn is empty. It is not the second turn's work.
if (mode === "stale-tool-work" && number === 2)
emit({ type: "message.part.updated", properties: { part: { id: "native-late", messageID: "assistant-1", sessionID, type: "tool", tool: "bash", callID: "call-late",
state: { status: "completed", input: { command: "owned-controlled-command" }, output: "Late.", time: { start: 1, end: 2 } } } } });
if (mode.startsWith("tool-work") && number === 1)
emit({ type: "message.part.updated", properties: { part: { id: "native-work", messageID, sessionID, type: "tool", tool: "bash", callID: "call-work",
state: { status: "completed", input: { command: "owned-controlled-command" }, output: "Saved.", time: { start: 1, end: 2 } } } } });
if (mode === "reasoning-echo-reasoning-after" && number === 1) {
emit({ type: "message.part.updated", properties: { sessionID, part: { id: "part-1-text", messageID, sessionID, type: "text", text: recordedReasoning, time: { start: 1, end: 2 } } } });
emit({ type: "message.part.updated", properties: { sessionID, part: { id: "part-1-reasoning", messageID, sessionID, type: "reasoning", text: recordedReasoning, time: { start: 1, end: 3 } } } });
@@ -83,7 +95,17 @@ it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow
emit({ type: "session.status", properties: { sessionID, status: { type: "idle" } } });
return;
}
const answer = mode === "normal" || mode === "foreign-idle" || mode === "queued-tool" || number === 2 && ["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches"].includes(mode);
if (mode === "tool-call-markup" && number === 1) {
const leaked = { id: "part-1-text", messageID, sessionID, type: "text", text: "", time: { start: 1 } };
emit({ type: "message.part.updated", properties: { sessionID, part: leaked } });
for (const delta of [recordedMarkup.slice(0, 4), recordedMarkup.slice(4, 9), recordedMarkup.slice(9)])
emit({ type: "message.part.delta", properties: { sessionID, messageID, partID: leaked.id, field: "text", delta } });
emit({ type: "message.part.updated", properties: { sessionID, part: { ...leaked, text: recordedMarkup, time: { start: 1, end: 2 } } } });
emit({ type: "session.idle", properties: { sessionID } });
emit({ type: "session.status", properties: { sessionID, status: { type: "idle" } } });
return;
}
const answer = mode === "normal" || mode === "stale-tool-work" && number === 1 || mode === "foreign-idle" || mode === "queued-tool" || number === 3 && mode === "tool-work-text" || number === 2 && ["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches", "tool-call-markup"].includes(mode);
emit({ type: "message.part.updated", properties: { sessionID, part: { id: `part-${number}`, messageID,
type: answer ? "text" : "reasoning", text: answer ? (mode === "reasoning-echo-correction-matches" ? recordedReasoning : "Here is the actual final answer.") : "Synthetic reasoning must not become the answer.", time: { start: 1, end: 2 } } } });
emit({ type: "session.idle", properties: { sessionID } });
@@ -123,14 +145,24 @@ it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow
}
await vi.advanceTimersByTimeAsync(mode.endsWith("idle-stall") ? 20_001 : mode === "slow-native-tool" ? 1_999 : 5_001);
const events = await completed;
const succeeds = ["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow-native-tool", "normal", "foreign-idle", "queued-tool", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches"].includes(mode);
const succeeds = ["stale-tool-work", "tool-work-text", "reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow-native-tool", "normal", "foreign-idle", "queued-tool", "reasoning-echo", "reasoning-echo-text-first", "reasoning-echo-reasoning-after", "reasoning-echo-correction-matches", "tool-call-markup"].includes(mode);
expect(events.at(-1)?.eventType).toBe(succeeds ? "turn.completed" : "turn.failed");
expect(events.filter(event => event.eventType === "turn.started")).toHaveLength(1);
expect(events.every(event => !event.turnId || event.turnId === turnId)).toBe(true);
const final = events.filter(event => event.eventType === "item.completed" && event.payload.kind === "agentMessage" && event.payload.channel === "final");
expect(final.map(event => event.payload.text)).toEqual(succeeds ? [mode === "reasoning-echo-correction-matches" ? recordedReasoning : "Here is the actual final answer."] : []);
expect(prompts).toHaveLength(["normal", "foreign-idle", "queued-tool"].includes(mode) ? 1 : 2);
if (prompts.length === 2) {
// Only a turn that already did tool work gets the second, plain-text request.
expect(prompts).toHaveLength(["normal", "foreign-idle", "queued-tool", "stale-tool-work"].includes(mode) ? 1 : mode.startsWith("tool-work") ? 3 : 2);
if (prompts.length === 3) {
expect(prompts[2]).toMatchObject({ providerID: prompts[0]!.providerID, modelID: prompts[0]!.modelID, system: prompts[0]!.system, variant: "paperclip-no-reasoning" });
// Text first, so a chat reply survives a dropped call; then the
// completion call that an execution task needs to settle.
expect(JSON.stringify(prompts[2]!.parts)).toContain("Start this response with a short plain-text final answer");
expect(JSON.stringify(prompts[2]!.parts)).toContain("After that text, submit paperclip_finish");
}
if (mode === "tool-work-empty") expect(events.at(-1)?.payload).toMatchObject({ error: { code: "opencode_empty_response",
message: "OpenCode ended without a final answer or accepted completion report after two corrections." } });
if (prompts.length >= 2) {
expect(prompts[0]!.variant).toBe(mode === "empty-again" || mode === "reply" || mode.startsWith("reasoning-echo") ? "paperclip-default" : "paperclip-no-reasoning");
expect(prompts[1]).toMatchObject({ providerID: prompts[0]!.providerID, modelID: prompts[0]!.modelID, system: prompts[0]!.system, variant: "paperclip-no-reasoning" });
expect(JSON.stringify(prompts[1]!.parts)).toContain("Do not repeat completed actions");
@@ -141,6 +173,24 @@ it.each(["reply", "reply-no-finish", "reply-tool-finish", "two-turn-idle", "slow
expect(assistantText.join("")).not.toContain(recordedReasoning.slice(0, 20));
expect(events.some(event => event.eventType === "harness.diagnostic" && event.payload.code === "opencode_reasoning_echo_discarded")).toBe(true);
}
if (mode === "tool-call-markup") {
const assistantText = events.filter(event => event.payload.kind === "agentMessage").map(event => String(event.payload.text ?? ""));
expect(assistantText.join("")).not.toContain("DSML");
expect(assistantText.join("")).not.toContain("<|");
expect(events.some(event => event.eventType === "harness.diagnostic" && event.payload.code === "opencode_tool_call_markup_discarded")).toBe(true);
expect(JSON.stringify(prompts[1]!.parts)).toContain("wrote a tool call as plain text");
}
if (mode === "stale-tool-work") {
const nextEvents = collect();
await session.startTurn({ message: { role: "user", text: "Answer the next request." }, reasoningMode: "disabled" });
const nextCompleted = guard(nextEvents, 5_000);
await vi.advanceTimersByTimeAsync(0);
await vi.advanceTimersByTimeAsync(5_001);
const rows = await nextCompleted;
expect(rows.at(-1)?.eventType).toBe("turn.failed");
// One prompt and one correction; the earlier turn's tool update earns no plain-text request.
expect(prompts).toHaveLength(3);
}
if (mode === "two-turn-idle") {
const nextEvents = collect();
const next = await session.startTurn({ message: { role: "user", text: "Answer the next request." }, reasoningMode: "disabled" });
@@ -1249,6 +1249,64 @@ describe("OpenCodeServerDriver", () => {
}
});
it("keeps a finished call's host on its usage while OpenCode's next model call is already in flight", async () => {
await chmod(fixture, 0o755);
const model = "deepseek/deepseek-v4.1-flash-1017";
let releaseNext: (() => void) | undefined;
let call = 0;
const upstream = createHttpServer((request, response) => {
void (async () => {
for await (const _chunk of request) void _chunk;
call += 1;
response.writeHead(200, { "content-type": "text/event-stream" });
if (call === 1) {
response.end('data: {"id":"gen-first","provider":"Novita","choices":[{"delta":{"content":"Hi"}}]}\n\ndata: [DONE]\n\n');
return;
}
response.write('data: {"id":"gen-next","provider":"Chutes","choices":[{"delta":{"content":"Hi"}}]}\n\n');
await new Promise<void>(resolve => { releaseNext = resolve; });
response.end("data: [DONE]\n\n");
})().catch(() => response.destroy());
});
await new Promise<void>(resolve => upstream.listen(0, "127.0.0.1", resolve));
const address = upstream.address();
if (!address || typeof address === "string") throw new Error("Missing fixture address");
upstreamTransport.endpoint = `http://127.0.0.1:${address.port}/chat/completions`;
upstreamTransport.urls = [];
const root = await mkdtemp(join(tmpdir(), "paperclip-openrouter-inflight-"));
roots.push(root);
let session: Awaited<ReturnType<OpenCodeServerDriver["openSession"]>> | undefined;
try {
const driver = new OpenCodeServerDriver({ model: `openrouter/${model}`, runtimeDirectory: root, command: fixture,
environment: { PATH: process.env.PATH, OPENROUTER_API_KEY: "synthetic-inflight-key" } });
session = await driver.openSession({ runId: "inflight", normalizedSessionId: "inflight", workingDirectory: root });
const config = JSON.parse(await readFile(join(root, "inflight", "config", "opencode", "opencode.json"), "utf8"));
const { baseURL, apiKey } = config.provider.openrouter.options;
const send = () => fetch(`${baseURL}/chat/completions`, { method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({ model, stream: true, messages: [{ role: "user", content: "synthetic" }] }) });
await (await send()).arrayBuffer();
const next = await send();
expect(next.status).toBe(200);
const reader = next.body!.getReader();
expect(new TextDecoder().decode((await reader.read()).value)).toContain('"provider":"Chutes"');
await session.startTurn({ message: { role: "user", text: "finish" } });
const events = await collectTurnEvents(session.events());
const usage = events.find(event => event.eventType === "item.completed" && event.payload.kind === "usage")?.payload.usage;
expect(usage).toMatchObject({ upstreamProvider: "Novita", providerRequestId: "gen-first" });
releaseNext?.();
while (!(await reader.read()).done);
await session.startTurn({ message: { role: "user", text: "finish" } });
await collectTurnEvents(session.events());
expect(await session.usage?.()).toMatchObject({ upstreamProvider: "Chutes", providerRequestId: "gen-next" });
} finally {
releaseNext?.();
await session?.close({ reason: "test" });
upstreamTransport.endpoint = "";
await new Promise<void>(resolve => { upstream.close(() => resolve()); upstream.closeAllConnections(); });
}
});
it("does not carry an earlier call's host onto a call the tap skips, or into another run", async () => {
await chmod(fixture, 0o755);
const model = "deepseek/deepseek-v4.1-flash-1017";
@@ -96,6 +96,7 @@ import {
type OpenCodeMcpBridgeOptions,
} from "./mcp-bridge.js";
import { nativeMcpLaunchBinding } from "../native-mcp.js";
import { toolCallMarkupStart, visibleBeforeToolCallMarkup } from "./tool-call-markup.js";
import {
materializeNativeRuntimeSkills,
releaseMaterializedNativeRuntimeSkills,
@@ -567,6 +568,7 @@ class OpenCodeHarnessSession implements HarnessSession {
#semanticResultTextBoundary: number | null = null;
#semanticResultProviderMessageId: string | null = null;
#lastNonTerminalToolSourceSeq = 0;
#lastToolCallMarkupSourceSeq = 0;
#usage: Record<string, unknown> | null = null;
#upstreamServed: UpstreamServed | null = null;
readonly #conversationMode: "task" | "prepared";
@@ -575,8 +577,10 @@ class OpenCodeHarnessSession implements HarnessSession {
#closed = false;
#completionSettlement: Promise<void> | null = null;
#turnStartSourceSeq = 0;
/** The active turn, once it has reported its own non-terminal tool work. */
#toolWorkTurnId: string | null = null;
#turnReasoningMode: OpenCodeReasoningMode = "default";
#emptyResponseRecovery: { turnId: string; priorMessages: Set<string>; responseStarted: boolean; responseFinished: boolean } | null = null;
#emptyResponseRecovery: { turnId: string; attempt: 1 | 2; priorMessages: Set<string>; responseStarted: boolean; responseFinished: boolean } | null = null;
#emptyResponseAckTimer: ReturnType<typeof setTimeout> | undefined;
#interruptedTurnId: string | null = null;
#pendingToolCalls = 0;
@@ -703,6 +707,7 @@ class OpenCodeHarnessSession implements HarnessSession {
this.#semanticResultTextBoundary = null;
this.#semanticResultProviderMessageId = null;
this.#lastNonTerminalToolSourceSeq = 0;
this.#lastToolCallMarkupSourceSeq = 0;
this.#completedTextPartIds.clear();
this.#completedReasoningPartIds.clear();
this.#reasoningTexts.clear();
@@ -870,7 +875,7 @@ class OpenCodeHarnessSession implements HarnessSession {
// request. Keep in-flight tool work gated by the checks above.
if (this.#interruptedTurnId === turnId) return false;
const recovery = this.#emptyResponseRecovery;
const boundary = Math.max(this.#turnStartSourceSeq, this.#lastNonTerminalToolSourceSeq);
const boundary = Math.max(this.#turnStartSourceSeq, this.#lastNonTerminalToolSourceSeq, this.#lastToolCallMarkupSourceSeq);
if (this.#completedTextParts.some(part => part.observedSourceSeq > boundary && !this.#isOutputLimited(part) && !this.#isReasoningEcho(part))) return false;
// Both idle event forms can remain queued from the empty response. Wait
// for correction evidence. A completed answer part is sufficient even
@@ -882,22 +887,46 @@ class OpenCodeHarnessSession implements HarnessSession {
this.#armEmptyResponseAckTimer(turnId, "OpenCode became idle without completing its requested final response.");
return true;
}
if (recovery) {
this.#failEmptyResponse(turnId, "OpenCode ended without a final answer or accepted completion report after one correction.");
if (recovery?.attempt === 1 && this.#toolWorkTurnId === turnId) {
// The turn already did real tool work, so the person must get an
// answer, not a failed run. Some hosts drop a tool-only response (the
// completion call) and return nothing. The last request asks for the
// answer as text first: a chat reply then arrives even if the call is
// dropped again, and an execution task still gets its completion call.
this.#requestFinalResponse(turnId, 2);
return true;
}
this.#emptyResponseRecovery = { turnId, priorMessages: new Set(this.#messageRoles.keys()), responseStarted: false, responseFinished: false };
if (recovery) {
this.#failEmptyResponse(turnId, `OpenCode ended without a final answer or accepted completion report after ${recovery.attempt === 1 ? "one correction" : "two corrections"}.`);
return true;
}
this.#requestFinalResponse(turnId, 1);
return true;
}
/**
* Ask for the final response after an empty completion. A turn makes at
* most two such requests, and the second only after real tool work.
*/
#requestFinalResponse(turnId: string, attempt: 1 | 2): void {
this.#emptyResponseRecovery = { turnId, attempt, priorMessages: new Set(this.#messageRoles.keys()), responseStarted: false, responseFinished: false };
for (const part of this.#completedTextParts)
if (this.#echoesReasoning(part.text, true)) this.#reasoningEchoPartIds.add(part.partId);
this.#reasoningTexts.clear();
this.#emit("harness.diagnostic", { code: "opencode_empty_response_correction", message: "Requesting one final response after an empty OpenCode completion." }, { turnId });
this.#emit("harness.diagnostic", attempt === 1
? { code: "opencode_empty_response_correction", message: "Requesting one final response after an empty OpenCode completion." }
: { code: "opencode_empty_response_text_correction", message: "Requesting a plain-text final answer after the correction also came back empty." }, { turnId });
this.#armEmptyResponseAckTimer(turnId, "OpenCode did not start its requested final response.");
const opening = this.#turnHitOutputLimit(turnId)
? "Your previous response reached the output limit and was discarded as incomplete."
: "Your response ended without a user-visible final answer or an accepted completion report.";
void this.#submitPrompt(`${opening} Continue this same request from the work already done. Give the user a concise final answer and submit paperclip_finish (or paperclip_block when blocked) with the current completion contract. Do not repeat completed actions.`, "disabled")
: this.#lastToolCallMarkupSourceSeq > this.#turnStartSourceSeq
? "Your previous response wrote a tool call as plain text, so the tool did not run. Call tools only through the tool-calling interface, never as text."
: "Your response ended without a user-visible final answer or an accepted completion report.";
const prompt = attempt === 1
? `${opening} Continue this same request from the work already done. Give the user a concise final answer and submit paperclip_finish (or paperclip_block when blocked) with the current completion contract. Do not repeat completed actions.`
: "Your last response was empty again. Start this response with a short plain-text final answer for the user that says what you did and what, if anything, is left. After that text, submit paperclip_finish (or paperclip_block when blocked) with the current completion contract. Do not repeat completed actions.";
void this.#submitPrompt(prompt, "disabled")
.catch(() => this.#failEmptyResponse(turnId, "OpenCode could not request a final response after an empty completion."));
return true;
}
async interrupt(input: { turnId?: string; reason?: string }): Promise<void> {
@@ -2128,6 +2157,9 @@ class OpenCodeHarnessSession implements HarnessSession {
)
) {
this.#lastNonTerminalToolSourceSeq = this.#sourceSequence;
// A late part from an earlier turn keeps that turn's id, so it never
// counts as this turn's work.
if (turnId === this.#activeTurnId) this.#toolWorkTurnId = turnId;
}
if (partType === "patch") {
const paths = Array.isArray(part.files) ? part.files : [];
@@ -2179,11 +2211,17 @@ class OpenCodeHarnessSession implements HarnessSession {
// the start of a completed reasoning part, and release it once it differs.
if (partType === "reasoning" && content.trim()) this.#reasoningTexts.set(partId, content.trim());
const reasoningEcho = partType === "text" && this.#echoesReasoning(content, completed);
if (!reasoningEcho) this.#partText.set(partId, content);
if (partType === "text" && content.length > 0 && !reasoningEcho) {
const markupStart = partType === "text" && completed ? toolCallMarkupStart(content) : -1;
const visible = partType !== "text"
? content
: completed
? markupStart < 0 ? content : content.slice(0, markupStart)
: visibleBeforeToolCallMarkup(content);
if (!reasoningEcho) this.#partText.set(partId, visible);
if (partType === "text" && visible.length > 0 && !reasoningEcho) {
for (const reference of paperclipWorkspaceFileReferencesFromText(
this.#workingDirectory,
content,
visible,
turnId,
)) {
if (this.#emittedFileReferences.has(reference.referenceId)) continue;
@@ -2195,9 +2233,9 @@ class OpenCodeHarnessSession implements HarnessSession {
);
}
}
const delta = content.startsWith(previous)
? content.slice(previous.length)
: content;
const delta = visible.startsWith(previous)
? visible.slice(previous.length)
: visible;
if (delta && !reasoningEcho) {
// OpenCode calls assistant prose a `text` part, but `text` is not a PRP
// item identity and is consequently ignored by the task projection.
@@ -2284,6 +2322,15 @@ class OpenCodeHarnessSession implements HarnessSession {
);
return;
}
if (markupStart >= 0) {
this.#lastToolCallMarkupSourceSeq = this.#sourceSequence;
this.#emit(
"harness.diagnostic",
{ code: "opencode_tool_call_markup_discarded", message: "OpenCode returned a tool call as text instead of a tool call; the text was not used as a response." },
{ turnId },
);
return;
}
this.#completedTextParts.push({
partId,
messageId,
@@ -2309,7 +2356,7 @@ class OpenCodeHarnessSession implements HarnessSession {
// be a final response. When no such text exists, emit no final agentMessage
// and let the accepted semantic summary resolve the durable reply.
const afterLastWorkTool = (part: { observedSourceSeq: number }) =>
part.observedSourceSeq > this.#lastNonTerminalToolSourceSeq;
part.observedSourceSeq > Math.max(this.#lastNonTerminalToolSourceSeq, this.#lastToolCallMarkupSourceSeq);
const eligibleText = this.#completedTextParts.filter(part => afterLastWorkTool(part) && !this.#isOutputLimited(part) && !this.#isReasoningEcho(part));
// OpenCode exposes no prose channel, so final selection must use provider
// structure rather than text length or content. When OpenCode reports the
@@ -2517,32 +2564,37 @@ async function startOpenCodeProviderProxy(baseUrl: string, key: string, model: s
const redacted = redactOpenCodeModelRequest(body, secretValues, payload);
if (redacted) body = redacted;
}
try { onServed?.(null); } catch { /* Recording never affects the request. */ }
const upstream = await new Promise<IncomingMessage>((resolve, reject) => {
const outgoing = (upstreamUrl.protocol === "https:" ? requestHttps : requestHttp)(upstreamUrl, {
method: "POST",
agent,
headers: { ...(isOpenRouterUrl(baseUrl) ? OPENROUTER_ATTRIBUTION_HEADERS : {}), "Content-Type": "application/json", "Content-Length": body.length, ...(key ? { Authorization: `Bearer ${key}` } : {}) },
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(600_000)]),
}, resolve);
outgoing.once("error", reject);
outgoing.end(body);
});
// Never forward authentication to a redirect destination.
const status = upstream.statusCode ?? 502;
if (status >= 300 && status < 400) {
upstream.destroy();
throw new Error("Provider redirects are not supported");
let served: UpstreamServed | null = null;
try {
const upstream = await new Promise<IncomingMessage>((resolve, reject) => {
const outgoing = (upstreamUrl.protocol === "https:" ? requestHttps : requestHttp)(upstreamUrl, {
method: "POST",
agent,
headers: { ...(isOpenRouterUrl(baseUrl) ? OPENROUTER_ATTRIBUTION_HEADERS : {}), "Content-Type": "application/json", "Content-Length": body.length, ...(key ? { Authorization: `Bearer ${key}` } : {}) },
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(600_000)]),
}, resolve);
outgoing.once("error", reject);
outgoing.end(body);
});
// Never forward authentication to a redirect destination.
const status = upstream.statusCode ?? 502;
if (status >= 300 && status < 400) {
upstream.destroy();
throw new Error("Provider redirects are not supported");
}
const headers: Record<string, string> = {};
for (const name of ["content-type", "content-encoding", "cache-control", "retry-after"]) {
const value = upstream.headers[name];
if (typeof value === "string") headers[name] = value;
}
response.writeHead(status, headers);
if (onServed && status >= 200 && status < 300) {
await pipeline(upstream, createUpstreamServedTap({ contentType: headers["content-type"], contentEncoding: headers["content-encoding"],
onServed: value => { served = value; } }), response);
} else await pipeline(upstream, response);
} finally {
try { onServed?.(served); } catch { /* Recording never affects the response. */ }
}
const headers: Record<string, string> = {};
for (const name of ["content-type", "content-encoding", "cache-control", "retry-after"]) {
const value = upstream.headers[name];
if (typeof value === "string") headers[name] = value;
}
response.writeHead(status, headers);
if (onServed && status >= 200 && status < 300) {
await pipeline(upstream, createUpstreamServedTap({ contentType: headers["content-type"], contentEncoding: headers["content-encoding"], onServed }), response);
} else await pipeline(upstream, response);
})().catch(() => {
if (!response.headersSent) response.writeHead(502).end("Provider request failed");
else response.destroy();
@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import { containsToolCallMarkup, visibleBeforeToolCallMarkup } from "./tool-call-markup.js";
const dsml = "<|DSML| calls>\n<|DSML| invoke name=\"paperclip_paperclip_finish\">\n<|DSML| parameter name=\"summary\" string=\"true\">Done.</|DSML| parameter>\n</|DSML| invoke>\n</|DSML| calls>";
const markupForms = {
"recorded DSML block": dsml,
"ASCII-bar DSML": "<|DSML| invoke name=\"x\">",
"DeepSeek call tokens": "<|tool▁calls▁begin|><|tool▁call▁begin|>function",
"ASCII call tokens": "<|tool_calls_begin|><|tool_call_begin|>function",
"function_calls wrapper": "<function_calls>\n<invoke name=\"paperclip_finish\">\n</invoke>\n</function_calls>",
"tool_call wrapper": "<tool_call>\n{\"name\": \"paperclip_finish\", \"arguments\": {}}\n</tool_call>",
};
describe("leaked tool-call markup", () => {
it.each(Object.entries(markupForms))("detects %s alone and after prose", (_label, markup) => {
expect(containsToolCallMarkup(`\n\n${markup}`)).toBe(true);
expect(containsToolCallMarkup(`Saved the file.\n${markup}`)).toBe(true);
});
it("detects a sentinel inline after prose", () => {
expect(containsToolCallMarkup(`Saved the file.${dsml}`)).toBe(true);
});
it.each([
["plain prose", "Created the file and saved the plan."],
["prose naming a tag", "The model emits a <tool_call> tag when it wants a tool."],
["comparison operators", "Use x < 3 and y > 2."],
["HTML answer", "<div>\n<p>Hello</p>\n</div>"],
["wrapper without a call body", "<tool_call>\nis the tag Hermes models use.</tool_call>"],
["markup in a backtick fence", `Here is the format:\n\`\`\`\n${dsml}\n<function_calls>\n<invoke name="x">\n\`\`\`\nThat is all.`],
["markup in a tilde fence", `~~~text\n${dsml}\n~~~`],
["shorter fence lines inside a longer fence", `\`\`\`\`markdown\n\`\`\`\n${dsml}\n\`\`\`\n\`\`\`\``],
["other fence characters inside a fence", `~~~\n\`\`\`\n${dsml}\n~~~`],
["an indented fence line inside a top-level fence", `\`\`\`\n \`\`\`\n${dsml}\n\`\`\``],
["a list-indented fence", `10. Example:\n\n \`\`\`\n ${dsml}\n \`\`\``],
])("ignores %s", (_label, text) => {
expect(containsToolCallMarkup(text)).toBe(false);
});
it("detects markup after a closed fence", () => {
expect(containsToolCallMarkup(`\`\`\`\`\nexample\n\`\`\`\`\n${dsml}`)).toBe(true);
});
it.each(Object.entries(markupForms))("streams %s without showing any of it, at every split point", (_label, markup) => {
const answer = `Saved the file. Done <\n\n${markup}`;
let shown = "";
for (let end = 1; end <= answer.length; end += 1) {
const visible = visibleBeforeToolCallMarkup(answer.slice(0, end));
expect(visible.startsWith(shown)).toBe(true);
shown = visible;
}
expect(shown).toBe("Saved the file. Done <\n\n");
});
it("releases a held fragment once it cannot become markup", () => {
expect(visibleBeforeToolCallMarkup("a < b")).toBe("a < b");
expect(visibleBeforeToolCallMarkup("Done <")).toBe("Done ");
expect(visibleBeforeToolCallMarkup("Done <|tool_call")).toBe("Done ");
expect(visibleBeforeToolCallMarkup("Done <|tool_call>")).toBe("Done <|tool_call>");
expect(visibleBeforeToolCallMarkup("Done <b")).toBe("Done <b");
});
});
@@ -0,0 +1,79 @@
const SENTINEL_FORMS = ["|", "|"].flatMap(bar => [
`<${bar}DSML${bar}`,
...["tool▁calls▁begin", "tool_calls_begin", "tool▁call▁begin", "tool_call_begin"].map(name => `<${bar}${name}${bar}>`),
]);
const LINE_FORMS = [
{ wrapper: "<function_calls>", body: '<invokename="', pattern: /^<function_calls>\s*<invoke\s+name\s*=/ },
{ wrapper: "<tool_call>", body: '{"name":', pattern: /^<tool_call>\s*\{\s*"name"\s*:/ },
];
const LOOK_AHEAD = 256;
function couldBecomeLineForm(rest: string): boolean {
const compact = rest.replace(/\s+/g, "");
if (!compact) return false;
return LINE_FORMS.some(({ wrapper, body }) =>
compact.length <= wrapper.length
? wrapper.startsWith(compact)
: compact.startsWith(wrapper) && body.startsWith(compact.slice(wrapper.length)));
}
function firstSentinel(line: string): number {
let first = -1;
for (const form of SENTINEL_FORMS) {
const index = line.indexOf(form);
if (index >= 0 && (first < 0 || index < first)) first = index;
}
return first;
}
function fenceOf(line: string): { indent: number; char: string; length: number; rest: string } | null {
const match = /^([ \t]*)(`{3,}|~{3,})(.*)$/.exec(line);
return match
? { indent: match[1]!.replace(/\t/g, " ").length, char: match[2]![0]!, length: match[2]!.length, rest: match[3]! }
: null;
}
export function toolCallMarkupStart(content: string, options: { streaming?: boolean } = {}): number {
if (!content.includes("<")) return -1;
let offset = 0;
let openFence: { indent: number; char: string; length: number } | null = null;
const lines = content.split("\n");
for (const [index, line] of lines.entries()) {
const lineStart = offset;
offset += line.length + 1;
const fence = fenceOf(line);
if (openFence) {
if (fence && fence.indent <= openFence.indent + 3 && fence.char === openFence.char && fence.length >= openFence.length && !fence.rest.trim())
openFence = null;
continue;
}
if (fence && !(fence.char === "`" && fence.rest.includes("`"))) {
openFence = { indent: fence.indent, char: fence.char, length: fence.length };
continue;
}
if (!line.trim()) continue;
const sentinel = firstSentinel(line);
if (sentinel >= 0) return lineStart + sentinel;
const indent = line.length - line.trimStart().length;
const rest = line[indent] === "<" ? content.slice(lineStart + indent, lineStart + indent + LOOK_AHEAD) : "";
if (rest && LINE_FORMS.some(({ pattern }) => pattern.test(rest))) return lineStart + indent;
if (!options.streaming) continue;
if (rest && couldBecomeLineForm(rest)) return lineStart + indent;
if (index === lines.length - 1) {
const lastOpen = line.lastIndexOf("<");
if (lastOpen >= 0 && SENTINEL_FORMS.some(form => form.startsWith(line.slice(lastOpen)))) return lineStart + lastOpen;
}
}
return -1;
}
export function containsToolCallMarkup(content: string): boolean {
return toolCallMarkupStart(content) >= 0;
}
export function visibleBeforeToolCallMarkup(content: string): string {
const start = toolCallMarkupStart(content, { streaming: true });
return start < 0 ? content : content.slice(0, start);
}
+8
View File
@@ -385,6 +385,14 @@ export const INSTANCE_FEATURE_CATALOG: Record<InstanceFeatureKey, FeatureCatalog
cloudDefault: true,
selfHostedDefault: false,
},
enableMcpTasks: {
title: "Durable app actions (MCP Tasks)",
description:
"Let connected apps run long actions, such as CI runs or deploys, as tasks that Paperclip keeps track of across timeouts, restarts, and deploys, so the work is never started twice.",
tier: "managed",
cloudDefault: false,
selfHostedDefault: false,
},
enableSandboxDuplexBridge: {
title: "Sandbox Duplex Bridge",
description:
+3 -1
View File
@@ -1601,6 +1601,8 @@ export type {
ToolApplication,
ToolConnection,
ToolCatalogEntry,
ProviderToolIconEntry,
ProviderToolIconsResponse,
ToolRuntimeSlot,
ToolConnectionHealthCheckResult,
ToolCatalogRefreshResult,
@@ -2852,7 +2854,7 @@ export {
} from "./runtime-exposure/loopback-bind.js";
export { ACCOUNT_HANDLE_MAX_LENGTH, toAccountHandle } from "./account-handle.js";
export type { ExecutionContinuationEnvelope } from "./types/execution-continuation.js";
export type { ExecutionProjection, ExecutionReconciliation, ExecutionBlocker, TaskInterruptionPresentation } from "./types/execution-projection.js";
export type { ExecutionAgentQueue, ExecutionProjection, ExecutionReconciliation, ExecutionBlocker, TaskInterruptionPresentation } from "./types/execution-projection.js";
export { EXECUTION_RECONCILIATION_CAUSES, requiresExecutionReconciliation } from "./types/execution-projection.js";
export * from "./types/voice-sessions.js";
+176
View File
@@ -221,3 +221,179 @@ export function buildMcpAppCsp(csp: McpAppResourceCsp): string {
"form-action 'none'",
].join("; ");
}
/* ------------------------------------------------------------------------- */
/* View-to-chat messages (`ui/message`) */
/* ------------------------------------------------------------------------- */
/** Longest message a view may propose to the task chat. */
export const MCP_APP_MESSAGE_MAX_CHARS = 8_000;
/**
* The text of a `ui/message` request (`{ role: "user", content: ContentBlock[] }`).
* Only text blocks are kept. Returns null when there is no text, the role is
* not "user", or the text is too long.
*/
export function readMcpAppMessageText(params: unknown): string | null {
const value = record(params);
if (!value || (value.role !== undefined && value.role !== "user")) return null;
const blocks = Array.isArray(value.content) ? value.content : record(value.content) ? [value.content] : [];
const text = blocks
.map((block) => record(block))
.filter((block): block is Record<string, unknown> => block?.type === "text" && typeof block.text === "string")
.map((block) => block.text as string)
.join("\n\n")
.trim();
if (!text || text.length > MCP_APP_MESSAGE_MAX_CHARS) return null;
return text;
}
/**
* Body of `POST /api/issues/:issueId/mcp-app-views/:viewId/messages`. The
* viewer has already sent the comment through the task's normal comment path;
* this records that it came from the view.
*/
export const mcpAppMessageSentSchema = z.object({
/** The `clientRequestId` the viewer's comment was sent with. */
clientRequestId: z.string().uuid(),
}).strict();
export type McpAppMessageSentRequest = z.infer<typeof mcpAppMessageSentSchema>;
/* ------------------------------------------------------------------------- */
/* View context for the agent (`ui/update-model-context`) */
/* ------------------------------------------------------------------------- */
/** Largest stored context per view, in UTF-8 bytes of its JSON. */
export const MCP_APP_MODEL_CONTEXT_MAX_BYTES = 16 * 1024;
/** The latest context a view gave the agent. Untrusted app data, never instructions. */
export interface McpAppModelContext {
text: string | null;
structuredContent: Record<string, unknown> | null;
}
/** Body of `PUT /api/issues/:issueId/mcp-app-views/:viewId/model-context`. */
export const mcpAppModelContextUpdateSchema = z.object({
content: z.array(z.unknown()).max(64).optional(),
structuredContent: z.record(z.string(), z.unknown()).optional(),
}).strict();
export type McpAppModelContextUpdate = z.infer<typeof mcpAppModelContextUpdateSchema>;
/**
* Normalizes `ui/update-model-context` params: text blocks only, plus the
* structured content. Returns null for an empty update (which clears the
* context) and throws a RangeError when the result exceeds the size limit.
*/
export function normalizeMcpAppModelContext(params: unknown): McpAppModelContext | null {
const value = record(params) ?? {};
const blocks = Array.isArray(value.content) ? value.content : [];
const text = blocks
.map((block) => record(block))
.filter((block): block is Record<string, unknown> => block?.type === "text" && typeof block.text === "string")
.map((block) => block.text as string)
.join("\n\n")
.trim();
const structuredContent = record(value.structuredContent);
const context: McpAppModelContext = {
text: text || null,
structuredContent: structuredContent && Object.keys(structuredContent).length > 0 ? structuredContent : null,
};
if (!context.text && !context.structuredContent) return null;
if (utf8Length(JSON.stringify(context)) > MCP_APP_MODEL_CONTEXT_MAX_BYTES) {
throw new RangeError(`App context is larger than ${MCP_APP_MODEL_CONTEXT_MAX_BYTES} bytes`);
}
return context;
}
function utf8Length(value: string): number {
return new TextEncoder().encode(value).length;
}
/* ------------------------------------------------------------------------- */
/* Tool icons (SEP-973) */
/* ------------------------------------------------------------------------- */
/** A provider icon for a tool, resource or prompt, after sanitizing. */
export interface McpIcon {
src: string;
mimeType?: string;
sizes?: string[];
theme?: "light" | "dark";
}
export const MCP_ICON_MAX_COUNT = 4;
export const MCP_ICON_MAX_URL_LENGTH = 2048;
/** A `data:` icon larger than this is dropped. */
export const MCP_ICON_MAX_DATA_URI_LENGTH = 32 * 1024;
const RASTER_ICON_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/x-icon", "image/vnd.microsoft.icon"]);
const SVG_MIME_TYPE = "image/svg+xml";
/**
* Accepts only `https:` raster images and `data:image/*` URIs. SVG is allowed
* only inline as `data:`: a remote SVG could change after review. Icons are
* always rendered as `<img referrerPolicy="no-referrer">`, never inlined, so
* an SVG's scripts never run.
*/
export function sanitizeMcpIconSrc(src: unknown, mimeType?: string | null): string | null {
if (typeof src !== "string") return null;
const trimmed = src.trim();
if (/^data:/i.test(trimmed)) {
if (trimmed.length > MCP_ICON_MAX_DATA_URI_LENGTH) return null;
const match = /^data:(image\/[a-z0-9.+-]+)(;[a-z0-9=.+-]+)*,/i.exec(trimmed);
if (!match) return null;
const type = match[1]!.toLowerCase();
return type === SVG_MIME_TYPE || RASTER_ICON_MIME_TYPES.has(type) ? trimmed : null;
}
if (trimmed.length > MCP_ICON_MAX_URL_LENGTH) return null;
let url: URL;
try {
url = new URL(trimmed);
} catch {
return null;
}
if (url.protocol !== "https:" || url.username || url.password) return null;
if (mimeType && mimeType.toLowerCase() === SVG_MIME_TYPE) return null;
if (/\.svgz?$/i.test(url.pathname)) return null;
return url.toString();
}
/** Reads and sanitizes an MCP `icons` array. Returns null when none survive. */
export function readMcpIcons(value: unknown): McpIcon[] | null {
if (!Array.isArray(value)) return null;
const icons: McpIcon[] = [];
for (const item of value) {
if (icons.length >= MCP_ICON_MAX_COUNT) break;
const icon = record(item);
if (!icon) continue;
const rawMime = typeof icon.mimeType === "string" ? icon.mimeType.trim().toLowerCase() : null;
const mimeType = rawMime && (rawMime === SVG_MIME_TYPE || RASTER_ICON_MIME_TYPES.has(rawMime)) ? rawMime : null;
if (rawMime && !mimeType) continue;
const src = sanitizeMcpIconSrc(icon.src, mimeType);
if (!src) continue;
const sizes = Array.isArray(icon.sizes)
? icon.sizes.filter((size): size is string => typeof size === "string" && /^(any|\d{1,4}x\d{1,4})$/i.test(size)).slice(0, 8)
: [];
icons.push({
src,
...(mimeType ? { mimeType } : {}),
...(sizes.length > 0 ? { sizes } : {}),
...(icon.theme === "light" || icon.theme === "dark" ? { theme: icon.theme } : {}),
});
}
return icons.length > 0 ? icons : null;
}
/** The icon to show for a theme: a matching or theme-less icon, preferring small sizes. */
export function pickMcpIcon(icons: readonly McpIcon[] | null | undefined, theme: "light" | "dark"): McpIcon | null {
if (!icons?.length) return null;
const candidates = icons.filter((icon) => !icon.theme || icon.theme === theme);
const pool = candidates.length > 0 ? candidates : icons;
const smallest = (icon: McpIcon) => Math.min(...(icon.sizes ?? ["any"]).map((size) => {
const match = /^(\d+)x/i.exec(size);
return match ? Math.abs(Number(match[1]) - 32) : 1_000;
}));
return [...pool].sort((a, b) => smallest(a) - smallest(b))[0] ?? null;
}
+65
View File
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import {
MCP_ICON_MAX_COUNT,
MCP_ICON_MAX_DATA_URI_LENGTH,
pickMcpIcon,
readMcpIcons,
sanitizeMcpIconSrc,
} from "./mcp-apps.js";
const PNG = "https://cdn.example.com/icons/tool.png";
const SVG_DATA = "data:image/svg+xml;base64,PHN2Zy8+";
describe("sanitizeMcpIconSrc", () => {
it("keeps https raster images and data:image URIs, including inline SVG", () => {
expect(sanitizeMcpIconSrc(PNG)).toBe(PNG);
expect(sanitizeMcpIconSrc(SVG_DATA)).toBe(SVG_DATA);
expect(sanitizeMcpIconSrc("data:image/png;base64,iVBORw0KGgo=")).toBe("data:image/png;base64,iVBORw0KGgo=");
});
it("drops other schemes, remote SVG, credentials and oversize data", () => {
expect(sanitizeMcpIconSrc("http://cdn.example.com/tool.png")).toBeNull();
expect(sanitizeMcpIconSrc("javascript:alert(1)")).toBeNull();
expect(sanitizeMcpIconSrc("data:text/html;base64,PHNjcmlwdD4=")).toBeNull();
expect(sanitizeMcpIconSrc("https://cdn.example.com/tool.svg")).toBeNull();
expect(sanitizeMcpIconSrc("https://cdn.example.com/tool", "image/svg+xml")).toBeNull();
expect(sanitizeMcpIconSrc("https://user:pw@cdn.example.com/tool.png")).toBeNull();
expect(sanitizeMcpIconSrc(`data:image/png;base64,${"A".repeat(MCP_ICON_MAX_DATA_URI_LENGTH)}`)).toBeNull();
expect(sanitizeMcpIconSrc(42)).toBeNull();
});
});
describe("readMcpIcons", () => {
it("keeps valid icons with their metadata and drops the rest", () => {
expect(readMcpIcons([
{ src: PNG, mimeType: "image/png", sizes: ["32x32", "bogus"], theme: "dark" },
{ src: "http://insecure.example.com/a.png" },
{ src: "https://cdn.example.com/b", mimeType: "text/html" },
{ src: SVG_DATA, mimeType: "image/svg+xml", theme: "neon" },
])).toEqual([
{ src: PNG, mimeType: "image/png", sizes: ["32x32"], theme: "dark" },
{ src: SVG_DATA, mimeType: "image/svg+xml" },
]);
});
it("bounds the count and returns null when nothing survives", () => {
const many = Array.from({ length: 10 }, (_, i) => ({ src: `https://cdn.example.com/${i}.png` }));
expect(readMcpIcons(many)).toHaveLength(MCP_ICON_MAX_COUNT);
expect(readMcpIcons([{ src: "javascript:1" }])).toBeNull();
expect(readMcpIcons("nope")).toBeNull();
expect(readMcpIcons(undefined)).toBeNull();
});
});
describe("pickMcpIcon", () => {
it("prefers the theme's icon and a size near 32px", () => {
const icons = [
{ src: "https://a.example.com/light.png", theme: "light" as const },
{ src: "https://a.example.com/dark-512.png", theme: "dark" as const, sizes: ["512x512"] },
{ src: "https://a.example.com/dark-32.png", theme: "dark" as const, sizes: ["32x32"] },
];
expect(pickMcpIcon(icons, "dark")?.src).toBe("https://a.example.com/dark-32.png");
expect(pickMcpIcon(icons, "light")?.src).toBe("https://a.example.com/light.png");
expect(pickMcpIcon(null, "light")).toBeNull();
});
});
+2
View File
@@ -3,6 +3,8 @@ export interface ActivityEvent {
companyId: string;
actorType: "agent" | "user" | "system" | "plugin";
actorId: string;
/** Person-facing name of the actor, such as an agent's or member's name, or "Board". */
actorName?: string;
action: string;
entityType: string;
entityId: string;
@@ -26,6 +26,23 @@ export interface ExecutionBlocker {
};
}
/**
* Where a queued, never-started run waits while its agent's concurrency limit
* is full. Position follows the order the server starts the agent's queued runs.
*/
export interface ExecutionAgentQueue {
agentId: string;
agentName: string;
/** The agent's concurrency limit (runtimeConfig.heartbeat.maxConcurrentRuns, as enforced). */
maxConcurrentRuns: number;
/** The agent's runs that are running now. */
runningCount: number;
/** 1-based place among the agent's queued runs; 1 starts when the next slot frees. */
position: number;
/** All of the agent's queued runs. */
queuedCount: number;
}
/** Presentation of existing execution records, not a second task status machine. */
export interface ExecutionProjection {
/** The board can Stop this run now: any queued or running run, or a failed native run whose retry is still pending. */
@@ -53,6 +70,8 @@ export interface ExecutionProjection {
permittedActions: Array<"inspect_run" | "inspect_recovery">;
predecessorRunId: string | null;
successorRunId: string | null;
/** Set when phase is "queued" because the agent's concurrency limit is full (cause "agent_at_capacity"). */
agentQueue?: ExecutionAgentQueue | null;
}
/** These incidents require an explicit reconciliation, never a generic Retry. */
@@ -145,6 +164,7 @@ export interface TaskInterruptionPresentation {
state: "working" | "retry_scheduled" | "failed" | "waiting_for_user" | "resolved";
nextRetryAt: string | null;
canRetry: boolean;
retryAction?: "move_forward";
userAction: "approval" | "reconnect" | "assign_agent" | "choose_model" | "resume" | "budget" | "project_access"
/** Board confirms that a previous server, which can no longer report, stopped its workspace copyback. */
| "confirm_owner_stop"
+2
View File
@@ -541,6 +541,8 @@ export type {
ToolAuditOutcome,
ToolCallEvent,
ToolCatalogEntry,
ProviderToolIconEntry,
ProviderToolIconsResponse,
ToolCatalogEntryKind,
ToolCatalogEntryStatus,
ToolAppAttentionItem,
+6
View File
@@ -146,6 +146,12 @@ export interface InstanceExperimentalSettings {
* redeploy.
*/
enableSandboxDuplexBridge: boolean;
/**
* MCP Tasks: long provider tool calls become durable tasks that survive
* timeouts, restarts, and deploys. Default off: the extension is not
* declared, so behavior matches a client without it.
*/
enableMcpTasks: boolean;
/**
* @deprecated Compatibility-only. Provider WebSocket ingress now follows
* enableNativeRunner and this value has no runtime effect.
+4
View File
@@ -1001,6 +1001,8 @@ export interface Issue {
watchdog?: IssueWatchdogSummary | null;
scheduledRetry?: IssueScheduledRetry | null;
liveDescendantCount?: number;
/** Descendants whose run started; excludes runs still waiting for an agent slot. */
runningDescendantCount?: number;
relatedWork?: IssueRelatedWorkSummary;
referencedIssueIdentifiers?: string[];
planDocument?: IssueDocument | null;
@@ -1076,6 +1078,8 @@ export type CompactIssue = Pick<
blockedInboxAttention?: IssueBlockedInboxAttention | null;
scheduledRetry?: IssueScheduledRetry | null;
liveDescendantCount?: number;
/** Descendants whose run started; excludes runs still waiting for an agent slot. */
runningDescendantCount?: number;
myLastTouchAt?: Date | null;
lastExternalCommentAt?: Date | null;
lastActivityAt?: Date | null;
+17 -1
View File
@@ -1,4 +1,4 @@
import type { McpAppToolUi } from "../mcp-apps.js";
import type { McpAppToolUi, McpIcon } from "../mcp-apps.js";
import type {
ConnectionTokenIssuanceOutcome,
ConnectionTokenIssuancePath,
@@ -571,6 +571,8 @@ export interface ToolCatalogEntry {
annotations: Record<string, unknown> | null;
/** MCP Apps view declaration (`_meta.ui`), when the tool renders one. */
uiMeta?: McpAppToolUi | null;
/** Sanitized provider icons (SEP-973), when the tool declares any. */
icons?: McpIcon[] | null;
riskLevel: ToolRiskLevel;
isReadOnly: boolean;
isWrite: boolean;
@@ -1761,3 +1763,17 @@ export interface ToolConnectionTestCallStatus {
/** ISO timestamp the request was resolved (approved/denied/cancelled), when applicable. */
resolvedAt?: string | null;
}
/** A connected tool's provider icons, keyed by its tool gateway name. */
export interface ProviderToolIconEntry {
/** `mcp.<app>-<connection>:<tool>`, as agents see the tool. */
gatewayToolName: string;
/** `app_<name>_<digest>`, the name native runners (and so their transcripts) use. */
nativeToolName?: string;
icons: McpIcon[];
}
/** `GET /api/companies/:companyId/tool-icons` */
export interface ProviderToolIconsResponse {
icons: ProviderToolIconEntry[];
}
@@ -93,6 +93,9 @@ export const instanceExperimentalSettingsSchema = z.object({
// off the host keeps the file bridge for every run with no manifest change and
// no redeploy. The host reads this per run before it selects the transport.
enableSandboxDuplexBridge: z.boolean().default(false),
// MCP Tasks (io.modelcontextprotocol/tasks): durable long provider calls.
// Off: Paperclip never declares the extension, so servers never return tasks.
enableMcpTasks: z.boolean().default(false),
// Deprecated compatibility key. Runner ingress follows enableNativeRunner;
// this remains accepted so older stored rows and managed configs keep loading.
enableRunnerPreviewIngress: z.boolean().default(false),
+1
View File
@@ -646,6 +646,7 @@ export const retryWorkspaceExportSchema = z.object({
export const taskRetrySchema = z.object({
idempotencyKey: z.string().guid(),
observedRunId: z.string().guid().nullable(),
retryAction: z.literal("move_forward").optional(),
}).strict();
export const recoverWorkspaceSchema = z.object({