Add ACPX local adapter runtime (#4893)

## Thinking Path

> - Paperclip orchestrates AI-agent companies through a control plane
that can start, supervise, and recover agent runs.
> - Local adapters are the bridge between Paperclip issues and concrete
agent runtimes such as Claude, Codex, and other ACP-compatible tools.
> - The roadmap calls out broader “bring your own agent” and claw-style
agent support, and ACPX gives Paperclip one path to normalize multiple
ACP agents behind a single adapter.
> - The branch needed to become one reviewable PR against current
`paperclipai/paperclip:master`, without carrying stale base conflicts or
generated lockfile churn.
> - This pull request adds an experimental built-in `acpx_local`
adapter, integrates it through the server/CLI/UI adapter surfaces, and
adds regression coverage for runtime execution, skill sync, stream
parsing, diagnostics, and log redaction.
> - The benefit is that Paperclip can run Claude/Codex/custom ACP agents
through ACPX while keeping operator configuration, skills, logging, and
transcript rendering inside the existing adapter model.

## What Changed

- Added `@paperclipai/adapter-acpx-local` with server execution, config
schema, ACPX session handling, CLI formatting, UI config helpers, and
stdout parsing.
- Registered `acpx_local` across CLI, server, shared constants, UI
adapter metadata, adapter capabilities, and agent creation/editing
surfaces.
- Added ACPX runtime execution support with persistent sessions,
local-agent JWT environment handling, skill snapshots, runtime skill
materialization, and isolation/security regressions.
- Added ACPX adapter diagnostics and marked the adapter experimental in
the UI.
- Added command/env secret redaction for resolved command metadata in
adapter-utils, server event storage, and the Agent Detail invocation UI.
- Added Storybook coverage for ACPX config, transcript rendering, and
skill states, plus PR screenshots under `docs/pr-screenshots/pap-2944/`.
- Rebased the branch onto current `public-gh/master`; `pnpm-lock.yaml`
is intentionally not included and there are no migration/schema changes.

## Verification

- `pnpm exec vitest run
packages/adapters/acpx-local/src/server/execute.test.ts
packages/adapters/acpx-local/src/server/test.test.ts
packages/adapters/acpx-local/src/cli/format-event.test.ts
packages/adapters/acpx-local/src/ui/parse-stdout.test.ts
packages/adapter-utils/src/server-utils.test.ts
server/src/__tests__/redaction.test.ts
server/src/__tests__/acpx-local-execute.test.ts
server/src/__tests__/acpx-local-skill-sync.test.ts
server/src/__tests__/acpx-local-adapter-environment.test.ts
server/src/__tests__/adapter-routes.test.ts
server/src/__tests__/agent-skills-routes.test.ts
ui/src/adapters/metadata.test.ts` — 12 files, 87 tests passed.
- `pnpm --filter @paperclipai/adapter-acpx-local typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm --filter @paperclipai/ui typecheck` — passed.
- Confirmed PR diff does not include `pnpm-lock.yaml`, database schema
files, or migrations.

Screenshots:

![ACPX Claude skills
light](https://github.com/cryppadotta/paperclip-1/blob/PAP-2944-acpx-make-a-claude_local-adapter-that-uses-acpx-instead/docs/pr-screenshots/pap-2944/skills-claude-light.png?raw=true)
![ACPX Claude skills
dark](https://github.com/cryppadotta/paperclip-1/blob/PAP-2944-acpx-make-a-claude_local-adapter-that-uses-acpx-instead/docs/pr-screenshots/pap-2944/skills-claude-dark.png?raw=true)
![ACPX custom skills
light](https://github.com/cryppadotta/paperclip-1/blob/PAP-2944-acpx-make-a-claude_local-adapter-that-uses-acpx-instead/docs/pr-screenshots/pap-2944/skills-custom-light.png?raw=true)

## Risks

- Medium risk: this introduces a new built-in adapter package and
touches runtime execution, adapter registration, agent config, skills,
and transcript rendering.
- ACPX and ACP agent behavior can vary by installed tool versions; the
adapter is marked experimental to set operator expectations.
- `pnpm-lock.yaml` is excluded per repository PR policy, so dependency
lock refresh must be handled by the repo’s automation or maintainers.
- No database migration risk: no schema or migration files changed.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex coding agent based on GPT-5, with repository tool use,
shell execution, git operations, and local verification. Exact hosted
context window was not exposed in this environment.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Dotta 2026-04-30 19:57:05 -05:00 committed by GitHub
parent ad5432fece
commit 4272c1604d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
70 changed files with 5521 additions and 31 deletions

View file

@ -0,0 +1,64 @@
{
"name": "@paperclipai/adapter-acpx-local",
"version": "0.3.1",
"license": "MIT",
"homepage": "https://github.com/paperclipai/paperclip",
"bugs": {
"url": "https://github.com/paperclipai/paperclip/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/paperclipai/paperclip",
"directory": "packages/adapters/acpx-local"
},
"type": "module",
"exports": {
".": "./src/index.ts",
"./server": "./src/server/index.ts",
"./ui": "./src/ui/index.ts",
"./cli": "./src/cli/index.ts"
},
"publishConfig": {
"access": "public",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./server": {
"types": "./dist/server/index.d.ts",
"import": "./dist/server/index.js"
},
"./ui": {
"types": "./dist/ui/index.d.ts",
"import": "./dist/ui/index.js"
},
"./cli": {
"types": "./dist/cli/index.d.ts",
"import": "./dist/cli/index.js"
}
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"files": [
"dist",
"skills"
],
"scripts": {
"build": "tsc",
"clean": "rm -rf dist",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@agentclientprotocol/claude-agent-acp": "^0.31.4",
"@paperclipai/adapter-utils": "workspace:*",
"@zed-industries/codex-acp": "^0.12.0",
"acpx": "^0.6.1",
"picocolors": "^1.1.1"
},
"devDependencies": {
"@types/node": "^24.6.0",
"typescript": "^5.7.3"
}
}

View file

@ -0,0 +1,121 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { printAcpxStreamEvent } from "./format-event.js";
function emit(payload: Record<string, unknown>): string {
return JSON.stringify(payload);
}
interface CapturedOutput {
log: string[];
stdout: string[];
}
function captureOutput(): { capture: CapturedOutput; restore: () => void } {
const log: string[] = [];
const stdout: string[] = [];
const logSpy = vi.spyOn(console, "log").mockImplementation((value?: unknown) => {
log.push(String(value ?? ""));
});
const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => {
stdout.push(String(chunk ?? ""));
return true;
}) as typeof process.stdout.write);
return {
capture: { log, stdout },
restore: () => {
logSpy.mockRestore();
stdoutSpy.mockRestore();
},
};
}
function strip(value: string): string {
return value.replace(/\x1b\[[0-9;]*m/g, "");
}
describe("printAcpxStreamEvent", () => {
let captured: CapturedOutput;
let restore: () => void;
beforeEach(() => {
const result = captureOutput();
captured = result.capture;
restore = result.restore;
});
afterEach(() => {
restore();
});
it("renders acpx.session as a labeled session header", () => {
printAcpxStreamEvent(
emit({
type: "acpx.session",
agent: "claude",
acpSessionId: "acp-1",
mode: "persistent",
permissionMode: "approve-all",
}),
false,
);
expect(captured.log.map(strip)).toEqual(["claude session: acp-1 [persistent / approve-all]"]);
});
it("streams output text_delta to stdout for live progress", () => {
printAcpxStreamEvent(
emit({ type: "acpx.text_delta", text: "hello", channel: "output" }),
false,
);
expect(captured.log).toEqual([]);
expect(captured.stdout.map(strip)).toEqual(["hello"]);
});
it("renders thought text_delta on its own line", () => {
printAcpxStreamEvent(
emit({ type: "acpx.text_delta", text: "thinking…", channel: "thought" }),
false,
);
expect(captured.log.map(strip)).toEqual(["thinking…"]);
});
it("renders tool_call with status and id", () => {
printAcpxStreamEvent(
emit({
type: "acpx.tool_call",
name: "read",
toolCallId: "tool-1",
status: "running",
text: "read README.md",
}),
false,
);
expect(captured.log.map(strip)).toEqual([
"tool_call: read [running] (tool-1)",
"read README.md",
]);
});
it("renders status events with optional context window", () => {
printAcpxStreamEvent(
emit({ type: "acpx.status", tag: "context_window", used: 100, size: 200000 }),
false,
);
expect(captured.log.map(strip)).toEqual(["status: context_window (100/200000 ctx)"]);
});
it("renders acpx.result and acpx.error", () => {
printAcpxStreamEvent(emit({ type: "acpx.result", summary: "completed", stopReason: "end_turn" }), false);
printAcpxStreamEvent(emit({ type: "acpx.error", message: "auth required" }), false);
expect(captured.log.map(strip)).toEqual(["result: completed", "error: auth required"]);
});
it("falls back to plain output for non-JSON lines", () => {
printAcpxStreamEvent("not json", false);
expect(captured.log).toEqual(["not json"]);
});
it("still emits unknown / non-JSON lines when debug is enabled", () => {
printAcpxStreamEvent("not json", true);
expect(strip(captured.log[0])).toBe("not json");
});
});

View file

@ -0,0 +1,121 @@
import pc from "picocolors";
function parseJson(line: string): Record<string, unknown> | null {
try {
const parsed = JSON.parse(line);
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
return parsed as Record<string, unknown>;
} catch {
return null;
}
}
function asString(value: unknown, fallback = ""): string {
return typeof value === "string" ? value : fallback;
}
function asNumber(value: unknown, fallback = 0): number {
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
}
function stringify(value: unknown): string {
if (typeof value === "string") return value;
if (value === null || value === undefined) return "";
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
function pickToolUseId(parsed: Record<string, unknown>): string {
return (
asString(parsed.toolCallId) ||
asString(parsed.toolUseId) ||
asString(parsed.id)
);
}
function statusLine(parsed: Record<string, unknown>): string {
const text = asString(parsed.text).trim();
const tag = asString(parsed.tag).trim();
const used = asNumber(parsed.used, -1);
const size = asNumber(parsed.size, -1);
const parts: string[] = [];
if (text) parts.push(text);
if (tag && !text) parts.push(tag);
if (used >= 0 && size > 0) parts.push(`(${used}/${size} ctx)`);
return parts.join(" ") || tag || "status";
}
export function printAcpxStreamEvent(raw: string, debug: boolean): void {
const line = raw.trim();
if (!line) return;
const parsed = parseJson(line);
if (!parsed) {
if (debug) console.log(pc.gray(line));
else console.log(line);
return;
}
const type = asString(parsed.type);
if (type === "acpx.session") {
const agent = asString(parsed.agent, "acpx");
const session =
asString(parsed.acpSessionId) ||
asString(parsed.sessionId) ||
asString(parsed.runtimeSessionName);
const mode = asString(parsed.mode);
const permissionMode = asString(parsed.permissionMode);
const tail = [mode, permissionMode].filter(Boolean).join(" / ");
const suffix = tail ? ` [${tail}]` : "";
console.log(pc.blue(`${agent} session${session ? `: ${session}` : ""}${suffix}`));
return;
}
if (type === "acpx.text_delta") {
const text = asString(parsed.text);
if (!text) return;
const channel = asString(parsed.channel) || asString(parsed.stream);
const isThought = channel === "thought" || channel === "thinking";
if (isThought) console.log(pc.gray(text));
else process.stdout.write(pc.green(text));
return;
}
if (type === "acpx.tool_call") {
const name = asString(parsed.name, "acp_tool");
const status = asString(parsed.status);
const id = pickToolUseId(parsed);
const header = status ? `tool_call: ${name} [${status}]` : `tool_call: ${name}`;
const idSuffix = id ? ` (${id})` : "";
const isError = status === "failed" || status === "cancelled";
console.log((isError ? pc.red : pc.yellow)(`${header}${idSuffix}`));
if (parsed.input !== undefined) {
console.log(pc.gray(stringify(parsed.input)));
} else {
const text = asString(parsed.text).trim();
if (text) console.log(pc.gray(text));
}
return;
}
if (type === "acpx.tool_result") {
const isError = parsed.isError === true || parsed.error !== undefined;
console.log((isError ? pc.red : pc.cyan)(`tool_result: ${asString(parsed.name, "acp_tool")}`));
const content = stringify(parsed.content ?? parsed.output ?? parsed.error);
if (content) console.log((isError ? pc.red : pc.gray)(content));
return;
}
if (type === "acpx.status") {
console.log(pc.gray(`status: ${statusLine(parsed)}`));
return;
}
if (type === "acpx.result") {
const summary = asString(parsed.summary, asString(parsed.stopReason, asString(parsed.subtype, "complete")));
console.log(pc.blue(`result: ${summary}`));
return;
}
if (type === "acpx.error") {
console.log(pc.red(`error: ${asString(parsed.message, line)}`));
return;
}
console.log(debug ? pc.gray(line) : line);
}

View file

@ -0,0 +1 @@
export { printAcpxStreamEvent } from "./format-event.js";

View file

@ -0,0 +1,47 @@
export const type = "acpx_local";
export const label = "ACPX (local)";
export const DEFAULT_ACPX_LOCAL_AGENT = "claude";
export const DEFAULT_ACPX_LOCAL_MODE = "persistent";
export const DEFAULT_ACPX_LOCAL_PERMISSION_MODE = "approve-all";
export const DEFAULT_ACPX_LOCAL_NON_INTERACTIVE_PERMISSIONS = "deny";
export const DEFAULT_ACPX_LOCAL_TIMEOUT_SEC = 0;
export const acpxAgentOptions = [
{ id: "claude", label: "Claude via ACPX" },
{ id: "codex", label: "Codex via ACPX" },
{ id: "custom", label: "Custom ACP command" },
] as const;
export const agentConfigurationDoc = `# acpx_local agent configuration
Adapter: acpx_local
Use when:
- The agent should run through Agent Client Protocol via ACPX on the Paperclip host or a managed execution environment.
- You want one built-in adapter that can target Claude, Codex, or a custom ACP server command.
- You need Paperclip-managed session identity and live streamed ACP events in later ACPX runtime phases.
Don't use when:
- You need today's stable Claude Code or Codex CLI wrapper behavior. Use claude_local or codex_local until acpx_local runtime execution is enabled.
- The host cannot satisfy ACPX's Node >=22.12.0 prerequisite.
- The agent runtime is not an ACP server and cannot be launched through ACPX.
Core fields:
- agent (string, optional): claude, codex, or custom. Defaults to claude.
- agentCommand (string, optional): custom ACP command when agent=custom, or an override for a built-in ACP agent command.
- mode (string, optional): persistent or oneshot. Defaults to persistent.
- cwd (string, optional): default absolute working directory fallback for the agent process.
- permissionMode (string, optional): defaults to approve-all, meaning ACPX permission requests are auto-approved.
- nonInteractivePermissions (string, optional): fallback behavior when ACPX cannot ask interactively. Supported values are deny and fail.
- stateDir (string, optional): ACPX state directory. Defaults to a Paperclip-managed company/agent scoped location.
- instructionsFilePath (string, optional): absolute path to a markdown instructions file used by Paperclip prompt construction.
- promptTemplate (string, optional): run prompt template.
- bootstrapPromptTemplate (string, optional): first-run bootstrap prompt template.
- timeoutSec (number, optional): run timeout in seconds. Defaults to 0, meaning no adapter timeout.
- env (object, optional): KEY=VALUE environment variables or secret bindings.
Dependency decision:
- acpx_local declares direct dependencies on acpx, @agentclientprotocol/claude-agent-acp, and @zed-industries/codex-acp so the built-in adapter has deterministic package resolution instead of relying on globally installed ACP commands.
- ACPX currently requires Node >=22.12.0. Paperclip keeps the repo-wide Node >=20 engine and surfaces the stricter runtime prerequisite through acpx_local diagnostics.
`;

View file

@ -0,0 +1,102 @@
import type { AdapterConfigSchema } from "@paperclipai/adapter-utils";
import {
DEFAULT_ACPX_LOCAL_AGENT,
DEFAULT_ACPX_LOCAL_MODE,
DEFAULT_ACPX_LOCAL_NON_INTERACTIVE_PERMISSIONS,
DEFAULT_ACPX_LOCAL_PERMISSION_MODE,
DEFAULT_ACPX_LOCAL_TIMEOUT_SEC,
acpxAgentOptions,
} from "../index.js";
export function getConfigSchema(): AdapterConfigSchema {
return {
fields: [
{
key: "agent",
label: "ACP agent",
type: "select",
default: DEFAULT_ACPX_LOCAL_AGENT,
required: true,
options: acpxAgentOptions.map((agent) => ({ value: agent.id, label: agent.label })),
hint: "Choose the ACP agent launched through ACPX.",
},
{
key: "agentCommand",
label: "Agent command",
type: "text",
hint: "Required for custom agents; optional override for built-in Claude or Codex ACP commands.",
},
{
key: "mode",
label: "Session mode",
type: "select",
default: DEFAULT_ACPX_LOCAL_MODE,
options: [
{ value: "persistent", label: "Persistent" },
{ value: "oneshot", label: "One shot" },
],
},
{
key: "permissionMode",
label: "Permission mode",
type: "select",
default: DEFAULT_ACPX_LOCAL_PERMISSION_MODE,
options: [
{ value: "approve-all", label: "Approve all" },
{ value: "default", label: "Approve reads" },
],
hint: "Defaults to maximum permissions. Approve reads grants read-only requests and asks for approval on writes.",
},
{
key: "nonInteractivePermissions",
label: "Non-interactive permissions",
type: "select",
default: DEFAULT_ACPX_LOCAL_NON_INTERACTIVE_PERMISSIONS,
options: [
{ value: "deny", label: "Deny" },
{ value: "fail", label: "Fail" },
],
},
{
key: "cwd",
label: "Working directory",
type: "text",
hint: "Absolute fallback directory. Paperclip execution workspaces can override this at runtime.",
},
{
key: "stateDir",
label: "State directory",
type: "text",
hint: "Optional ACPX session state directory. Defaults to Paperclip-managed company/agent scoped storage.",
},
{
key: "instructionsFilePath",
label: "Instructions file",
type: "text",
hint: "Optional absolute path to markdown instructions injected into the run prompt.",
},
{
key: "promptTemplate",
label: "Prompt template",
type: "textarea",
},
{
key: "bootstrapPromptTemplate",
label: "Bootstrap prompt template",
type: "textarea",
},
{
key: "timeoutSec",
label: "Timeout seconds",
type: "number",
default: DEFAULT_ACPX_LOCAL_TIMEOUT_SEC,
},
{
key: "env",
label: "Environment JSON",
type: "textarea",
hint: "Optional JSON object of environment values or secret bindings.",
},
],
};
}

View file

@ -0,0 +1,362 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createAcpxLocalExecutor } from "./execute.js";
const tempRoots: string[] = [];
async function makeTempRoot() {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-skills-"));
tempRoots.push(root);
return root;
}
afterEach(async () => {
await Promise.all(tempRoots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
});
async function pathExists(candidate: string): Promise<boolean> {
return fs.access(candidate).then(() => true).catch(() => false);
}
async function onlyChildDir(parent: string): Promise<string> {
const entries = await fs.readdir(parent);
expect(entries).toHaveLength(1);
return path.join(parent, entries[0]!);
}
async function createSkill(root: string, name: string, body = `---\nrequired: false\n---\n# ${name}\n`) {
const skillDir = path.join(root, name);
await fs.mkdir(skillDir, { recursive: true });
await fs.writeFile(path.join(skillDir, "SKILL.md"), body, "utf8");
return {
key: `paperclipai/test/${name}`,
runtimeName: name,
source: skillDir,
required: false,
};
}
function buildRuntime() {
return {
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: "completed", stopReason: "end_turn" }),
cancel: async () => {},
}),
close: async () => {},
};
}
async function runExecutor(config: Record<string, unknown>) {
const runtimeOptions: Record<string, unknown>[] = [];
const meta: Record<string, unknown>[] = [];
const logs: Array<{ stream: string; text: string }> = [];
const execute = createAcpxLocalExecutor({
createRuntime: (options) => {
runtimeOptions.push(options as unknown as Record<string, unknown>);
return buildRuntime() as never;
},
});
const result = await execute({
runId: "run-1",
agent: {
id: "agent-1",
companyId: "company-1",
},
runtime: {},
config,
context: {},
onLog: async (stream: "stdout" | "stderr", text: string) => {
logs.push({ stream, text });
},
onMeta: async (payload: unknown) => {
meta.push(payload as Record<string, unknown>);
},
} as never);
expect(result.exitCode).toBe(0);
return { logs, meta, runtimeOptions, result };
}
describe("acpx_local runtime skill isolation", () => {
it.skipIf(process.platform === "win32")("materializes ACPX Claude skills without symlinked descendants", async () => {
const root = await makeTempRoot();
const skillRoot = path.join(root, "skills");
const outsideRoot = path.join(root, "outside");
await fs.mkdir(outsideRoot, { recursive: true });
await fs.writeFile(path.join(outsideRoot, "secret.txt"), "do not expose", "utf8");
const skill = await createSkill(skillRoot, "danger");
await fs.symlink(path.join(outsideRoot, "secret.txt"), path.join(skill.source, "leak.txt"));
await fs.symlink(outsideRoot, path.join(skill.source, "leak-dir"));
const stateDir = path.join(root, "state");
const { meta } = await runExecutor({
agent: "claude",
stateDir,
paperclipRuntimeSkills: [skill],
paperclipSkillSync: { desiredSkills: [skill.key] },
});
const mountedRoot = await onlyChildDir(path.join(stateDir, "runtime-skills", "claude"));
const skillsHome = path.join(mountedRoot, ".claude", "skills");
const materializedSkill = path.join(skillsHome, skill.runtimeName);
expect(await fs.readFile(path.join(materializedSkill, "SKILL.md"), "utf8")).toContain("# danger");
expect(await pathExists(path.join(materializedSkill, "leak.txt"))).toBe(false);
expect(await pathExists(path.join(materializedSkill, "leak-dir"))).toBe(false);
expect(String(meta[0]?.prompt ?? "")).toContain(`Skill root: ${skillsHome}`);
});
it.skipIf(process.platform === "win32")("revokes removed ACPX Codex skills and skips symlinked descendants", async () => {
const root = await makeTempRoot();
const skillRoot = path.join(root, "skills");
const outsideRoot = path.join(root, "outside");
const codexHome = path.join(root, "codex-home");
await fs.mkdir(outsideRoot, { recursive: true });
await fs.writeFile(path.join(outsideRoot, "secret.txt"), "do not expose", "utf8");
const keep = await createSkill(skillRoot, "keep");
const remove = await createSkill(skillRoot, "remove");
await fs.symlink(path.join(outsideRoot, "secret.txt"), path.join(keep.source, "leak.txt"));
await fs.symlink(outsideRoot, path.join(keep.source, "leak-dir"));
const baseConfig = {
agent: "codex",
stateDir: path.join(root, "state"),
env: { CODEX_HOME: codexHome },
paperclipRuntimeSkills: [keep, remove],
};
await runExecutor({
...baseConfig,
paperclipSkillSync: { desiredSkills: [keep.key, remove.key] },
});
expect(await pathExists(path.join(codexHome, "skills", remove.runtimeName, "SKILL.md"))).toBe(true);
await runExecutor({
...baseConfig,
paperclipSkillSync: { desiredSkills: [keep.key] },
});
expect(await pathExists(path.join(codexHome, "skills", keep.runtimeName, "SKILL.md"))).toBe(true);
expect(await pathExists(path.join(codexHome, "skills", keep.runtimeName, "leak.txt"))).toBe(false);
expect(await pathExists(path.join(codexHome, "skills", keep.runtimeName, "leak-dir"))).toBe(false);
expect(await pathExists(path.join(codexHome, "skills", remove.runtimeName))).toBe(false);
});
it.skipIf(process.platform === "win32")("removes legacy ACPX Codex skill symlinks when a skill is no longer desired", async () => {
const root = await makeTempRoot();
const skillRoot = path.join(root, "skills");
const codexHome = path.join(root, "codex-home");
const legacy = await createSkill(skillRoot, "legacy");
const skillsHome = path.join(codexHome, "skills");
await fs.mkdir(skillsHome, { recursive: true });
await fs.symlink(legacy.source, path.join(skillsHome, legacy.runtimeName));
await runExecutor({
agent: "codex",
stateDir: path.join(root, "state"),
env: { CODEX_HOME: codexHome },
paperclipRuntimeSkills: [legacy],
paperclipSkillSync: { desiredSkills: [] },
});
expect(await pathExists(path.join(skillsHome, legacy.runtimeName))).toBe(false);
});
it.skipIf(process.platform === "win32")("replaces stale managed Codex auth files with source symlinks", async () => {
const root = await makeTempRoot();
const sourceCodexHome = path.join(root, "source-codex-home");
const paperclipHome = path.join(root, "paperclip-home");
const managedCodexHome = path.join(
paperclipHome,
"instances",
"default",
"companies",
"company-1",
"codex-home",
);
await fs.mkdir(sourceCodexHome, { recursive: true });
await fs.mkdir(managedCodexHome, { recursive: true });
const sourceAuth = path.join(sourceCodexHome, "auth.json");
const managedAuth = path.join(managedCodexHome, "auth.json");
await fs.writeFile(sourceAuth, "{\"source\":true}", "utf8");
await fs.writeFile(managedAuth, "{\"stale\":true}", "utf8");
const previousCodexHome = process.env.CODEX_HOME;
const previousPaperclipHome = process.env.PAPERCLIP_HOME;
try {
process.env.CODEX_HOME = sourceCodexHome;
process.env.PAPERCLIP_HOME = paperclipHome;
await runExecutor({
agent: "codex",
stateDir: path.join(root, "state"),
paperclipRuntimeSkills: [],
paperclipSkillSync: { desiredSkills: [] },
});
} finally {
if (previousCodexHome === undefined) delete process.env.CODEX_HOME;
else process.env.CODEX_HOME = previousCodexHome;
if (previousPaperclipHome === undefined) delete process.env.PAPERCLIP_HOME;
else process.env.PAPERCLIP_HOME = previousPaperclipHome;
}
const authStat = await fs.lstat(managedAuth);
expect(authStat.isSymbolicLink()).toBe(true);
expect(path.resolve(path.dirname(managedAuth), await fs.readlink(managedAuth))).toBe(sourceAuth);
});
it("keeps fresh credential wrapper scripts across ACPX agent changes", async () => {
const root = await makeTempRoot();
const stateDir = path.join(root, "state");
const baseConfig = {
agentCommand: "node ./fake-acp.js",
stateDir,
};
await runExecutor({
...baseConfig,
agent: "custom-a",
env: { PAPERCLIP_API_KEY: "old-key" },
});
await runExecutor({
...baseConfig,
agent: "custom-b",
env: { PAPERCLIP_API_KEY: "new-key" },
});
const wrappers = await fs.readdir(path.join(stateDir, "wrappers"));
expect(wrappers.filter((name) => name.endsWith(".sh"))).toHaveLength(2);
expect(wrappers.filter((name) => name.endsWith(".env"))).toHaveLength(2);
expect(wrappers.some((name) => name.startsWith("custom-a-"))).toBe(true);
expect(wrappers.some((name) => name.startsWith("custom-b-"))).toBe(true);
const wrapperPath = path.join(stateDir, "wrappers", wrappers.find((name) => name.startsWith("custom-b-") && name.endsWith(".sh"))!);
const envPath = path.join(stateDir, "wrappers", wrappers.find((name) => name.startsWith("custom-b-") && name.endsWith(".env"))!);
const wrapper = await fs.readFile(wrapperPath, "utf8");
const env = await fs.readFile(envPath, "utf8");
expect((await fs.stat(envPath)).mode & 0o777).toBe(0o600);
expect((await fs.stat(wrapperPath)).mode & 0o777).toBe(0o700);
expect(wrapper).toContain("node ./fake-acp.js");
expect(wrapper).not.toContain("PAPERCLIP_API_KEY");
expect(wrapper).not.toContain("new-key");
expect(wrapper).not.toContain("old-key");
expect(env).toContain("PAPERCLIP_API_KEY='new-key'");
expect(env).not.toContain("old-key");
});
it("cleans aged credential wrapper scripts across ACPX agent changes", async () => {
const root = await makeTempRoot();
const stateDir = path.join(root, "state");
const wrappersDir = path.join(stateDir, "wrappers");
const baseConfig = {
agentCommand: "node ./fake-acp.js",
stateDir,
};
await runExecutor({
...baseConfig,
agent: "custom-a",
env: { PAPERCLIP_API_KEY: "old-key" },
});
const oldDate = new Date(Date.now() - 16 * 60 * 1000);
await Promise.all(
(await fs.readdir(wrappersDir))
.filter((name) => name.startsWith("custom-a-"))
.map((name) => fs.utimes(path.join(wrappersDir, name), oldDate, oldDate)),
);
await runExecutor({
...baseConfig,
agent: "custom-b",
env: { PAPERCLIP_API_KEY: "new-key" },
});
const wrappers = await fs.readdir(wrappersDir);
expect(wrappers.filter((name) => name.endsWith(".sh"))).toHaveLength(1);
expect(wrappers.filter((name) => name.endsWith(".env"))).toHaveLength(1);
expect(wrappers.some((name) => name.startsWith("custom-a-"))).toBe(false);
expect(wrappers.some((name) => name.startsWith("custom-b-"))).toBe(true);
});
it("keeps distinct wrapper env files for concurrent runs with different credentials", async () => {
const root = await makeTempRoot();
const stateDir = path.join(root, "state");
const baseConfig = {
agent: "custom-a",
agentCommand: "node ./fake-acp.js",
stateDir,
};
await runExecutor({
...baseConfig,
env: { PAPERCLIP_API_KEY: "first-key" },
});
await runExecutor({
...baseConfig,
env: { PAPERCLIP_API_KEY: "second-key" },
});
const envFileNames = (await fs.readdir(path.join(stateDir, "wrappers"))).filter((name) => name.endsWith(".env"));
expect(envFileNames).toHaveLength(2);
const envFiles = await Promise.all(
envFileNames.map(async (name) => fs.readFile(path.join(stateDir, "wrappers", name), "utf8")),
);
expect(envFiles.filter((contents) => contents.includes("PAPERCLIP_API_KEY='first-key'"))).toHaveLength(1);
expect(envFiles.filter((contents) => contents.includes("PAPERCLIP_API_KEY='second-key'"))).toHaveLength(1);
});
it("passes Paperclip env through the ACP agent wrapper instead of process.env", async () => {
let observedApiKeyDuringStream: string | undefined;
const execute = createAcpxLocalExecutor({
createRuntime: () => ({
ensureSession: async () => ({
backendSessionId: "backend-session",
agentSessionId: "agent-session",
runtimeSessionName: "runtime-session",
}),
startTurn: () => ({
events: (async function* () {
await Promise.resolve();
observedApiKeyDuringStream = process.env.PAPERCLIP_API_KEY;
yield { type: "done", stopReason: "end_turn" };
})(),
result: Promise.resolve({ status: "completed", stopReason: "end_turn" }),
cancel: async () => {},
}),
close: async () => {},
}) as never,
});
const previousApiKey = process.env.PAPERCLIP_API_KEY;
try {
delete process.env.PAPERCLIP_API_KEY;
const result = await execute({
runId: "run-1",
agent: {
id: "agent-1",
companyId: "company-1",
},
runtime: {},
config: { agent: "custom", agentCommand: "node ./fake-acp.js" },
context: {},
authToken: "runtime-key",
onLog: async () => {},
onMeta: async () => {},
} as never);
expect(result.exitCode).toBe(0);
expect(observedApiKeyDuringStream).toBeUndefined();
} finally {
if (previousApiKey === undefined) delete process.env.PAPERCLIP_API_KEY;
else process.env.PAPERCLIP_API_KEY = previousApiKey;
}
});
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,5 @@
export { execute, createAcpxLocalExecutor } from "./execute.js";
export { testEnvironment } from "./test.js";
export { getConfigSchema } from "./config-schema.js";
export { sessionCodec } from "./session-codec.js";
export { listAcpxSkills, syncAcpxSkills } from "./skills.js";

View file

@ -0,0 +1,50 @@
import type { AdapterSessionCodec } from "@paperclipai/adapter-utils";
function readString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function readRecord(value: unknown): Record<string, unknown> | null {
return typeof value === "object" && value !== null && !Array.isArray(value) ? { ...(value as Record<string, unknown>) } : null;
}
export const sessionCodec: AdapterSessionCodec = {
deserialize(raw: unknown) {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
const record = raw as Record<string, unknown>;
const runtimeSessionName = readString(record.runtimeSessionName);
const acpSessionId = readString(record.acpSessionId);
const agentSessionId = readString(record.agentSessionId);
const remoteExecution = readRecord(record.remoteExecution);
if (!runtimeSessionName && !acpSessionId && !agentSessionId) return null;
return {
...(runtimeSessionName ? { runtimeSessionName } : {}),
...(readString(record.sessionKey) ? { sessionKey: readString(record.sessionKey) } : {}),
...(readString(record.acpxRecordId) ? { acpxRecordId: readString(record.acpxRecordId) } : {}),
...(acpSessionId ? { acpSessionId } : {}),
...(agentSessionId ? { agentSessionId } : {}),
...(readString(record.agent) ? { agent: readString(record.agent) } : {}),
...(readString(record.cwd) ? { cwd: readString(record.cwd) } : {}),
...(readString(record.mode) ? { mode: readString(record.mode) } : {}),
...(readString(record.stateDir) ? { stateDir: readString(record.stateDir) } : {}),
...(readString(record.configFingerprint) ? { configFingerprint: readString(record.configFingerprint) } : {}),
...(readString(record.workspaceId) ? { workspaceId: readString(record.workspaceId) } : {}),
...(readString(record.repoUrl) ? { repoUrl: readString(record.repoUrl) } : {}),
...(readString(record.repoRef) ? { repoRef: readString(record.repoRef) } : {}),
...(remoteExecution ? { remoteExecution } : {}),
};
},
serialize(params: Record<string, unknown> | null) {
if (!params) return null;
return this.deserialize(params);
},
getDisplayId(params: Record<string, unknown> | null) {
if (!params) return null;
return (
readString(params.runtimeSessionName) ??
readString(params.acpSessionId) ??
readString(params.agentSessionId)
);
},
};

View file

@ -0,0 +1,106 @@
import path from "node:path";
import { fileURLToPath } from "node:url";
import type {
AdapterSkillContext,
AdapterSkillEntry,
AdapterSkillSnapshot,
} from "@paperclipai/adapter-utils";
import {
readPaperclipRuntimeSkillEntries,
resolvePaperclipDesiredSkillNames,
} from "@paperclipai/adapter-utils/server-utils";
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
type AcpxSkillAgent = "claude" | "codex" | "custom";
function normalizeAcpxSkillAgent(config: Record<string, unknown>): AcpxSkillAgent {
const configured = typeof config.agent === "string" ? config.agent.trim() : "";
if (configured === "codex" || configured === "custom") return configured;
if (configured === "claude" || configured === "") return "claude";
return "claude";
}
function configuredDetail(agent: AcpxSkillAgent): string {
if (agent === "codex") {
return "Will be linked into the effective CODEX_HOME/skills/ directory for the next ACPX Codex session.";
}
return "Will be mounted into the next ACPX Claude session.";
}
function unsupportedDetail(): string {
return "Desired state is stored in Paperclip only; custom ACP commands need an explicit skill integration contract before runtime sync is available.";
}
async function buildAcpxSkillSnapshot(config: Record<string, unknown>): Promise<AdapterSkillSnapshot> {
const acpxAgent = normalizeAcpxSkillAgent(config);
const availableEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
const availableByKey = new Map(availableEntries.map((entry) => [entry.key, entry]));
const desiredSkills = resolvePaperclipDesiredSkillNames(config, availableEntries);
const desiredSet = new Set(desiredSkills);
const supported = acpxAgent !== "custom";
const warnings: string[] = supported
? []
: [
"Custom ACP commands do not expose a Paperclip skill integration contract yet; selected skills are tracked only.",
];
const entries: AdapterSkillEntry[] = availableEntries.map((entry) => {
const desired = desiredSet.has(entry.key);
return {
key: entry.key,
runtimeName: entry.runtimeName,
desired,
managed: true,
state: desired ? "configured" : "available",
origin: entry.required ? "paperclip_required" : "company_managed",
originLabel: entry.required ? "Required by Paperclip" : "Managed by Paperclip",
readOnly: false,
sourcePath: entry.source,
targetPath: null,
detail: desired ? (supported ? configuredDetail(acpxAgent) : unsupportedDetail()) : null,
required: Boolean(entry.required),
requiredReason: entry.requiredReason ?? null,
};
});
for (const desiredSkill of desiredSkills) {
if (availableByKey.has(desiredSkill)) continue;
warnings.push(`Desired skill "${desiredSkill}" is not available from the Paperclip skills directory.`);
entries.push({
key: desiredSkill,
runtimeName: null,
desired: true,
managed: true,
state: "missing",
origin: "external_unknown",
originLabel: "External or unavailable",
readOnly: false,
sourcePath: null,
targetPath: null,
detail: "Paperclip cannot find this skill in the local runtime skills directory.",
});
}
entries.sort((left, right) => left.key.localeCompare(right.key));
return {
adapterType: "acpx_local",
supported,
mode: supported ? "ephemeral" : "unsupported",
desiredSkills,
entries,
warnings,
};
}
export async function listAcpxSkills(ctx: AdapterSkillContext): Promise<AdapterSkillSnapshot> {
return buildAcpxSkillSnapshot(ctx.config);
}
export async function syncAcpxSkills(
ctx: AdapterSkillContext,
_desiredSkills: string[],
): Promise<AdapterSkillSnapshot> {
return buildAcpxSkillSnapshot(ctx.config);
}

View file

@ -0,0 +1,49 @@
import { afterEach, describe, expect, it } from "vitest";
import { testEnvironment } from "./test.js";
const originalNodeVersion = process.version;
function setNodeVersion(version: string): void {
Object.defineProperty(process, "version", {
configurable: true,
enumerable: true,
value: version,
});
}
afterEach(() => {
setNodeVersion(originalNodeVersion);
});
describe("acpx_local environment diagnostics", () => {
it("does not force healthy default Claude diagnostics to warn", async () => {
setNodeVersion("v22.12.0");
const result = await testEnvironment({
adapterType: "acpx_local",
companyId: "test-company",
config: { agent: "claude" },
});
expect(result.status).toBe("pass");
expect(result.checks).toContainEqual(
expect.objectContaining({
code: "acpx_agent_selected",
level: "info",
message: "ACP agent selected: claude",
}),
);
expect(result.checks).toContainEqual(
expect.objectContaining({
code: "acpx_runtime_scaffold",
level: "info",
}),
);
expect(result.checks).not.toContainEqual(
expect.objectContaining({
code: "acpx_runtime_scaffold",
level: "warn",
}),
);
});
});

View file

@ -0,0 +1,295 @@
import { createRequire } from "node:module";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type {
AdapterEnvironmentCheck,
AdapterEnvironmentTestContext,
AdapterEnvironmentTestResult,
} from "@paperclipai/adapter-utils";
import {
asString,
parseObject,
} from "@paperclipai/adapter-utils/server-utils";
const require = createRequire(import.meta.url);
const MIN_NODE_MAJOR = 22;
const MIN_NODE_MINOR = 12;
const MIN_NODE_PATCH = 0;
function summarizeStatus(checks: AdapterEnvironmentCheck[]): AdapterEnvironmentTestResult["status"] {
if (checks.some((check) => check.level === "error")) return "fail";
if (checks.some((check) => check.level === "warn")) return "warn";
return "pass";
}
function nodeVersionMeetsMinimum(version: string): boolean {
const [major = 0, minor = 0, patch = 0] = version
.replace(/^v/, "")
.split(".")
.map((part) => Number.parseInt(part, 10));
if (major > MIN_NODE_MAJOR) return true;
if (major < MIN_NODE_MAJOR) return false;
if (minor > MIN_NODE_MINOR) return true;
if (minor < MIN_NODE_MINOR) return false;
return patch >= MIN_NODE_PATCH;
}
function isNonEmpty(value: unknown): value is string {
return typeof value === "string" && value.trim().length > 0;
}
function getStringEnv(configEnv: Record<string, string>, key: string): string | undefined {
const configured = configEnv[key];
if (typeof configured === "string") return configured;
return process.env[key];
}
function credentialSource(configEnv: Record<string, string>, key: string): string {
return typeof configEnv[key] === "string" ? "adapter config env" : "server environment";
}
async function readJsonObject(filePath: string): Promise<Record<string, unknown> | null> {
try {
const parsed = JSON.parse(await fs.readFile(filePath, "utf8")) as unknown;
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
? parsed as Record<string, unknown>
: null;
} catch {
return null;
}
}
function readNestedString(record: Record<string, unknown>, pathSegments: string[]): string | null {
let current: unknown = record;
for (const segment of pathSegments) {
if (typeof current !== "object" || current === null || Array.isArray(current)) return null;
current = (current as Record<string, unknown>)[segment];
}
return isNonEmpty(current) ? current.trim() : null;
}
async function hasClaudeSubscriptionCredentials(configDir: string): Promise<boolean> {
for (const filename of [".credentials.json", "credentials.json"]) {
const credentials = await readJsonObject(path.join(configDir, filename));
if (!credentials) continue;
if (readNestedString(credentials, ["claudeAiOauth", "accessToken"])) return true;
}
return false;
}
async function hasCodexNativeCredentials(codexHome: string): Promise<boolean> {
const auth = await readJsonObject(path.join(codexHome, "auth.json"));
if (!auth) return false;
return Boolean(
readNestedString(auth, ["accessToken"]) ||
readNestedString(auth, ["tokens", "access_token"]) ||
readNestedString(auth, ["OPENAI_API_KEY"]),
);
}
async function buildCredentialHintChecks(
agent: string,
configEnv: Record<string, string>,
): Promise<AdapterEnvironmentCheck[]> {
if (agent === "claude") {
const bedrockFlag = getStringEnv(configEnv, "CLAUDE_CODE_USE_BEDROCK");
const bedrockBaseUrl = getStringEnv(configEnv, "ANTHROPIC_BEDROCK_BASE_URL");
const hasBedrock =
bedrockFlag === "1" ||
/^true$/i.test(bedrockFlag ?? "") ||
isNonEmpty(bedrockBaseUrl);
const bedrockSourceKey = isNonEmpty(bedrockFlag)
? "CLAUDE_CODE_USE_BEDROCK"
: "ANTHROPIC_BEDROCK_BASE_URL";
const anthropicApiKey = getStringEnv(configEnv, "ANTHROPIC_API_KEY");
const claudeConfigDir = isNonEmpty(getStringEnv(configEnv, "CLAUDE_CONFIG_DIR"))
? path.resolve(getStringEnv(configEnv, "CLAUDE_CONFIG_DIR") as string)
: path.join(os.homedir(), ".claude");
if (hasBedrock) {
return [{
code: "acpx_claude_bedrock_auth_detected",
level: "info",
message: "Claude credential hint: Bedrock auth indicators are configured.",
detail: `Detected in ${credentialSource(configEnv, bedrockSourceKey)}.`,
hint: "Ensure AWS credentials and AWS_REGION are available to the ACPX-launched Claude agent.",
}];
}
if (isNonEmpty(anthropicApiKey)) {
return [{
code: "acpx_claude_anthropic_api_key_detected",
level: "info",
message: "Claude credential hint: ANTHROPIC_API_KEY is set.",
detail: `Detected in ${credentialSource(configEnv, "ANTHROPIC_API_KEY")}.`,
}];
}
if (await hasClaudeSubscriptionCredentials(claudeConfigDir)) {
return [{
code: "acpx_claude_subscription_auth_detected",
level: "info",
message: "Claude credential hint: local Claude subscription credentials were found.",
detail: `Credentials found in ${claudeConfigDir}.`,
}];
}
return [{
code: "acpx_claude_credentials_missing",
level: "info",
message: "Claude credential hint: no Claude API, Bedrock, or local subscription credentials were detected.",
hint: "Set ANTHROPIC_API_KEY, configure Bedrock, or run `claude login` before starting an ACPX Claude agent.",
}];
}
if (agent === "codex") {
const openAiApiKey = getStringEnv(configEnv, "OPENAI_API_KEY");
const codexHome = isNonEmpty(getStringEnv(configEnv, "CODEX_HOME"))
? path.resolve(getStringEnv(configEnv, "CODEX_HOME") as string)
: path.join(os.homedir(), ".codex");
if (isNonEmpty(openAiApiKey)) {
return [{
code: "acpx_codex_openai_api_key_detected",
level: "info",
message: "Codex credential hint: OPENAI_API_KEY is set.",
detail: `Detected in ${credentialSource(configEnv, "OPENAI_API_KEY")}.`,
}];
}
if (await hasCodexNativeCredentials(codexHome)) {
return [{
code: "acpx_codex_native_auth_detected",
level: "info",
message: "Codex credential hint: local Codex auth configuration was found.",
detail: `Credentials found in ${path.join(codexHome, "auth.json")}.`,
}];
}
return [{
code: "acpx_codex_credentials_missing",
level: "info",
message: "Codex credential hint: no OpenAI API key or local Codex auth configuration was detected.",
hint: "Set OPENAI_API_KEY or run `codex login` before starting an ACPX Codex agent.",
}];
}
return [];
}
function resolvePackage(name: string): AdapterEnvironmentCheck {
try {
const resolved = require.resolve(`${name}/package.json`);
return {
code: `acpx_package_${name.replace(/[^a-z0-9]+/gi, "_").toLowerCase()}_present`,
level: "info",
message: `${name} is resolvable.`,
detail: resolved,
};
} catch {
return {
code: `acpx_package_${name.replace(/[^a-z0-9]+/gi, "_").toLowerCase()}_missing`,
level: "error",
message: `${name} is not resolvable from the acpx_local adapter package.`,
hint: "Run pnpm install so the ACPX adapter dependencies are installed.",
};
}
}
async function checkDirectory(pathValue: string, code: string, label: string): Promise<AdapterEnvironmentCheck | null> {
const dir = pathValue.trim();
if (!dir) return null;
try {
await fs.mkdir(dir, { recursive: true });
await fs.access(dir);
return {
code,
level: "info",
message: `${label} is writable: ${dir}`,
};
} catch (err) {
return {
code: `${code}_invalid`,
level: "error",
message: err instanceof Error ? err.message : `${label} is not writable.`,
detail: dir,
};
}
}
export async function testEnvironment(
ctx: AdapterEnvironmentTestContext,
): Promise<AdapterEnvironmentTestResult> {
const config = parseObject(ctx.config);
const envConfig = parseObject(config.env);
const configEnv: Record<string, string> = {};
for (const [key, value] of Object.entries(envConfig)) {
if (typeof value === "string") configEnv[key] = value;
}
const checks: AdapterEnvironmentCheck[] = [];
const nodeVersion = process.version;
checks.push({
code: nodeVersionMeetsMinimum(nodeVersion) ? "acpx_node_supported" : "acpx_node_unsupported",
level: nodeVersionMeetsMinimum(nodeVersion) ? "info" : "error",
message: nodeVersionMeetsMinimum(nodeVersion)
? `Node ${nodeVersion} satisfies ACPX's >=22.12.0 requirement.`
: `Node ${nodeVersion} does not satisfy ACPX's >=22.12.0 requirement.`,
hint: nodeVersionMeetsMinimum(nodeVersion)
? undefined
: "Run acpx_local agents with Node >=22.12.0 or use claude_local/codex_local on Node 20.",
});
checks.push(resolvePackage("acpx"));
checks.push(resolvePackage("@agentclientprotocol/claude-agent-acp"));
checks.push(resolvePackage("@zed-industries/codex-acp"));
const agent = asString(config.agent, "claude");
if (!["claude", "codex", "custom"].includes(agent)) {
checks.push({
code: "acpx_agent_invalid",
level: "error",
message: `Unsupported ACP agent: ${agent}`,
hint: "Use agent=claude, agent=codex, or agent=custom.",
});
} else {
checks.push({
code: "acpx_agent_selected",
level: "info",
message: `ACP agent selected: ${agent}`,
});
checks.push(...await buildCredentialHintChecks(agent, configEnv));
}
if (agent === "custom" && !asString(config.agentCommand, "")) {
checks.push({
code: "acpx_custom_command_missing",
level: "error",
message: "agentCommand is required when agent=custom.",
});
}
const stateDirCheck = await checkDirectory(asString(config.stateDir, ""), "acpx_state_dir_writable", "ACPX state directory");
if (stateDirCheck) checks.push(stateDirCheck);
const permissionMode = asString(config.permissionMode, "approve-all");
checks.push({
code: "acpx_permission_mode",
level: "info",
message: `Effective permission mode: ${permissionMode || "approve-all"}`,
});
checks.push({
code: "acpx_runtime_scaffold",
level: "info",
message: "acpx_local runtime execution is available through the bundled ACPX runtime.",
});
return {
adapterType: ctx.adapterType,
status: summarizeStatus(checks),
checks,
testedAt: new Date().toISOString(),
};
}

View file

@ -0,0 +1,139 @@
import type { CreateConfigValues } from "@paperclipai/adapter-utils";
import {
DEFAULT_ACPX_LOCAL_AGENT,
DEFAULT_ACPX_LOCAL_MODE,
DEFAULT_ACPX_LOCAL_NON_INTERACTIVE_PERMISSIONS,
DEFAULT_ACPX_LOCAL_PERMISSION_MODE,
DEFAULT_ACPX_LOCAL_TIMEOUT_SEC,
} from "../index.js";
function parseCommaArgs(value: string): string[] {
return value
.split(",")
.map((item) => item.trim())
.filter(Boolean);
}
function parseEnvVars(text: string): Record<string, string> {
const env: Record<string, string> = {};
for (const line of text.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eq = trimmed.indexOf("=");
if (eq <= 0) continue;
const key = trimmed.slice(0, eq).trim();
const value = trimmed.slice(eq + 1);
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
env[key] = value;
}
return env;
}
function parseEnvBindings(bindings: unknown): Record<string, unknown> {
if (typeof bindings !== "object" || bindings === null || Array.isArray(bindings)) return {};
const env: Record<string, unknown> = {};
for (const [key, raw] of Object.entries(bindings)) {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
if (typeof raw === "string") {
env[key] = { type: "plain", value: raw };
continue;
}
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) continue;
const rec = raw as Record<string, unknown>;
if (rec.type === "plain" && typeof rec.value === "string") {
env[key] = { type: "plain", value: rec.value };
continue;
}
if (rec.type === "secret_ref" && typeof rec.secretId === "string") {
env[key] = {
type: "secret_ref",
secretId: rec.secretId,
...(typeof rec.version === "number" || rec.version === "latest"
? { version: rec.version }
: {}),
};
}
}
return env;
}
function parseJsonObject(text: string): Record<string, unknown> | null {
const trimmed = text.trim();
if (!trimmed) return null;
try {
const parsed = JSON.parse(trimmed);
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
return parsed as Record<string, unknown>;
} catch {
return null;
}
}
function readNumber(value: unknown, fallback: number): number {
if (typeof value === "number" && Number.isFinite(value)) return value;
if (typeof value === "string" && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return parsed;
}
return fallback;
}
export function buildAcpxLocalConfig(v: CreateConfigValues): Record<string, unknown> {
const schemaValues = v.adapterSchemaValues ?? {};
const ac: Record<string, unknown> = {
agent: schemaValues.agent || DEFAULT_ACPX_LOCAL_AGENT,
mode: schemaValues.mode || DEFAULT_ACPX_LOCAL_MODE,
permissionMode: schemaValues.permissionMode || DEFAULT_ACPX_LOCAL_PERMISSION_MODE,
nonInteractivePermissions:
schemaValues.nonInteractivePermissions || DEFAULT_ACPX_LOCAL_NON_INTERACTIVE_PERMISSIONS,
timeoutSec: readNumber(schemaValues.timeoutSec, DEFAULT_ACPX_LOCAL_TIMEOUT_SEC),
};
for (const key of [
"agentCommand",
"cwd",
"stateDir",
"instructionsFilePath",
"promptTemplate",
"bootstrapPromptTemplate",
]) {
const value = schemaValues[key];
if (typeof value === "string" && value.trim()) ac[key] = value.trim();
}
if (!ac.cwd && v.cwd) ac.cwd = v.cwd;
if (!ac.instructionsFilePath && v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;
if (!ac.promptTemplate && v.promptTemplate) ac.promptTemplate = v.promptTemplate;
if (!ac.bootstrapPromptTemplate && v.bootstrapPrompt) ac.bootstrapPromptTemplate = v.bootstrapPrompt;
const env = parseEnvBindings(v.envBindings);
const legacy = parseEnvVars(v.envVars);
for (const [key, value] of Object.entries(legacy)) {
if (!Object.prototype.hasOwnProperty.call(env, key)) {
env[key] = { type: "plain", value };
}
}
if (typeof schemaValues.env === "string") {
const schemaEnv = parseJsonObject(schemaValues.env);
if (schemaEnv) Object.assign(env, schemaEnv);
} else if (typeof schemaValues.env === "object" && schemaValues.env !== null && !Array.isArray(schemaValues.env)) {
Object.assign(env, schemaValues.env as Record<string, unknown>);
}
if (Object.keys(env).length > 0) ac.env = env;
if (v.workspaceStrategyType === "git_worktree") {
ac.workspaceStrategy = {
type: "git_worktree",
...(v.workspaceBaseRef ? { baseRef: v.workspaceBaseRef } : {}),
...(v.workspaceBranchTemplate ? { branchTemplate: v.workspaceBranchTemplate } : {}),
...(v.worktreeParentDir ? { worktreeParentDir: v.worktreeParentDir } : {}),
};
}
const runtimeServices = parseJsonObject(v.runtimeServicesJson ?? "");
if (runtimeServices && Array.isArray(runtimeServices.services)) {
ac.workspaceRuntime = runtimeServices;
}
if (v.command) ac.command = v.command;
if (v.extraArgs) ac.extraArgs = parseCommaArgs(v.extraArgs);
return ac;
}

View file

@ -0,0 +1,2 @@
export { parseAcpxStdoutLine } from "./parse-stdout.js";
export { buildAcpxLocalConfig } from "./build-config.js";

View file

@ -0,0 +1,160 @@
import { describe, expect, it } from "vitest";
import { parseAcpxStdoutLine } from "./parse-stdout.js";
const TS = "2026-04-30T00:00:00.000Z";
function emit(payload: Record<string, unknown>): string {
return JSON.stringify(payload);
}
describe("parseAcpxStdoutLine", () => {
it("renders an init entry from acpx.session", () => {
const entries = parseAcpxStdoutLine(
emit({
type: "acpx.session",
agent: "claude",
acpSessionId: "acp-1",
runtimeSessionName: "runtime-1",
mode: "persistent",
permissionMode: "approve-all",
}),
TS,
);
expect(entries).toEqual([
{
kind: "init",
ts: TS,
model: "claude (persistent / approve-all)",
sessionId: "acp-1",
},
]);
});
it("routes output text_delta to the assistant transcript", () => {
const entries = parseAcpxStdoutLine(
emit({ type: "acpx.text_delta", text: "hello", channel: "output", tag: "agent_message_chunk" }),
TS,
);
expect(entries).toEqual([
{ kind: "assistant", ts: TS, text: "hello", delta: true },
]);
});
it("routes thought text_delta to the thinking transcript", () => {
const entries = parseAcpxStdoutLine(
emit({ type: "acpx.text_delta", text: "thinking…", channel: "thought" }),
TS,
);
expect(entries).toEqual([
{ kind: "thinking", ts: TS, text: "thinking…", delta: true },
]);
});
it("falls back to stream when channel is missing", () => {
const entries = parseAcpxStdoutLine(
emit({ type: "acpx.text_delta", text: "thinking…", stream: "thought" }),
TS,
);
expect(entries[0]).toMatchObject({ kind: "thinking" });
});
it("renders status events as system text with optional ctx usage", () => {
expect(
parseAcpxStdoutLine(
emit({ type: "acpx.status", text: "thinking", tag: "agent_thought_chunk" }),
TS,
),
).toEqual([{ kind: "system", ts: TS, text: "thinking" }]);
expect(
parseAcpxStdoutLine(
emit({ type: "acpx.status", tag: "context_window", used: 12000, size: 200000 }),
TS,
),
).toEqual([{ kind: "system", ts: TS, text: "context_window (12000/200000 ctx)" }]);
});
it("emits a tool_call entry that preserves toolCallId, status, and input", () => {
const entries = parseAcpxStdoutLine(
emit({
type: "acpx.tool_call",
name: "read",
toolCallId: "tool-1",
status: "running",
text: "read README.md",
}),
TS,
);
expect(entries).toEqual([
{
kind: "tool_call",
ts: TS,
name: "read",
toolUseId: "tool-1",
input: { text: "read README.md", status: "running" },
},
]);
});
it("emits a paired tool_result entry when a tool_call reports terminal status", () => {
const completed = parseAcpxStdoutLine(
emit({
type: "acpx.tool_call",
name: "read",
toolCallId: "tool-1",
status: "completed",
text: "ok",
}),
TS,
);
expect(completed[1]).toEqual({
kind: "tool_result",
ts: TS,
toolUseId: "tool-1",
toolName: "read",
content: "ok",
isError: false,
});
const failed = parseAcpxStdoutLine(
emit({
type: "acpx.tool_call",
name: "edit",
toolCallId: "tool-2",
status: "failed",
text: "permission denied",
}),
TS,
);
expect(failed[1]).toMatchObject({ kind: "tool_result", isError: true, content: "permission denied" });
});
it("renders acpx.result with summary fallback to stopReason", () => {
const entries = parseAcpxStdoutLine(
emit({ type: "acpx.result", summary: "completed", stopReason: "end_turn" }),
TS,
);
expect(entries[0]).toMatchObject({ kind: "result", text: "completed", subtype: "end_turn", isError: false });
});
it("treats acpx.error as a stderr entry", () => {
const entries = parseAcpxStdoutLine(
emit({ type: "acpx.error", message: "auth required", code: "ACP_AUTH" }),
TS,
);
expect(entries).toEqual([{ kind: "stderr", ts: TS, text: "auth required" }]);
});
it("renders unknown acpx.* events as system entries", () => {
const entries = parseAcpxStdoutLine(
emit({ type: "acpx.misc", message: "unhandled" }),
TS,
);
expect(entries).toEqual([{ kind: "system", ts: TS, text: "unhandled" }]);
});
it("falls back to a stdout entry for non-JSON lines", () => {
const entries = parseAcpxStdoutLine("not json", TS);
expect(entries).toEqual([{ kind: "stdout", ts: TS, text: "not json" }]);
});
});

View file

@ -0,0 +1,158 @@
import type { TranscriptEntry } from "@paperclipai/adapter-utils";
function parseJson(line: string): Record<string, unknown> | null {
try {
const parsed = JSON.parse(line);
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
return parsed as Record<string, unknown>;
} catch {
return null;
}
}
function asString(value: unknown, fallback = ""): string {
return typeof value === "string" ? value : fallback;
}
function asNumber(value: unknown, fallback = 0): number {
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
}
function stringify(value: unknown): string {
if (typeof value === "string") return value;
if (value === null || value === undefined) return "";
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
function pickToolUseId(parsed: Record<string, unknown>): string {
return (
asString(parsed.toolCallId) ||
asString(parsed.toolUseId) ||
asString(parsed.id)
);
}
function statusText(parsed: Record<string, unknown>): string {
const text = asString(parsed.text).trim();
const tag = asString(parsed.tag).trim();
const used = asNumber(parsed.used, -1);
const size = asNumber(parsed.size, -1);
const parts: string[] = [];
if (text) parts.push(text);
if (tag && !text) parts.push(tag);
if (used >= 0 && size > 0) parts.push(`(${used}/${size} ctx)`);
return parts.join(" ") || tag || "status";
}
export function parseAcpxStdoutLine(line: string, ts: string): TranscriptEntry[] {
const parsed = parseJson(line);
if (!parsed) return [{ kind: "stdout", ts, text: line }];
const type = asString(parsed.type);
if (type === "acpx.session") {
const agent = asString(parsed.agent, "acpx");
const mode = asString(parsed.mode);
const permissionMode = asString(parsed.permissionMode);
const tail = [mode, permissionMode].filter(Boolean).join(" / ");
return [{
kind: "init",
ts,
model: tail ? `${agent} (${tail})` : agent,
sessionId:
asString(parsed.acpSessionId) ||
asString(parsed.sessionId) ||
asString(parsed.runtimeSessionName),
}];
}
if (type === "acpx.text_delta") {
const text = asString(parsed.text);
if (!text) return [];
const channel = asString(parsed.channel) || asString(parsed.stream);
return [{
kind: channel === "thought" || channel === "thinking" ? "thinking" : "assistant",
ts,
text,
delta: true,
}];
}
if (type === "acpx.tool_call") {
const status = asString(parsed.status);
const text = asString(parsed.text);
const name = asString(parsed.name, "acp_tool");
const toolUseId = pickToolUseId(parsed);
const input =
parsed.input !== undefined
? parsed.input
: text || status
? { ...(text ? { text } : {}), ...(status ? { status } : {}) }
: {};
const entries: TranscriptEntry[] = [
{
kind: "tool_call",
ts,
name,
toolUseId: toolUseId || undefined,
input,
},
];
if (status === "completed" || status === "failed" || status === "cancelled") {
entries.push({
kind: "tool_result",
ts,
toolUseId: toolUseId || name,
toolName: name,
content: text || status,
isError: status !== "completed",
});
}
return entries;
}
if (type === "acpx.tool_result") {
return [{
kind: "tool_result",
ts,
toolUseId: pickToolUseId(parsed) || asString(parsed.name, "acp_tool"),
toolName: asString(parsed.name) || undefined,
content: stringify(parsed.content ?? parsed.output ?? parsed.error),
isError: parsed.isError === true || parsed.error !== undefined,
}];
}
if (type === "acpx.status") {
return [{ kind: "system", ts, text: statusText(parsed) }];
}
if (type === "acpx.result") {
return [{
kind: "result",
ts,
text: asString(parsed.summary, asString(parsed.stopReason, asString(parsed.text))),
inputTokens: asNumber(parsed.inputTokens),
outputTokens: asNumber(parsed.outputTokens),
cachedTokens: asNumber(parsed.cachedTokens),
costUsd: asNumber(parsed.costUsd),
subtype: asString(parsed.subtype, asString(parsed.stopReason, "acpx.result")),
isError: parsed.isError === true,
errors: Array.isArray(parsed.errors)
? parsed.errors.map((error) => stringify(error)).filter(Boolean)
: [],
}];
}
if (type === "acpx.error") {
return [{ kind: "stderr", ts, text: asString(parsed.message, line) }];
}
if (type.startsWith("acpx.")) {
return [{ kind: "system", ts, text: asString(parsed.message, type) }];
}
return [{ kind: "stdout", ts, text: line }];
}

View file

@ -0,0 +1,8 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"]
}

View file

@ -0,0 +1,7 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "node",
},
});