Merge origin/master into claude/plugin-model-connect

Master removed the sign-in environment select from the shared step,
so the connect page no longer needs its own guard for it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
TonioandClaude Fable 5.2 committed 2026-12-04 22:10:47 -08:00
commit ba1f5cc38b
592 files changed
+46966 -11223

No files matched your search

+32 -1
View File
@@ -173,7 +173,38 @@ Ask the user where to write the package. Common options:
- Org chart as a markdown list or table showing agents, titles, reporting structure, and skills
- Brief description of each agent's role
- Citations and references: link to the source repo (if from-repo), link to the Agent Companies spec (https://agentcompanies.io/specification), and link to Paperclip (https://github.com/paperclipai/paperclip)
- A "Getting Started" section explaining how to import: `paperclipai company import --from <path>`
- A "Getting Started" section explaining how to import. **Verify the invocation
against this checkout before writing it** — never copy it from memory or from an
older README. Resolve it, in this order:
1. `grep -n 'command("import"' -A 12 cli/src/commands/client/company.ts` — the
source of truth for the arguments the CLI actually accepts;
2. if no such command exists, fall back to the HTTP route:
`grep -n 'companies/import' server/src/routes/openapi.ts`
(`POST /api/companies/import/preview`, then `POST /api/companies/import`).
As of this checkout the source is a POSITIONAL argument, **not** `--from`:
```bash
paperclipai company import <pathOrUrl> \
--include company,agents,projects,issues,tasks,skills \
--target new --new-company-name "<Name>"
```
Always pass `--include` explicitly, listing every part the package actually
contains. An under-specified include set imports a SUBSET and still reports
success — a package can land with zero projects, tasks and skills and look like
it worked.
This applies to the HTTP fallback too. Omitting `include` there does not mean
"import everything". The server fills in `DEFAULT_INCLUDE`
(`server/src/services/company-portability.ts`), which is:
```
company: true, agents: true, projects: false, issues: false, skills: false
```
The request then succeeds while it drops every project, issue and skill in the
package. Send `include` with each part set explicitly.
**LICENSE** — include a LICENSE file. The copyright holder is the user creating the company, not the upstream repo author (they made the skills, the user is making the company). Use the same license type as the source repo (if from-repo) or ask the user (if from-scratch). Default to MIT if unclear.
+8
View File
@@ -67,6 +67,14 @@ updates:
- dependency-name: "@types/node"
update-types:
- "version-update:semver-major"
# @cloudflare/sandbox 1.0 removes the Sandbox Durable Object class and
# getSandbox(), which the Cloudflare bridge template is built on. Moving to
# 1.0 also needs a new wrangler config, a new container image, and a deploy
# that operators cannot roll back. Stay on 0.x until that migration is
# planned with operator docs; do it by hand, not through Dependabot.
- dependency-name: "@cloudflare/sandbox"
update-types:
- "version-update:semver-major"
# Daytona is the only provider with its own lockfile. The release build and the
# Daytona end-to-end job install it frozen, so the shared workspace above leaves
+1 -1
View File
@@ -27,7 +27,7 @@ jobs:
build-and-sign:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v7
- uses: actions/checkout@v7.0.1
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
@@ -39,7 +39,7 @@ jobs:
PAPERCLIP_BACKUP_CHECKPOINT_RESTORE_TEST_DATABASE_URL: postgres://paperclip:backup-qualification-fixture@127.0.0.1:5432/backup_restore_test
PAPERCLIP_BACKUP_QUALIFICATION_RECEIPT: ${{ github.workspace }}/backup-checkpoint-evidence/qualification.json
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
- uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86
with:
version: 9.15.4
+2 -2
View File
@@ -21,12 +21,12 @@ jobs:
timeout-minutes: 5
steps:
- name: Checkout base branch (never PR code)
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: master
- name: Dependency Review
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec # v5.0.1
with:
base-ref: ${{ github.event.pull_request.base.sha }}
head-ref: ${{ github.event.pull_request.head.sha }}
+1 -1
View File
@@ -128,7 +128,7 @@ jobs:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
persist-credentials: false
# Same history as docker.yml, for `git describe` below.
+1 -1
View File
@@ -231,7 +231,7 @@ jobs:
actions: read # download a verified merge-queue image artifact of this commit
steps:
- name: Checkout
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
# Full history and tags so `git describe` below can compute the
# release version to stamp into the image.
+1 -1
View File
@@ -33,7 +33,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
- name: Setup pnpm
uses: pnpm/action-setup@v6
+2 -2
View File
@@ -63,7 +63,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
- name: Setup Node.js
uses: actions/setup-node@v7
@@ -124,7 +124,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
- name: Setup pnpm
uses: pnpm/action-setup@v6
+10 -10
View File
@@ -403,7 +403,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
ref: ${{ github.sha }}
fetch-depth: 0
@@ -540,7 +540,7 @@ jobs:
canary_version: ${{ steps.select.outputs.canary_version }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
ref: master
fetch-depth: 0
@@ -655,7 +655,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
ref: ${{ needs.select_nightly.outputs.sha }}
fetch-depth: 0
@@ -792,7 +792,7 @@ jobs:
mode: ${{ steps.select.outputs.mode }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
ref: master
fetch-depth: 0
@@ -944,7 +944,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
ref: ${{ needs.select_beta.outputs.sha }}
fetch-depth: 0
@@ -1084,7 +1084,7 @@ jobs:
pull-requests: read
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
ref: master
fetch-depth: 0
@@ -1176,7 +1176,7 @@ jobs:
notes_ref: ${{ steps.notes.outputs.notes_ref }}
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
ref: master
fetch-depth: 0
@@ -1335,7 +1335,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
ref: ${{ needs.preflight_stable.outputs.sha }}
@@ -1403,7 +1403,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
ref: ${{ needs.preflight_stable.outputs.sha }}
@@ -1568,7 +1568,7 @@ jobs:
contents: write
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
with:
ref: master
fetch-depth: 0
+1 -1
View File
@@ -45,7 +45,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v7
uses: actions/checkout@v7.0.1
- name: Setup pnpm
uses: pnpm/action-setup@v6
+10
View File
@@ -118,6 +118,16 @@ suite when it resolves a remaining local/platform-specific gap or is explicitly
required for qualification. See `AGENTS.md` and `doc/DEVELOPING.md` for result reuse
and coverage requirements.
### Troubleshooting: `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` on a fresh clone
If `pnpm install --frozen-lockfile` fails on a **freshly cloned, unmodified `master`** -- before you have touched anything -- this is almost always not your environment. It means `master` itself is temporarily inconsistent between `package.json` and `pnpm-lock.yaml` (a manifest field, most often `patchedDependencies` or `overrides`, drifted out of sync with the lockfile on a recent merge). See #10393 for the ongoing tracker and root cause.
Before debugging your own setup:
1. Check the [Issues list](https://github.com/paperclipai/paperclip/issues?q=is%3Aissue+ERR_PNPM_LOCKFILE_CONFIG_MISMATCH) for a fresh report matching your commit -- this class of drift is usually already known and self-heals via an automated `chore(lockfile): refresh pnpm-lock.yaml` PR within minutes to hours of the breaking merge.
2. If a refresh PR already exists and is green, you can safely `pnpm install --no-frozen-lockfile` locally on your branch to unblock yourself while you wait for it to merge -- do **not** commit the resulting `pnpm-lock.yaml` diff yourself; a manual lockfile diff in a normal PR triggers `pr.yml`'s "lockfile edits" failure. Rebase once the refresh PR lands.
3. If no report or refresh PR exists yet, file one per [Bug fix](.github/ISSUE_TEMPLATE/bug_report.yml), noting the exact manifest field mismatch (visible in the error output) and the commit SHA of the merge that introduced it.
### Telemetry Changes
This repo has three separate data paths: Telemetry, Observability, and the run log. See [`rules/data-paths.mdc`](rules/data-paths.mdc) for the full definitions and the review level each path needs.
+13 -3
View File
@@ -75,6 +75,14 @@ Mobile task conversations size their shell to the visible viewport, with one
message scroller and a normal flex footer for the composer. Navigation stays at
the layout viewport bottom, behind the keyboard.
A task conversation is the one exception to stable page padding. Its message
scroller drives the navigation, measured from the latest message. Reading back
through the thread slides the composer and the navigation away together, and
the thread takes the freed height. The chrome hides only after the reader is
farther back than that freed height, so hiding never snaps the thread to the
latest message. Moving back toward the latest message, or reaching it, brings
both back. An open keyboard always keeps the composer on screen.
Cold task opens reveal the instruction and recent conversation independently of
recovery, related metadata, and historical run activity. Saved document cards,
the saved plan, and the bounded latest turn arrive before first reveal so they
@@ -776,9 +784,11 @@ Recents appears only when it contains entries, without an empty state.
Task entries require the viewer's own participation under the Mine inbox rule,
regardless of inbox archive state. Automated provenance, account ownership and
read-only visits do not establish participation. A qualifying task's title and
status stay current, but passive visits and background updates do not promote it
above newer user activity. A first passive visit places a qualifying candidate
below existing history. Readable subtasks remain contextual navigation under a
status stay current, but clicking or passively visiting an existing entry and
background updates do not promote it above newer user activity. A first passive
visit seeds an unseen qualifying entry from its latest activity timestamp (or
below existing history when unavailable) so newer items sort near the top
without re-sorting on click. Readable subtasks remain contextual navigation under a
qualifying parent.
### Reuse collection behavior as well as appearance
+2 -1
View File
@@ -68,6 +68,7 @@ describe("chat CLI guidance", () => {
it("names only commands, arguments and flags this CLI supports", () => {
for (const command of commands) expect(command.error, command.path).toBeUndefined();
expect(resolve(program, "issue create --project-id <projectId> --title <title>").error).toBeUndefined();
});
it("detects an invented command or flag", () => {
@@ -75,6 +76,6 @@ describe("chat CLI guidance", () => {
expect(resolve(program, "context select <name>").error).toMatch(/unknown subcommand select/);
expect(resolve(program, "issue document:get <task> and more").error).toMatch(/missing arguments/);
expect(resolve(program, "context set --profile --use").error).toMatch(/missing value for --profile/);
expect(resolve(program, "issue create --project-id <projectId> creates").error).toMatch(/missing required --company-id/);
expect(resolve(program, "issue create --project-id <projectId> creates").error).toMatch(/missing required --title/);
});
});
@@ -0,0 +1,88 @@
import { Command } from "commander";
import { describe, expect, it } from "vitest";
import { registerCompanyCommands } from "../commands/client/company.js";
import { registerIssueCommands } from "../commands/client/issue.js";
import { registerAgentCommands } from "../commands/client/agent.js";
import { registerApprovalCommands } from "../commands/client/approval.js";
import { registerActivityCommands } from "../commands/client/activity.js";
import { registerDashboardCommands } from "../commands/client/dashboard.js";
import { registerFeedbackCommands } from "../commands/client/feedback.js";
import { registerGoalCommands } from "../commands/client/goal.js";
import { registerPluginCommands } from "../commands/client/plugin.js";
import { registerProjectCommands } from "../commands/client/project.js";
import { registerSecretCommands } from "../commands/client/secrets.js";
import { registerTokenCommands } from "../commands/client/token.js";
interface CommandNode {
path: string;
command: Command;
}
/**
* Walk the full command tree (recursively, through all subcommands) and
* return every node along with its dotted path (e.g. "agent list").
*/
function walkCommands(command: Command, path: string[] = []): CommandNode[] {
const currentPath = [...path, command.name()].filter(Boolean).join(" ");
const nodes: CommandNode[] = [{ path: currentPath || "<root>", command }];
for (const sub of command.commands) {
nodes.push(...walkCommands(sub, [...path, command.name()].filter(Boolean)));
}
return nodes;
}
describe("--company-id option registration", () => {
it("never declares --company-id as a mandatory (required) option", () => {
const program = new Command();
registerCompanyCommands(program);
registerIssueCommands(program);
registerAgentCommands(program);
registerApprovalCommands(program);
registerActivityCommands(program);
registerDashboardCommands(program);
registerFeedbackCommands(program);
registerGoalCommands(program);
registerPluginCommands(program);
registerProjectCommands(program);
registerSecretCommands(program);
registerTokenCommands(program);
const nodes = walkCommands(program);
// Trap: commander's `option.required` merely reflects that the flag takes
// a value (`<id>`). The `.requiredOption` discriminator is
// `option.mandatory`. Asserting on `required` would pass on the broken
// (pre-fix) tree and is worthless.
const offenders = nodes
.filter((node) => node.command.options.some((option) => option.long === "--company-id" && option.mandatory === true))
.map((node) => node.path);
expect(offenders, `--company-id must never be mandatory; offending commands: ${offenders.join(", ")}`).toEqual([]);
});
it("never declares --company-id more than once on the same command", () => {
const program = new Command();
registerCompanyCommands(program);
registerIssueCommands(program);
registerAgentCommands(program);
registerApprovalCommands(program);
registerActivityCommands(program);
registerDashboardCommands(program);
registerFeedbackCommands(program);
registerGoalCommands(program);
registerPluginCommands(program);
registerProjectCommands(program);
registerSecretCommands(program);
registerTokenCommands(program);
const nodes = walkCommands(program);
const duplicates = nodes
.filter((node) => node.command.options.filter((option) => option.long === "--company-id").length > 1)
.map((node) => node.path);
expect(duplicates, `--company-id must not be declared more than once; offending commands: ${duplicates.join(", ")}`).toEqual([]);
});
});
@@ -12,6 +12,7 @@ import {
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { createStoredZipArchive } from "./helpers/zip.js";
import { CliServerStartupError, retryCliServerStartup } from "./helpers/server-startup.js";
import { removeTestHome } from "../../../tests/helpers/remove-test-home.js";
import { PAPERCLIP_RUNTIME_INFO_FILENAME, readRuntimeInfo } from "../runtime-info.js";
@@ -193,7 +194,7 @@ function collectTextFiles(root: string, current: string, files: Record<string, s
}
async function stopServerProcess(child: ServerProcess | null) {
if (!child || child.exitCode !== null) return;
if (!child || child.exitCode !== null || child.signalCode !== null) return;
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.once("exit", () => resolve());
@@ -264,13 +265,11 @@ async function waitForServer(
runtimeInfoPath: string,
child: ServerProcess,
output: { stdout: string[]; stderr: string[] },
deadline: number,
) {
const startedAt = Date.now();
while (Date.now() - startedAt < SERVER_STARTUP_TIMEOUT_MS) {
if (child.exitCode !== null) {
throw new Error(
`paperclipai run exited before healthcheck succeeded.\nstdout:\n${output.stdout.join("")}\nstderr:\n${output.stderr.join("")}`,
);
while (Date.now() < deadline) {
if (child.exitCode !== null || child.signalCode !== null) {
throw new CliServerStartupError(output.stdout.join(""), output.stderr.join(""), child.exitCode);
}
const runtime = readRuntimeInfo(instanceId, runtimeInfoPath);
@@ -315,43 +314,49 @@ describeEmbeddedPostgres("paperclipai company import/export e2e", () => {
mkdirSync(cliShellHome, { recursive: true });
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-company-cli-db-");
const { connectionString } = tempDb;
const startupDeadline = Date.now() + SERVER_STARTUP_TIMEOUT_MS;
apiBase = await retryCliServerStartup(async () => {
await stopServerProcess(serverProcess);
await requestedPortReservation?.release();
requestedPortReservation = null;
requestedPortReservation = await reserveRequestedPort();
const { port } = requestedPortReservation;
writeTestConfig(configPath, tempRoot, port, connectionString);
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
const output = { stdout: [] as string[], stderr: [] as string[] };
const child = spawn(
process.execPath,
["--import", createRequire(import.meta.url).resolve("tsx"), path.join(repoRoot, "cli/src/index.ts"), "run", "--config", configPath],
{
cwd: repoRoot,
env: createServerEnv(configPath, port, connectionString, {
paperclipHome,
instanceId: paperclipInstanceId,
shellHome: cliShellHome,
}),
stdio: ["ignore", "pipe", "pipe"],
},
);
serverProcess = child;
child.stdout?.on("data", (chunk) => {
output.stdout.push(String(chunk));
});
child.stderr?.on("data", (chunk) => {
output.stderr.push(String(chunk));
});
requestedPortReservation = await reserveRequestedPort();
const { port } = requestedPortReservation;
writeTestConfig(configPath, tempRoot, port, tempDb.connectionString);
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
const output = { stdout: [] as string[], stderr: [] as string[] };
const child = spawn(
process.execPath,
["--import", createRequire(import.meta.url).resolve("tsx"), path.join(repoRoot, "cli/src/index.ts"), "run", "--config", configPath],
{
cwd: repoRoot,
env: createServerEnv(configPath, port, tempDb.connectionString, {
paperclipHome,
instanceId: paperclipInstanceId,
shellHome: cliShellHome,
}),
stdio: ["ignore", "pipe", "pipe"],
},
);
serverProcess = child;
child.stdout?.on("data", (chunk) => {
output.stdout.push(String(chunk));
const apiBase = await waitForServer(
paperclipInstanceId,
path.join(paperclipHome, "instances", paperclipInstanceId, PAPERCLIP_RUNTIME_INFO_FILENAME),
child,
output,
startupDeadline,
);
expect(new URL(apiBase).port).not.toBe(String(port));
return apiBase;
});
child.stderr?.on("data", (chunk) => {
output.stderr.push(String(chunk));
});
apiBase = await waitForServer(
paperclipInstanceId,
path.join(paperclipHome, "instances", paperclipInstanceId, PAPERCLIP_RUNTIME_INFO_FILENAME),
child,
output,
);
expect(new URL(apiBase).port).not.toBe(String(port));
// Room for the embedded database start on top of the server budget.
}, SERVER_STARTUP_TIMEOUT_MS + 30_000);
@@ -0,0 +1,27 @@
export class CliServerStartupError extends Error {
constructor(
stdout: string,
readonly stderr: string,
readonly exitCode: number | null,
) {
super(`paperclipai run exited before healthcheck succeeded.\nstdout:\n${stdout}\nstderr:\n${stderr}`);
}
}
export async function retryCliServerStartup<T>(startAttempt: () => Promise<T>): Promise<T> {
for (let attempt = 1; ; attempt += 1) {
try {
return await startAttempt();
} catch (error) {
if (
attempt >= 3 ||
!(error instanceof CliServerStartupError) ||
error.exitCode !== 1 ||
!/^(?:Error: )?listen EADDRINUSE: address already in use /m.test(error.stderr)
) {
throw error;
}
console.warn(`CLI test server bind collision; starting attempt ${attempt + 1} of 3`);
}
}
}
+94
View File
@@ -0,0 +1,94 @@
import { execFile } from "node:child_process";
import net from "node:net";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { CliServerStartupError, retryCliServerStartup } from "./helpers/server-startup.js";
const execFileAsync = promisify(execFile);
async function runChild(script: string): Promise<string> {
try {
const { stdout } = await execFileAsync(process.execPath, ["-e", script]);
return stdout.trim();
} catch (error) {
const result = error as { code: number; stdout: string; stderr: string };
if (typeof result.code !== "number") throw error;
throw new CliServerStartupError(result.stdout, result.stderr, result.code);
}
}
async function occupyPort() {
const server = net.createServer();
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const port = (server.address() as net.AddressInfo).port;
return {
port,
close: () => new Promise<void>((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
}),
};
}
function listenerScript(port: number) {
return `
const server = require('node:net').createServer();
server.on('error', (error) => {
console.error(error.message);
process.exitCode = 1;
});
server.listen(${port}, '127.0.0.1', () => {
console.log(server.address().port);
server.close();
});
`;
}
describe("CLI test server startup", () => {
it("starts a fresh attempt after a real listener bind collision", async () => {
const occupied = await occupyPort();
let attempts = 0;
try {
const port = await retryCliServerStartup(async () => {
attempts += 1;
return Number(await runChild(listenerScript(attempts === 1 ? occupied.port : 0)));
});
expect(attempts).toBe(2);
expect(port).toBeGreaterThan(0);
expect(port).not.toBe(occupied.port);
} finally {
await occupied.close();
}
});
it.each([
[1, "invalid server configuration"],
[2, "listen EADDRINUSE: address already in use 127.0.0.1:3100"],
])("preserves a non-bind startup failure (exit %s)", async (exitCode, stderr) => {
let attempts = 0;
await expect(retryCliServerStartup(async () => {
attempts += 1;
return await runChild(`console.error(${JSON.stringify(stderr)}); process.exitCode = ${exitCode};`);
})).rejects.toMatchObject({ exitCode, stderr: `${stderr}\n` });
expect(attempts).toBe(1);
});
it("fails after three bind collisions and retains the final diagnostics", async () => {
const occupied = await occupyPort();
let attempts = 0;
try {
await expect(retryCliServerStartup(async () => {
attempts += 1;
return await runChild(listenerScript(occupied.port));
})).rejects.toMatchObject({
exitCode: 1,
stderr: expect.stringContaining(`EADDRINUSE: address already in use 127.0.0.1:${occupied.port}`),
});
expect(attempts).toBe(3);
} finally {
await occupied.close();
}
});
});
+8 -3
View File
@@ -10,7 +10,7 @@ let root: string;
let previousHome: string | undefined;
let previousPaperclipHome: string | undefined;
function record(payloadPath: string, version: string, channel: "latest" | "canary" | "pinned" = "latest"): InstallRecord {
function record(payloadPath: string, version: string, channel: "latest" | "beta" | "nightly" | "canary" | "pinned" = "latest"): InstallRecord {
return { source: "npm", version, channel, payloadPath, installedAt: `2026-07-22T00:00:0${version}.000Z` };
}
function createPayload(payloadPath: string, version: string): string {
@@ -104,11 +104,16 @@ describe("update command", () => {
expect(detectInstallMode(path.join(source, "cli", "src", "index.ts"), paths)).toBe("source");
});
it("resolves channels and keeps pinned installs pinned by default", () => {
it("resolves every channel and preserves the recorded channel by default", () => {
const manifest = { channel: "pinned", version: "1.2.3" } as InstallManifest;
expect(resolveUpdateRequest(manifest, {})).toEqual({ spec: "1.2.3", channel: "pinned", explicit: false });
expect(resolveUpdateRequest(manifest, { latest: true })).toEqual({ spec: "latest", channel: "latest", explicit: true });
expect(() => resolveUpdateRequest(manifest, { latest: true, canary: true })).toThrow("only one");
expect(resolveUpdateRequest(manifest, { beta: true })).toEqual({ spec: "beta", channel: "beta", explicit: true });
expect(resolveUpdateRequest(manifest, { nightly: true })).toEqual({ spec: "nightly", channel: "nightly", explicit: true });
expect(resolveUpdateRequest(manifest, { canary: true })).toEqual({ spec: "canary", channel: "canary", explicit: true });
expect(resolveUpdateRequest({ ...manifest, channel: "beta" }, {})).toEqual({ spec: "beta", channel: "beta", explicit: false });
expect(resolveUpdateRequest({ ...manifest, channel: "nightly" }, {})).toEqual({ spec: "nightly", channel: "nightly", explicit: false });
expect(() => resolveUpdateRequest(manifest, { latest: true, beta: true })).toThrow("only one");
});
it("re-resolves a moving git branch and activates the new SHA payload", async () => {
+13 -3
View File
@@ -2,10 +2,11 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { resolveInstallStorePaths, writeInstallManifestAtomic } from "../install-store.js";
import { checkForUpdateNotice, isUpdateNoticeEnabled } from "../update-notice.js";
let root: string; let previous: string | undefined;
beforeEach(() => { root = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-notice-")); previous = process.env.PAPERCLIP_UPDATE_CHECK; delete process.env.PAPERCLIP_UPDATE_CHECK; });
afterEach(() => { if (previous === undefined) delete process.env.PAPERCLIP_UPDATE_CHECK; else process.env.PAPERCLIP_UPDATE_CHECK = previous; fs.rmSync(root, { recursive: true, force: true }); });
let root: string; let previous: string | undefined; let previousPaperclipHome: string | undefined;
beforeEach(() => { root = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-notice-")); previous = process.env.PAPERCLIP_UPDATE_CHECK; previousPaperclipHome = process.env.PAPERCLIP_HOME; delete process.env.PAPERCLIP_UPDATE_CHECK; process.env.PAPERCLIP_HOME = path.join(root, "paperclip"); });
afterEach(() => { if (previous === undefined) delete process.env.PAPERCLIP_UPDATE_CHECK; else process.env.PAPERCLIP_UPDATE_CHECK = previous; if (previousPaperclipHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousPaperclipHome; fs.rmSync(root, { recursive: true, force: true }); });
describe("update notice", () => {
it("honors the environment and config kill switches", () => {
process.env.PAPERCLIP_UPDATE_CHECK = "0"; expect(isUpdateNoticeEnabled(path.join(root, "missing.json"))).toBe(false);
@@ -17,4 +18,13 @@ describe("update notice", () => {
expect(await checkForUpdateNotice({ cachePath, now: 2000, fetchImpl })).toBe("99.0.0");
expect(fetchImpl).toHaveBeenCalledOnce();
});
it.each(["beta", "nightly"] as const)("checks the recorded %s channel", async (channel) => {
const paths = resolveInstallStorePaths();
writeInstallManifestAtomic({ schemaVersion: 1, source: "npm", version: `1.0.0-${channel}.0`, channel, payloadPath: path.join(root, "payload"), installedAt: "2026-08-20T00:00:00.000Z", previous: [] }, paths);
const cachePath = path.join(root, "cache.json");
const target = `99.0.0-${channel}.1`;
const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ "dist-tags": { latest: "0.3.1", beta: "99.0.0-beta.1", nightly: "99.0.0-nightly.1" } }), { status: 200 }));
expect(await checkForUpdateNotice({ cachePath, now: 1000, fetchImpl })).toBe(target);
expect(JSON.parse(fs.readFileSync(cachePath, "utf8"))).toMatchObject({ latest: target, tag: channel });
});
});
+2 -2
View File
@@ -25,7 +25,7 @@ export function registerActivityCommands(program: Command): void {
activity
.command("list")
.description("List company activity log entries")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.option("--agent-id <id>", "Filter by agent ID")
.option("--entity-type <type>", "Filter by entity type")
.option("--entity-id <id>", "Filter by entity ID")
@@ -75,7 +75,7 @@ export function registerActivityCommands(program: Command): void {
activity
.command("create")
.description("Create a company activity log entry")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--payload-json <json>", "CreateActivity JSON payload")
.action(async (opts: ActivityListOptions) => {
try {
+2 -2
View File
@@ -298,7 +298,7 @@ export function registerAgentCommands(program: Command): void {
agent
.command("list")
.description("List agents for a company")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (opts: AgentListOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
@@ -853,7 +853,7 @@ export function registerAgentCommands(program: Command): void {
"Create an agent API key, install local Paperclip skills for Codex/Claude, and print shell exports",
)
.argument("<agentRef>", "Agent ID or shortname/url-key")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.option("--key-name <name>", "API key label", "local-cli")
.option(
"--no-install-skills",
+2 -2
View File
@@ -50,7 +50,7 @@ export function registerApprovalCommands(program: Command): void {
approval
.command("list")
.description("List approvals for a company")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.option("--status <status>", "Status filter")
.action(async (opts: ApprovalListOptions) => {
try {
@@ -111,7 +111,7 @@ export function registerApprovalCommands(program: Command): void {
approval
.command("create")
.description("Create an approval request")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--type <type>", "Approval type (hire_agent|approve_ceo_strategy)")
.requiredOption("--payload <json>", "Approval payload as JSON object")
.option("--requested-by-agent-id <id>", "Requesting agent ID")
+2 -2
View File
@@ -1499,7 +1499,7 @@ export function registerCompanyCommands(program: Command): void {
company
.command("feedback:list")
.description("List feedback traces for a company")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.option("--target-type <type>", "Filter by target type")
.option("--vote <vote>", "Filter by vote value")
.option("--status <status>", "Filter by trace status")
@@ -1541,7 +1541,7 @@ export function registerCompanyCommands(program: Command): void {
company
.command("feedback:export")
.description("Export feedback traces for a company")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.option("--target-type <type>", "Filter by target type")
.option("--vote <vote>", "Filter by vote value")
.option("--status <status>", "Filter by trace status")
+1 -1
View File
@@ -20,7 +20,7 @@ export function registerDashboardCommands(program: Command): void {
dashboard
.command("get")
.description("Get dashboard summary for a company")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (opts: DashboardGetOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
+1 -1
View File
@@ -95,7 +95,7 @@ export function registerGoalCommands(program: Command): void {
goal
.command("create")
.description("Create a goal")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--title <title>", "Goal title")
.option("--description <text>", "Goal description")
.option("--level <level>", "Goal level")
+1 -1
View File
@@ -300,7 +300,7 @@ export function registerIssueCommands(program: Command): void {
issue
.command("create")
.description("Create an issue")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--title <title>", "Issue title")
.option("--description <text>", "Issue description")
.option("--status <status>", "Issue status")
+4 -4
View File
@@ -849,7 +849,7 @@ function addPluginLocalFolderGet(parent: Command, name: string, description: str
.command(name)
.description(description)
.argument("<pluginId>", "Plugin ID or key")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (pluginId: string, opts: PluginCompanyOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
@@ -869,7 +869,7 @@ function addPluginLocalFolderKeyGet(parent: Command, name: string, description:
.description(description)
.argument("<pluginId>", "Plugin ID or key")
.argument("<folderKey>", "Local folder key")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (pluginId: string, folderKey: string, opts: PluginCompanyOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
@@ -892,7 +892,7 @@ function addPluginLocalFolderKeyPost(parent: Command, name: string, description:
.description(description)
.argument("<pluginId>", "Plugin ID or key")
.argument("<folderKey>", "Local folder key")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.option("--payload-json <json>", "JSON payload", "{}")
.action(async (pluginId: string, folderKey: string, opts: PluginCompanyOptions) => {
try {
@@ -919,7 +919,7 @@ function addPluginLocalFolderKeyPut(parent: Command, name: string, description:
.description(description)
.argument("<pluginId>", "Plugin ID or key")
.argument("<folderKey>", "Local folder key")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--payload-json <json>", "JSON payload")
.action(async (pluginId: string, folderKey: string, opts: PluginCompanyOptions) => {
try {
+1 -1
View File
@@ -107,7 +107,7 @@ export function registerProjectCommands(program: Command): void {
project
.command("create")
.description("Create a project")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--name <name>", "Project name")
.option("--description <text>", "Project description")
.option("--status <status>", "Project status")
+9 -9
View File
@@ -371,7 +371,7 @@ export function registerSecretCommands(program: Command): void {
secrets
.command("list")
.description("List secret metadata for a company")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (opts: SecretListOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
@@ -387,7 +387,7 @@ export function registerSecretCommands(program: Command): void {
secrets
.command("declarations")
.description("List portable env declarations emitted by company export")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.option("--include <values>", "Comma-separated include set: company,agents,projects,issues,tasks,skills", "company,agents,projects")
.option("--kind <kind>", "Filter declarations: all | secret | plain", "all")
.action(async (opts: SecretDeclarationsOptions) => {
@@ -414,7 +414,7 @@ export function registerSecretCommands(program: Command): void {
secrets
.command("create")
.description("Create a Paperclip-managed secret")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--name <name>", "Secret display name")
.option("--key <key>", "Portable secret key")
.option("--provider <provider>", "Secret provider id")
@@ -442,7 +442,7 @@ export function registerSecretCommands(program: Command): void {
secrets
.command("link")
.description("Link an external provider-owned secret without storing its value in Paperclip")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--name <name>", "Secret display name")
.requiredOption("--provider <provider>", "Secret provider id")
.requiredOption("--external-ref <ref>", "Provider secret ARN/name/path/reference")
@@ -556,7 +556,7 @@ export function registerSecretCommands(program: Command): void {
secrets
.command("doctor")
.description("Run secret provider health checks through the Paperclip API")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (opts: SecretDoctorOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
@@ -574,7 +574,7 @@ export function registerSecretCommands(program: Command): void {
secrets
.command("providers")
.description("List configured secret provider descriptors")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (opts: SecretDoctorOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
@@ -592,7 +592,7 @@ export function registerSecretCommands(program: Command): void {
secrets
.command("provider-configs")
.description("List company secret provider vault configs")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.action(async (opts: SecretDoctorOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
@@ -622,7 +622,7 @@ export function registerSecretCommands(program: Command): void {
secrets
.command("migrate-inline-env")
.description("Migrate inline sensitive agent env values into secret references")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.option("--apply", "Persist changes; default is a dry run", false)
.action(async (opts: SecretMigrateInlineEnvOptions) => {
try {
@@ -639,7 +639,7 @@ function addCompanySecretJsonPost(parent: Command, name: string, description: st
parent
.command(name)
.description(description)
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--payload-json <json>", "JSON payload")
.action(async (opts: SecretJsonOptions) => {
try {
+3 -3
View File
@@ -66,7 +66,7 @@ export function registerTokenCommands(program: Command): void {
agent
.command("create")
.description("Create an agent API key")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--agent <agent>", "Agent ID, shortname, or unambiguous name")
.option("--name <name>", "API key label", "cli-agent")
.action(async (opts: AgentTokenOptions) => {
@@ -96,7 +96,7 @@ export function registerTokenCommands(program: Command): void {
agent
.command("list")
.description("List agent API keys")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--agent <agent>", "Agent ID, shortname, or unambiguous name")
.action(async (opts: AgentTokenOptions) => {
try {
@@ -123,7 +123,7 @@ export function registerTokenCommands(program: Command): void {
.command("revoke")
.description("Revoke an agent API key")
.argument("<keyId>", "Agent API key ID")
.requiredOption("-C, --company-id <id>", "Company ID")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--agent <agent>", "Agent ID, shortname, or unambiguous name")
.action(async (keyId: string, opts: AgentTokenOptions) => {
try {
+8 -6
View File
@@ -16,7 +16,7 @@ import { packageVersion } from "../version.js";
const execFileAsync = promisify(execFile);
export type InstallMode = "managed" | "global-npm" | "npx" | "source" | "unknown";
export type UpdateOptions = { canary?: boolean; latest?: boolean; version?: string; rollback?: boolean; check?: boolean; dryRun?: boolean; json?: boolean; yes?: boolean; backup?: boolean };
export type UpdateOptions = { latest?: boolean; beta?: boolean; nightly?: boolean; canary?: boolean; version?: string; rollback?: boolean; check?: boolean; dryRun?: boolean; json?: boolean; yes?: boolean; backup?: boolean };
type Dependencies = { executablePath: string; runCommand: CommandRunner; backup: () => Promise<void>; confirm: (message: string) => Promise<boolean>; now: () => Date; paths: InstallStorePaths; restartActiveService: (expectedVersion: string) => Promise<boolean>; hasInstanceData: () => boolean };
const DATABASE_UNREACHABLE_CODES = new Set(["ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "ETIMEDOUT"]);
@@ -114,14 +114,16 @@ export function compareVersions(left: string, right: string): number {
return 0;
}
export function resolveUpdateRequest(manifest: InstallManifest | null, options: Pick<UpdateOptions, "canary" | "latest" | "version">): { spec: string; channel: InstallChannel; explicit: boolean } {
const selected = Number(Boolean(options.canary)) + Number(Boolean(options.latest)) + Number(Boolean(options.version));
if (selected > 1) throw new Error("Choose only one of --latest, --canary, or --version.");
export function resolveUpdateRequest(manifest: InstallManifest | null, options: Pick<UpdateOptions, "latest" | "beta" | "nightly" | "canary" | "version">): { spec: string; channel: InstallChannel; explicit: boolean } {
const selected = Number(Boolean(options.latest)) + Number(Boolean(options.beta)) + Number(Boolean(options.nightly)) + Number(Boolean(options.canary)) + Number(Boolean(options.version));
if (selected > 1) throw new Error("Choose only one of --latest, --beta, --nightly, --canary, or --version.");
if (options.version) return { spec: options.version.trim(), channel: "pinned", explicit: true };
if (options.canary) return { spec: "canary", channel: "canary", explicit: true };
if (options.latest) return { spec: "latest", channel: "latest", explicit: true };
if (options.beta) return { spec: "beta", channel: "beta", explicit: true };
if (options.nightly) return { spec: "nightly", channel: "nightly", explicit: true };
if (options.canary) return { spec: "canary", channel: "canary", explicit: true };
if (manifest?.channel === "pinned") return { spec: manifest.version, channel: "pinned", explicit: false };
const channel = manifest?.channel === "canary" ? "canary" : "latest";
const channel = manifest?.channel ?? "latest";
return { spec: channel, channel, explicit: false };
}
+2
View File
@@ -97,6 +97,8 @@ program
.alias("upgrade")
.description("Check, update, or roll back the Paperclip CLI")
.option("--latest", "Switch to the latest stable channel")
.option("--beta", "Switch to the beta channel")
.option("--nightly", "Switch to the nightly channel")
.option("--canary", "Switch to the canary channel")
.option("--version <version>", "Install an exact published version")
.option("--rollback", "Flip back to the retained previous managed payload")
+1 -1
View File
@@ -9,7 +9,7 @@ export const PATH_BLOCK_START = "# >>> paperclipai managed PATH >>>";
export const PATH_BLOCK_END = "# <<< paperclipai managed PATH <<<";
export type InstallSource = "npm" | "git";
export type InstallChannel = "latest" | "canary" | "pinned";
export type InstallChannel = "latest" | "beta" | "nightly" | "canary" | "pinned";
export type InstallRecord = {
source: InstallSource;
+4 -3
View File
@@ -12,8 +12,9 @@ export function isUpdateNoticeEnabled(configPath?: string): boolean {
export async function checkForUpdateNotice(options: { configPath?: string; now?: number; fetchImpl?: typeof fetch; cachePath?: string } = {}): Promise<string | null> {
if (!isUpdateNoticeEnabled(options.configPath)) return null;
const paths = resolveInstallStorePaths(); const cachePath = options.cachePath ?? path.join(paths.cliRoot, "update-check.json"); const now = options.now ?? Date.now();
try { const cache = JSON.parse(fs.readFileSync(cachePath, "utf8")) as { checkedAt?: number; latest?: string }; if (cache.checkedAt && now - cache.checkedAt < NOTICE_INTERVAL_MS) return cache.latest && compareVersions(cache.latest, packageVersion) > 0 ? cache.latest : null; } catch {}
const tag = readInstallManifest(paths)?.channel === "canary" ? "canary" : "latest";
try { const response = await (options.fetchImpl ?? fetch)("https://registry.npmjs.org/paperclipai", { signal: AbortSignal.timeout(2500) }); if (!response.ok) return null; const body = await response.json() as { ["dist-tags"]?: Record<string, string> }; const latest = body["dist-tags"]?.[tag]; fs.mkdirSync(path.dirname(cachePath), { recursive: true, mode: 0o700 }); fs.writeFileSync(cachePath, JSON.stringify({ checkedAt: now, latest: latest ?? null }) + "\n", { mode: 0o600 }); return latest && compareVersions(latest, packageVersion) > 0 ? latest : null; } catch { return null; }
const manifestChannel = readInstallManifest(paths)?.channel;
const tag = manifestChannel && manifestChannel !== "pinned" ? manifestChannel : "latest";
try { const cache = JSON.parse(fs.readFileSync(cachePath, "utf8")) as { checkedAt?: number; latest?: string; tag?: string }; if ((cache.tag ?? "latest") === tag && cache.checkedAt && now - cache.checkedAt < NOTICE_INTERVAL_MS) return cache.latest && compareVersions(cache.latest, packageVersion) > 0 ? cache.latest : null; } catch {}
try { const response = await (options.fetchImpl ?? fetch)("https://registry.npmjs.org/paperclipai", { signal: AbortSignal.timeout(2500) }); if (!response.ok) return null; const body = await response.json() as { ["dist-tags"]?: Record<string, string> }; const latest = body["dist-tags"]?.[tag]; fs.mkdirSync(path.dirname(cachePath), { recursive: true, mode: 0o700 }); fs.writeFileSync(cachePath, JSON.stringify({ checkedAt: now, latest: latest ?? null, tag }) + "\n", { mode: 0o600 }); return latest && compareVersions(latest, packageVersion) > 0 ? latest : null; } catch { return null; }
}
export async function printUpdateNotice(configPath?: string): Promise<void> { const latest = await checkForUpdateNotice({ configPath }); if (latest) console.log(`Update available: ${latest} — run \`paperclipai update\``); }
+15 -4
View File
@@ -139,9 +139,19 @@ The application supplies the worker driver at startup.
`updateConfiguration` owns the transaction for an ordinary configuration update.
The module locks the agent. The configuration service validates and prepares the
patch. The module saves it and invalidates an old verification result when
execution configuration changes during setup. The service then updates dependent
execution configuration changes during verification. A change to instructions
alone keeps the verification. The service then updates dependent
records and saves the configuration revision in the same transaction.
A change to the harness, model, credentials, or instructions does not restart
`preparing`. Preparation restarts only when the agent moves to an environment
that needs setup.
There is no separate invalidation operation for callers.
A prepared setup draft waits in `verifying` with no background work. Edits keep
it prepared. If an edit means that the draft no longer needs preparation, the
draft pauses. When the draft becomes a hire on the same environment driver, a
prepared draft goes directly to verification. A draft that is still `preparing`
keeps its operation, and the hire verifies after that operation completes. A
hire that needs setup for another environment starts `preparing` again.
Configuration writes reject caller-supplied lifecycle fields.
For `updateAndTransition`, lifecycle owns the transaction and calls the
same configuration operation. Both changes commit together.
@@ -222,9 +232,10 @@ the agent.
Saving an environment or the instance default that gives such a plugin to `ready`
or `verifying` agents without that selection returns a conflict. The same applies
when the change keeps the plugin but changes its driver; then every `ready` or
`verifying` agent on the environment needs setup. Pause those agents, save the
change, and then resume them.
when the change keeps the plugin but changes its driver; then every `ready`,
`preparing`, or `verifying` agent on the environment needs setup. A preparation
in progress belongs to the previous driver. Pause those agents, save the change,
and then resume them.
This save check trusts a selection when the old environment uses another plugin
or none. An agent keeps its selection after it leaves the plugin's environment.
+9 -4
View File
@@ -68,10 +68,15 @@ scripting).
## Switching channels
Channel choice is per-install: install from a different tag and you're on that
channel. Moving forward (stable → nightly) is always safe. Moving backward
(nightly → stable) can mean running an older schema than your data was created
with — treat a downgrade like a restore and keep a backup of your data
For a managed CLI install, use `paperclipai update` with `--latest`, `--beta`,
`--nightly`, or `--canary` to switch to any published channel. Later updates
without a channel flag stay on the recorded channel. Exact versions selected
with `--version` remain pinned.
For an ephemeral npm / npx install, channel choice comes from the dist-tag in
the install command. Moving forward (stable → nightly) is always safe. Moving
backward (nightly → stable) can mean running an older schema than your data was
created with — treat a downgrade like a restore and keep a backup of your data
directory before switching down.
## Reading version strings
+1 -1
View File
@@ -286,7 +286,7 @@ paperclipai install --canary
paperclipai install --version <version>
paperclipai install --ref <branch|tag|sha> [--repo owner/repo]
paperclipai update
paperclipai update --latest|--canary|--version <version>
paperclipai update --latest|--beta|--nightly|--canary|--version <version>
paperclipai update --rollback
paperclipai upgrade
paperclipai uninstall
+1 -1
View File
@@ -52,7 +52,7 @@ The homepage surfaces companies across several dimensions:
- **Featured** — editorially curated, high-quality templates
- **Popular** — ranked by downloads, stars, and forks
- **Recent** — latest published or updated
- **Categories** — browseable by use case (see Categories below)
- **Categories** — browsable by use case (see Categories below)
Each listing shows: name, short description, org size (agent count), category, adapter types used, star count, download count, and a mini org chart preview.
+18 -1
View File
@@ -36,7 +36,23 @@ This mode is ideal for local development and one-command installs.
Docker note: the Docker quickstart image also uses embedded PostgreSQL by default. Persist `/paperclip` to keep DB state across container restarts (see `doc/DOCKER.md`).
## 2. Local PostgreSQL (Docker)
## 2. Local PostgreSQL
### Unix sockets
For a local PostgreSQL service with Unix sockets, set the socket directory in
the connection URI's `host` query parameter:
```sh
export DATABASE_URL='postgresql://paperclip@localhost:5432/paperclip?host=/run/postgresql'
```
The query parameter selects the socket directory instead of the URI hostname.
Percent-encoded paths, such as `host=%2Frun%2Fpostgresql`, also work. PostgreSQL's
local authentication rules still apply. Application connections, migrations,
database backups, and restores use the same socket setting.
### Docker
For a full PostgreSQL server locally, use the included Docker Compose setup:
@@ -133,6 +149,7 @@ DATABASE_PREPARED_STATEMENTS=false # use false when the pooler does not suppor
DATABASE_POOL_MAX=25 # connection pool size; default: 10
DATABASE_IDLE_TIMEOUT_SECONDS=60 # close idle pooled connections; default: 60 (0 = keep open)
DATABASE_CONNECT_TIMEOUT_SECONDS=10 # default: 30
DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS=2000 # time for each address of the host before the next; default: 2000
DATABASE_MAX_LIFETIME_SECONDS=1800 # recycle a pooled connection after this long; default: 30-60 min (random)
DATABASE_APPLICATION_NAME=paperclip # application_name in pg_stat_activity; default for the server's main pool: paperclip:<boot id>
```
+6
View File
@@ -220,10 +220,16 @@ Select a different release source explicitly:
```sh
paperclipai update --latest
paperclipai update --beta
paperclipai update --nightly
paperclipai update --canary
paperclipai update --version 2026.720.0
```
`--latest`, `--beta`, `--nightly`, and `--canary` follow the corresponding npm
dist-tag. A later `paperclipai update` with no channel flag stays on the channel
recorded in the install manifest. `--version` pins that exact version instead.
Managed updates create a database backup before switching payloads, verify the
new CLI, atomically flip `current`, and restart an installed service. A failed
install or verification leaves the previous payload active.
+33 -7
View File
@@ -102,6 +102,14 @@ Tasks have parentage. Every task exists in service of a parent task, all the way
The current issue model includes stable issue identifiers, parent/sub-issues, blockers, a single assignee, comments, issue documents, attachments and work products, and review/approval handoffs. That structure keeps work inspectable by both the board and agents while still allowing agents to decompose work into smaller tasks.
A native agent that stops for a human decision must save an answerable request
and cite its receipt in the blocker report. A comment that says “decision needed”
does not create a question. The request must require a human response and resume
the work after the answer. Agents can reuse a current request, linked approval,
or open decision. Muse's first-party task catalog also supports these durable
human-input requests. Answered, dismissed, expired, and unrelated requests do
not justify another wait.
Task lists load additional pages as you scroll, with a **Load more tasks** button
available as well. This applies to personal views, including Mine, Recent, Unread,
Everything, and Blocked, and to organization views and their board layouts.
@@ -120,10 +128,18 @@ The Tasks tab keeps the full relationship list and shows each task once. Project
groups omit tasks already shown in the other sections and disappear when empty.
Sidebar Recents and Classic Recent Tasks show tasks from the viewer’s own
recent activity as a flat list. A subtask has its own row and its own unread
marker. Tasks archived from the viewer’s inbox leave Recents. Canceled and
completed tasks remain eligible. Opening a recent task moves its row to the top
of Recents.
recent activity as a flat list ordered by most recent activity. A subtask has
its own row and its own unread marker. Tasks archived from the viewer’s inbox
leave Recents. Canceled and completed tasks remain eligible. Clicking or opening
an existing item in Recents does not move it to the top; items re-sort only
when new activity occurs. Any task a person opens is eligible for their Recents,
including routine, channel, and agent-created tasks. When a person runs a
routine manually, the task that run creates goes to the top of their Recents at
once, before they open it. Neither of these adds the task to Mine. The server
keeps each person’s recent tasks per company (the newest 200), so every browser
and device shows the same list in the same order, and a change on one client
reaches the others through live updates. The first visit after this change
imports the list that the browser kept locally.
Standard Recents also shows recent chats and projects.
The Coordinator sidebar pins **Plugins** above **More** by default. Users can
@@ -149,6 +165,9 @@ Tasks waiting between automatic checks show **Monitoring** with a blue clock.
Task lists, board columns, filters, search, recent navigation and task properties
use the same read-only display state. The task retains its execution lifecycle
status, and the monitor banner shows when the next check is due.
While a task-linked run is queued or running, hide its monitor banner and
composer notice. Restore them after the run ends if a monitor is still scheduled.
The saved schedule remains in place while work runs.
Automatic monitor checks pause when a task is blocked. A person can use Check now
to request one check of a retained monitor through normal execution admission.
@@ -189,6 +208,10 @@ the latest agent that assigned it to them. If no assignment is available, it use
the latest other commenter, or leaves the recipient empty. A manual recipient
choice stays selected while task data refreshes.
The composer assignee picker shows up to five recent choices for the company,
most recent first. Remaining agents appear before the remaining people. Use
**No assignee** at the end of the list or find it with search.
Task reply and new-task composers submit with Enter by default; Shift+Enter
adds a new line. Settings → Experimental → **Command/Ctrl+Enter to Submit**
restores the previous behavior, where Enter adds a new line and Command/Ctrl+Enter
@@ -595,9 +618,12 @@ order per person and company. Old `/inbox/*` links redirect to their Tasks view.
Archive is personal. Use it from Mine, Unread, or a task-table row to
remove a task from your Mine and Unread views. All tasks and its status views
still include archived tasks. Use Undo after archiving, or open **Archived**
from the Views menu and restore a task. New replies from other people, mentions,
and other inbox activity such as a new decision request can bring a task back.
still include archived tasks. If you archive a task directly from Mine or
Unread, press **U** there to undo the most recent archive. To restore a task
archived from any view, open **Archived** from the Views menu and select
**Restore**.
New replies from other people, mentions, and other inbox activity such as a new
decision request can bring a task back.
### Combined Inbox + Task List
+13 -1
View File
@@ -3,7 +3,7 @@
## Current profile identity
Pi runs as **profile 37** on `pi-acp` 0.0.33 and
`@earendil-works/pi-coding-agent` 1.0.0. Its `commandDigest` attests the
`@earendil-works/pi-coding-agent` 1.7.0. Its `commandDigest` attests the
upstream release: the package versions, the Node version and the complete
distribution closure for each qualified platform. The closure includes the
patched wrapper, the runtime helper and the Paperclip extension, so a change to
@@ -52,6 +52,18 @@ for the exact source/image evidence and merge status.
All dated checkpoints below describe historical qualification attempts. Their
failures and profile numbers are retained; they are not current release gates.
Pi 1.7.0 (December 2026) replaced 1.0.0 to take the undici 8.12.4 security
fixes. Since 1.6.0, Pi publishes exact dependency pins instead of a bundled
`npm-shrinkwrap.json`, and pins `brace-expansion` 5.0.12 itself, so the
materializer no longer applies a brace-expansion patch. It now checks that
every dependency Pi declares installs at exactly that version and that every
`undici`, `brace-expansion` and `minimatch` copy in the lock is the reviewed
release. Pi 1.7.0 pins minimatch 11.0.3, so the distribution overrides it to
11.0.8 (`PI_SECURITY_OVERRIDES`); the override fails closed when Pi changes
that pin, so the next Pi upgrade reviews it again. The
profile version is unchanged; the new `commandDigest` starts saved Pi sessions
fresh.
## User-selected models (2026-10-06)
Native Pi accepts any explicit provider/model ID. The settings builder, server,
+6
View File
@@ -383,6 +383,12 @@ blocked task whose latest failure and active configuration recovery still match
the card. A newer failure, reassignment, manual hold, or restricted external chat
does not resume through an old card.
Codex CLI authentication failures are classified from protocol error events and
process diagnostics. Command output and agent messages may quote application
errors such as "expired refresh token" during a source review; those quotes do
not invalidate the selected AI connection. A non-authentication provider failure
keeps its original message and does not request sign-in again on that basis.
An attributed managed credential is marked as needing reauthorization only if
its stored generation still matches the failed run. Late failures cannot
invalidate a refreshed or reconnected credential. Repair preserves the selected
+65
View File
@@ -0,0 +1,65 @@
# LinkedIn Connection
Paperclip connects to LinkedIn through a reviewed native REST adapter (`server/src/services/connectors/linkedin/`) because LinkedIn does not publish an official remote MCP server.
## Scope & v1 vs. v2 Capabilities
LinkedIn separates its APIs into two approval tiers:
- **v1 (Self-Serve — shipped):** Uses *Sign In with LinkedIn using OpenID Connect* (`openid`, `profile`, `email`) and *Share on LinkedIn* (`w_member_social`).
- `linkedin_get_profile` (`read`): Reads the authenticated member's profile and `urn:li:person:<sub>`. Also used for health checks (`probe()`).
- `linkedin_create_post` (`destructive`, S4): Publishes a personal text or link/article post via `POST https://api.linkedin.com/rest/posts`. Always derives `author` from the authenticated grant so callers cannot spoof another member.
- `linkedin_delete_post` (`destructive`, S4): Deletes a personal post by URN via `DELETE https://api.linkedin.com/rest/posts/{encoded_urn}`.
- **v2 (Deferred — requires LinkedIn Community Management API commercial review):** Company Page posting, reading posts/comments (`r_member_social` / `r_organization_social`), analytics, and programmatic 365-day refresh tokens.
- **Not supported by LinkedIn public APIs:** DMs/messaging, connection requests, feed browsing, and people search.
## Service Involvement Statement
- **Managed method (`managed`, `platform_shared`):** Uses **Paperclip Cloud** (`my.paperclip.app/v1/connector/oauth/linkedin/callback`, profile `linkedin.share`) for the fixed LinkedIn OAuth callback and token exchange. Tokens are immediately sealed to the originating Paperclip instance's X25519 key and stored durably in the instance vault. **Paperclip ID (`id.paperclip.ing`)** never stores LinkedIn tokens.
- **Customer-owned OAuth (`oauth-own-app`, `customer`):** Completely instance-local. Neither Paperclip ID nor Paperclip Cloud participates.
## Connection Flow
```mermaid
sequenceDiagram
actor U as Paperclip User
participant P as Paperclip Instance
participant C as Paperclip Cloud Broker
participant L as LinkedIn OAuth and REST API
U->>P: Connect LinkedIn (managed)
P->>C: Signed session request (profile linkedin.share)
C-->>P: LinkedIn authorize URL
U->>L: Approve openid profile email w_member_social
L-->>C: Callback /v1/connector/oauth/linkedin/callback?code=...
C->>L: POST /oauth/v2/accessToken (code + client_secret)
L-->>C: 60-day access_token
C-->>P: X25519 sealed credential claim
P->>P: Vault user-scoped token ref
P->>L: GET /v2/userinfo (probe)
```
### Exact Endpoints
- **Authorize:** `https://www.linkedin.com/oauth/v2/authorization`
- **Token:** `https://www.linkedin.com/oauth/v2/accessToken`
- **Paperclip Cloud managed callback:** `https://my.paperclip.app/v1/connector/oauth/linkedin/callback`
- **Customer-owned callback:** `<instance-origin>/api/tools/oauth/callback`
- **REST API base:** `https://api.linkedin.com` (`/v2/userinfo`, `/rest/posts`)
- **Required Rest.li headers:** `X-Restli-Protocol-Version: 2.0.0`, `LinkedIn-Version: 202611`
- **Redirect constraints:** `https-or-loopback-http` (byte-for-byte registered in LinkedIn Developer Portal)
## Administrator Setup
### Managed (`paperclip-cloud` operators)
1. Create an app in the [LinkedIn Developer Portal](https://www.linkedin.com/developers/apps) and add **Sign In with LinkedIn using OpenID Connect** and **Share on LinkedIn**.
2. Register `https://my.paperclip.app/v1/connector/oauth/linkedin/callback` (and staging callback) under **Auth → OAuth 2.0 settings**.
3. Store the client secret in AWS Secrets Manager and configure `CLOUD_HARNESS_CONNECTOR_LINKEDIN_CLIENT_ID`, `CLOUD_HARNESS_CONNECTOR_LINKEDIN_CLIENT_SECRET_REF`, and `CLOUD_HARNESS_CONNECTOR_LINKEDIN_ENABLED_PROFILES=linkedin.share` on Paperclip Cloud.
### Customer-Owned OAuth (`oauth-own-app`)
1. Create an app in the [LinkedIn Developer Portal](https://www.linkedin.com/developers/apps) with **Sign In with LinkedIn using OpenID Connect** and **Share on LinkedIn** enabled.
2. Add `<your-paperclip-origin>/api/tools/oauth/callback` under **Auth → OAuth 2.0 settings**.
3. Enter the Client ID and Client Secret in Paperclip's LinkedIn **Use your own OAuth app** setup form.
## Token Lifetime & Revocation
- Standard self-serve LinkedIn access tokens expire after **60 days** and do not include a `refresh_token`. Users reconnect when the token expires.
- LinkedIn does not expose an RFC 7009 revocation endpoint for self-serve OAuth; removing the connection in Paperclip deletes the vaulted token immediately and blocks all subsequent tool calls.
+1 -1
View File
@@ -29,7 +29,7 @@ organization connections where no person signs in).
Long-term memory: [Experimental memory connectors](./MEMORY.md).
Provider notes: [Google Workspace](./GOOGLE-WORKSPACE.md),
[Gmail](./GMAIL.md), [AWS](./AWS.md), [Asana](./ASANA.md), [Sentry](./SENTRY.md), [PostHog](./POSTHOG.md), [Braintrust](./BRAINTRUST.md), [Neon](./NEON.md), [Superagent](./SUPERAGENT.md), [Gauge](./GAUGE.md), [Ditto](./DITTO.md), [Circleback](./CIRCLEBACK.md),
[Gmail](./GMAIL.md), [AWS](./AWS.md), [Asana](./ASANA.md), [LinkedIn](./LINKEDIN.md), [Sentry](./SENTRY.md), [PostHog](./POSTHOG.md), [Braintrust](./BRAINTRUST.md), [Neon](./NEON.md), [Superagent](./SUPERAGENT.md), [Gauge](./GAUGE.md), [Ditto](./DITTO.md), [Circleback](./CIRCLEBACK.md),
[1Password](./1PASSWORD.md), [Unikraft](./UNIKRAFT.md), [AgentMail](./AGENTMAIL.md), [Telem.AI](./TELEM.md), [iMessage Photon](./IMESSAGE-PHOTON.md),
[Enterpret](./ENTERPRET.md), [Supabase](./SUPABASE.md), and
[Vercel](./vercel.md). Optional credential custody:
@@ -2,6 +2,47 @@
"reviewedAt": "2026-09-30",
"evidenceLevel": "Official documentation and public MCP metadata; no account-bound read/write proof. Runtime discovery never expands this allowlist.",
"methods": [
{
"app": "linkedin",
"method": "managed",
"auth": "oauth",
"policy": "explicit",
"requestedScopes": [
"openid",
"profile",
"email",
"w_member_social"
],
"capability": "write",
"supportedActions": "Verify connected member identity (linkedin_get_profile) and publish or delete personal LinkedIn posts (linkedin_create_post, linkedin_delete_post) via the reviewed REST adapter. Company Page management, post reading (r_member_social), analytics, and DMs are excluded in v1.",
"evidence": [
"https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin",
"https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/sign-in-with-linkedin-v2",
"https://learn.microsoft.com/en-us/linkedin/marketing/community-management/shares/posts-api"
],
"reviewedAt": "2026-12-01",
"liveProof": "not-run"
},
{
"app": "linkedin",
"method": "oauth-own-app",
"auth": "oauth",
"policy": "explicit",
"requestedScopes": [
"openid",
"profile",
"email",
"w_member_social"
],
"capability": "write",
"supportedActions": "Verify connected member identity (linkedin_get_profile) and publish or delete personal LinkedIn posts (linkedin_create_post, linkedin_delete_post) using a customer-owned LinkedIn Developer App with OIDC Sign In and Share on LinkedIn enabled.",
"evidence": [
"https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin",
"https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow"
],
"reviewedAt": "2026-12-01",
"liveProof": "not-run"
},
{
"app": "google-workspace",
"method": "paperclip-workspace",
@@ -32,5 +32,6 @@ Paperclip combines native `AppDefinition` entries with public aggregator snapsho
- **Observations are not grants:** `tool_connection_app_snapshots` and `tool_connection_app_syncs` store read-only account observations scoped to `(company, gateway, viewing human, effective credential version)` via `/api/tool-connections/:connectionId/aggregator/apps` (`/sync`, `/refresh`). They are never executable connections or authorization grants.
- **Explicit human choice for fallback:** `connections_search` owns next-step instructions. Falling back to an external aggregator requires an explicit `ask_user_questions` answer (`providerQuestion`) persisted and validated via `selectionInteractionId` in `connection_request`. A decline stays effective across continuations.
- **Direct Composio app setup vs. Arcade task draft:** Composio calls `COMPOSIO_MANAGE_CONNECTIONS` directly from the board (no task created, hosted auth link not persisted in audit/results; management console at `https://dashboard.composio.dev/~/org/connect/apps`). Arcade opens a task draft (`navigateOnCreate`) so the assigned agent verifies tools and requests human authorization via `connection_request` with frozen `toolNames`.
- If Composio cannot return a sign-in link for Buffer, Plugins offers direct setup with Buffer's MCP server. Use a Buffer API key from **Settings → API** and select **Key or token** in Paperclip. To connect through Composio, configure a custom Buffer OAuth app in a Composio Platform project and use a session from that project. [Buffer MCP setup](https://developers.buffer.com/guides/integrations/other-ai-tools.html) · [Composio's Buffer requirements](https://composio.dev/toolkits/buffer) · [Composio Platform auth configs](https://docs.composio.dev/kb/guide/dashboard-auth-configs-navigation)
- **Managed inventory bounds:** Arcade discovery paginates its admin account list using a separate user-owned project key (never substituting an OAuth gateway token). Executor reads its MCP integration inventory or fixed read-only `connections.list`/`integrations.list` calls — never arbitrary generated code.
- **Acceptance fixtures:** `server/src/__tests__/aggregator-app-discovery.test.ts`, `server/src/__tests__/aggregator-app-sync.test.ts`, `ui/src/pages/apps/Browse.test.tsx`, `tests/aggregator-accounts/test-drive.ts`.
+5 -4
View File
@@ -14,10 +14,11 @@ failed or deferred admissions retain their bounded deadlines.
A monitor deadline is the earliest time for a check. An active native run or an
unfinished finalization holds the check until the prior work settles. The task
banner explains the active run wait instead of promising the next scheduler tick
or showing it as overdue. Once the run clears, the banner resumes its countdown
and offers Check now. Finalization notifications restore monitor scheduling from
the saved rows; they do not bypass execution admission.
banner and composer monitor notice stay hidden while a task-linked run is queued
or running. A saved follow-up schedule does not mean the active agent is waiting.
Once the run clears, a retained monitor shows its countdown and Check now again.
Finalization notifications restore monitor scheduling from the saved rows; they
do not bypass execution admission.
Both idle drains and ordinary maintenance drains pause monitor dispatch. The
worker retains its pending request without repeatedly reading monitor tables.
+7
View File
@@ -25,6 +25,13 @@ history, changed authoritative task status/version, or a retired selected
completion review. The owner still classifies the selected result and appends
assessments and decisions through the existing status committer.
Once an ordinary conversation turn has an applied preserve decision and a
published reply, subsequent active/in-progress and waiting/in-review transitions
belong to the conversation. Status/version drift alone does not append a new
assessment to that answered run. Existing audit history is retained. Changed
work products, retired reviews and changes to other task statuses still enter
the normal reassessment path. Missing replies retain their recovery path.
A settled worker makes no recurring queries. Insufficient evidence is dormant.
Real contention or operational failure keeps a retry. A saved retry or lease
expiry keeps its actual future deadline. Startup reconstructs candidates in
+1 -1
View File
@@ -552,7 +552,7 @@ You can also export a running company as a template:
GET /api/templates/export → downloads the current company as a template JSON
```
This makes companies shareable and clonable.
This makes companies shareable and cloneable.
---
+5 -3
View File
@@ -532,9 +532,11 @@ ambiguous transitions remain fenced by the existing durable recovery checks.
Changes to account, credential generation, workspace, runtime or process policy
retire the old owner before recovery. A new authority epoch archives the stopped
checkpoint under its stable archive key and preserves provider session files.
Warm status monitoring relies on PRP after startup and does not poll an idle
Launcher. ACPX uses this task-provider contract; other execution transports retain
their provider-specific lifecycle policies.
Live per-turn and warm status monitoring rely on PRP after startup and do not
poll Launcher while a task is running or idle; Core checks `status` only on PRP
reconnect, close quiescence, or stop settlement. ACPX uses this task-provider
contract; other execution transports retain their provider-specific lifecycle
policies.
### Operation-time GitHub credentials
+8
View File
@@ -416,6 +416,7 @@ export interface PaperclipPluginManifestV1 {
agentEnvironmentDriver?: string;
taskSidePanel?: {
availabilityPath: string;
closePath?: string;
/** Match runtime.activity.recorded for automatic opening; manual views need no mapping. */
activation?: { namespace: string; activityKey: string };
};
@@ -434,6 +435,13 @@ unavailable configuration hides the restricted view. A transient connection
failure preserves the last known configuration. Eligibility does not depend
on runtime readiness, agent lifecycle state, or automatic panel activation.
A task side panel can declare an optional `closePath` with the same path rules as
`availabilityPath`. The host sends a POST to it when the person closes the panel
tab, also when the tab is in the background. The host does not send it on a tab
switch, when the person leaves the task, or when the host removes a panel that is
no longer available. The manifest must declare the path as a board POST route
scoped to agent `:entityId`.
Rules:
- `id` must be globally unique
+4 -1
View File
@@ -58,7 +58,10 @@ manifest-managed skills. Selecting that environment adds those skills to the
normal authorized skill selection, including an explicitly empty optional
selection. Core installs a missing managed skill in the current company's
library during lifecycle reconciliation or new-run admission and preserves existing
skill edits and explicit version pins. New managed skills use
skill edits and explicit version pins. When a person creates a setup draft, Core
also starts this installation once in the background. The draft does not wait for
it. A failure is logged, and the next run installs the missing skills. One
installation checks Core's bundled skills once, for all missing keys. New managed skills use
`plugin-<short-plugin-id>-<skill-slug>` for both the library slug and SKILL.md name.
The short ID is the final dot-separated plugin ID component, without a leading
`plugin-`. An unrelated skill can keep the same slug in a separate canonical
+2 -1
View File
@@ -73,7 +73,7 @@ statements longer than 8 KB. If a prepared statement fails because the pooler's
stale after a schema change or was lost, Paperclip stops preparing that
statement and retries it once unprepared.
Related optional client tuning: `DATABASE_POOL_MAX`, `DATABASE_IDLE_TIMEOUT_SECONDS`, `DATABASE_CONNECT_TIMEOUT_SECONDS`, `DATABASE_MAX_LIFETIME_SECONDS`, `DATABASE_APPLICATION_NAME`. Driver defaults apply when unset, except that idle pooled connections close after 60 seconds (`DATABASE_IDLE_TIMEOUT_SECONDS=0` keeps them open) and the server's main pool reports `application_name=paperclip:<boot id>` (other pools use names that start with `paperclip`). See [Connection pool settings](#connection-pool-settings).
Related optional client tuning: `DATABASE_POOL_MAX`, `DATABASE_IDLE_TIMEOUT_SECONDS`, `DATABASE_CONNECT_TIMEOUT_SECONDS`, `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS`, `DATABASE_MAX_LIFETIME_SECONDS`, `DATABASE_APPLICATION_NAME`. Driver defaults apply when unset, except that idle pooled connections close after 60 seconds (`DATABASE_IDLE_TIMEOUT_SECONDS=0` keeps them open), each address of the database host gets 2 seconds to answer a connection attempt, and the server's main pool reports `application_name=paperclip:<boot id>` (other pools use names that start with `paperclip`). See [Connection pool settings](#connection-pool-settings).
## Connection Pool Settings
@@ -84,6 +84,7 @@ The server opens one postgres.js pool for its own queries (and a second one when
| `DATABASE_POOL_MAX` | `10` (driver) | Maximum pooled connections. |
| `DATABASE_IDLE_TIMEOUT_SECONDS` | `60` | Close a pooled connection after this much idle time. `0` keeps idle connections open forever (the driver default). |
| `DATABASE_CONNECT_TIMEOUT_SECONDS` | `30` (driver) | Give up on a connection attempt after this long. |
| `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` | `2000` | When the database host name resolves to several addresses, wait this long for one address before trying the next. Node's own default (250 ms) is shorter than one TCP retransmission, so a single dropped packet could fail the connection. `DATABASE_CONNECT_TIMEOUT_SECONDS` still bounds the whole attempt. |
| `DATABASE_MAX_LIFETIME_SECONDS` | 30–60 min, randomized (driver) | Recycle a pooled connection once it is this old. |
| `DATABASE_APPLICATION_NAME` | `paperclip:<boot id>` (server main pool) | Value of `application_name` in `pg_stat_activity`. The boot id tells the sessions of each server process apart after a restart. Find Paperclip's backends with `SELECT * FROM pg_stat_activity WHERE application_name LIKE 'paperclip%';` |
| `DATABASE_DEDICATED_CONNECTION_MAX` | `24` | Dedicated lock connections in use at once per process before new callers wait. Nested callers do not wait. |
@@ -32,6 +32,7 @@ import {
buildAcpxRunSummary,
buildSessionFingerprint,
buildSessionKey,
classifyAcpxTurnFailureErrorFamily,
createAcpxEngineExecutor,
findAncestorBin,
geminiVersionSupportsNativeAcpFlag,
@@ -3615,6 +3616,47 @@ describe("ACP activity diagnostics", () => {
expect(result).toMatchObject({ errorCode: "provider_tool_definition_invalid", errorFamily: "configuration" });
expect(JSON.stringify(result.resultJson?.terminalSessionFailure)).not.toContain("128");
});
it.each([
{
name: "falls back to transient_upstream for a stall no classifier claimed",
category: "connection",
adapter: null,
expected: { errorCode: "acpx_turn_failed", errorFamily: "transient_upstream" },
},
{
name: "keeps the adapter classification ahead of the stall fallback",
category: "connection",
adapter: { errorCode: "provider_quota", errorFamily: "provider_quota" as const },
expected: { errorCode: "provider_quota", errorFamily: "provider_quota" },
},
{
name: "does not relabel an unclaimed limit failure that mentions a stall",
category: "limit",
adapter: null,
expected: { errorCode: "acpx_turn_failed", errorFamily: undefined },
},
])("$name", async ({ category, adapter, expected }) => {
const root = await makeTempRoot(), cwd = path.join(root, "worktree");
await fs.mkdir(cwd, { recursive: true });
const execute = createAcpxEngineExecutor({
classifyTerminalSessionFailure: () => adapter,
createRuntime: () => ({ ...buildRuntime(), startTurn: () => ({
events: (async function* () {})(),
cancel: async () => {},
result: Promise.resolve({
status: "completed",
stopReason: "end_turn",
_meta: { jetbrains: { air: { version: 1, sessionFailure: { severity: "error", category, details: "Response stalled mid-stream" } } } },
}),
}) }) as never,
});
const result = await execute({ runId: `stall-${category}`, agent: { id: "agent-1", companyId: "company-1" }, runtime: {},
config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state"), cwd },
context: {}, onMeta: async () => {}, onLog: async () => {} } as never);
expect(result.errorCode).toBe(expected.errorCode);
expect(result.errorFamily).toBe(expected.errorFamily);
expect(result.resultJson?.errorFamily).toBe(expected.errorFamily);
});
it.each(["terminal", "relay_error", "no_events"])(
"snapshots %s activity before usage reads, failure logging, and cleanup", async (outcome) => {
const root = await makeTempRoot();
@@ -8553,6 +8595,73 @@ describe("ACPX engine sandbox bridge run-disposition seam (fail-closed)", () =>
expect(result.resultJson).toMatchObject({ status: "failed" });
});
it("tags a mid-stream transport-stall terminal with errorFamily transient_upstream", async () => {
const sandbox = await setupRemoteSandbox();
const fake = createFakeBridgeHandle();
// The turn ends with a failed terminal whose error is the observed
// transport stall — the class the bounded transient-retry ladder exists for.
const runtime = {
ensureSession: async () => ({
backendSessionId: "backend-session",
agentSessionId: "agent-session",
runtimeSessionName: "runtime-session",
}),
startTurn: () => ({
events: (async function* () {
yield { type: "done", stopReason: "end_turn" };
})(),
result: Promise.resolve({
status: "failed" as const,
error: { message: "Response stalled mid-stream", retryable: true },
}),
cancel: async () => {},
}),
setConfigOption: async () => {},
close: async () => {},
};
const result = await runRemote(fake.handle, runtime, sandbox);
expect(result.errorCode).toBe("acpx_turn_failed");
// The engine emits the family both at the top level (which the server
// merges into resultJson) and inside resultJson, so the heartbeat
// classifier reads it and arms the bounded retry ladder.
expect(result.errorFamily).toBe("transient_upstream");
expect(result.resultJson?.errorFamily).toBe("transient_upstream");
});
it("leaves a capacity/session-cap terminal unclassified so it keeps its own quota path", async () => {
const sandbox = await setupRemoteSandbox();
const fake = createFakeBridgeHandle();
// A hard session cap shares the acpx_turn_failed code but must NOT become
// transient_upstream — it belongs on the provider_quota wait path (#10344).
const runtime = {
ensureSession: async () => ({
backendSessionId: "backend-session",
agentSessionId: "agent-session",
runtimeSessionName: "runtime-session",
}),
startTurn: () => ({
events: (async function* () {
yield { type: "done", stopReason: "end_turn" };
})(),
result: Promise.resolve({
status: "failed" as const,
error: { message: "You've hit your session limit · resets 11pm" },
}),
cancel: async () => {},
}),
setConfigOption: async () => {},
close: async () => {},
};
const result = await runRemote(fake.handle, runtime, sandbox);
expect(result.errorCode).toBe("acpx_turn_failed");
expect(result.errorFamily ?? null).toBeNull();
expect(result.resultJson?.errorFamily ?? null).toBeNull();
});
it("releases the runtime locally and places no remote close call once the duplex channel is lost", async () => {
const sandbox = await setupRemoteSandbox();
const fake = createFakeBridgeHandle();
@@ -9397,3 +9506,99 @@ describe("ACPX startup handshake guard and late-completion fence", () => {
}
}, 10000);
});
describe("classifyAcpxTurnFailureErrorFamily", () => {
it("tags the observed mid-stream transport stall as transient_upstream", () => {
expect(
classifyAcpxTurnFailureErrorFamily({ message: "Response stalled mid-stream" }),
).toBe("transient_upstream");
});
it("tags idle-timeout / connection-reset transport stalls as transient_upstream", () => {
for (const message of [
"Stream idle timeout - partial response received",
"The response stream stalled before completion",
"connection reset by peer",
"socket hang up",
"HTTP/2 bridge session stalled: no PING ack within the stall bound.",
]) {
expect(classifyAcpxTurnFailureErrorFamily({ message })).toBe("transient_upstream");
}
});
it("tags a connection closed mid-response as transient_upstream (bare and API-error-prefixed forms)", () => {
for (const message of [
"Connection closed mid-response. The response above may be incomplete.",
"API Error: Connection closed mid-response. The response above may be incomplete.",
"Internal error: API Error: Connection closed mid-response. The response above may be incomplete.",
"ACP agent disconnected during request (connection_close, exit=null, signal=null)",
]) {
expect(classifyAcpxTurnFailureErrorFamily({ message })).toBe("transient_upstream");
}
});
it("leaves pre-stream connect failures and auth/context failures unset", () => {
// ConnectionRefused / ENOTFOUND fail before any stream exists; they are a
// different subclass (#6731) and stay out of the mid-stream signature.
for (const message of [
"Internal error: API Error: Unable to connect to API (ConnectionRefused)",
"Internal error: API Error: Unable to connect to API (ENOTFOUND)",
"Prompt is too long",
"API Error: 401 authentication_error: invalid x-api-key",
]) {
expect(classifyAcpxTurnFailureErrorFamily({ message })).toBeNull();
}
});
it("also matches a transport-stall signal carried on the runtime error code, not the message", () => {
expect(
classifyAcpxTurnFailureErrorFamily({
message: "turn failed",
detailCode: "TRANSPORT_STALL",
}),
).toBe("transient_upstream");
});
it("does NOT tag a capacity / session-cap failure — it stays on its own (provider_quota) path", () => {
for (const message of [
"You've hit your session limit · resets 11pm",
"You've hit your usage limit for this model.",
"The model is at capacity for this model",
"weekly limit reached",
]) {
expect(classifyAcpxTurnFailureErrorFamily({ message })).toBeNull();
}
});
it("keeps the capacity guard winning even when a cap message also mentions a stall word", () => {
// The two subclasses must never be lumped: a cap message is vetoed first,
// regardless of any stall-ish wording it happens to carry.
expect(
classifyAcpxTurnFailureErrorFamily({
message: "You've hit your session limit; the stream stalled. resets 11pm",
}),
).toBeNull();
});
it("reads typed AIR terminalSessionFailure title/details when the turn error message is generic", () => {
expect(
classifyAcpxTurnFailureErrorFamily(
{ message: "ACP agent reported a terminal connection failure.", code: "RUNTIME" },
{ category: "connection", details: "Response stalled mid-stream" },
),
).toBe("transient_upstream");
expect(
classifyAcpxTurnFailureErrorFamily(
{ message: "ACP agent reported a terminal connection failure.", code: "RUNTIME" },
{ category: "connection", title: "Session limit reached", details: "Response stalled mid-stream" },
),
).toBeNull();
});
it("returns null for an unrelated failure and for an empty error", () => {
expect(
classifyAcpxTurnFailureErrorFamily({ message: "tool call raised a TypeError" }),
).toBeNull();
expect(classifyAcpxTurnFailureErrorFamily({ message: "" })).toBeNull();
});
});
@@ -113,6 +113,7 @@ import {
type AcpRuntimeStatus,
type AcpRuntimeTurn,
type AcpRuntimeTurnResult,
type AcpRuntimeTurnResultError,
type AcpRuntimeUsageBreakdown,
type AcpRuntimeUsageCost,
} from "acpx/runtime";
@@ -3459,6 +3460,71 @@ function resultErrorMessage(result: AcpRuntimeTurnResult): string | null {
return result.error.message;
}
// A capacity / session-cap / usage-limit failure — e.g. "You've hit your
// session limit · resets 11pm". It shares the `acpx_turn_failed` code with a
// transport stall but must NOT be retried on a short backoff: the wall clears
// on the provider's own schedule (#10344). The adapter classifiers move the
// wording they recognise onto `provider_quota`; anything cap-like they do not
// recognise is vetoed here so it can never be relabelled transient. The
// "resets" alternative is anchored to a clock time so it cannot swallow a
// "connection reset" transport stall below.
const ACPX_CAPACITY_CAP_RE =
/(?:hit your (?:session|usage|weekly|daily|monthly|plan|account)\b|(?:session|usage|weekly|daily|monthly|plan|account|message|token|credit)\s+limit\b|usage limit|\bquota\b|at capacity|capacity limit|out of (?:credits?|usage)|resets?\s+(?:at\s+)?(?:\d|midnight|noon|tomorrow|today))/i;
// The mid-stream transport-stall subclass of a failed ACPX turn: a transport
// interruption that ended the turn with no terminal answer — the observed
// "Response stalled mid-stream", an idle / PING-ack stall, or a connection
// reset. It is very likely to succeed on a later attempt, which is exactly
// what the server's bounded transient-retry ladder exists for.
const ACPX_TRANSPORT_STALL_RE =
/(?:response[\s_-]?stalled|stalled[\s_-]?mid[\s_-]?stream|mid[\s_-]?stream[\s_-]?stall|(?:stream|response|turn)[\s_-]?stalled|stream[\s_-]?(?:stall|idle)|idle[\s_-]?timeout|no ping ack|stalled ping|transport[\s_-]?(?:stall|lost|closed|reset)|connection[\s_-]?reset|connection[\s_-]?closed?\b|econnreset|socket hang ?up|premature[\s_-]?(?:close|end)|unexpected end of (?:stream|json|data|input)|stream[\s_-]?(?:closed|ended)[\s_-]?(?:unexpectedly|prematurely)|\bgoaway\b)/i;
// Terminal-session categories that already have their own recovery contract
// (sign-in, quota/context/budget limits). A stall-ish word in their text must
// not move them onto the transient-retry ladder.
const NON_TRANSIENT_TERMINAL_CATEGORIES = new Set(["access", "limit"]);
/**
* Engine-level fallback for a failed ACPX turn that neither the tool-definition
* classifier nor the adapter's `classifyTerminalSessionFailure` claimed.
*
* Tags only the mid-stream transport-stall subclass as `transient_upstream`,
* so the server's heartbeat bounded-retry ladder arms for it (#11257). The
* capacity/quota subclass and any `access` / `limit` terminal-session failure
* return `null` and keep today's behaviour byte-for-byte.
*/
export function classifyAcpxTurnFailureErrorFamily(
error: Pick<AcpRuntimeTurnResultError, "message" | "code" | "detailCode">,
terminalSessionFailure?: Pick<AcpxTerminalSessionFailure, "category" | "title" | "details"> | null,
): "transient_upstream" | null {
if (terminalSessionFailure && NON_TRANSIENT_TERMINAL_CATEGORIES.has(terminalSessionFailure.category)) {
return null;
}
const haystack = [
error.message,
error.code,
error.detailCode,
terminalSessionFailure?.title,
terminalSessionFailure?.details,
]
.filter((part): part is string => typeof part === "string" && part.length > 0)
.join(" ");
if (!haystack) return null;
// Checked first so a cap message can never be relabelled, even if it also
// carries a stall-ish word.
if (ACPX_CAPACITY_CAP_RE.test(haystack)) return null;
if (ACPX_TRANSPORT_STALL_RE.test(haystack)) return "transient_upstream";
return null;
}
function classifyTransportStallFallback(
error: AcpRuntimeTurnResultError,
terminalSessionFailure: AcpxTerminalSessionFailure | null,
): AcpxTerminalFailureClassification | null {
const errorFamily = classifyAcpxTurnFailureErrorFamily(error, terminalSessionFailure);
return errorFamily ? { errorFamily } : null;
}
function usageBreakdownsEqual(
left: AcpRuntimeUsageBreakdown,
right: AcpRuntimeUsageBreakdown,
@@ -5522,9 +5588,12 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
? toolStalledMessage
: formatTerminalSessionFailure(resultErrorMessage(terminal), failureDiagnostic);
const terminalStopReason = terminal.status === "failed" ? terminal.error.message : terminal.stopReason;
const classifiedFailure = !timedOut && !channelLost && !toolStalled && terminal.status === "failed"
? terminalFailureClassification
: null;
// Adapter-specific classification wins; the engine-level transport-stall
// fallback only labels a failure nothing else claimed.
const classifiedFailure: AcpxTerminalFailureClassification | null =
!timedOut && !channelLost && !toolStalled && terminal.status === "failed"
? terminalFailureClassification ?? classifyTransportStallFallback(terminal.error, terminalSessionFailure)
: null;
await emitAcpxLog(ctx, {
type: turnSucceeded ? "acpx.result" : "acpx.error",
summary: channelLost ? "duplex_channel_lost" : toolStalled ? "tool_stalled" : terminal.status,
@@ -5,7 +5,9 @@ describe("verified API billing", () => {
it.each([
["openrouter", "OPENROUTER_API_KEY"], ["openai", "OPENAI_API_KEY"],
["anthropic", "ANTHROPIC_API_KEY"], ["deepseek", "DEEPSEEK_API_KEY"],
])("classifies %s with its matching credential", (provider, key) => {
["google", "GOOGLE_GENERATIVE_AI_API_KEY"], ["google", "GEMINI_API_KEY"],
["xai", "XAI_API_KEY"], ["groq", "GROQ_API_KEY"], ["opencode", "OPENCODE_API_KEY"],
])("classifies %s with its matching credential (%s)", (provider, key) => {
expect(apiKeyBillingType(provider, { [key]: "fixture-key" })).toBe("metered_api");
});
it("recognizes Codex's key alias only for the Codex runtime", () => {
@@ -14,7 +16,7 @@ describe("verified API billing", () => {
expect(apiKeyBillingType("openai", env)).toBe("unknown");
expect(apiKeyBillingType("openrouter", env, "codex")).toBe("unknown");
});
it.each(["openrouter", "openai", "constructor", "toString", null, "unsupported"]) ("does not infer billing for %s", provider => {
it.each(["openrouter", "openai", "google", "constructor", "toString", null, "unsupported"]) ("does not infer billing for %s", provider => {
expect(apiKeyBillingType(provider, { ANTHROPIC_API_KEY: "unrelated-key", OPENAI_API_KEY: " " })).toBe("unknown");
});
});
@@ -5,6 +5,10 @@ const API_KEY_NAMES: Readonly<Record<string, readonly string[]>> = {
openrouter: ["OPENROUTER_API_KEY"],
anthropic: ["ANTHROPIC_API_KEY"],
deepseek: ["DEEPSEEK_API_KEY"],
google: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"],
xai: ["XAI_API_KEY"],
groq: ["GROQ_API_KEY"],
opencode: ["OPENCODE_API_KEY"],
};
/** A model/provider name alone does not prove billing. Only a matching API
@@ -5,9 +5,10 @@ import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { afterEach, describe, expect, it } from "vitest";
import { CONNECTION_INTENT_AGENT_GUIDANCE } from "@paperclipai/shared";
import {
commandPathCandidates,
readPaperclipRuntimeSkillEntries,
applyPaperclipWorkspaceEnv,
appendWithByteCap,
@@ -259,6 +260,50 @@ describe("buildInvocationEnvForLogs", () => {
});
});
describe("commandPathCandidates", () => {
const originalPlatform = process.platform;
const setPlatform = (platform: NodeJS.Platform) =>
Object.defineProperty(process, "platform", { configurable: true, value: platform });
afterEach(() => setPlatform(originalPlatform));
it("probes each PATHEXT form of a bare command on Windows", () => {
setPlatform("win32");
expect(commandPathCandidates("bin", "codex-acp", { env: { PATHEXT: ".EXE;.CMD" } })).toEqual([
path.join("bin", "codex-acp.EXE"),
path.join("bin", "codex-acp.CMD"),
]);
});
it("probes the bare name last on Windows when asked", () => {
setPlatform("win32");
expect(
commandPathCandidates("bin", "codex-acp", {
env: { PATHEXT: ".EXE;.CMD" },
includeBareName: true,
}),
).toEqual([
path.join("bin", "codex-acp.EXE"),
path.join("bin", "codex-acp.CMD"),
path.join("bin", "codex-acp"),
]);
});
it("probes a command that already has an extension as-is on Windows", () => {
setPlatform("win32");
expect(commandPathCandidates("bin", "codex-acp.exe", { env: { PATHEXT: ".EXE;.CMD" } })).toEqual([
path.join("bin", "codex-acp.exe"),
]);
});
it("probes only the bare command on other platforms", () => {
setPlatform("linux");
expect(commandPathCandidates("bin", "codex-acp", { env: { PATHEXT: ".EXE;.CMD" } })).toEqual([
path.join("bin", "codex-acp"),
]);
});
});
describe("sanitizeSshRemoteEnv", () => {
it("drops inherited host shell identity variables for SSH remote execution", () => {
expect(
+20 -10
View File
@@ -3678,6 +3678,25 @@ function windowsPathExts(env: NodeJS.ProcessEnv): string[] {
return (env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean);
}
/**
* Files to probe for `command` in one PATH directory; on Windows, one per PATHEXT entry,
* then the bare name when `includeBareName` is set.
*/
export function commandPathCandidates(
dir: string,
command: string,
options: { env?: NodeJS.ProcessEnv; includeBareName?: boolean } = {},
): string[] {
const bare = path.join(dir, command);
if (process.platform !== "win32" || path.extname(command).length > 0) {
return [bare];
}
const withExts = windowsPathExts(options.env ?? process.env).map((ext) =>
path.join(dir, `${command}${ext}`),
);
return options.includeBareName ? [...withExts, bare] : withExts;
}
async function pathExists(candidate: string) {
try {
await fs.access(
@@ -3706,18 +3725,9 @@ async function resolveCommandPath(
const pathValue = env.PATH ?? env.Path ?? "";
const delimiter = process.platform === "win32" ? ";" : ":";
const dirs = pathValue.split(delimiter).filter(Boolean);
const exts = process.platform === "win32" ? windowsPathExts(env) : [""];
const hasExtension =
process.platform === "win32" && path.extname(command).length > 0;
for (const dir of dirs) {
const candidates =
process.platform === "win32"
? hasExtension
? [path.join(dir, command)]
: exts.map((ext) => path.join(dir, `${command}${ext}`))
: [path.join(dir, command)];
for (const candidate of candidates) {
for (const candidate of commandPathCandidates(dir, command, { env })) {
if (await pathExists(candidate)) return candidate;
}
}
+70 -1
View File
@@ -1,4 +1,4 @@
import { execFile, spawn } from "node:child_process";
import { execFile, execFileSync, spawn } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
import net from "node:net";
import os from "node:os";
@@ -567,6 +567,75 @@ describe("ssh env-lab fixture", () => {
await target.cleanup();
});
// Debian and Ubuntu use dash as /bin/sh. A bash-only line in a login profile,
// such as `export -a`, is a special builtin error, and dash exits the whole
// shell on it: `|| true` never runs. The wrapper must survive that profile
// and keep the PATH that the profile exported before the failing line.
const dashPath = (() => {
try {
return execFileSync("sh", ["-c", "command -v dash"], { encoding: "utf8" }).trim() || null;
} catch {
return null;
}
})();
it.skipIf(!dashPath)(
"survives a bash-only login profile when the remote /bin/sh is dash",
async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-ssh-dash-profile-"));
try {
const homeDir = path.join(rootDir, "home");
const binDir = path.join(rootDir, "bin");
await mkdir(homeDir, { recursive: true });
await mkdir(binDir, { recursive: true });
// Route the wrapper's `sh -c` through dash, as on a Debian/Ubuntu host.
await symlink(dashPath!, path.join(binDir, "sh"));
await writeFile(
path.join(homeDir, ".bash_profile"),
'if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc"; fi\n',
);
await writeFile(
path.join(homeDir, ".bashrc"),
[
'export PATH="/opt/from-bashrc/bin:$PATH"',
'if [[ -n "$PS1" ]]; then :; fi',
"export -a",
"",
].join("\n"),
);
const target = await buildSshSpawnTarget({
spec: {
host: "ssh.example.test",
port: 22,
username: "ssh-user",
remoteCwd: rootDir,
remoteWorkspacePath: rootDir,
privateKey: null,
knownHosts: null,
strictHostKeyChecking: true,
},
command: "sh",
args: ["-c", 'printf "%s" "$PATH"'],
env: { FOO: "bar" },
});
await target.cleanup();
// The last ssh argument is the command line the remote login shell runs.
const remoteCommandLine = String(target.args.at(-1) ?? "");
const output = execFileSync(dashPath!, ["-c", remoteCommandLine], {
encoding: "utf8",
input: target.stdinPrefix,
env: { HOME: homeDir, PATH: `${binDir}:/usr/bin:/bin` },
});
expect(output.split(":")[0]).toBe("/opt/from-bashrc/bin");
} finally {
await rm(rootDir, { recursive: true, force: true });
}
},
);
it("rejects invalid environment variable keys when constructing SSH spawn targets", async () => {
await expect(
buildSshSpawnTarget({
+15 -8
View File
@@ -1361,6 +1361,19 @@ export function buildKnownHostsEntry(input: {
return `[${input.host}]:${input.port} ${input.publicKey.trim()}`;
}
// Login-profile sourcing shared by runSshCommand and buildSshSpawnTarget.
// `command .` removes the POSIX special-builtin behavior of `.`: under dash
// (/bin/sh on Debian and Ubuntu), a bash-only line in a profile such as
// `export -a` would otherwise exit the whole shell before `|| true` runs. With
// `command .`, the profile stops at the failing line, the exports made before
// it stay in effect, and the wrapper goes on to run the command.
const LOGIN_PROFILE_SOURCE_LINES = [
'if [ -f /etc/profile ]; then command . /etc/profile >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.profile" ]; then command . "$HOME/.profile" >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.bash_profile" ]; then command . "$HOME/.bash_profile" >/dev/null 2>&1 || true; elif [ -f "$HOME/.bashrc" ]; then command . "$HOME/.bashrc" >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.zprofile" ]; then command . "$HOME/.zprofile" >/dev/null 2>&1 || true; fi',
];
export async function runSshCommand(
config: SshConnectionConfig,
remoteCommand: string,
@@ -1397,10 +1410,7 @@ export async function runSshCommand(
// .bashrc still resolves node without a double-run of the setup.
const envArgs = envEntries.map(([key, value]) => `${key}=${shellQuote(value)}`);
const remoteScript = [
'if [ -f /etc/profile ]; then . /etc/profile >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.profile" ]; then . "$HOME/.profile" >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.bash_profile" ]; then . "$HOME/.bash_profile" >/dev/null 2>&1 || true; elif [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc" >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.zprofile" ]; then . "$HOME/.zprofile" >/dev/null 2>&1 || true; fi',
...LOGIN_PROFILE_SOURCE_LINES,
envArgs.length > 0
? `exec env ${envArgs.join(" ")} sh -c ${shellQuote(remoteCommand)}`
: `exec sh -c ${shellQuote(remoteCommand)}`,
@@ -1457,10 +1467,7 @@ export async function buildSshSpawnTarget(input: {
// directly when no .bash_profile exists, so a host that adds nvm in
// .bashrc still resolves node without a double-run of the setup.
const remoteScript = [
'if [ -f /etc/profile ]; then . /etc/profile >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.profile" ]; then . "$HOME/.profile" >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.bash_profile" ]; then . "$HOME/.bash_profile" >/dev/null 2>&1 || true; elif [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc" >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.zprofile" ]; then . "$HOME/.zprofile" >/dev/null 2>&1 || true; fi',
...LOGIN_PROFILE_SOURCE_LINES,
`cd ${shellQuote(input.spec.remoteCwd)}`,
envArgs.length > 0
? `exec env ${envArgs.join(" ")} ${remoteCommandParts}`
@@ -38,6 +38,7 @@ import {
asBoolean,
asNumber,
asString,
commandPathCandidates,
parseObject,
} from "@paperclipai/adapter-utils/server-utils";
import { resolveEnvBillingIdentity, resolveManagedApiKeyBilling } from "./acp-billing.js";
@@ -523,8 +524,9 @@ async function findCommandOnPath(binName: string): Promise<string | null> {
const pathValue = process.env.PATH ?? "";
for (const segment of pathValue.split(path.delimiter)) {
if (!segment) continue;
const candidate = path.join(segment, binName);
if (await pathExists(candidate)) return candidate;
for (const candidate of commandPathCandidates(segment, binName, { includeBareName: true })) {
if (await pathExists(candidate)) return candidate;
}
}
return null;
}
@@ -597,6 +597,8 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
{ path: path.join(path.dirname(sharedClaudeConfigDir), ".claude.json"), access: "rw" },
{ path: promptBundle.addDir, access: "ro" },
{ path: localMcpConfigDir, access: "ro" },
// The bundle links each skill to its source; mount the sources so the links resolve.
...mountableSkillEntries.map((entry) => ({ path: entry.source, access: "ro" as const })),
],
extraPaths: parseLocalProcessSandboxExtraPaths(config.filesystemExtraPaths),
homeDir: filesystemScope ? path.dirname(sharedClaudeConfigDir) : null,
@@ -336,6 +336,33 @@ describe("codex_local ACP lane", () => {
).resolves.toMatchObject({ engine: "acp", explicit: true, unavailableReason: expect.stringContaining("Node") });
});
it("finds a Windows codex-acp.exe on PATH for a bare command", async () => {
const root = await makeTempRoot("paperclip-codex-acp-pathext-");
const binDir = path.join(root, "bin");
await fs.mkdir(binDir, { recursive: true });
await fs.writeFile(path.join(binDir, "codex-acp.EXE"), "", "utf8");
setNodeVersion("v24.11.0");
const originalPlatform = process.platform;
const originalPath = process.env.PATH;
const originalPathExt = process.env.PATHEXT;
Object.defineProperty(process, "platform", { configurable: true, value: "win32" });
process.env.PATH = binDir;
process.env.PATHEXT = ".COM;.EXE;.BAT;.CMD";
try {
await expect(
resolveCodexExecutionEngineForRun({
config: { agentCommand: "codex-acp" },
executionTarget: null,
}),
).resolves.toEqual({ engine: "acp", explicit: false });
} finally {
Object.defineProperty(process, "platform", { configurable: true, value: originalPlatform });
process.env.PATH = originalPath;
if (originalPathExt === undefined) delete process.env.PATHEXT;
else process.env.PATHEXT = originalPathExt;
}
});
it("requires explicit CLI selection for local filesystem or network scope", async () => {
await expect(
resolveCodexExecutionEngineForRun({
@@ -36,6 +36,7 @@ import {
asNumber,
asString,
asStringArray,
commandPathCandidates,
parseObject,
} from "@paperclipai/adapter-utils/server-utils";
import { createWorkspaceRestoreTeardown } from "@paperclipai/adapter-utils/workspace-restore-teardown";
@@ -429,8 +430,9 @@ async function findCommandOnPath(binName: string): Promise<string | null> {
const pathValue = process.env.PATH ?? "";
for (const segment of pathValue.split(path.delimiter)) {
if (!segment) continue;
const candidate = path.join(segment, binName);
if (await pathExists(candidate)) return candidate;
for (const candidate of commandPathCandidates(segment, binName, { includeBareName: true })) {
if (await pathExists(candidate)) return candidate;
}
}
return null;
}
@@ -1114,12 +1114,31 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const biller = managedBilling?.biller ?? resolveCodexBiller(effectiveEnv, billingType);
const networkScope = parseLocalProcessNetworkScope(config.networkScope);
const filesystemScope = parseLocalProcessFilesystemScope(config.filesystemScope);
if (filesystemScope && !executionTargetIsRemote) {
for (const entry of codexSkillEntries.filter((e) => desiredSkillNames.includes(e.key))) {
const link = path.join(codexSkillsDir, entry.runtimeName);
const linkedPath = await fs.readlink(link).catch(() => null);
if (linkedPath && path.resolve(codexSkillsDir, linkedPath) !== entry.source) {
await onLog(
"stderr",
`[paperclip] Codex skill "${entry.runtimeName}" links to ${path.resolve(codexSkillsDir, linkedPath)}, outside the Paperclip skill sources: it is not mounted and will not be readable in the workspace sandbox.\n`,
);
}
}
}
const localProcessSandbox: LocalProcessSandboxOptions | null =
(filesystemScope || networkScope) && !executionTargetIsRemote
? {
workspaceDir: effectiveExecutionCwd,
filesystemScope,
managedPaths: [{ path: effectiveCodexHome, access: "rw" }],
managedPaths: [
{ path: effectiveCodexHome, access: "rw" },
// Only the Paperclip source of each skill: CODEX_HOME is writable in the sandbox, so what a
// kept link resolves to is agent-controlled and must not be mounted.
...codexSkillEntries
.filter((entry) => desiredSkillNames.includes(entry.key))
.map((entry) => ({ path: entry.source, access: "ro" as const })),
],
extraPaths: parseLocalProcessSandboxExtraPaths(config.filesystemExtraPaths),
pathAliases: targetWorkspaceRealization?.mode === "copy"
? targetWorkspaceRealization.pathAliases
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
classifyCodexAuthRefreshFailure,
extractCodexRetryNotBefore,
@@ -181,6 +181,65 @@ describe("classifyCodexAuthRefreshFailure", () => {
expect(classifyCodexAuthRefreshFailure({ errorMessage: "chatgpt wham api returned 401" })).toBeNull();
expect(classifyCodexAuthRefreshFailure({ errorMessage: "You've hit your usage limit for GPT-5." })).toBeNull();
});
it.each([
"Invalid or expired refresh token",
"refresh_token_reused",
"credential refresh returned 401 Unauthorized",
])("does not revoke auth when a failed review quotes %s in tool or agent output", (quotedError) => {
const providerError = "This content was flagged for possible cybersecurity risk.";
const stdout = [
JSON.stringify({ type: "thread.started", thread_id: "review-thread" }),
JSON.stringify({
type: "item.completed",
item: { type: "command_execution", aggregated_output: `throw unauthorized('${quotedError}');` },
}),
JSON.stringify({ type: "item.completed", item: { type: "agent_message", text: quotedError } }),
JSON.stringify({ type: "error", message: providerError }),
JSON.stringify({ type: "turn.failed", error: { message: providerError } }),
].join("\n");
expect(classifyCodexAuthRefreshFailure({ stdout, errorMessage: parseCodexJsonl(stdout).errorMessage })).toBeNull();
expect(parseCodexJsonl(stdout).errorMessage).toBe(providerError);
});
it.each([
["refresh_token_reused", "refresh_token_reused"],
["refresh token has expired", "refresh_token_expired"],
["OAuth failed: invalid_grant", "refresh_token_invalidated"],
])("still classifies a real protocol failure: %s", (message, expected) => {
const stdout = [
JSON.stringify({ type: "thread.started", thread_id: "auth-thread" }),
JSON.stringify({ type: "error", message }),
JSON.stringify({ type: "turn.failed", error: { message } }),
].join("\n");
expect(classifyCodexAuthRefreshFailure({ stdout })).toBe(expected);
});
it("uses the final protocol failure rather than a recovered earlier error", () => {
const stdout = [
JSON.stringify({ type: "error", message: "refresh_token_expired" }),
JSON.stringify({ type: "turn.failed", error: { message: "Unrelated provider failure" } }),
].join("\n");
expect(classifyCodexAuthRefreshFailure({ stdout })).toBeNull();
});
it("ignores quoted auth errors when the protocol stops without a terminal error", () => {
const stdout = JSON.stringify({
type: "item.completed",
item: { type: "command_execution", aggregated_output: "Invalid or expired refresh token" },
});
expect(classifyCodexAuthRefreshFailure({ stdout, stderr: "Process terminated unexpectedly" })).toBeNull();
});
it("retains a real stderr auth failure after protocol output", () => {
const stdout = JSON.stringify({
type: "item.completed",
item: { type: "agent_message", text: "Application error: refresh_token_reused" },
});
expect(classifyCodexAuthRefreshFailure({ stdout, stderr: "OAuth failed: refresh token has expired" })).toBe(
"refresh_token_expired",
);
});
});
describe("isCodexUnknownSessionError", () => {
@@ -205,6 +264,10 @@ describe("isCodexUnknownSessionError", () => {
});
describe("isCodexTransientUpstreamError", () => {
afterEach(() => {
vi.unstubAllEnvs();
});
it("classifies the remote-compaction high-demand failure as transient upstream", () => {
expect(
isCodexTransientUpstreamError({
@@ -230,6 +293,44 @@ describe("isCodexTransientUpstreamError", () => {
);
});
it("extracts the retry time from the subscription usage-limit wording", () => {
// ChatGPT Plus wording reported in #15613: no model name, no
// "switch to another model" clause, and a zone-less local reset clock.
const errorMessage = "You've hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro), visit https://chatgpt.com/codex/settings/usage to purchase more credits or try again at 8:13 PM.";
vi.stubEnv("TZ", "America/Chicago");
const now = new Date("2026-10-09T00:45:00.000Z");
expect(isCodexProviderQuotaError({ errorMessage })).toBe(true);
expect(extractCodexRetryNotBefore({ errorMessage }, now)?.toISOString()).toBe(
"2026-10-09T01:13:00.000Z",
);
});
it("rolls a past subscription reset clock to the next local day", () => {
const errorMessage = "You've hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro), visit https://chatgpt.com/codex/settings/usage to purchase more credits or try again at 8:13 PM.";
vi.stubEnv("TZ", "America/Chicago");
const now = new Date("2026-10-09T02:00:00.000Z");
expect(extractCodexRetryNotBefore({ errorMessage }, now)?.toISOString()).toBe(
"2026-10-10T01:13:00.000Z",
);
});
it("parses an explicit timezone hint on the subscription wording", () => {
const errorMessage = "You've hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro), visit https://chatgpt.com/codex/settings/usage to purchase more credits or try again at 11:31 PM (America/Chicago).";
const now = new Date("2026-04-23T03:29:02.000Z");
expect(extractCodexRetryNotBefore({ errorMessage }, now)?.toISOString()).toBe(
"2026-04-23T04:31:00.000Z",
);
});
it("returns no retry time for the subscription wording without a clock", () => {
const errorMessage = "You've hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro) to keep going.";
expect(extractCodexRetryNotBefore({ errorMessage })).toBeNull();
});
it("classifies model-capacity messages as provider quota without reset metadata", () => {
const errorMessage = "The requested model is at capacity. Please try again later.";
@@ -9,6 +9,14 @@ const CODEX_TRANSIENT_UPSTREAM_RE =
const CODEX_REMOTE_COMPACTION_RE = /remote\s+compact\s+task/i;
const CODEX_USAGE_LIMIT_RE =
/you(?:'|’)ve hit your usage limit for .+\.\s+switch to another model now,\s+or try again at\s+([^.!\n]+)(?:[.!]|\n|$)/i;
// Subscription plans (for example ChatGPT Plus) get a different wording with
// no model name and no "switch to another model" clause: "You've hit your
// usage limit. Upgrade to Pro (...), visit ... to purchase more credits or
// try again at 8:13 PM." The reset clock in this wording is also printed in
// the host's local time, so it goes through the same parseLocalClockTime
// path as the model wording.
const CODEX_USAGE_LIMIT_SUBSCRIPTION_RE =
/you(?:'|’)ve hit your usage limit\.[^\n]*?\btry again at\s+([^.!\n]+)(?:[.!]|\n|$)/i;
const CODEX_PROVIDER_QUOTA_RE =
/(?:you(?:'|’)ve hit your usage limit|usage limit|model (?:is )?at capacity|at capacity for this model|capacity limit)/i;
const CODEX_REFRESH_TOKEN_REUSED_RE =
@@ -164,7 +172,16 @@ export function classifyCodexAuthRefreshFailure(input: {
stderr?: string | null;
errorMessage?: string | null;
}): CodexAuthRefreshFailureClass | null {
const haystack = buildCodexErrorHaystack(input);
// JSONL items contain untrusted agent text and command output. A source-code
// review may quote an application error such as "expired refresh token";
// treating that as a provider failure would revoke a healthy shared account.
// Use only the last protocol error, plus process diagnostics. Retain plain
// stdout support for CLI failures that occur before the protocol starts.
const parsed = parseCodexJsonl(input.stdout ?? "");
const haystack = buildCodexErrorHaystack({
...input,
stdout: parsed.sawProtocolEvent ? parsed.errorMessage : input.stdout,
});
if (CODEX_REFRESH_TOKEN_REUSED_RE.test(haystack)) return "refresh_token_reused";
if (CODEX_REFRESH_TOKEN_EXPIRED_RE.test(haystack)) return "refresh_token_expired";
@@ -314,7 +331,9 @@ export function extractCodexRetryNotBefore(input: {
errorMessage?: string | null;
}, now = new Date()): Date | null {
const haystack = buildCodexErrorHaystack(input);
const usageLimitMatch = haystack.match(CODEX_USAGE_LIMIT_RE);
const usageLimitMatch =
haystack.match(CODEX_USAGE_LIMIT_RE) ??
haystack.match(CODEX_USAGE_LIMIT_SUBSCRIPTION_RE);
if (!usageLimitMatch) return null;
return parseLocalClockTime(usageLimitMatch[1] ?? "", now);
}
@@ -311,6 +311,26 @@ describe("gemini_local ACP lane", () => {
).resolves.toMatchObject({ engine: "acp", explicit: true, unavailableReason: expect.stringContaining("Node") });
});
it("uses the configured PATHEXT to find a Windows command on the configured PATH", async () => {
const root = await makeTempRoot("paperclip-gemini-acp-pathext-");
const bin = path.join(root, "bin");
await fs.mkdir(bin, { recursive: true });
await fs.writeFile(path.join(bin, "gemini.ACP"), "", "utf8");
setNodeVersion("v24.11.0");
const originalPlatform = process.platform;
Object.defineProperty(process, "platform", { configurable: true, value: "win32" });
try {
await expect(
resolveGeminiExecutionEngineForRun({
config: { env: { PATH: bin, PATHEXT: ".ACP" } },
executionTarget: null,
}),
).resolves.toEqual({ engine: "acp", explicit: false });
} finally {
Object.defineProperty(process, "platform", { configurable: true, value: originalPlatform });
}
});
it("reports unavailable ACP for SSH runs without a managed account", async () => {
setNodeVersion("v24.11.0");
await expect(
@@ -29,6 +29,7 @@ import type {
import {
asNumber,
asString,
commandPathCandidates,
parseObject,
} from "@paperclipai/adapter-utils/server-utils";
import { createWorkspaceRestoreTeardown } from "@paperclipai/adapter-utils/workspace-restore-teardown";
@@ -296,11 +297,16 @@ function firstShellToken(command: string): string | null {
return trimmed.split(/\s+/, 1)[0] ?? null;
}
async function findCommandOnPath(binName: string, pathValue = process.env.PATH ?? ""): Promise<string | null> {
async function findCommandOnPath(
binName: string,
pathValue = process.env.PATH ?? "",
pathExt = process.env.PATHEXT,
): Promise<string | null> {
for (const segment of pathValue.split(path.delimiter)) {
if (!segment) continue;
const candidate = path.join(segment, binName);
if (await pathExists(candidate)) return candidate;
for (const candidate of commandPathCandidates(segment, binName, { env: { PATHEXT: pathExt }, includeBareName: true })) {
if (await pathExists(candidate)) return candidate;
}
}
return null;
}
@@ -312,6 +318,13 @@ function resolveConfigPath(config: Record<string, unknown>): string {
: process.env.PATH ?? "";
}
function resolveConfigPathExt(config: Record<string, unknown> | undefined): string | undefined {
const envConfig = parseObject(config?.env);
return typeof envConfig.PATHEXT === "string" && envConfig.PATHEXT.trim().length > 0
? envConfig.PATHEXT
: process.env.PATHEXT;
}
async function commandIsResolvable(
command: string,
pathValue = process.env.PATH ?? "",
@@ -337,7 +350,7 @@ async function commandIsResolvable(
}
}
if (path.isAbsolute(token) || hasPathSeparator(token)) return pathExists(token);
return (await findCommandOnPath(token, pathValue)) !== null;
return (await findCommandOnPath(token, pathValue, resolveConfigPathExt(input?.config))) !== null;
}
function resolveGeminiAcpCommand(config: Record<string, unknown>): string {
+2 -2
View File
@@ -97,7 +97,7 @@ In the Paperclip UI or via API, create an agent with adapter type `hermes_local`
"adapterConfig": {
"model": "anthropic/claude-sonnet-4",
"maxIterations": 50,
"timeoutSec": 300,
"timeoutSec": 1800,
"persistSession": true,
"enabledToolsets": ["terminal", "file", "web"]
}
@@ -222,7 +222,7 @@ Create issues in Paperclip and assign them to your Hermes agent. On each heartbe
|-------|------|---------|-------------|
| `model` | string | `anthropic/claude-sonnet-4` | Model in `provider/model` format |
| `provider` | string | *(auto-detected)* | API provider: `auto`, `openrouter`, `nous`, `openai-codex`, `zai`, `kimi-coding`, `minimax`, `minimax-cn` |
| `timeoutSec` | number | `300` | Execution timeout in seconds |
| `timeoutSec` | number | `1800` | Execution timeout in seconds |
| `graceSec` | number | `10` | Grace period before SIGKILL |
### Tools
@@ -10,6 +10,18 @@ import {
hermesGatewayType,
} from "./index.js";
import { createServerAdapter as createGatewayServerAdapterFromSubpath } from "./gateway/index.js";
import { agentConfigurationDoc } from "./index.js";
import { DEFAULT_TIMEOUT_SEC } from "./shared/constants.js";
test("agent configuration doc states the enforced timeoutSec default", () => {
// The doc table once stated 300 while the code enforced an 1800 floor, and
// runs configured from the doc died at the wall. Keep them in lockstep.
const row = agentConfigurationDoc
.split("\n")
.find((line) => line.includes("timeoutSec") && line.includes("Execution timeout"));
expect(row).toBeDefined();
expect(row).toContain(`| ${DEFAULT_TIMEOUT_SEC} |`);
});
test("root package export exposes Paperclip external adapter entrypoint", () => {
const adapter = createServerAdapter();
+1 -1
View File
@@ -86,7 +86,7 @@ tools, persistent memory, session persistence, skills, and MCP support.
|-------|------|---------|-------------|
| model | string | (Hermes configured default) | Optional explicit model in provider/model format. Leave blank to use Hermes's configured default model. |
| provider | string | (auto) | API provider: auto, openrouter, nous, openai-codex, zai, kimi-coding, minimax, minimax-cn. Usually not needed — Hermes auto-detects from model name. |
| timeoutSec | number | 300 | Execution timeout in seconds |
| timeoutSec | number | 1800 | Execution timeout in seconds |
| graceSec | number | 10 | Grace period after SIGTERM before SIGKILL |
## Tool Configuration
@@ -1,10 +1,36 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
buildKimiAcpConfig,
nodeVersionMeetsKimiAcpMinimum,
resolveKimiExecutionEngine,
resolveKimiExecutionEngineForRun,
} from "./acp.js";
describe("resolveKimiExecutionEngineForRun on Windows", () => {
it("uses the configured PATHEXT to find the command on the configured PATH", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-kimi-acp-pathext-"));
const bin = path.join(root, "bin");
await fs.mkdir(bin, { recursive: true });
await fs.writeFile(path.join(bin, "kimi.ACP"), "", "utf8");
const originalPlatform = process.platform;
Object.defineProperty(process, "platform", { configurable: true, value: "win32" });
try {
await expect(
resolveKimiExecutionEngineForRun({
config: { env: { PATH: bin, PATHEXT: ".ACP" } },
executionTarget: null,
}),
).resolves.toEqual({ engine: "acp", explicit: false });
} finally {
Object.defineProperty(process, "platform", { configurable: true, value: originalPlatform });
await fs.rm(root, { recursive: true, force: true });
}
});
});
describe("resolveKimiExecutionEngine", () => {
it("defaults to ACP (non-explicit) when engine is unset", () => {
expect(resolveKimiExecutionEngine({})).toEqual({ engine: "acp", explicit: false });
+17 -4
View File
@@ -23,6 +23,7 @@ import type { AcpxEngineExecutorOptions } from "@paperclipai/adapter-utils/acpx-
import {
asNumber,
asString,
commandPathCandidates,
parseObject,
} from "@paperclipai/adapter-utils/server-utils";
import { DEFAULT_KIMI_LOCAL_MODEL } from "../index.js";
@@ -186,11 +187,16 @@ function firstShellToken(command: string): string | null {
return trimmed.split(/\s+/, 1)[0] ?? null;
}
async function findCommandOnPath(binName: string, pathValue = process.env.PATH ?? ""): Promise<string | null> {
async function findCommandOnPath(
binName: string,
pathValue = process.env.PATH ?? "",
pathExt = process.env.PATHEXT,
): Promise<string | null> {
for (const segment of pathValue.split(path.delimiter)) {
if (!segment) continue;
const candidate = path.join(segment, binName);
if (await pathExists(candidate)) return candidate;
for (const candidate of commandPathCandidates(segment, binName, { env: { PATHEXT: pathExt }, includeBareName: true })) {
if (await pathExists(candidate)) return candidate;
}
}
return null;
}
@@ -202,6 +208,13 @@ function resolveConfigPath(config: Record<string, unknown>): string {
: process.env.PATH ?? "";
}
function resolveConfigPathExt(config: Record<string, unknown> | undefined): string | undefined {
const envConfig = parseObject(config?.env);
return typeof envConfig.PATHEXT === "string" && envConfig.PATHEXT.trim().length > 0
? envConfig.PATHEXT
: process.env.PATHEXT;
}
async function commandIsResolvable(
command: string,
pathValue = process.env.PATH ?? "",
@@ -227,7 +240,7 @@ async function commandIsResolvable(
}
}
if (path.isAbsolute(token) || hasPathSeparator(token)) return pathExists(token);
return (await findCommandOnPath(token, pathValue)) !== null;
return (await findCommandOnPath(token, pathValue, resolveConfigPathExt(input?.config))) !== null;
}
function resolveKimiAcpCommand(config: Record<string, unknown>): string {
@@ -315,4 +315,58 @@ describe("openCode models", () => {
await assertion;
expect(spy).toHaveBeenCalledTimes(3);
});
it("mirrors GEMINI_API_KEY into GOOGLE_GENERATIVE_AI_API_KEY during model discovery", async () => {
const spy = vi.spyOn(serverUtils, "runChildProcess").mockResolvedValueOnce({
exitCode: 0,
signal: null,
timedOut: false,
stdout: "google/gemini-2.5-flash\n",
stderr: "",
pid: 1,
startedAt: new Date().toISOString(),
});
await expect(
discoverOpenCodeModels({
env: { GEMINI_API_KEY: "gemini-discovery-key" },
}),
).resolves.toEqual([
{ id: "google/gemini-2.5-flash", label: "google/gemini-2.5-flash" },
]);
expect(spy.mock.calls[0]?.[3]?.env).toMatchObject({
GEMINI_API_KEY: "gemini-discovery-key",
GOOGLE_GENERATIVE_AI_API_KEY: "gemini-discovery-key",
});
});
it("does not repopulate an explicitly blanked GOOGLE_GENERATIVE_AI_API_KEY from ambient GEMINI_API_KEY", async () => {
vi.stubEnv("GEMINI_API_KEY", "ambient-host-gemini-key");
vi.stubEnv("GOOGLE_GENERATIVE_AI_API_KEY", "ambient-host-google-key");
const spy = vi.spyOn(serverUtils, "runChildProcess").mockResolvedValue({
exitCode: 0,
signal: null,
timedOut: false,
stdout: "google/gemini-2.5-flash\n",
stderr: "",
pid: 1,
startedAt: new Date().toISOString(),
});
try {
await discoverOpenCodeModels({
env: { GOOGLE_GENERATIVE_AI_API_KEY: "" },
});
expect(spy.mock.calls[0]?.[3]?.env?.GOOGLE_GENERATIVE_AI_API_KEY).toBe("");
await discoverOpenCodeModels({
env: { GEMINI_API_KEY: "explicit-run-gemini-key" },
});
expect(spy.mock.calls[1]?.[3]?.env).toMatchObject({
GEMINI_API_KEY: "explicit-run-gemini-key",
GOOGLE_GENERATIVE_AI_API_KEY: "explicit-run-gemini-key",
});
} finally {
vi.unstubAllEnvs();
}
});
});
@@ -7,6 +7,7 @@ import {
runChildProcess,
} from "@paperclipai/adapter-utils/server-utils";
import { isValidOpenCodeModelId } from "../index.js";
import { applyOpenCodeProviderEnvAliases } from "./runtime-config.js";
const MODELS_CACHE_TTL_MS = 60_000;
const MODELS_DISCOVERY_TIMEOUT_MS = 20_000;
@@ -159,10 +160,16 @@ export async function discoverOpenCodeModels(
// image). Fall back to process.env.HOME.
}
// Prevent OpenCode from writing an opencode.json into the working directory.
// Apply Google alias independently to host and explicit envs before merging so
// an explicit blank GOOGLE_GENERATIVE_AI_API_KEY cannot be repopulated by an
// ambient host GEMINI_API_KEY, while an explicit GEMINI_API_KEY still overrides
// an ambient host GOOGLE_GENERATIVE_AI_API_KEY.
const aliasedHostEnv = applyOpenCodeProviderEnvAliases(normalizeEnv(process.env));
const aliasedExplicitEnv = applyOpenCodeProviderEnvAliases(env);
const runtimeEnv = normalizeEnv(
ensurePathInEnv({
...process.env,
...env,
...aliasedHostEnv,
...aliasedExplicitEnv,
...(resolvedHome ? { HOME: resolvedHome } : {}),
OPENCODE_DISABLE_PROJECT_CONFIG: "true",
}),
@@ -5,7 +5,7 @@ import { execFileSync, spawnSync } from "node:child_process";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, it, vi } from "vitest";
import { OPENROUTER_ATTRIBUTION_HEADERS } from "@paperclipai/adapter-utils/openrouter-attribution";
import { prepareOpenCodeRuntimeConfig } from "./runtime-config.js";
import { applyOpenCodeProviderEnvAliases, prepareOpenCodeRuntimeConfig } from "./runtime-config.js";
const cleanupPaths = new Set<string>();
@@ -482,4 +482,37 @@ describe("prepareOpenCodeRuntimeConfig", () => {
expect(config.provider.openrouter.options.headers["HTTP-Referer"]).toBe("https://paperclip.ing");
await prepared.cleanup();
});
it("mirrors GEMINI_API_KEY into GOOGLE_GENERATIVE_AI_API_KEY when absent or blank", async () => {
const configHome = await makeConfigHome();
const prepared = await prepareOpenCodeRuntimeConfig({
env: { XDG_CONFIG_HOME: configHome, GEMINI_API_KEY: "gemini-fixture-key" },
config: { model: "google/gemini-2.5-flash" },
});
cleanupPaths.add(prepared.env.XDG_CONFIG_HOME);
expect(prepared.env.GEMINI_API_KEY).toBe("gemini-fixture-key");
expect(prepared.env.GOOGLE_GENERATIVE_AI_API_KEY).toBe("gemini-fixture-key");
await prepared.cleanup();
});
it("preserves explicit GOOGLE_GENERATIVE_AI_API_KEY and blank managed isolation", () => {
expect(
applyOpenCodeProviderEnvAliases({
GEMINI_API_KEY: "gemini-key",
GOOGLE_GENERATIVE_AI_API_KEY: "explicit-google-key",
}),
).toEqual({
GEMINI_API_KEY: "gemini-key",
GOOGLE_GENERATIVE_AI_API_KEY: "explicit-google-key",
});
expect(
applyOpenCodeProviderEnvAliases({
GEMINI_API_KEY: "",
GOOGLE_GENERATIVE_AI_API_KEY: "",
}),
).toEqual({
GEMINI_API_KEY: "",
GOOGLE_GENERATIVE_AI_API_KEY: "",
});
});
});
@@ -104,14 +104,36 @@ async function readJsonObject(filepath: string): Promise<Record<string, unknown>
}
}
/**
* OpenCode's built-in Google provider (@ai-sdk/google) reads
* GOOGLE_GENERATIVE_AI_API_KEY, whereas Paperclip's Google/Antigravity setup
* and managed connections supply GEMINI_API_KEY. Mirror a non-empty
* GEMINI_API_KEY into GOOGLE_GENERATIVE_AI_API_KEY when the latter is absent
* or empty, while leaving explicit blank managed isolation untouched.
*/
export function applyOpenCodeProviderEnvAliases(
env: Record<string, string>,
): Record<string, string> {
const geminiKey = env.GEMINI_API_KEY?.trim();
const googleGenAiKey = env.GOOGLE_GENERATIVE_AI_API_KEY?.trim();
if (!googleGenAiKey && geminiKey) {
return {
...env,
GOOGLE_GENERATIVE_AI_API_KEY: geminiKey,
};
}
return env;
}
export async function prepareOpenCodeRuntimeConfig(input: {
env: Record<string, string>;
config: Record<string, unknown>;
sandboxToolOomPreference?: boolean;
}): Promise<PreparedOpenCodeRuntimeConfig> {
const skipPermissions = asBoolean(input.config.dangerouslySkipPermissions, true);
const aliasedEnv = applyOpenCodeProviderEnvAliases(input.env);
const sourceConfigDir = path.join(resolveXdgConfigHome(input.env), "opencode");
const sourceConfigDir = path.join(resolveXdgConfigHome(aliasedEnv), "opencode");
const runtimeConfigHome = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-config-"));
const runtimeConfigDir = path.join(runtimeConfigHome, "opencode");
const runtimeConfigPath = path.join(runtimeConfigDir, "opencode.json");
@@ -227,7 +249,7 @@ export async function prepareOpenCodeRuntimeConfig(input: {
return {
env: {
...input.env,
...aliasedEnv,
XDG_CONFIG_HOME: runtimeConfigHome,
...(inlineContent ? { OPENCODE_CONFIG_CONTENT: inlineConfig
? JSON.stringify({ ...inlineConfig, provider: nextProvider }) : inlineContent } : {}),
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { parsePiStdoutLine } from "./parse-stdout.js";
const ts = "2026-08-20T10:00:00.000Z";
describe("parsePiStdoutLine message_end", () => {
it("renders user messages as user transcript entries", () => {
const line = JSON.stringify({
type: "message_end",
message: {
role: "user",
content: [{ type: "text", text: "## Paperclip Wake Payload" }],
},
});
expect(parsePiStdoutLine(line, ts)).toEqual([
{ kind: "user", ts, text: "## Paperclip Wake Payload" },
]);
});
it("does not duplicate tool-result messages", () => {
const line = JSON.stringify({
type: "message_end",
message: {
role: "toolResult",
content: [{ type: "text", text: "file contents" }],
},
});
expect(parsePiStdoutLine(line, ts)).toEqual([]);
});
it("keeps assistant text and thinking entries", () => {
const line = JSON.stringify({
type: "message_end",
message: {
role: "assistant",
content: [
{ type: "thinking", thinking: "checking" },
{ type: "text", text: "done" },
],
},
});
expect(parsePiStdoutLine(line, ts)).toEqual([
{ kind: "thinking", ts, text: "checking" },
{ kind: "assistant", ts, text: "done" },
]);
});
it("ignores unsupported message roles", () => {
const line = JSON.stringify({
type: "message_end",
message: { role: "system", content: "internal message" },
});
expect(parsePiStdoutLine(line, ts)).toEqual([]);
});
});
@@ -232,25 +232,30 @@ export function parsePiStdoutLine(line: string, ts: string): TranscriptEntry[] {
if (type === "message_end") {
const message = asRecord(parsed.message);
if (message) {
const content = message.content as string | Array<{ type: string; text?: string; thinking?: string }>;
const { text, thinking } = extractTextContent(content);
const entries: TranscriptEntry[] = [];
// Emit final thinking block if present
if (thinking) {
entries.push({ kind: "thinking", ts, text: thinking });
}
// Emit final text block if present
if (text) {
entries.push({ kind: "assistant", ts, text });
}
return entries;
if (!message) return [];
const role = asString(message.role);
const content = message.content as string | Array<{ type: string; text?: string; thinking?: string }>;
const { text, thinking } = extractTextContent(content);
if (role === "user") {
return text ? [{ kind: "user", ts, text }] : [];
}
return [];
if (role !== "assistant") return [];
const entries: TranscriptEntry[] = [];
// Emit final thinking block if present
if (thinking) {
entries.push({ kind: "thinking", ts, text: thinking });
}
// Emit final text block if present
if (text) {
entries.push({ kind: "assistant", ts, text });
}
return entries;
}
// Tool execution
+107 -11
View File
@@ -1,11 +1,12 @@
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import os from "node:os";
import path from "node:path";
import { gunzipSync, gzipSync } from "node:zlib";
import { afterEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import postgres from "postgres";
import { createBufferedTextFileWriter, runDatabaseBackup, runDatabaseRestore } from "./backup-lib.js";
import { ensurePostgresDatabase } from "./client.js";
import { closeRegisteredClients, createDb, ensurePostgresDatabase, getPostgresDataDirectory } from "./client.js";
import {
EMBEDDED_POSTGRES_TEST_TIMEOUT_MS,
getEmbeddedPostgresTestSupport,
@@ -13,8 +14,6 @@ import {
} from "./test-embedded-postgres.js";
const cleanups: Array<() => Promise<void> | void> = [];
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
function createTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
@@ -46,12 +45,6 @@ afterEach(async () => {
}
}, 60_000);
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping embedded Postgres backup tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
describe("createBufferedTextFileWriter", () => {
it("preserves line boundaries across buffered flushes", async () => {
const tempDir = createTempDir("paperclip-buffered-writer-");
@@ -75,7 +68,13 @@ describe("createBufferedTextFileWriter", () => {
});
});
describeEmbeddedPostgres("runDatabaseBackup", () => {
describe("runDatabaseBackup", () => {
let support: ReturnType<typeof getEmbeddedPostgresTestSupport> | undefined;
beforeEach(async ({ skip }) => {
const result = await (support ??= getEmbeddedPostgresTestSupport());
if (!result.supported) skip(result.reason ?? "Embedded PostgreSQL is not supported");
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
it("preserves a post-pg_dump verification error without falling back or pruning", async () => {
const connectionString = await createTempDatabase();
const backupDir = createTempDir("checkpoint-pg-dump-");
@@ -663,4 +662,101 @@ describeEmbeddedPostgres("runDatabaseBackup", () => {
},
20_000,
);
});
describe("runDatabaseBackup (local PostgreSQL)", () => {
it.skipIf(process.platform === "win32").for([
{ backupEngine: "javascript", native: false },
{ backupEngine: "auto", native: false },
{ backupEngine: "auto", native: true },
{ backupEngine: "pg_dump", native: true },
] as const)(
"backs up and restores over a Unix socket with $backupEngine (native tools: $native)",
{ timeout: 60_000 },
async ({ backupEngine, native }, context) => {
const nativeClientMajors: number[] = [];
if (native) {
for (const command of [process.env.PAPERCLIP_PG_DUMP_PATH || "pg_dump", process.env.PAPERCLIP_PSQL_PATH || "psql"]) {
const result = spawnSync(command, ["--version"], { timeout: 5_000, encoding: "utf8" });
if (result.status !== 0) {
context.skip("Native socket round trip requires both pg_dump and psql");
}
const major = result.stdout.match(/\(PostgreSQL\)\s+(\d+)/)?.[1];
if (!major) context.skip("Cannot determine native PostgreSQL client versions");
nativeClientMajors.push(Number(major));
}
}
const options = { localOnly: true };
const support = await getEmbeddedPostgresTestSupport(options);
if (!support.supported) context.skip(support.reason ?? "Embedded PostgreSQL is not supported");
const db = await startEmbeddedPostgresTestDatabase("paperclip-db-backup-socket-", options);
context.onTestFinished(db.cleanup);
const tcpUrl = db.connectionString;
const probe = postgres(tcpUrl, { max: 1 });
let socketDir: string;
try {
const [row] = await probe`SHOW unix_socket_directories`;
socketDir = row.unix_socket_directories.split(",")[0].trim();
if (native) {
const [version] = await probe`SHOW server_version_num`;
const serverMajor = Math.floor(Number(version.server_version_num) / 10_000);
const [pgDumpMajor] = nativeClientMajors;
if (pgDumpMajor < serverMajor) {
context.skip(`pg_dump ${pgDumpMajor} cannot dump PostgreSQL ${serverMajor}`);
}
if (serverMajor < 17 && pgDumpMajor >= 17) {
context.skip(`PostgreSQL ${serverMajor} cannot restore pg_dump ${pgDumpMajor}'s SET transaction_timeout`);
}
}
} finally {
await probe.end();
}
expect(path.isAbsolute(socketDir)).toBe(true);
const url = new URL(tcpUrl);
url.hostname = "127.0.0.2";
url.searchParams.set("host", socketDir);
const sourceUrl = url.toString();
const targetUrl = await createSiblingDatabase(sourceUrl, "socket_restore_target");
const source = createDb(sourceUrl, { connectTimeoutSeconds: 2 }).$client;
const target = createDb(targetUrl, { connectTimeoutSeconds: 2 }).$client;
const originalPgDumpPath = process.env.PAPERCLIP_PG_DUMP_PATH;
const originalPsqlPath = process.env.PAPERCLIP_PSQL_PATH;
try {
if (!native) {
const missingTools = createTempDir("paperclip-no-native-tools-");
process.env.PAPERCLIP_PG_DUMP_PATH = path.join(missingTools, "pg_dump");
process.env.PAPERCLIP_PSQL_PATH = path.join(missingTools, "psql");
}
const [connection] = await source`SELECT inet_server_addr() AS address`;
expect(connection.address).toBeNull();
expect(await getPostgresDataDirectory(sourceUrl)).toBe(await getPostgresDataDirectory(tcpUrl));
await source`CREATE TABLE socket_probe (value text NOT NULL)`;
await source`INSERT INTO socket_probe VALUES ('socket-backup-fixture')`;
const backup = await runDatabaseBackup({
connectionString: sourceUrl,
backupDir: createTempDir("paperclip-socket-backup-"),
retention: { dailyDays: 7, weeklyWeeks: 4, monthlyMonths: 2 },
backupEngine,
});
const dump = gunzipSync(fs.readFileSync(backup.backupFile)).toString("utf8");
expect(dump).toContain(native ? "-- PostgreSQL database dump" : "-- Paperclip database backup");
await runDatabaseRestore({ connectionString: targetUrl, backupFile: backup.backupFile });
const [restored] = await target`SELECT value FROM socket_probe`;
expect(restored.value).toBe("socket-backup-fixture");
} finally {
if (originalPgDumpPath === undefined) {
delete process.env.PAPERCLIP_PG_DUMP_PATH;
} else {
process.env.PAPERCLIP_PG_DUMP_PATH = originalPgDumpPath;
}
if (originalPsqlPath === undefined) {
delete process.env.PAPERCLIP_PSQL_PATH;
} else {
process.env.PAPERCLIP_PSQL_PATH = originalPsqlPath;
}
await closeRegisteredClients(sourceUrl);
}
},
);
});
+5 -4
View File
@@ -1,3 +1,4 @@
import { connectPostgres } from "./postgres-connection.js";
import { createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
import { basename, resolve } from "node:path";
import { createInterface } from "node:readline";
@@ -540,7 +541,7 @@ export async function runDatabaseBackup(opts: RunDatabaseBackupOptions): Promise
const canUsePgDump = !hasBackupTransforms(opts);
const excludedTableNames = normalizeTableNameSet(opts.excludeTables);
const nullifiedColumnsByTable = normalizeNullifyColumnMap(opts.nullifyColumns);
let sql = postgres(opts.connectionString, { max: 1, connect_timeout: connectTimeout });
let sql: ReturnType<typeof postgres> = connectPostgres(opts.connectionString, { max: 1, connect_timeout: connectTimeout });
let sqlClosed = false;
const closeSql = async () => {
if (sqlClosed) return;
@@ -575,7 +576,7 @@ export async function runDatabaseBackup(opts: RunDatabaseBackupOptions): Promise
throw error;
}
effectiveBackupEngine = "javascript";
sql = postgres(opts.connectionString, { max: 1, connect_timeout: connectTimeout });
sql = connectPostgres(opts.connectionString, { max: 1, connect_timeout: connectTimeout });
sqlClosed = false;
}
if (dumped) {
@@ -979,7 +980,7 @@ export async function runDatabaseBackup(opts: RunDatabaseBackupOptions): Promise
if (effectiveBackupEngine !== "javascript" && nullifiedColumns.size === 0) {
emit(`COPY ${qualifiedTableName} (${colNames}) FROM stdin;`);
await writer.writeRaw("\n");
const copySql = postgres(opts.connectionString, { max: 1, connect_timeout: connectTimeout });
const copySql = connectPostgres(opts.connectionString, { max: 1, connect_timeout: connectTimeout });
try {
const copyStream = await copySql
.unsafe(`COPY ${qualifiedTableName} (${colNames}) TO STDOUT`)
@@ -1111,7 +1112,7 @@ export async function runDatabaseRestore(opts: RunDatabaseRestoreOptions): Promi
}
}
const sql = postgres(opts.connectionString, { max: 1, connect_timeout: connectTimeout });
const sql = connectPostgres(opts.connectionString, { max: 1, connect_timeout: connectTimeout });
try {
await sql`SELECT 1`;
+13 -2
View File
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_DATABASE_APPLICATION_NAME,
DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS,
DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS,
databaseClientOptionsFromEnv,
postgresJsOptions,
@@ -35,6 +36,7 @@ describe("databaseClientOptionsFromEnv", () => {
DATABASE_POOL_MAX: "25",
DATABASE_IDLE_TIMEOUT_SECONDS: "60",
DATABASE_CONNECT_TIMEOUT_SECONDS: "10",
DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS: "1500",
DATABASE_MAX_LIFETIME_SECONDS: "1800",
DATABASE_APPLICATION_NAME: " paperclip-web ",
}),
@@ -42,6 +44,7 @@ describe("databaseClientOptionsFromEnv", () => {
maxConnections: 25,
idleTimeoutSeconds: 60,
connectTimeoutSeconds: 10,
connectAttemptTimeoutMs: 1500,
maxLifetimeSeconds: 1800,
applicationName: "paperclip-web",
});
@@ -60,6 +63,9 @@ describe("databaseClientOptionsFromEnv", () => {
expect(() => databaseClientOptionsFromEnv({ DATABASE_CONNECT_TIMEOUT_SECONDS: "1.5" })).toThrow(
/DATABASE_CONNECT_TIMEOUT_SECONDS/,
);
expect(() => databaseClientOptionsFromEnv({ DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS: "0" })).toThrow(
/DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS/,
);
expect(() => databaseClientOptionsFromEnv({ DATABASE_IDLE_TIMEOUT_SECONDS: "-1" })).toThrow(
/DATABASE_IDLE_TIMEOUT_SECONDS/,
);
@@ -81,6 +87,7 @@ describe("databaseClientOptionsFromEnv", () => {
maxConnections: 25,
idleTimeoutSeconds: 60,
connectTimeoutSeconds: 10,
connectAttemptTimeoutMs: 1500,
maxLifetimeSeconds: 1800,
applicationName: "paperclip-web",
}),
@@ -89,6 +96,7 @@ describe("databaseClientOptionsFromEnv", () => {
max: 25,
idle_timeout: 60,
connect_timeout: 10,
auto_select_family_attempt_timeout: 1500,
max_lifetime: 1800,
connection: { application_name: "paperclip-web" },
});
@@ -102,13 +110,15 @@ describe("databaseClientOptionsFromEnv", () => {
});
describe("resolveDatabaseClientOptions", () => {
it("reaps idle connections and names the pool when the environment sets nothing", () => {
it("reaps idle connections, bounds each address attempt and names the pool when the environment sets nothing", () => {
expect(resolveDatabaseClientOptions({})).toEqual({
idleTimeoutSeconds: DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS,
connectAttemptTimeoutMs: DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS,
applicationName: DEFAULT_DATABASE_APPLICATION_NAME,
});
expect(postgresJsOptions(resolveDatabaseClientOptions(databaseClientOptionsFromEnv({})))).toEqual({
idle_timeout: DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS,
auto_select_family_attempt_timeout: DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS,
connection: { application_name: DEFAULT_DATABASE_APPLICATION_NAME },
});
});
@@ -118,9 +128,10 @@ describe("resolveDatabaseClientOptions", () => {
resolveDatabaseClientOptions({
maxConnections: 3,
idleTimeoutSeconds: 0,
connectAttemptTimeoutMs: 500,
applicationName: "paperclip-cli",
}),
).toEqual({ maxConnections: 3, idleTimeoutSeconds: 0, applicationName: "paperclip-cli" });
).toEqual({ maxConnections: 3, idleTimeoutSeconds: 0, connectAttemptTimeoutMs: 500, applicationName: "paperclip-cli" });
expect(postgresJsOptions(resolveDatabaseClientOptions({ idleTimeoutSeconds: 0 }))).toMatchObject({
idle_timeout: 0,
});
@@ -124,6 +124,22 @@ describe("closeRegisteredClients", () => {
}
});
it("does not close TCP clients when closing a socket URI with the same authority", async () => {
const started = await startFakePostgresServer();
server = started.server;
const tcpUrl = `postgres://test:test@127.0.0.1:${started.port}/test`;
const db = createDb(tcpUrl, { connectTimeoutSeconds: 5 });
try {
await db.$client`select 1`;
await closeRegisteredClients(`${tcpUrl}?host=/other/postgres`);
await expect(db.$client`select 1`).resolves.toEqual([]);
await closeRegisteredClients(`postgres://test@localhost:${started.port}/test?host=127.0.0.1`);
await expect(db.$client`select 1`).rejects.toMatchObject({ code: "CONNECTION_ENDED" });
} finally {
await closeRegisteredClients(tcpUrl);
}
});
it("does not throw when createDb receives a URL that new URL() cannot parse", async () => {
let db: ReturnType<typeof createDb> | undefined;
expect(() => {
+32 -5
View File
@@ -2,7 +2,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
import { createHash } from "node:crypto";
import { readFile, readdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import postgres from "postgres";
import { connectPostgres as postgres } from "./postgres-connection.js";
import { installDatabaseWorkSignals } from "./work-signals.js";
import { installDatabaseResponseCapture } from "./response-capture.js";
import { createPreparedQueryState, installPreparedQueries, preparedQueryStats, type PreparedQueryState, type PreparedQueryStats } from "./prepared-queries.js";
@@ -31,7 +31,8 @@ type RegisteredPostgresClient = ReturnType<typeof postgres>;
*/
function hostPortKey(url: string): string {
const parsed = new URL(url);
return `${parsed.hostname}:${parsed.port || "5432"}`;
const host = parsed.searchParams.get("host") || parsed.hostname;
return `${host}:${parsed.port || "5432"}`;
}
/**
@@ -151,6 +152,13 @@ export interface DatabaseClientOptions {
idleTimeoutSeconds?: number;
/** postgres.js `connect_timeout` in seconds (driver default: 30). */
connectTimeoutSeconds?: number;
/**
* Time in milliseconds that one connection attempt gives each address of the
* database host before it tries the next one (Node's
* `autoSelectFamilyAttemptTimeout`, default 250). The whole attempt is still
* bounded by `connectTimeoutSeconds`.
*/
connectAttemptTimeoutMs?: number;
/**
* postgres.js `max_lifetime` in seconds. Bounds how long one pooled
* connection is reused before the client replaces it (driver default: a
@@ -183,6 +191,16 @@ export interface DatabaseClientOptions {
export const DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS = 60;
/** `application_name` reported to PostgreSQL unless `DATABASE_APPLICATION_NAME` overrides it. */
export const DEFAULT_DATABASE_APPLICATION_NAME = "paperclip";
/**
* Each address of the database host gets this many milliseconds unless
* `DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS` says otherwise. Node's own default of
* 250 ms is shorter than the first SYN retransmission (1 s on Linux). When the
* host name also has AAAA records and this machine has no IPv6 route, the last
* address fails at once, so a connection failed after about 750 ms when one
* packet was dropped, long before `connect_timeout`. 2 s lets each address
* answer a retransmitted SYN.
*/
export const DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS = 2_000;
function envBoolean(env: NodeJS.ProcessEnv, name: string): boolean | undefined {
const value = env[name]?.trim().toLowerCase();
@@ -235,6 +253,8 @@ export function databaseClientOptionsFromEnv(env: NodeJS.ProcessEnv = process.en
if (idleTimeoutSeconds !== undefined) options.idleTimeoutSeconds = idleTimeoutSeconds;
const connectTimeoutSeconds = envPositiveInteger(env, "DATABASE_CONNECT_TIMEOUT_SECONDS");
if (connectTimeoutSeconds !== undefined) options.connectTimeoutSeconds = connectTimeoutSeconds;
const connectAttemptTimeoutMs = envPositiveInteger(env, "DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS");
if (connectAttemptTimeoutMs !== undefined) options.connectAttemptTimeoutMs = connectAttemptTimeoutMs;
const maxLifetimeSeconds = envPositiveInteger(env, "DATABASE_MAX_LIFETIME_SECONDS");
if (maxLifetimeSeconds !== undefined) options.maxLifetimeSeconds = maxLifetimeSeconds;
const applicationName = envNonEmptyString(env, "DATABASE_APPLICATION_NAME");
@@ -248,15 +268,17 @@ export function databaseClientOptionsFromEnv(env: NodeJS.ProcessEnv = process.en
/**
* Fills in Paperclip's defaults for the options the caller left unset: idle
* connections are reaped after `DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS`, and the
* pool identifies itself as `DEFAULT_DATABASE_APPLICATION_NAME`. Everything
* else stays at the driver default. An explicit value (including
* connections are reaped after `DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS`, each
* address of the database host gets `DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS`,
* and the pool identifies itself as `DEFAULT_DATABASE_APPLICATION_NAME`.
* Everything else stays at the driver default. An explicit value (including
* `idleTimeoutSeconds: 0`) always wins over the default.
*/
export function resolveDatabaseClientOptions(options: DatabaseClientOptions): DatabaseClientOptions {
return {
...options,
idleTimeoutSeconds: options.idleTimeoutSeconds ?? DEFAULT_DATABASE_IDLE_TIMEOUT_SECONDS,
connectAttemptTimeoutMs: options.connectAttemptTimeoutMs ?? DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS,
applicationName: options.applicationName ?? DEFAULT_DATABASE_APPLICATION_NAME,
};
}
@@ -267,6 +289,10 @@ export function postgresJsOptions(options: DatabaseClientOptions): Record<string
if (options.maxConnections !== undefined) driverOptions.max = options.maxConnections;
if (options.idleTimeoutSeconds !== undefined) driverOptions.idle_timeout = options.idleTimeoutSeconds;
if (options.connectTimeoutSeconds !== undefined) driverOptions.connect_timeout = options.connectTimeoutSeconds;
// Read by the patched postgres.js connect (patches/postgres@3.4.9.patch).
if (options.connectAttemptTimeoutMs !== undefined) {
driverOptions.auto_select_family_attempt_timeout = options.connectAttemptTimeoutMs;
}
if (options.maxLifetimeSeconds !== undefined) driverOptions.max_lifetime = options.maxLifetimeSeconds;
const connection: Record<string, string> = {};
if (options.applicationName !== undefined) connection.application_name = options.applicationName;
@@ -926,6 +952,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([
"0511_simple_the_hunter.sql",
"0512_stormy_the_hood.sql",
"0513_closed_wither.sql",
"0516_exotic_spectrum.sql",
]);
async function applyPendingMigrationsManually(
@@ -0,0 +1 @@
ALTER TABLE "issue_attachments" ADD COLUMN "issue_level" boolean DEFAULT false NOT NULL;
@@ -0,0 +1,15 @@
CREATE TABLE "user_recent_tasks" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"company_id" uuid NOT NULL,
"user_id" text NOT NULL,
"issue_id" uuid NOT NULL,
"recorded_at" timestamp with time zone DEFAULT now() NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "user_recent_tasks" ADD CONSTRAINT "user_recent_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 "user_recent_tasks" ADD CONSTRAINT "user_recent_tasks_issue_id_issues_id_fk" FOREIGN KEY ("issue_id") REFERENCES "public"."issues"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "user_recent_tasks_company_user_recorded_idx" ON "user_recent_tasks" USING btree ("company_id","user_id","recorded_at");--> statement-breakpoint
CREATE INDEX "user_recent_tasks_issue_idx" ON "user_recent_tasks" USING btree ("issue_id");--> statement-breakpoint
CREATE UNIQUE INDEX "user_recent_tasks_company_user_issue_uq" ON "user_recent_tasks" USING btree ("company_id","user_id","issue_id");
@@ -0,0 +1,2 @@
CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_actions_github_run_publications_idx" ON "chat_actions" USING btree ("company_id","endpoint_id",("payload"->'session'->>'issueId'),("payload"->'session'->>'runId')) WHERE "chat_actions"."kind" = 'github_review_publication';--> statement-breakpoint
CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_actions_pending_work_idx" ON "chat_actions" USING btree ("kind","created_at","id") WHERE "chat_actions"."status" IN ('received', 'processing', 'queued', 'provider_confirmed', 'admitting', 'resolving', 'validating', 'dispatching') OR ("chat_actions"."kind" = 'failed_run_retry' AND "chat_actions"."status" IN ('issued', 'processing')) OR ("chat_actions"."status" = 'failed' AND "chat_actions"."result"->>'retryable' = 'true');
File diff suppressed because it is too large. Load diff
+21
View File
@@ -3585,6 +3585,27 @@
"when": 1796171923647,
"tag": "0513_closed_wither",
"breakpoints": true
},
{
"idx": 514,
"version": "7",
"when": 1796346310107,
"tag": "0514_lame_ricochet",
"breakpoints": true
},
{
"idx": 515,
"version": "7",
"when": 1796362090964,
"tag": "0515_fixed_grandmaster",
"breakpoints": true
},
{
"idx": 516,
"version": "7",
"when": 1796435141126,
"tag": "0516_exotic_spectrum",
"breakpoints": true
}
]
}
@@ -0,0 +1,48 @@
import net from "node:net";
import postgres from "postgres";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS,
postgresJsOptions,
resolveDatabaseClientOptions,
} from "./client.js";
// Node tries each address of a database host name in turn (happy eyeballs) and
// by default gives every address but the last only 250 ms. When the last
// address is IPv6 on a host with no IPv6 route, it fails at once, so a host
// name with three A and three AAAA records fails to connect after about 750 ms
// whatever `connect_timeout` says. A single dropped SYN then fails the query.
describe("database connect attempt timeout", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("gives each address of the database host enough time for a retransmitted SYN by default", () => {
expect(DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS).toBeGreaterThanOrEqual(1_000);
expect(postgresJsOptions(resolveDatabaseClientOptions({}))).toMatchObject({
auto_select_family_attempt_timeout: DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS,
});
});
it("passes the per-address budget to the socket that postgres.js opens", async () => {
const connect = vi.spyOn(net.Socket.prototype, "connect");
// Port 1 on loopback refuses at once; only the connect arguments matter.
const sql = postgres("postgres://paperclip:unused@127.0.0.1:1/paperclip", {
...postgresJsOptions(resolveDatabaseClientOptions({ connectTimeoutSeconds: 5 })),
max: 1,
onnotice: () => {},
});
try {
await expect(sql`select 1`).rejects.toMatchObject({ code: "ECONNREFUSED" });
} finally {
await sql.end({ timeout: 0 });
}
expect(connect).toHaveBeenCalled();
expect(connect.mock.calls[0]?.[0]).toMatchObject({
host: "127.0.0.1",
port: 1,
autoSelectFamilyAttemptTimeout: DEFAULT_DATABASE_CONNECT_ATTEMPT_TIMEOUT_MS,
});
});
});
@@ -0,0 +1,37 @@
import { expect, it } from "vitest";
import { connectPostgres } from "./postgres-connection.js";
it("uses a Unix socket rather than TCP for libpq host URIs", async () => {
const client = connectPostgres("postgresql://runtime@localhost:5433/example?host=/run/postgresql");
try {
expect(client.options.host).toEqual(["/run/postgresql"]);
expect(client.options.path).toBe("/run/postgresql/.s.PGSQL.5433");
expect(client.options.connection).not.toHaveProperty("host");
} finally {
await client.end();
}
});
it("preserves explicit driver host overrides", async () => {
const client = connectPostgres("postgresql://runtime@localhost/example?host=/run/postgresql", {
host: "/other/socket",
port: 5434,
});
try {
expect(client.options.path).toBe("/other/socket/.s.PGSQL.5434");
expect(client.options.connection).not.toHaveProperty("host");
} finally {
await client.end();
}
});
it("supports TCP hosts in the libpq host query parameter", async () => {
const client = connectPostgres("postgresql://runtime@localhost:5433/example?host=db.example");
try {
expect(client.options.host).toEqual(["db.example"]);
expect(client.options.path).toBeFalsy();
expect(client.options.connection).not.toHaveProperty("host");
} finally {
await client.end();
}
});
+14
View File
@@ -0,0 +1,14 @@
import postgres from "postgres";
export function connectPostgres(connectionString: string, options: Record<string, unknown> = {}) {
let url: URL;
try {
url = new URL(connectionString);
} catch {
return postgres(connectionString, options);
}
const host = url.searchParams.get("host");
if (!host) return postgres(connectionString, options);
url.searchParams.delete("host");
return postgres(url.toString(), { host, ...options });
}
+35
View File
@@ -0,0 +1,35 @@
import { expect, it } from "vitest";
import { closeRegisteredClients, createDb } from "./client.js";
it.each(["/run/postgresql", "%2Frun%2Fpostgresql"])(
"connects through the URI socket host %s while preserving pool options",
async (host) => {
const url = `postgresql://runtime@localhost:5433/example?host=${host}`;
const db = createDb(url, { prepare: false, maxConnections: 2, applicationName: "socket-test" });
try {
expect(db.$client.options.host).toEqual(["/run/postgresql"]);
expect(db.$client.options.path).toBe("/run/postgresql/.s.PGSQL.5433");
expect(db.$client.options.connection).not.toHaveProperty("host");
expect(db.$client.options.connection.application_name).toBe("socket-test");
expect(db.$client.options.prepare).toBe(false);
expect(db.$client.options.max).toBe(2);
} finally {
await closeRegisteredClients(url);
}
},
);
it("keeps ordinary TCP URI options", async () => {
const url = "postgresql://runtime:fixture%3Apassword@db.example:5433/example?sslmode=require";
const db = createDb(url);
try {
expect(db.$client.options.host).toEqual(["db.example"]);
expect(db.$client.options.port).toEqual([5433]);
expect(db.$client.options.path).toBeFalsy();
expect(db.$client.options.database).toBe("example");
expect(db.$client.options.user).toBe("runtime");
expect(db.$client.options.ssl).toBe("require");
} finally {
await closeRegisteredClients(url);
}
});
+15
View File
@@ -715,6 +715,21 @@ export const chatActions = pgTable(
.on(table.companyId, table.endpointId, sql`(${table.payload}->'session'->>'issueId')`, table.updatedAt)
.where(sql`${table.kind} = 'github_review_publication' and ${table.status} = 'processed'`)
.concurrently(),
index("chat_actions_github_run_publications_idx")
.on(
table.companyId,
table.endpointId,
sql`(${table.payload}->'session'->>'issueId')`,
sql`(${table.payload}->'session'->>'runId')`,
)
.where(sql`${table.kind} = 'github_review_publication'`)
.concurrently(),
index("chat_actions_pending_work_idx")
.on(table.kind, table.createdAt, table.id)
.where(
sql`${table.status} IN ('received', 'processing', 'queued', 'provider_confirmed', 'admitting', 'resolving', 'validating', 'dispatching') OR (${table.kind} = 'failed_run_retry' AND ${table.status} IN ('issued', 'processing')) OR (${table.status} = 'failed' AND ${table.result}->>'retryable' = 'true')`,
)
.concurrently(),
index("chat_actions_github_terminal_work_idx").on(table.id).where(sql`${table.kind} = 'github_response_comment'
and ${table.status} = 'processed' and ${table.deliveryId} is not null
and coalesce(${table.result}->>'final', 'false') <> 'true'`),
Loaded 100 of 592 files, more files were not shown because too many files have changed in this diff. Show more