Merge origin/master and integrate environment selection

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-11 06:18:05 -05:00
commit fed4802b72
159 files changed
+13953 -2027

No files matched your search

@@ -153,6 +153,7 @@ describe("opencode remote execution", () => {
config: {
command: "opencode",
model: "opencode/gpt-5-nano",
extraArgs: ["--", "--dir"],
...(managed ? {
managedAiConnection: { provider: "openrouter", method: "api_key" },
} : {}),
@@ -236,6 +237,7 @@ describe("opencode remote execution", () => {
`${managedRemoteWorkspace}/.paperclip-runtime/opencode/xdgConfig`,
);
expect(modelProbeCall?.[3].remoteExecution?.remoteCwd).toBe("/remote/workspace");
expect(runCall?.[2].slice(-4)).toEqual(["--dir", managedRemoteWorkspace, "--", "--dir"]);
const call = runCall as
| [string, string, string[], { env: Record<string, string>; remoteExecution?: { remoteCwd: string } | null }]
| undefined;
@@ -335,7 +337,7 @@ describe("opencode remote execution", () => {
expect(startAdapterExecutionTargetPaperclipBridge).not.toHaveBeenCalled();
});
it("resumes saved OpenCode sessions for remote SSH execution only when the identity matches", async () => {
it("resumes matching remote sessions and preserves an explicit run directory", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-remote-resume-"));
cleanupDirs.push(rootDir);
const workspaceDir = path.join(rootDir, "workspace");
@@ -370,6 +372,7 @@ describe("opencode remote execution", () => {
config: {
command: "opencode",
model: "opencode/gpt-5-nano",
extraArgs: ["--dir", "/operator-supplied"],
},
context: {
paperclipWorkspace: {
@@ -397,5 +400,7 @@ describe("opencode remote execution", () => {
| undefined;
expect(call?.[2]).toContain("--session");
expect(call?.[2]).toContain("session-123");
expect(call?.[2].slice(-2)).toEqual(["--dir", "/operator-supplied"]);
expect(call?.[2].filter((arg) => arg === "--dir" || arg.startsWith("--dir="))).toHaveLength(1);
});
});
@@ -621,6 +621,13 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
if (resumeSessionId) args.push("--session", resumeSessionId);
if (model) args.push("--model", model);
if (variant) args.push("--variant", variant);
// OpenCode prefers the inherited PWD over process.cwd(). Use the realized
// workspace unless the operator already selected a directory explicitly.
const optionTerminator = extraArgs.indexOf("--");
const extraOptionArgs = optionTerminator === -1 ? extraArgs : extraArgs.slice(0, optionTerminator);
if (!extraOptionArgs.some((arg) => arg === "--dir" || arg.startsWith("--dir="))) {
args.push("--dir", effectiveExecutionCwd);
}
if (extraArgs.length > 0) args.push(...extraArgs);
return args;
};
@@ -1,3 +1,6 @@
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
ensurePiModelConfiguredAndAvailable,
@@ -30,4 +33,34 @@ describe("pi models", () => {
}),
).rejects.toThrow();
});
it("does not embed the model catalogue when the configured model is unavailable", async () => {
const directory = await mkdtemp(join(tmpdir(), "paperclip-pi-models-"));
const command = join(directory, "pi");
const modelIds = Array.from({ length: 13 }, (_, index) => `provider/model-${index}`);
await writeFile(
command,
`#!/bin/sh\nprintf 'provider model\\n';\n${modelIds
.map((id) => {
const [provider, model] = id.split("/");
return `printf '${provider} ${model}\\n'`;
})
.join(";\n")}\n`,
);
await chmod(command, 0o755);
try {
await expect(
ensurePiModelConfiguredAndAvailable({
command,
model: "provider/missing",
}),
).rejects.toMatchObject({
message:
"Configured Pi model is unavailable: provider/missing. 13 models are available; list them with `pi --list-models`.",
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});
@@ -188,9 +188,8 @@ export async function ensurePiModelConfiguredAndAvailable(input: {
}
if (!models.some((entry) => entry.id === model)) {
const sample = models.slice(0, 12).map((entry) => entry.id).join(", ");
throw new Error(
`Configured Pi model is unavailable: ${model}. Available models: ${sample}${models.length > 12 ? ", ..." : ""}`,
`Configured Pi model is unavailable: ${model}. ${models.length} models are available; list them with \`pi --list-models\`.`,
);
}
+13 -7
View File
@@ -467,12 +467,12 @@ async function recordMigrationHistoryEntry(
);
}
// These idempotent privacy migrations commit keyset batches inside their DO
// blocks. Execute each statement at top level so DDL locks and completed batches
// are released before the next batch. History is recorded only after completion.
const MIGRATIONS_WITH_BATCH_COMMITS = new Set([
// These idempotent migrations require top-level statements for batch commits
// or concurrent index builds. History is recorded only after completion.
const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([
"0313_private_task_access.sql",
"0314_private_task_draft_assets.sql",
"0332_little_night_nurse.sql",
]);
async function applyPendingMigrationsManually(
@@ -493,7 +493,13 @@ async function applyPendingMigrationsManually(
try {
// A session lock survives each batch COMMIT. Reserve the connection so
// pool rotation cannot release it while another migrator is waiting.
await sql`SELECT pg_advisory_lock(hashtextextended('paperclip:migrations', 0))`;
// A blocking lock SELECT retains its statement snapshot while waiting.
// A partial concurrent index build can wait for that snapshot, forming a
// deadlock with this lock. Each failed try ends its snapshot before sleep.
while (!(await sql<{ locked: boolean }[]>`
SELECT pg_try_advisory_lock(hashtextextended('paperclip:migrations', 0)) AS locked`)[0]?.locked) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
const { migrationTableSchema, columnNames } = await ensureMigrationJournalTable(sql);
const qualifiedTable = `${quoteIdentifier(migrationTableSchema)}.${quoteIdentifier(DRIZZLE_MIGRATIONS_TABLE)}`;
@@ -511,7 +517,7 @@ async function applyPendingMigrationsManually(
const applyMigration = async () => {
for (const statement of splitMigrationStatements(migrationContent)) {
if (MIGRATIONS_WITH_BATCH_COMMITS.has(migrationFile)) {
if (MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS.has(migrationFile)) {
// A cancelled concurrent build leaves an invalid index. IF NOT
// EXISTS alone would skip it on retry and journal an incomplete index.
const index = statement.replace(/^\s*--.*$/gm, "").trim()
@@ -545,7 +551,7 @@ async function applyPendingMigrationsManually(
folderMillisByFileName.get(migrationFile) ?? Date.now(),
);
};
if (MIGRATIONS_WITH_BATCH_COMMITS.has(migrationFile)) {
if (MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS.has(migrationFile)) {
await applyMigration();
} else {
await runInTransaction(sql, applyMigration);
@@ -229,7 +229,8 @@ describeEmbeddedPostgres("heartbeat run issue privacy migration", () => {
contender = applyPendingMigrations(database.connectionString).then(() => null, error => error);
await expect.poll(async () => {
const [row] = await sql`SELECT count(*)::int AS n FROM pg_stat_activity
WHERE datname = current_database() AND wait_event = 'advisory'
WHERE datname = current_database() AND query LIKE '%SELECT pg_try_advisory_lock%'
AND query NOT LIKE '%FROM pg_stat_activity%'
AND strpos(query, 'paperclip:migrations') > 0`;
return row.n;
}, { timeout: 10_000 }).toBe(1);
@@ -0,0 +1,74 @@
CREATE TABLE IF NOT EXISTS "company_fast_responses" (
"company_id" uuid PRIMARY KEY NOT NULL,
"connection_id" uuid,
"grant_id" uuid,
"model" text,
"provider" text,
"enabled" boolean DEFAULT false NOT NULL,
"allow_sponsored" boolean DEFAULT true NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "company_fast_responses_configured" CHECK (("company_fast_responses"."connection_id" is null) = ("company_fast_responses"."grant_id" is null) and (not "company_fast_responses"."enabled" or ("company_fast_responses"."connection_id" is not null and "company_fast_responses"."model" is not null)))
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "fast_response_requests" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"company_id" uuid NOT NULL,
"source_key" text NOT NULL,
"source_comment_id" uuid,
"issue_id" uuid,
"project_id" uuid,
"agent_id" uuid,
"responsible_user_id" text,
"sponsored" boolean DEFAULT false NOT NULL,
"endpoint_id" uuid,
"conversation_id" uuid,
"delivery_id" uuid,
"session_generation" integer,
"status" text DEFAULT 'pending' NOT NULL,
"publication_status" text DEFAULT 'pending' NOT NULL,
"connection_id" uuid,
"grant_id" uuid,
"provider" text,
"model" text,
"provider_request_id" text,
"cost_event_id" uuid,
"error_code" text,
"comment_id" uuid,
"accepted_at" timestamp with time zone DEFAULT now() NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"started_at" timestamp with time zone,
"finished_at" timestamp with time zone,
"duration_ms" integer,
"input_tokens" integer,
"output_tokens" integer,
CONSTRAINT "fast_response_requests_status_check" CHECK ("fast_response_requests"."status" in ('pending', 'running', 'succeeded', 'failed', 'unknown', 'skipped'))
);
--> statement-breakpoint
ALTER TABLE "budget_reservations" DROP CONSTRAINT IF EXISTS "budget_reservations_source_check";--> statement-breakpoint
ALTER TABLE "cost_events" DROP CONSTRAINT IF EXISTS "cost_events_usage_kind_check";--> statement-breakpoint
ALTER TABLE "budget_reservations" ADD COLUMN IF NOT EXISTS "fast_response_request_id" uuid;--> statement-breakpoint
ALTER TABLE "issue_comments" ADD COLUMN IF NOT EXISTS "origin" text DEFAULT 'comment' NOT NULL;--> statement-breakpoint
ALTER TABLE "issue_comments" ADD COLUMN IF NOT EXISTS "fast_response_request_id" uuid;--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "company_fast_responses" ADD CONSTRAINT "company_fast_responses_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "fast_response_requests" ADD CONSTRAINT "fast_response_requests_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "fast_response_requests" ADD CONSTRAINT "fast_response_requests_cost_event_id_cost_events_id_fk" FOREIGN KEY ("cost_event_id") REFERENCES "public"."cost_events"("id") ON DELETE no action ON UPDATE no action;
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
--> statement-breakpoint
CREATE UNIQUE INDEX IF NOT EXISTS "fast_response_requests_source_idx" ON "fast_response_requests" USING btree ("company_id","source_key");--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "fast_response_requests_history_idx" ON "fast_response_requests" USING btree ("company_id","accepted_at");--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "fast_response_requests_work_idx" ON "fast_response_requests" USING btree ("expires_at") WHERE "fast_response_requests"."status" in ('pending', 'running');--> statement-breakpoint
CREATE UNIQUE INDEX IF NOT EXISTS "budget_reservations_fast_response_idx" ON "budget_reservations" USING btree ("company_id","fast_response_request_id");--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "budget_reservations" ADD CONSTRAINT "budget_reservations_source_check" CHECK (("budget_reservations"."run_id" is not null)::int + ("budget_reservations"."decision_invocation_id" is not null)::int + ("budget_reservations"."fast_response_request_id" is not null)::int = 1);
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "cost_events" ADD CONSTRAINT "cost_events_usage_kind_check" CHECK ("cost_events"."usage_kind" in ('decision', 'fast_response') or ("cost_events"."usage_kind" = 'agent' and "cost_events"."agent_id" is not null));
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
@@ -0,0 +1 @@
CREATE INDEX CONCURRENTLY IF NOT EXISTS "agent_wakeup_requests_question_response_history_idx" ON "agent_wakeup_requests" USING btree ("company_id","idempotency_key") WHERE "agent_wakeup_requests"."idempotency_key" LIKE 'question-response:%';
@@ -28,17 +28,17 @@ ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "workspace_binding_revision" integ
ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "workspace_selection" jsonb;--> statement-breakpoint
ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "workspace_pending_selection" jsonb;--> statement-breakpoint
DO $migration$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = 'execution_workspace_repositories'::regclass AND conname = 'execution_workspace_repositories_company_id_companies_id_fk') THEN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = 'execution_workspace_repositories'::regclass AND conname = 'execution_workspace_repositories_company_id_companies_id_fk'::name) THEN
ALTER TABLE "execution_workspace_repositories" ADD CONSTRAINT "execution_workspace_repositories_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
END IF;
END $migration$;--> statement-breakpoint
DO $migration$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = 'execution_workspace_repositories'::regclass AND conname = 'execution_workspace_repositories_execution_workspace_id_execution_workspaces_id_fk') THEN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = 'execution_workspace_repositories'::regclass AND conname = 'execution_workspace_repositories_execution_workspace_id_execution_workspaces_id_fk'::name) THEN
ALTER TABLE "execution_workspace_repositories" ADD CONSTRAINT "execution_workspace_repositories_execution_workspace_id_execution_workspaces_id_fk" FOREIGN KEY ("execution_workspace_id") REFERENCES "public"."execution_workspaces"("id") ON DELETE cascade ON UPDATE no action;
END IF;
END $migration$;--> statement-breakpoint
DO $migration$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = 'execution_workspace_repositories'::regclass AND conname = 'execution_workspace_repositories_requested_by_issue_id_issues_id_fk') THEN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = 'execution_workspace_repositories'::regclass AND conname = 'execution_workspace_repositories_requested_by_issue_id_issues_id_fk'::name) THEN
ALTER TABLE "execution_workspace_repositories" ADD CONSTRAINT "execution_workspace_repositories_requested_by_issue_id_issues_id_fk" FOREIGN KEY ("requested_by_issue_id") REFERENCES "public"."issues"("id") ON DELETE set null ON UPDATE no action;
END IF;
END $migration$;--> statement-breakpoint
@@ -46,4 +46,4 @@ CREATE UNIQUE INDEX IF NOT EXISTS "execution_workspace_repositories_identity_idx
CREATE UNIQUE INDEX IF NOT EXISTS "execution_workspace_repositories_path_idx" ON "execution_workspace_repositories" USING btree ("execution_workspace_id","relative_path");--> statement-breakpoint
CREATE UNIQUE INDEX IF NOT EXISTS "execution_workspace_repositories_request_idx" ON "execution_workspace_repositories" USING btree ("execution_workspace_id","request_key");--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "execution_workspace_repositories_company_workspace_idx" ON "execution_workspace_repositories" USING btree ("company_id","execution_workspace_id");--> statement-breakpoint
ALTER TABLE "execution_workspaces" ADD CONSTRAINT "execution_workspaces_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE restrict ON UPDATE no action;
ALTER TABLE "execution_workspaces" ADD CONSTRAINT "execution_workspaces_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE restrict ON UPDATE no action;
+417 -282
View File
@@ -1,5 +1,5 @@
{
"id": "fadaea95-8f4d-4184-8247-cd25505c9f83",
"id": "5c09a14d-e323-49b1-b855-dcd12b974bcc",
"prevId": "0a93bc99-bf0c-4ea2-ab27-6043b6746cd5",
"version": "7",
"dialect": "postgresql",
@@ -416,6 +416,12 @@
"primaryKey": false,
"notNull": false
},
"fast_response_request_id": {
"name": "fast_response_request_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"agent_id": {
"name": "agent_id",
"type": "uuid",
@@ -462,6 +468,27 @@
}
},
"indexes": {
"budget_reservations_fast_response_idx": {
"name": "budget_reservations_fast_response_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "fast_response_request_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
},
"budget_reservations_decision_idx": {
"name": "budget_reservations_decision_idx",
"columns": [
@@ -580,7 +607,7 @@
"checkConstraints": {
"budget_reservations_source_check": {
"name": "budget_reservations_source_check",
"value": "(\"budget_reservations\".\"run_id\" is not null)::int + (\"budget_reservations\".\"decision_invocation_id\" is not null)::int = 1"
"value": "(\"budget_reservations\".\"run_id\" is not null)::int + (\"budget_reservations\".\"decision_invocation_id\" is not null)::int + (\"budget_reservations\".\"fast_response_request_id\" is not null)::int = 1"
},
"budget_reservations_state_check": {
"name": "budget_reservations_state_check",
@@ -9809,12 +9836,6 @@
"notNull": true,
"default": false
},
"execution_defaults": {
"name": "execution_defaults",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"metadata": {
"name": "metadata",
"type": "jsonb",
@@ -10055,12 +10076,6 @@
"notNull": true,
"default": "''"
},
"execution_defaults": {
"name": "execution_defaults",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"allow_direct_messages": {
"name": "allow_direct_messages",
"type": "boolean",
@@ -19838,7 +19853,7 @@
"checkConstraints": {
"cost_events_usage_kind_check": {
"name": "cost_events_usage_kind_check",
"value": "\"cost_events\".\"usage_kind\" = 'decision' or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)"
"value": "\"cost_events\".\"usage_kind\" in ('decision', 'fast_response') or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)"
},
"cost_events_nonnegative_amounts": {
"name": "cost_events_nonnegative_amounts",
@@ -26193,252 +26208,6 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.execution_workspace_repositories": {
"name": "execution_workspace_repositories",
"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
},
"execution_workspace_id": {
"name": "execution_workspace_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"requested_by_issue_id": {
"name": "requested_by_issue_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"repository_identity": {
"name": "repository_identity",
"type": "text",
"primaryKey": false,
"notNull": true
},
"catalog_repository_id": {
"name": "catalog_repository_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"repo_url": {
"name": "repo_url",
"type": "text",
"primaryKey": false,
"notNull": true
},
"relative_path": {
"name": "relative_path",
"type": "text",
"primaryKey": false,
"notNull": true
},
"requested_ref": {
"name": "requested_ref",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'HEAD'"
},
"pinned_commit": {
"name": "pinned_commit",
"type": "text",
"primaryKey": false,
"notNull": false
},
"branch_name": {
"name": "branch_name",
"type": "text",
"primaryKey": false,
"notNull": false
},
"request_key": {
"name": "request_key",
"type": "text",
"primaryKey": false,
"notNull": true
},
"request_keys": {
"name": "request_keys",
"type": "jsonb",
"primaryKey": false,
"notNull": true,
"default": "'[]'::jsonb"
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'pending'"
},
"failure_code": {
"name": "failure_code",
"type": "text",
"primaryKey": false,
"notNull": false
},
"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": {
"execution_workspace_repositories_identity_idx": {
"name": "execution_workspace_repositories_identity_idx",
"columns": [
{
"expression": "execution_workspace_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "repository_identity",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
},
"execution_workspace_repositories_path_idx": {
"name": "execution_workspace_repositories_path_idx",
"columns": [
{
"expression": "execution_workspace_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "relative_path",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
},
"execution_workspace_repositories_request_idx": {
"name": "execution_workspace_repositories_request_idx",
"columns": [
{
"expression": "execution_workspace_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "request_key",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
},
"execution_workspace_repositories_company_workspace_idx": {
"name": "execution_workspace_repositories_company_workspace_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "execution_workspace_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"execution_workspace_repositories_company_id_companies_id_fk": {
"name": "execution_workspace_repositories_company_id_companies_id_fk",
"tableFrom": "execution_workspace_repositories",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"execution_workspace_repositories_execution_workspace_id_execution_workspaces_id_fk": {
"name": "execution_workspace_repositories_execution_workspace_id_execution_workspaces_id_fk",
"tableFrom": "execution_workspace_repositories",
"tableTo": "execution_workspaces",
"columnsFrom": [
"execution_workspace_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"execution_workspace_repositories_requested_by_issue_id_issues_id_fk": {
"name": "execution_workspace_repositories_requested_by_issue_id_issues_id_fk",
"tableFrom": "execution_workspace_repositories",
"tableTo": "issues",
"columnsFrom": [
"requested_by_issue_id"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.execution_workspace_runtime_leases": {
"name": "execution_workspace_runtime_leases",
"schema": "",
@@ -26694,7 +26463,7 @@
"name": "project_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
"notNull": true
},
"project_workspace_id": {
"name": "project_workspace_id",
@@ -26972,7 +26741,7 @@
"columnsTo": [
"id"
],
"onDelete": "restrict",
"onDelete": "cascade",
"onUpdate": "no action"
},
"execution_workspaces_project_workspace_id_project_workspaces_id_fk": {
@@ -27749,6 +27518,378 @@
"checkConstraints": {},
"isRLSEnabled": false
},
"public.company_fast_responses": {
"name": "company_fast_responses",
"schema": "",
"columns": {
"company_id": {
"name": "company_id",
"type": "uuid",
"primaryKey": true,
"notNull": true
},
"connection_id": {
"name": "connection_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"grant_id": {
"name": "grant_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"model": {
"name": "model",
"type": "text",
"primaryKey": false,
"notNull": false
},
"provider": {
"name": "provider",
"type": "text",
"primaryKey": false,
"notNull": false
},
"enabled": {
"name": "enabled",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"allow_sponsored": {
"name": "allow_sponsored",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": true
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"company_fast_responses_company_id_companies_id_fk": {
"name": "company_fast_responses_company_id_companies_id_fk",
"tableFrom": "company_fast_responses",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {
"company_fast_responses_configured": {
"name": "company_fast_responses_configured",
"value": "(\"company_fast_responses\".\"connection_id\" is null) = (\"company_fast_responses\".\"grant_id\" is null) and (not \"company_fast_responses\".\"enabled\" or (\"company_fast_responses\".\"connection_id\" is not null and \"company_fast_responses\".\"model\" is not null))"
}
},
"isRLSEnabled": false
},
"public.fast_response_requests": {
"name": "fast_response_requests",
"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
},
"source_key": {
"name": "source_key",
"type": "text",
"primaryKey": false,
"notNull": true
},
"source_comment_id": {
"name": "source_comment_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"issue_id": {
"name": "issue_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"project_id": {
"name": "project_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"agent_id": {
"name": "agent_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"responsible_user_id": {
"name": "responsible_user_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"sponsored": {
"name": "sponsored",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"endpoint_id": {
"name": "endpoint_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"conversation_id": {
"name": "conversation_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"delivery_id": {
"name": "delivery_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"session_generation": {
"name": "session_generation",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'pending'"
},
"publication_status": {
"name": "publication_status",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'pending'"
},
"connection_id": {
"name": "connection_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"grant_id": {
"name": "grant_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"provider": {
"name": "provider",
"type": "text",
"primaryKey": false,
"notNull": false
},
"model": {
"name": "model",
"type": "text",
"primaryKey": false,
"notNull": false
},
"provider_request_id": {
"name": "provider_request_id",
"type": "text",
"primaryKey": false,
"notNull": false
},
"cost_event_id": {
"name": "cost_event_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false
},
"comment_id": {
"name": "comment_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"accepted_at": {
"name": "accepted_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"expires_at": {
"name": "expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"started_at": {
"name": "started_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"finished_at": {
"name": "finished_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"duration_ms": {
"name": "duration_ms",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"input_tokens": {
"name": "input_tokens",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"output_tokens": {
"name": "output_tokens",
"type": "integer",
"primaryKey": false,
"notNull": false
}
},
"indexes": {
"fast_response_requests_source_idx": {
"name": "fast_response_requests_source_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "source_key",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
},
"fast_response_requests_history_idx": {
"name": "fast_response_requests_history_idx",
"columns": [
{
"expression": "company_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "accepted_at",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"fast_response_requests_work_idx": {
"name": "fast_response_requests_work_idx",
"columns": [
{
"expression": "expires_at",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"where": "\"fast_response_requests\".\"status\" in ('pending', 'running')",
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {
"fast_response_requests_company_id_companies_id_fk": {
"name": "fast_response_requests_company_id_companies_id_fk",
"tableFrom": "fast_response_requests",
"tableTo": "companies",
"columnsFrom": [
"company_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"fast_response_requests_cost_event_id_cost_events_id_fk": {
"name": "fast_response_requests_cost_event_id_cost_events_id_fk",
"tableFrom": "fast_response_requests",
"tableTo": "cost_events",
"columnsFrom": [
"cost_event_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {
"fast_response_requests_status_check": {
"name": "fast_response_requests_status_check",
"value": "\"fast_response_requests\".\"status\" in ('pending', 'running', 'succeeded', 'failed', 'unknown', 'skipped')"
}
},
"isRLSEnabled": false
},
"public.feedback_exports": {
"name": "feedback_exports",
"schema": "",
@@ -32650,6 +32791,19 @@
"primaryKey": false,
"notNull": false
},
"origin": {
"name": "origin",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'comment'"
},
"fast_response_request_id": {
"name": "fast_response_request_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"body": {
"name": "body",
"type": "text",
@@ -37347,25 +37501,6 @@
"primaryKey": false,
"notNull": false
},
"workspace_binding_revision": {
"name": "workspace_binding_revision",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 0
},
"workspace_selection": {
"name": "workspace_selection",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"workspace_pending_selection": {
"name": "workspace_pending_selection",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"execution_workspace_preference": {
"name": "execution_workspace_preference",
"type": "text",
+16 -2
View File
@@ -2308,8 +2308,22 @@
{
"idx": 331,
"version": "7",
"when": 1791601811412,
"tag": "0331_harsh_newton_destine",
"when": 1791642049733,
"tag": "0331_panoramic_spyke",
"breakpoints": true
},
{
"idx": 332,
"version": "7",
"when": 1791693159075,
"tag": "0332_little_night_nurse",
"breakpoints": true
},
{
"idx": 333,
"version": "7",
"when": 1791717218544,
"tag": "0333_pretty_infant_terrible",
"breakpoints": true
}
]
@@ -0,0 +1,53 @@
import { createHash, randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import postgres from "postgres";
import { describe, expect, it } from "vitest";
import { applyPendingMigrations } from "./client.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js";
const support = await getEmbeddedPostgresTestSupport();
const indexName = "agent_wakeup_requests_question_response_history_idx";
const migrationFile = "0332_little_night_nurse.sql";
(support.supported ? describe : describe.skip)("question-response history migration", () => {
it("repairs an interrupted concurrent index build and serializes replay without deleting wakes", async () => {
const database = await startEmbeddedPostgresTestDatabase("question-history-migration-");
const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} });
try {
const companyId = randomUUID();
const agentId = randomUUID();
await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Migration fixture', 'QHM')`;
await sql`INSERT INTO agents (id, company_id, name, role, adapter_type)
VALUES (${agentId}, ${companyId}, 'Fixture', 'engineer', 'process')`;
await sql`INSERT INTO agent_wakeup_requests (company_id, agent_id, source, idempotency_key, status)
SELECT ${companyId}::uuid, ${agentId}::uuid, 'automation', 'question-response:' || n::text, 'failed'
FROM generate_series(1, 3) n`;
const content = await readFile(new URL(`./migrations/${migrationFile}`, import.meta.url), "utf8");
const hash = createHash("sha256").update(content).digest("hex");
await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`;
await sql.unsafe(`DROP INDEX ${indexName}`);
// A failed concurrent UNIQUE build leaves the same invalid-index state
// as an interrupted nonunique build, without relying on timing a cancel.
await expect(sql.unsafe(`CREATE UNIQUE INDEX CONCURRENTLY ${indexName} ON agent_wakeup_requests (company_id)`))
.rejects.toThrow();
const [invalid] = await sql`SELECT i.indisvalid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
WHERE c.relname = ${indexName}`;
expect(invalid?.indisvalid).toBe(false);
await Promise.all([applyPendingMigrations(database.connectionString), applyPendingMigrations(database.connectionString)]);
const [rebuilt] = await sql`SELECT i.indisvalid, i.indisunique, pg_get_indexdef(i.indexrelid) AS definition
FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid WHERE c.relname = ${indexName}`;
expect(rebuilt?.indisvalid).toBe(true);
expect(rebuilt?.indisunique).toBe(false);
expect(rebuilt?.definition).toContain("company_id, idempotency_key");
expect(rebuilt?.definition).toContain("question-response:%");
const [wakes] = await sql`SELECT count(*)::int AS n FROM agent_wakeup_requests WHERE company_id = ${companyId}`;
expect(wakes?.n).toBe(3);
const [history] = await sql`SELECT count(*)::int AS n FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`;
expect(history?.n).toBe(1);
await applyPendingMigrations(database.connectionString);
} finally {
await sql.end();
await database.cleanup();
}
}, 60_000);
});
+3 -1
View File
@@ -54,6 +54,7 @@ export const budgetReservations = pgTable("budget_reservations", {
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
runId: uuid("run_id").references(() => heartbeatRuns.id, { onDelete: "cascade" }),
decisionInvocationId: uuid("decision_invocation_id"),
fastResponseRequestId: uuid("fast_response_request_id"),
agentId: uuid("agent_id").references(() => agents.id, { onDelete: "cascade" }),
projectId: uuid("project_id"),
amountCents: numeric("amount_cents", { precision: 24, scale: 7 }).notNull(),
@@ -62,8 +63,9 @@ export const budgetReservations = pgTable("budget_reservations", {
settledAt: timestamp("settled_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
}, table => ({
fastResponse: uniqueIndex("budget_reservations_fast_response_idx").on(table.companyId, table.fastResponseRequestId),
decision: uniqueIndex("budget_reservations_decision_idx").on(table.companyId, table.decisionInvocationId),
source: check("budget_reservations_source_check", sql`(${table.runId} is not null)::int + (${table.decisionInvocationId} is not null)::int = 1`),
source: check("budget_reservations_source_check", sql`(${table.runId} is not null)::int + (${table.decisionInvocationId} is not null)::int + (${table.fastResponseRequestId} is not null)::int = 1`),
run: uniqueIndex("budget_reservations_run_idx").on(table.companyId, table.runId),
active: index("budget_reservations_active_idx").on(table.companyId, table.agentId, table.projectId).where(sql`${table.state} = 'held'`),
stateCheck: check("budget_reservations_state_check", sql`${table.state} in ('held', 'settled', 'released')`),
@@ -75,6 +75,12 @@ export const agentWakeupRequests = pgTable(
)
.on(table.companyId, table.idempotencyKey)
.where(sql`(${table.idempotencyKey} LIKE 'question-response:%' OR ${table.idempotencyKey} LIKE 'interaction:%') AND ${table.status} NOT IN ('skipped', 'failed', 'cancelled')`),
// Sleep checks also need failed/cancelled/skipped receipts, which the
// delivery idempotency fence deliberately excludes.
questionResponseHistoryIdx: index("agent_wakeup_requests_question_response_history_idx")
.on(table.companyId, table.idempotencyKey)
.concurrently()
.where(sql`${table.idempotencyKey} LIKE 'question-response:%'`),
connectionIntentDeliveryIdempotencyUq: uniqueIndex("agent_wakeup_requests_connection_intent_delivery_idempotency_uq")
.on(table.companyId, table.idempotencyKey)
.where(sql`${table.idempotencyKey} LIKE 'connection-intent:%' AND ${table.status} NOT IN ('skipped', 'failed', 'cancelled')`),
+1 -1
View File
@@ -40,7 +40,7 @@ export const costEvents = pgTable(
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
},
(table) => ({
usageKindCheck: check("cost_events_usage_kind_check", sql`${table.usageKind} = 'decision' or (${table.usageKind} = 'agent' and ${table.agentId} is not null)`),
usageKindCheck: check("cost_events_usage_kind_check", sql`${table.usageKind} in ('decision', 'fast_response') or (${table.usageKind} = 'agent' and ${table.agentId} is not null)`),
receiptUniqueIdx: uniqueIndex("cost_events_company_receipt_idx").on(table.companyId, table.idempotencyKey),
providerRequestIdx: index("cost_events_provider_request_idx").on(table.companyId, table.biller, table.providerRequestId),
nonnegativeAmounts: check("cost_events_nonnegative_amounts", sql`${table.costCents} >= 0 and ${table.inputTokens} >= 0 and ${table.cachedInputTokens} >= 0 and ${table.outputTokens} >= 0`),
+96
View File
@@ -0,0 +1,96 @@
import { sql } from "drizzle-orm";
import {
boolean,
check,
index,
integer,
pgTable,
text,
timestamp,
uniqueIndex,
uuid,
} from "drizzle-orm/pg-core";
import { companies } from "./companies.js";
import { costEvents } from "./cost_events.js";
export const companyFastResponses = pgTable(
"company_fast_responses",
{
companyId: uuid("company_id")
.primaryKey()
.references(() => companies.id, { onDelete: "cascade" }),
connectionId: uuid("connection_id"),
grantId: uuid("grant_id"),
model: text("model"),
provider: text("provider"),
enabled: boolean("enabled").notNull().default(false),
allowSponsored: boolean("allow_sponsored").notNull().default(true),
updatedAt: timestamp("updated_at", { withTimezone: true })
.notNull()
.defaultNow(),
},
(t) => ({
configured: check(
"company_fast_responses_configured",
sql`(${t.connectionId} is null) = (${t.grantId} is null) and (not ${t.enabled} or (${t.connectionId} is not null and ${t.model} is not null))`,
),
}),
);
/** Durable receipt job and content-free inference accounting. Never stores prompts or credentials. */
export const fastResponseRequests = pgTable(
"fast_response_requests",
{
id: uuid("id").primaryKey().defaultRandom(),
companyId: uuid("company_id")
.notNull()
.references(() => companies.id, { onDelete: "cascade" }),
sourceKey: text("source_key").notNull(),
sourceCommentId: uuid("source_comment_id"),
issueId: uuid("issue_id"),
projectId: uuid("project_id"),
agentId: uuid("agent_id"),
responsibleUserId: text("responsible_user_id"),
sponsored: boolean("sponsored").notNull().default(false),
endpointId: uuid("endpoint_id"),
conversationId: uuid("conversation_id"),
deliveryId: uuid("delivery_id"),
sessionGeneration: integer("session_generation"),
status: text("status").notNull().default("pending"),
publicationStatus: text("publication_status").notNull().default("pending"),
connectionId: uuid("connection_id"),
grantId: uuid("grant_id"),
provider: text("provider"),
model: text("model"),
providerRequestId: text("provider_request_id"),
costEventId: uuid("cost_event_id").references(() => costEvents.id),
errorCode: text("error_code"),
commentId: uuid("comment_id"),
acceptedAt: timestamp("accepted_at", { withTimezone: true })
.notNull()
.defaultNow(),
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
startedAt: timestamp("started_at", { withTimezone: true }),
finishedAt: timestamp("finished_at", { withTimezone: true }),
durationMs: integer("duration_ms"),
inputTokens: integer("input_tokens"),
outputTokens: integer("output_tokens"),
},
(t) => ({
source: uniqueIndex("fast_response_requests_source_idx").on(
t.companyId,
t.sourceKey,
),
history: index("fast_response_requests_history_idx").on(
t.companyId,
t.acceptedAt,
),
work: index("fast_response_requests_work_idx")
.on(t.expiresAt)
.where(sql`${t.status} in ('pending', 'running')`),
status: check(
"fast_response_requests_status_check",
sql`${t.status} in ('pending', 'running', 'succeeded', 'failed', 'unknown', 'skipped')`,
),
}),
);
+1
View File
@@ -246,3 +246,4 @@ export { userCompanyPreferences } from "./user_company_preferences.js";
export { aiSubscriptions, aiSubscriptionPrices, aiSubscriptionConnections } from "./ai_subscriptions.js";
export { executionWorkspaceRepositories } from "./execution_workspace_repositories.js";
export * from "./fast_responses.js";
+2
View File
@@ -32,6 +32,8 @@ export const issueComments = pgTable(
derivedAuthorSource: text("derived_author_source").$type<IssueCommentDerivedAuthorSource>(),
clientRequestId: text("client_request_id"),
conversationSessionGeneration: integer("conversation_session_generation"),
origin: text("origin").$type<"comment" | "fast_response">().notNull().default("comment"),
fastResponseRequestId: uuid("fast_response_request_id"),
body: text("body").notNull(),
presentation: jsonb("presentation").$type<IssueCommentPresentation | null>(),
metadata: jsonb("metadata").$type<IssueCommentMetadata | null>(),
+1 -1
View File
@@ -63,7 +63,7 @@
},
"sideEffects": false,
"scripts": {
"build": "pnpm run check:protocol-manifest && pnpm run build:typescript && pnpm run check:capability-contract && pnpm run check:capability-inventory && pnpm run check:protocol-coverage && pnpm run check:semantic-contracts && pnpm run check:runner-workflow-traceability && pnpm run build:binary && node scripts/generate-replay-goldens.mjs --check && node scripts/generate-semantic-action-catalog.mjs --check",
"build": "pnpm run check:protocol-manifest && pnpm run build:typescript && pnpm run check:capability-contract && pnpm run check:capability-inventory && pnpm run check:protocol-coverage && node scripts/generate-semantic-contracts.mjs --check && node scripts/check-runner-workflow-traceability.mjs && pnpm run build:binary && node scripts/generate-replay-goldens.mjs --check && node scripts/generate-semantic-action-catalog.mjs --check",
"build:typescript": "pnpm run check:acpx-profiles && pnpm run ensure:eval-build-deps && pnpm run check:protocol-types && node ./node_modules/typescript/bin/tsc --version && node ./node_modules/typescript/bin/tsc -p tsconfig.json && node ./node_modules/typescript/bin/tsc -p tsconfig.surfaces.json && node scripts/build-verified-provider-entrypoints.mjs",
"build:rust": "cargo build --manifest-path runner/Cargo.toml --locked --workspace --bins",
"build:binary": "cargo build --release --manifest-path runner/Cargo.toml --locked -p paperclip-runner-core --bin paperclip-runnerd && node scripts/stage-runner-binary.mjs",
@@ -689,6 +689,13 @@ describe("AppDefinition catalog", () => {
consoleLinks: { register: "https://app.asana.com/0/my-apps" },
});
expect(method("linear")?.ownershipModes).toEqual(["dcr", "customer"]);
expect(method("sentry")).toMatchObject({
key: "mcp-oauth",
defaults: {
serverUrl: "https://mcp.sentry.dev/mcp",
discoveryUrl: "https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp",
},
});
expect(method("zapier")).toMatchObject({
key: "generated-url",
auth: "none",
@@ -26,7 +26,7 @@
"whenToUse": "Use the provider-hosted connection for the quickest setup.",
"defaults": {
"serverUrl": "https://mcp.sentry.dev/mcp",
"discoveryUrl": "https://sentry.io/.well-known/oauth-authorization-server",
"discoveryUrl": "https://mcp.sentry.dev/.well-known/oauth-protected-resource/mcp",
"scopesHint": [
"org:read",
"project:write",
+69
View File
@@ -0,0 +1,69 @@
import { z } from "zod";
import type {
AiManagedConnectionSummary,
AiProvider,
} from "./ai-connections.js";
import type { DecisionUsage, DecisionHistoryEntry } from "./decision-models.js";
export const FAST_RESPONSE_DEADLINE_MS = 3_000;
export const FAST_RESPONSE_MAX_BYTES = 4_096;
export const FAST_RESPONSE_MAX_CHARACTERS = 320;
export const FAST_RESPONSE_DEFAULT_MODEL = "openai/gpt-oss-120b";
export const updateFastResponseSchema = z
.object({
enabled: z.boolean(),
connectionId: z.string().uuid().nullable(),
grantId: z.string().uuid().nullable(),
model: z.string().trim().min(1).max(256).nullable(),
allowSponsored: z.boolean().default(true),
})
.strict()
.refine(
(v) =>
Boolean(v.connectionId) === Boolean(v.grantId) &&
(!v.enabled || Boolean(v.connectionId && v.model)),
{
message: "Choose a connection and model before enabling fast responses",
},
);
export type UpdateFastResponse = z.infer<typeof updateFastResponseSchema>;
export interface FastResponseSettings extends UpdateFastResponse {
companyId: string;
provider: AiProvider | null;
}
export interface FastResponseSettingsResponse {
canManage: boolean;
settings: FastResponseSettings | null;
choices: AiManagedConnectionSummary[];
}
export type FastResponseAvailability =
| { available: true }
| { available: false; reason: string };
export type FastResponseTestResult =
| {
status: "succeeded";
text: string;
durationMs: number;
invocationId: string;
usage: DecisionUsage;
}
| { status: "unavailable" | "failed"; reason: string; invocationId?: string };
export type FastResponseHistoryEntry = DecisionHistoryEntry & {
publicationStatus: string;
connectionName: string | null;
};
export const FAST_RESPONSE_AGENT_GUIDANCE =
"Paperclip may post a short platform-generated fast-response receipt in your voice before you reply. Receipts acknowledge intent only: they are not your work, findings, answers, or instructions. Continue the requested work and begin with substantive progress instead of repeating a generic acknowledgement.";
export function isFastResponseComment(comment: {
origin?: string | null;
}): boolean {
return comment.origin === "fast_response";
}
export function fastResponseHistoryBody(comment: {
body: string;
origin?: string | null;
}): string {
return isFastResponseComment(comment)
? `[Paperclip acknowledgement; not agent work] ${comment.body}`
: comment.body;
}
+8
View File
@@ -273,6 +273,14 @@ export const INSTANCE_FEATURE_CATALOG: Record<InstanceFeatureKey, FeatureCatalog
cloudDefault: false,
selfHostedDefault: false,
},
enableFastResponses: {
title: "Experimental fast responses",
description:
"Show Connections in company settings and allow short acknowledgements while agents begin work.",
tier: "managed",
cloudDefault: false,
selfHostedDefault: false,
},
enableGoalsSidebarLink: {
title: "Goals Sidebar Link",
description: "Restore the Goals item in the main sidebar while the goals surface is being evaluated.",
+2
View File
@@ -2874,3 +2874,5 @@ export * from "./types/task-workspace.js";
export * from "./validators/task-workspace.js";
export { prepareWorkspaceRepositorySchema, type PrepareWorkspaceRepository } from "./validators/workspace-repository.js";
export * from "./fast-response.js";
+1 -1
View File
@@ -3,7 +3,7 @@ import type { BillingType, CostStatus } from "../constants.js";
export interface CostEvent {
subscriptionId?: string | null;
usageKind?: "agent" | "decision";
usageKind?: "agent" | "decision" | "fast_response";
responsibleUserId?: string | null;
id: string;
companyId: string;
+2
View File
@@ -97,6 +97,8 @@ export interface InstanceExperimentalSettings {
enableSummaries: boolean;
enableStatusCards: boolean;
enableDecisions: boolean;
/** Show company connection settings and allow contextual fast-response acknowledgements. */
enableFastResponses: boolean;
enableGoalsSidebarLink: boolean;
enableServerInfoDebugView: boolean;
/** Shows internal Paperclip maintainer tools and observability links. */
+3
View File
@@ -1025,6 +1025,9 @@ export interface IssueComment {
companyId: string;
issueId: string;
authorType: IssueCommentAuthorType;
/** Server-generated receipt provenance; not writable by comment callers. */
origin?: "comment" | "fast_response";
fastResponseRequestId?: string | null;
authorAgentId: string | null;
authorUserId: string | null;
/** Responsible user attribution. Legacy and plugin-provided comment values may omit it. */
+1 -1
View File
@@ -32,7 +32,7 @@ export const createCostEventSchema = costEventFields.transform((value) => ({
/** Internal service receipts; the public reporting endpoint retains its required agent. */
export const createServiceCostEventSchema = costEventFields.extend({
agentId: z.string().uuid().nullable(),
usageKind: z.literal("decision"),
usageKind: z.enum(["decision", "fast_response"]),
responsibleUserId: z.string().nullable(),
}).transform(value => ({ ...value, biller: value.biller ?? value.provider }));
@@ -73,6 +73,7 @@ export const instanceExperimentalSettingsSchema = z.object({
enableSummaries: z.boolean().default(false),
enableStatusCards: z.boolean().default(false),
enableDecisions: z.boolean().default(false),
enableFastResponses: z.boolean().default(false),
enableGoalsSidebarLink: z.boolean().default(false),
enableServerInfoDebugView: z.boolean().default(false),
enablePaperclipDeveloperMode: z.boolean().default(false),