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,129 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { testEnvironment } from "@paperclipai/adapter-acpx-local/server";
import type { AdapterEnvironmentCheck } from "@paperclipai/adapter-utils";
function credentialChecks(checks: AdapterEnvironmentCheck[]): AdapterEnvironmentCheck[] {
return checks.filter((check) => check.code.startsWith("acpx_claude_") || check.code.startsWith("acpx_codex_"));
}
describe("acpx_local environment credential diagnostics", () => {
beforeEach(() => {
vi.stubEnv("ANTHROPIC_API_KEY", "");
vi.stubEnv("ANTHROPIC_BEDROCK_BASE_URL", "");
vi.stubEnv("CLAUDE_CODE_USE_BEDROCK", "");
vi.stubEnv("CLAUDE_CONFIG_DIR", "");
vi.stubEnv("OPENAI_API_KEY", "");
vi.stubEnv("CODEX_HOME", "");
});
afterEach(() => {
vi.unstubAllEnvs();
});
it("emits an info-level Claude credential hint when ANTHROPIC_API_KEY is present", async () => {
const result = await testEnvironment({
companyId: "company-1",
adapterType: "acpx_local",
config: {
agent: "claude",
env: {
ANTHROPIC_API_KEY: "sk-ant-test",
},
},
});
expect(result.checks).toContainEqual(expect.objectContaining({
code: "acpx_claude_anthropic_api_key_detected",
level: "info",
}));
expect(result.checks.some((check) => check.code.startsWith("acpx_codex_"))).toBe(false);
});
it("emits an info-level Claude missing credential hint without changing diagnostic health", async () => {
const root = path.join(os.tmpdir(), `paperclip-acpx-claude-noauth-${Date.now()}-${Math.random().toString(16).slice(2)}`);
const claudeConfigDir = path.join(root, ".claude");
try {
await fs.mkdir(claudeConfigDir, { recursive: true });
const result = await testEnvironment({
companyId: "company-1",
adapterType: "acpx_local",
config: {
agent: "claude",
env: {
CLAUDE_CONFIG_DIR: claudeConfigDir,
},
},
});
expect(result.checks).toContainEqual(expect.objectContaining({
code: "acpx_claude_credentials_missing",
level: "info",
}));
expect(credentialChecks(result.checks).every((check) => check.level === "info")).toBe(true);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("emits an info-level Codex credential hint when native auth is present", async () => {
const root = path.join(os.tmpdir(), `paperclip-acpx-codex-auth-${Date.now()}-${Math.random().toString(16).slice(2)}`);
const codexHome = path.join(root, ".codex");
try {
await fs.mkdir(codexHome, { recursive: true });
await fs.writeFile(path.join(codexHome, "auth.json"), JSON.stringify({ accessToken: "token" }), "utf8");
const result = await testEnvironment({
companyId: "company-1",
adapterType: "acpx_local",
config: {
agent: "codex",
env: {
CODEX_HOME: codexHome,
},
},
});
expect(result.checks).toContainEqual(expect.objectContaining({
code: "acpx_codex_native_auth_detected",
level: "info",
}));
expect(result.checks.some((check) => check.code.startsWith("acpx_claude_"))).toBe(false);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("emits an info-level Codex missing credential hint without changing diagnostic health", async () => {
const root = path.join(os.tmpdir(), `paperclip-acpx-codex-noauth-${Date.now()}-${Math.random().toString(16).slice(2)}`);
const codexHome = path.join(root, ".codex");
try {
await fs.mkdir(codexHome, { recursive: true });
const result = await testEnvironment({
companyId: "company-1",
adapterType: "acpx_local",
config: {
agent: "codex",
env: {
CODEX_HOME: codexHome,
},
},
});
expect(result.checks).toContainEqual(expect.objectContaining({
code: "acpx_codex_credentials_missing",
level: "info",
}));
expect(credentialChecks(result.checks).every((check) => check.level === "info")).toBe(true);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
});

View file

@ -0,0 +1,603 @@
import { describe, expect, it } from "vitest";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { AdapterExecutionContext } from "@paperclipai/adapter-utils";
import { createAcpxLocalExecutor } from "@paperclipai/adapter-acpx-local/server";
import type {
AcpRuntime,
AcpRuntimeEvent,
AcpRuntimeHandle,
AcpRuntimeOptions,
AcpRuntimeTurn,
AcpRuntimeTurnResult,
} from "acpx/runtime";
type LogEntry = { stream: "stdout" | "stderr"; chunk: string };
type TestAcpRuntimeOptions = AcpRuntimeOptions & {
sessionOptions?: {
systemPrompt?: string | { append: string };
additionalRoots?: string[];
};
};
class FakeRuntime implements AcpRuntime {
ensureInputs: Array<{ sessionKey: string; agent: string; mode: "persistent" | "oneshot"; cwd?: string; resumeSessionId?: string }> = [];
startInputs: Array<{ handle: AcpRuntimeHandle; text: string; requestId: string; timeoutMs?: number }> = [];
closeInputs: Array<{ handle: AcpRuntimeHandle; reason: string; discardPersistentState?: boolean }> = [];
cancelInputs: Array<{ handle: AcpRuntimeHandle; reason?: string }> = [];
setModeInputs: Array<{ handle: AcpRuntimeHandle; mode: string }> = [];
setConfigInputs: Array<{ handle: AcpRuntimeHandle; key: string; value: string }> = [];
ensureCount = 0;
turnCount = 0;
nextEnsureError: Error | null = null;
constructor(
readonly options: TestAcpRuntimeOptions,
readonly events: AcpRuntimeEvent[] = [
{ type: "status", text: "thinking", tag: "agent_thought_chunk" },
{ type: "text_delta", text: "hello ", stream: "output", tag: "agent_message_chunk" },
{ type: "tool_call", text: "read README.md", title: "read", status: "running", toolCallId: "tool-1" },
{ type: "text_delta", text: "world", stream: "output", tag: "agent_message_chunk" },
],
readonly terminal: AcpRuntimeTurnResult = { status: "completed", stopReason: "end_turn" },
) {}
async ensureSession(input: { sessionKey: string; agent: string; mode: "persistent" | "oneshot"; cwd?: string; resumeSessionId?: string }): Promise<AcpRuntimeHandle> {
this.ensureInputs.push(input);
this.ensureCount += 1;
if (this.nextEnsureError) {
const err = this.nextEnsureError;
this.nextEnsureError = null;
throw err;
}
return {
sessionKey: input.sessionKey,
backend: "acpx",
runtimeSessionName: `runtime-${this.ensureCount}`,
cwd: input.cwd,
acpxRecordId: `record-${this.ensureCount}`,
backendSessionId: `acp-${this.ensureCount}`,
agentSessionId: `agent-${this.ensureCount}`,
};
}
startTurn(input: { handle: AcpRuntimeHandle; text: string; requestId: string; timeoutMs?: number }): AcpRuntimeTurn {
this.startInputs.push(input);
this.turnCount += 1;
let closed = false;
const events = this.events;
const terminal = this.terminal;
const cancelInputs = this.cancelInputs;
return {
requestId: input.requestId,
events: {
[Symbol.asyncIterator]: async function* () {
for (const event of events) {
if (closed) return;
yield event;
}
},
},
result: Promise.resolve(terminal),
cancel: async (args?: { reason?: string }) => {
cancelInputs.push({ handle: input.handle, reason: args?.reason });
closed = true;
},
closeStream: async () => {
closed = true;
},
};
}
runTurn(): AsyncIterable<AcpRuntimeEvent> {
throw new Error("not used");
}
getCapabilities() {
return { controls: [] };
}
getStatus() {
return Promise.resolve({});
}
async setMode(input: { handle: AcpRuntimeHandle; mode: string }) {
this.setModeInputs.push(input);
}
async setConfigOption(input: { handle: AcpRuntimeHandle; key: string; value: string }) {
this.setConfigInputs.push(input);
}
async cancel(input: { handle: AcpRuntimeHandle; reason?: string }) {
this.cancelInputs.push(input);
}
async close(input: { handle: AcpRuntimeHandle; reason: string; discardPersistentState?: boolean }) {
this.closeInputs.push(input);
}
}
async function createRuntimeSkill(root: string, input: {
key?: string;
runtimeName?: string;
body?: string;
}) {
const runtimeName = input.runtimeName ?? "paperclip-test-skill";
const key = input.key ?? `company/${runtimeName}`;
const source = path.join(root, "skills", runtimeName);
await fs.mkdir(source, { recursive: true });
await fs.writeFile(path.join(source, "SKILL.md"), input.body ?? "---\nrequired: false\n---\nUse the test skill.\n", "utf8");
return {
key,
runtimeName,
source,
required: false,
};
}
function parseStdoutLogs(logs: LogEntry[]) {
return logs
.filter((entry) => entry.stream === "stdout")
.flatMap((entry) => entry.chunk.trim().split(/\n+/).filter(Boolean))
.map((line) => JSON.parse(line) as Record<string, unknown>);
}
function buildContext(root: string, overrides: Partial<AdapterExecutionContext> = {}): AdapterExecutionContext {
return {
runId: "run-1",
agent: {
id: "agent-1",
companyId: "company-1",
name: "ACPX Coder",
adapterType: "acpx_local",
adapterConfig: {},
},
runtime: {
sessionId: null,
sessionParams: null,
sessionDisplayId: null,
taskKey: "PAP-1",
},
config: {
agent: "claude",
cwd: root,
stateDir: path.join(root, "state"),
promptTemplate: "Do the assigned work.",
},
context: {
issueId: "issue-1",
paperclipTaskMarkdown: "Task context",
},
onLog: async () => {},
...overrides,
};
}
describe("acpx_local execute", () => {
it("streams ACPX session, status, text, and tool events before returning success", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-success-"));
try {
const runtime = new FakeRuntime({} as AcpRuntimeOptions);
const logs: LogEntry[] = [];
let metaPermissionNote = "";
const execute = createAcpxLocalExecutor({
createRuntime: () => runtime,
});
const result = await execute(buildContext(root, {
onLog: async (stream, chunk) => logs.push({ stream, chunk }),
onMeta: async (meta) => {
metaPermissionNote = meta.commandNotes?.join("\n") ?? "";
},
}));
expect(result.exitCode).toBe(0);
expect(result.summary).toBe("hello world");
expect(result.sessionParams).toMatchObject({
agent: "claude",
cwd: root,
mode: "persistent",
acpSessionId: "acp-1",
});
expect(metaPermissionNote).toContain("Effective ACPX permission mode: approve-all");
const parsed = parseStdoutLogs(logs);
expect(parsed.map((event) => event.type)).toEqual([
"acpx.session",
"acpx.status",
"acpx.text_delta",
"acpx.tool_call",
"acpx.text_delta",
"acpx.result",
]);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("reuses a compatible warm session and starts fresh when cwd changes", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-reuse-"));
const other = path.join(root, "other");
await fs.mkdir(other);
try {
const runtimes: FakeRuntime[] = [];
const execute = createAcpxLocalExecutor({
createRuntime: (options) => {
const runtime = new FakeRuntime(options);
runtimes.push(runtime);
return runtime;
},
});
const first = await execute(buildContext(root));
const second = await execute(buildContext(root, {
runtime: {
sessionId: first.sessionId ?? null,
sessionParams: first.sessionParams ?? null,
sessionDisplayId: first.sessionDisplayId ?? null,
taskKey: "PAP-1",
},
}));
const third = await execute(buildContext(root, {
runtime: {
sessionId: first.sessionId ?? null,
sessionParams: first.sessionParams ?? null,
sessionDisplayId: first.sessionDisplayId ?? null,
taskKey: "PAP-1",
},
config: {
agent: "claude",
cwd: other,
stateDir: path.join(root, "state"),
promptTemplate: "Do the assigned work.",
},
}));
expect(runtimes).toHaveLength(2);
expect(runtimes[0].ensureCount).toBe(1);
expect(runtimes[0].turnCount).toBe(2);
expect(runtimes[1].ensureCount).toBe(1);
expect(second.sessionParams?.acpSessionId).toBe("acp-1");
expect(third.sessionParams?.cwd).toBe(other);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("closes duplicate warm handles from concurrent runs for the same session key", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-concurrent-"));
try {
const runtimes: FakeRuntime[] = [];
const warmHandles = new Map();
const execute = createAcpxLocalExecutor({
warmHandles,
createRuntime: (options) => {
const runtime = new FakeRuntime(options);
runtimes.push(runtime);
return runtime;
},
});
const [first, second] = await Promise.all([
execute(buildContext(root, { runId: "run-1" })),
execute(buildContext(root, { runId: "run-2" })),
]);
expect(first.exitCode).toBe(0);
expect(second.exitCode).toBe(0);
expect(runtimes).toHaveLength(2);
expect(warmHandles.size).toBe(1);
expect(runtimes.flatMap((runtime) => runtime.closeInputs).filter((input) =>
input.reason === "paperclip duplicate warm handle cleanup"
)).toHaveLength(1);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("retries with a fresh session when ACPX cannot resume the saved backend session", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-resume-"));
try {
const runtime = new FakeRuntime({} as AcpRuntimeOptions);
const firstExecute = createAcpxLocalExecutor({
createRuntime: () => runtime,
warmHandles: new Map(),
});
const initial = await firstExecute(buildContext(root));
const compatibleParams = {
...initial.sessionParams,
runtimeSessionName: "runtime-old",
acpSessionId: "acp-old",
};
runtime.nextEnsureError = new Error("session/load failed: no session acp-old");
const logs: LogEntry[] = [];
const execute = createAcpxLocalExecutor({
createRuntime: () => runtime,
warmHandles: new Map(),
});
const result = await execute(buildContext(root, {
runtime: {
sessionId: "acp-old",
sessionParams: compatibleParams,
sessionDisplayId: "acp-old",
taskKey: "PAP-1",
},
onLog: async (stream, chunk) => logs.push({ stream, chunk }),
}));
expect(result.exitCode).toBe(0);
expect(result.clearSession).toBe(true);
expect(runtime.ensureInputs.at(-2)?.resumeSessionId).toBe("acp-old");
expect(runtime.ensureInputs.at(-1)?.resumeSessionId).toBeUndefined();
expect(logs.some((entry) => entry.chunk.includes("retrying with a fresh session"))).toBe(true);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("cancels and closes stale handles on timeout", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-timeout-"));
try {
const neverFinishes = new FakeRuntime(
{} as AcpRuntimeOptions,
[],
{ status: "cancelled", stopReason: "cancelled" },
);
neverFinishes.startTurn = function (input): AcpRuntimeTurn {
this.startInputs.push(input);
let resolveResult!: (value: AcpRuntimeTurnResult) => void;
const result = new Promise<AcpRuntimeTurnResult>((resolve) => {
resolveResult = resolve;
});
return {
requestId: input.requestId,
events: {
[Symbol.asyncIterator]: async function* () {
await new Promise((resolve) => setTimeout(resolve, 50));
},
},
result,
cancel: async (args?: { reason?: string }) => {
this.cancelInputs.push({ handle: input.handle, reason: args?.reason });
resolveResult({ status: "cancelled", stopReason: args?.reason });
},
closeStream: async () => {},
};
};
const execute = createAcpxLocalExecutor({ createRuntime: () => neverFinishes });
const result = await execute(buildContext(root, {
config: {
agent: "claude",
cwd: root,
stateDir: path.join(root, "state"),
promptTemplate: "Do the assigned work.",
timeoutSec: 0.01,
},
}));
expect(result.timedOut).toBe(true);
expect(result.errorCode).toBe("acpx_timeout");
expect(neverFinishes.cancelInputs.length).toBeGreaterThan(0);
expect(neverFinishes.closeInputs.at(-1)?.discardPersistentState).toBe(true);
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("returns structured auth errors", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-error-"));
try {
const runtime = new FakeRuntime({} as AcpRuntimeOptions);
runtime.nextEnsureError = new Error("authentication required: login first");
const execute = createAcpxLocalExecutor({ createRuntime: () => runtime });
const result = await execute(buildContext(root));
expect(result.exitCode).toBe(1);
expect(result.errorCode).toBe("acpx_auth_required");
expect(result.errorMeta).toMatchObject({ category: "auth" });
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("returns structured ACP protocol errors", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-protocol-"));
try {
const runtime = new FakeRuntime({} as AcpRuntimeOptions);
runtime.nextEnsureError = Object.assign(new Error("protocol init failed"), {
code: "ACP_SESSION_INIT_FAILED",
});
const execute = createAcpxLocalExecutor({ createRuntime: () => runtime });
const result = await execute(buildContext(root));
expect(result.exitCode).toBe(1);
expect(result.errorCode).toBe("acpx_protocol_error");
expect(result.errorMeta).toMatchObject({
category: "protocol",
acpCode: "ACP_SESSION_INIT_FAILED",
});
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("materializes selected skills for ACPX Claude and passes public session metadata", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-claude-skills-"));
try {
const skill = await createRuntimeSkill(root, {});
let runtime: FakeRuntime | null = null;
let meta: Record<string, unknown> | null = null;
const execute = createAcpxLocalExecutor({
createRuntime: (options) => {
runtime = new FakeRuntime(options);
return runtime;
},
});
const result = await execute(buildContext(root, {
config: {
agent: "claude",
cwd: root,
stateDir: path.join(root, "state"),
promptTemplate: "Do the assigned work.",
paperclipRuntimeSkills: [skill],
paperclipSkillSync: {
desiredSkills: [skill.key],
},
},
onMeta: async (payload) => {
meta = payload as Record<string, unknown>;
},
}));
expect(result.exitCode).toBe(0);
expect(runtime?.options).not.toHaveProperty("sessionOptions");
const skillRoot = result.sessionParams?.skills && typeof result.sessionParams.skills === "object"
? (result.sessionParams.skills as { skillRoot?: string | null }).skillRoot
: null;
expect(skillRoot).toContain(path.join("state", "runtime-skills", "claude"));
await expect(fs.lstat(path.join(skillRoot!, skill.runtimeName))).resolves.toMatchObject({});
expect(result.sessionParams?.skills).toMatchObject({
mode: "claude",
selectedSkills: [skill.runtimeName],
});
expect(String(meta?.prompt ?? "")).toContain(`Skill root: ${skillRoot}`);
expect((meta?.commandNotes as string[]).join("\n")).toContain("Materialized 1 Paperclip skill");
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("includes skill content in the ACPX Claude session fingerprint", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-claude-fingerprint-"));
try {
const skill = await createRuntimeSkill(root, { body: "---\nrequired: false\n---\nFirst version.\n" });
const runtimes: FakeRuntime[] = [];
const execute = createAcpxLocalExecutor({
createRuntime: (options) => {
const runtime = new FakeRuntime(options);
runtimes.push(runtime);
return runtime;
},
});
const context = buildContext(root, {
config: {
agent: "claude",
cwd: root,
stateDir: path.join(root, "state"),
promptTemplate: "Do the assigned work.",
paperclipRuntimeSkills: [skill],
paperclipSkillSync: {
desiredSkills: [skill.key],
},
},
});
const first = await execute(context);
await fs.writeFile(path.join(skill.source, "SKILL.md"), "---\nrequired: false\n---\nSecond version.\n", "utf8");
const second = await execute({
...context,
runtime: {
sessionId: first.sessionId ?? null,
sessionParams: first.sessionParams ?? null,
sessionDisplayId: first.sessionDisplayId ?? null,
taskKey: "PAP-1",
},
});
expect(second.sessionParams?.configFingerprint).not.toBe(first.sessionParams?.configFingerprint);
expect(runtimes.at(-1)?.ensureInputs.at(-1)?.resumeSessionId).toBeUndefined();
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("materializes selected skills into the effective ACPX Codex CODEX_HOME", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-codex-skills-"));
try {
const skill = await createRuntimeSkill(root, {});
const codexHome = path.join(root, "codex-home");
let runtime: FakeRuntime | null = null;
let meta: Record<string, unknown> | null = null;
const execute = createAcpxLocalExecutor({
createRuntime: (options) => {
runtime = new FakeRuntime(options);
return runtime;
},
});
const result = await execute(buildContext(root, {
config: {
agent: "codex",
cwd: root,
stateDir: path.join(root, "state"),
promptTemplate: "Do the assigned work.",
env: { CODEX_HOME: codexHome },
paperclipRuntimeSkills: [skill],
paperclipSkillSync: {
desiredSkills: [skill.key],
},
},
onMeta: async (payload) => {
meta = payload as Record<string, unknown>;
},
}));
expect(result.exitCode).toBe(0);
await expect(fs.lstat(path.join(codexHome, "skills", skill.runtimeName))).resolves.toMatchObject({});
const wrapperPath = runtime?.options.agentRegistry.resolve("codex");
const wrapper = await fs.readFile(wrapperPath!, "utf8");
expect(wrapper).not.toContain("CODEX_HOME");
expect(wrapper).not.toContain(codexHome);
expect((meta?.env as Record<string, string>).CODEX_HOME).toBe(codexHome);
expect(result.sessionParams?.skills).toMatchObject({
mode: "codex",
codexHome,
selectedSkills: [skill.runtimeName],
});
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("keeps ACPX custom skill selection tracked without runtime materialization", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-acpx-custom-skills-"));
try {
const skill = await createRuntimeSkill(root, {});
let runtime: FakeRuntime | null = null;
let meta: Record<string, unknown> | null = null;
const execute = createAcpxLocalExecutor({
createRuntime: (options) => {
runtime = new FakeRuntime(options);
return runtime;
},
});
const result = await execute(buildContext(root, {
config: {
agent: "custom",
agentCommand: "custom-acp",
cwd: root,
stateDir: path.join(root, "state"),
promptTemplate: "Do the assigned work.",
paperclipRuntimeSkills: [skill],
paperclipSkillSync: {
desiredSkills: [skill.key],
},
},
onMeta: async (payload) => {
meta = payload as Record<string, unknown>;
},
}));
expect(result.exitCode).toBe(0);
expect(runtime?.options.sessionOptions).toBeUndefined();
await expect(fs.lstat(path.join(root, "state", "runtime-skills"))).rejects.toMatchObject({ code: "ENOENT" });
expect(result.sessionParams?.skills).toMatchObject({
mode: "custom_unsupported",
desiredSkillNames: [skill.key],
});
expect((meta?.commandNotes as string[]).join("\n")).toContain("tracked only");
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
});

View file

@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import {
listAcpxSkills,
syncAcpxSkills,
} from "@paperclipai/adapter-acpx-local/server";
describe("acpx local skill sync", () => {
const paperclipKey = "paperclipai/paperclip/paperclip";
const createAgentKey = "paperclipai/paperclip/paperclip-create-agent";
it("reports ACPX Claude skills as supported runtime-mounted state", async () => {
const snapshot = await listAcpxSkills({
agentId: "agent-1",
companyId: "company-1",
adapterType: "acpx_local",
config: {
agent: "claude",
paperclipSkillSync: {
desiredSkills: [paperclipKey],
},
},
});
expect(snapshot.adapterType).toBe("acpx_local");
expect(snapshot.supported).toBe(true);
expect(snapshot.mode).toBe("ephemeral");
expect(snapshot.desiredSkills).toContain(paperclipKey);
expect(snapshot.desiredSkills).toContain(createAgentKey);
expect(snapshot.entries.find((entry) => entry.key === paperclipKey)?.state).toBe("configured");
expect(snapshot.entries.find((entry) => entry.key === paperclipKey)?.detail).toContain("ACPX Claude session");
expect(snapshot.warnings).toEqual([]);
});
it("reports ACPX Codex skills with Codex home runtime detail", async () => {
const snapshot = await syncAcpxSkills({
agentId: "agent-2",
companyId: "company-1",
adapterType: "acpx_local",
config: {
agent: "codex",
paperclipSkillSync: {
desiredSkills: ["paperclip"],
},
},
}, ["paperclip"]);
expect(snapshot.supported).toBe(true);
expect(snapshot.mode).toBe("ephemeral");
expect(snapshot.desiredSkills).toContain(paperclipKey);
expect(snapshot.desiredSkills).not.toContain("paperclip");
expect(snapshot.entries.find((entry) => entry.key === paperclipKey)?.state).toBe("configured");
expect(snapshot.entries.find((entry) => entry.key === paperclipKey)?.detail).toContain("CODEX_HOME/skills/");
expect(snapshot.warnings).toEqual([]);
});
it("keeps ACPX custom skill selection tracked but unsupported", async () => {
const snapshot = await listAcpxSkills({
agentId: "agent-3",
companyId: "company-1",
adapterType: "acpx_local",
config: {
agent: "custom",
paperclipSkillSync: {
desiredSkills: [paperclipKey],
},
},
});
expect(snapshot.supported).toBe(false);
expect(snapshot.mode).toBe("unsupported");
expect(snapshot.desiredSkills).toContain(paperclipKey);
expect(snapshot.entries.find((entry) => entry.key === paperclipKey)?.desired).toBe(true);
expect(snapshot.entries.find((entry) => entry.key === paperclipKey)?.detail).toContain("stored in Paperclip only");
expect(snapshot.warnings).toContain(
"Custom ACP commands do not expose a Paperclip skill integration contract yet; selected skills are tracked only.",
);
});
});

View file

@ -202,6 +202,11 @@ describe("adapter routes", () => {
const codexLocal = res.body.find((a: any) => a.type === "codex_local");
expect(codexLocal).toBeDefined();
expect(codexLocal.capabilities.supportsSkills).toBe(true);
// acpx_local exposes runtime-aware skill snapshots for Claude/Codex/custom ACP agents
const acpxLocal = res.body.find((a: any) => a.type === "acpx_local");
expect(acpxLocal).toBeDefined();
expect(acpxLocal.capabilities.supportsSkills).toBe(true);
});
it("uses the active adapter when resolving config schema for a paused builtin override", async () => {
@ -225,6 +230,31 @@ describe("adapter routes", () => {
});
});
it("serves the built-in acpx_local config schema", async () => {
const app = createApp();
const res = await request(app).get("/api/adapters/acpx_local/config-schema");
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(res.body.fields).toEqual(
expect.arrayContaining([
expect.objectContaining({
key: "agent",
default: "claude",
options: expect.arrayContaining([
expect.objectContaining({ value: "claude" }),
expect.objectContaining({ value: "codex" }),
expect.objectContaining({ value: "custom" }),
]),
}),
expect.objectContaining({
key: "permissionMode",
default: "approve-all",
}),
]),
);
});
it("rejects signed-in users without org access", async () => {
const app = createApp({
userId: "outsider-1",

View file

@ -13,6 +13,7 @@ import {
sessionCodec as opencodeSessionCodec,
isOpenCodeUnknownSessionError,
} from "@paperclipai/adapter-opencode-local/server";
import { sessionCodec as acpxSessionCodec } from "@paperclipai/adapter-acpx-local/server";
describe("adapter session codecs", () => {
it("normalizes claude session params with cwd", () => {
@ -107,6 +108,50 @@ describe("adapter session codecs", () => {
});
expect(geminiSessionCodec.getDisplayId?.(serialized ?? null)).toBe("gemini-session-1");
});
it("preserves acpx session params required for compatibility checks", () => {
const parsed = acpxSessionCodec.deserialize({
sessionKey: "paperclip:company:agent:task:fingerprint",
runtimeSessionName: "runtime-session-1",
acpxRecordId: "record-1",
acpSessionId: "acp-session-1",
agentSessionId: "agent-session-1",
agent: "claude",
cwd: "/tmp/acpx",
mode: "persistent",
stateDir: "/tmp/acpx-state",
configFingerprint: "fingerprint",
workspaceId: "workspace-1",
repoUrl: "https://example.com/repo.git",
repoRef: "main",
remoteExecution: {
environmentId: "environment-1",
leaseId: "lease-1",
},
});
expect(parsed).toMatchObject({
sessionKey: "paperclip:company:agent:task:fingerprint",
runtimeSessionName: "runtime-session-1",
acpxRecordId: "record-1",
acpSessionId: "acp-session-1",
agentSessionId: "agent-session-1",
agent: "claude",
cwd: "/tmp/acpx",
mode: "persistent",
stateDir: "/tmp/acpx-state",
configFingerprint: "fingerprint",
workspaceId: "workspace-1",
repoUrl: "https://example.com/repo.git",
repoRef: "main",
remoteExecution: {
environmentId: "environment-1",
leaseId: "lease-1",
},
});
expect(acpxSessionCodec.serialize(parsed)).toEqual(parsed);
expect(acpxSessionCodec.getDisplayId?.(parsed)).toBe("runtime-session-1");
});
});
describe("codex resume recovery detection", () => {

View file

@ -362,6 +362,99 @@ describe.sequential("agent skill routes", () => {
expect(res.status, JSON.stringify(res.body)).toBe(200);
});
it("passes ACPX Claude config through the agent skill listing route", async () => {
mockAgentService.getById.mockResolvedValue({
...makeAgent("acpx_local"),
adapterConfig: { agent: "claude" },
});
mockSecretService.resolveAdapterConfigForRuntime.mockResolvedValueOnce({
config: { agent: "claude" },
});
mockAdapter.listSkills.mockResolvedValue({
adapterType: "acpx_local",
supported: true,
mode: "ephemeral",
desiredSkills: ["paperclipai/paperclip/paperclip"],
entries: [],
warnings: [],
});
const res = await requestApp(
await createApp(),
(baseUrl) => request(baseUrl)
.get("/api/agents/11111111-1111-4111-8111-111111111111/skills?companyId=company-1"),
);
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockCompanySkillService.listRuntimeSkillEntries).toHaveBeenCalledWith("company-1", {
materializeMissing: false,
});
expect(mockAdapter.listSkills).toHaveBeenCalledWith(
expect.objectContaining({
adapterType: "acpx_local",
config: expect.objectContaining({
agent: "claude",
paperclipRuntimeSkills: expect.any(Array),
}),
}),
);
});
it("persists ACPX Codex desired skills through the agent skill sync route", async () => {
mockAgentService.getById.mockResolvedValue({
...makeAgent("acpx_local"),
adapterConfig: { agent: "codex" },
});
mockAgentService.update.mockImplementationOnce(async (_id: string, patch: Record<string, unknown>) => ({
...makeAgent("acpx_local"),
adapterConfig: patch.adapterConfig ?? {},
}));
mockSecretService.resolveAdapterConfigForRuntime.mockResolvedValueOnce({
config: {
agent: "codex",
paperclipSkillSync: {
desiredSkills: ["paperclipai/paperclip/paperclip"],
},
},
});
mockAdapter.syncSkills.mockResolvedValue({
adapterType: "acpx_local",
supported: true,
mode: "ephemeral",
desiredSkills: ["paperclipai/paperclip/paperclip"],
entries: [],
warnings: [],
});
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
.post("/api/agents/11111111-1111-4111-8111-111111111111/skills/sync?companyId=company-1")
.send({ desiredSkills: ["paperclip"] }));
expect(res.status, JSON.stringify(res.body)).toBe(200);
expect(mockAgentService.update).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
adapterConfig: expect.objectContaining({
agent: "codex",
paperclipSkillSync: expect.objectContaining({
desiredSkills: ["paperclipai/paperclip/paperclip"],
}),
}),
}),
expect.any(Object),
);
expect(mockAdapter.syncSkills).toHaveBeenCalledWith(
expect.objectContaining({
adapterType: "acpx_local",
config: expect.objectContaining({
agent: "codex",
paperclipRuntimeSkills: expect.any(Array),
}),
}),
["paperclipai/paperclip/paperclip"],
);
});
it("keeps runtime materialization for persistent skill adapters", async () => {
mockAgentService.getById.mockResolvedValue(makeAgent("cursor"));
mockAdapter.listSkills.mockResolvedValue({

View file

@ -84,4 +84,51 @@ describe("redaction", () => {
expect(result).not.toContain(githubToken);
expect(result).not.toContain(jwt);
});
it("redacts inline secrets from command metadata without hiding safe command text", () => {
const input = {
command: "custom-acp --token ghp_example_secret env OPENAI_API_KEY=sk-live-example custom-acp",
commandArgs: ["--safe", "ok", "--token", "ghp_arg_secret", "--api-key=sk-inline-example"],
env: {
PAPERCLIP_RESOLVED_COMMAND: "env OPENAI_API_KEY=sk-live-example custom-acp --token ghp_example_secret",
SAFE_VALUE: "visible",
},
};
const result = redactEventPayload(input);
expect(result?.command).toBe(
`custom-acp --token ${REDACTED_EVENT_VALUE} env OPENAI_API_KEY=${REDACTED_EVENT_VALUE} custom-acp`,
);
expect(result?.commandArgs).toEqual([
"--safe",
"ok",
"--token",
REDACTED_EVENT_VALUE,
`--api-key=${REDACTED_EVENT_VALUE}`,
]);
expect(result?.env).toEqual({
PAPERCLIP_RESOLVED_COMMAND:
`env OPENAI_API_KEY=${REDACTED_EVENT_VALUE} custom-acp --token ${REDACTED_EVENT_VALUE}`,
SAFE_VALUE: "visible",
});
});
it("redacts non-string command args after secret flags", () => {
const result = redactEventPayload({
commandArgs: ["--api-key", { nested: "secret-value" }, "safe-next"],
});
expect(result?.commandArgs).toEqual(["--api-key", REDACTED_EVENT_VALUE, "safe-next"]);
});
it("does not treat bare args payloads as command args", () => {
const result = redactEventPayload({
args: ["--api-key", "not-a-command-secret"],
argv: ["--api-key", "command-secret"],
});
expect(result?.args).toEqual(["--api-key", "not-a-command-secret"]);
expect(result?.argv).toEqual(["--api-key", REDACTED_EVENT_VALUE]);
});
});

View file

@ -2,6 +2,7 @@
* Adapter types shipped with Paperclip. External plugins must not replace these.
*/
export const BUILTIN_ADAPTER_TYPES = new Set([
"acpx_local",
"claude_local",
"codex_local",
"cursor",

View file

@ -1,5 +1,14 @@
import type { AdapterModelProfileDefinition, ServerAdapterModule } from "./types.js";
import { getAdapterSessionManagement } from "@paperclipai/adapter-utils";
import {
execute as acpxExecute,
testEnvironment as acpxTestEnvironment,
sessionCodec as acpxSessionCodec,
getConfigSchema as getAcpxConfigSchema,
listAcpxSkills,
syncAcpxSkills,
} from "@paperclipai/adapter-acpx-local/server";
import { agentConfigurationDoc as acpxAgentConfigurationDoc } from "@paperclipai/adapter-acpx-local";
import {
execute as claudeExecute,
listClaudeSkills,
@ -154,6 +163,22 @@ const claudeLocalAdapter: ServerAdapterModule = {
getQuotaWindows: claudeGetQuotaWindows,
};
const acpxLocalAdapter: ServerAdapterModule = {
type: "acpx_local",
execute: acpxExecute,
testEnvironment: acpxTestEnvironment,
listSkills: listAcpxSkills,
syncSkills: syncAcpxSkills,
sessionCodec: acpxSessionCodec,
sessionManagement: getAdapterSessionManagement("acpx_local") ?? undefined,
supportsLocalAgentJwt: true,
supportsInstructionsBundle: true,
instructionsPathKey: "instructionsFilePath",
requiresMaterializedRuntimeSkills: false,
agentConfigurationDoc: acpxAgentConfigurationDoc,
getConfigSchema: getAcpxConfigSchema,
};
const codexLocalAdapter: ServerAdapterModule = {
type: "codex_local",
execute: codexExecute,
@ -335,6 +360,7 @@ const pausedOverrides = new Set<string>();
function registerBuiltInAdapters() {
for (const adapter of [
acpxLocalAdapter,
claudeLocalAdapter,
codexLocalAdapter,
openCodeLocalAdapter,

View file

@ -64,7 +64,8 @@ export function buildInvocationEnvForLogs(
const resolvedCommand = options.resolvedCommand?.trim();
if (resolvedCommand) {
merged[options.resolvedCommandEnvKey ?? "PAPERCLIP_RESOLVED_COMMAND"] = resolvedCommand;
merged[options.resolvedCommandEnvKey ?? "PAPERCLIP_RESOLVED_COMMAND"] =
serverUtils.redactCommandTextForLogs(resolvedCommand);
}
return redactEnvForLogs(merged);

View file

@ -1,12 +1,13 @@
import { redactCommandText } from "@paperclipai/adapter-utils";
const SECRET_PAYLOAD_KEY_RE =
/(api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)/i;
const COMMAND_PAYLOAD_KEY_RE =
/(^command$|^cmd$|command[-_]?line|resolved[-_]?command|PAPERCLIP_RESOLVED_COMMAND)/i;
const COMMAND_ARGS_PAYLOAD_KEY_RE = /^(commandArgs|command_?args|argv)$/i;
const JWT_VALUE_RE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/;
const JWT_TEXT_RE = /\b[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]{8,})?\b/g;
const OPENAI_KEY_TEXT_RE = /\bsk-[A-Za-z0-9_-]{12,}\b/g;
const GITHUB_TOKEN_TEXT_RE = /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g;
const AUTHORIZATION_BEARER_TEXT_RE = /(\bAuthorization\s*:\s*Bearer\s+)[^\s"'`]+/gi;
const ENV_SECRET_ASSIGNMENT_TEXT_RE =
/(\b[A-Za-z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|AUTHORIZATION|JWT)[A-Za-z0-9_]*\s*=\s*)[^\s"'`]+/gi;
const CLI_SECRET_FLAG_RE =
/^-{1,2}(?:api[-_]?key|(?:access[-_]?|auth[-_]?)?token|token|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)$/i;
const JSON_SECRET_FIELD_TEXT_RE =
/((?:"|')?(?:api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)(?:"|')?\s*:\s*(?:"|'))[^"'`\r\n]+((?:"|'))/gi;
const ESCAPED_JSON_SECRET_FIELD_TEXT_RE =
@ -38,9 +39,33 @@ function isPlainBinding(value: unknown): value is { type: "plain"; value: unknow
return value.type === "plain" && "value" in value;
}
function sanitizeCommandArgs(args: unknown[]): unknown[] {
let redactNext = false;
return args.map((arg) => {
if (redactNext) {
redactNext = false;
return REDACTED_EVENT_VALUE;
}
if (typeof arg !== "string") return sanitizeValue(arg);
if (CLI_SECRET_FLAG_RE.test(arg.trim())) {
redactNext = true;
return arg;
}
return redactSensitiveText(arg);
});
}
export function sanitizeRecord(record: Record<string, unknown>): Record<string, unknown> {
const redacted: Record<string, unknown> = {};
for (const [key, value] of Object.entries(record)) {
if (COMMAND_ARGS_PAYLOAD_KEY_RE.test(key) && Array.isArray(value)) {
redacted[key] = sanitizeCommandArgs(value);
continue;
}
if (COMMAND_PAYLOAD_KEY_RE.test(key) && typeof value === "string") {
redacted[key] = redactSensitiveText(value);
continue;
}
if (SECRET_PAYLOAD_KEY_RE.test(key)) {
if (isSecretRefBinding(value)) {
redacted[key] = sanitizeValue(value);
@ -69,12 +94,10 @@ export function redactEventPayload(payload: Record<string, unknown> | null): Rec
}
export function redactSensitiveText(input: string): string {
return input
.replace(AUTHORIZATION_BEARER_TEXT_RE, `$1${REDACTED_EVENT_VALUE}`)
.replace(JSON_SECRET_FIELD_TEXT_RE, `$1${REDACTED_EVENT_VALUE}$2`)
.replace(ESCAPED_JSON_SECRET_FIELD_TEXT_RE, `$1${REDACTED_EVENT_VALUE}$2`)
.replace(ENV_SECRET_ASSIGNMENT_TEXT_RE, `$1${REDACTED_EVENT_VALUE}`)
.replace(OPENAI_KEY_TEXT_RE, REDACTED_EVENT_VALUE)
.replace(GITHUB_TOKEN_TEXT_RE, REDACTED_EVENT_VALUE)
.replace(JWT_TEXT_RE, REDACTED_EVENT_VALUE);
return redactCommandText(
input
.replace(JSON_SECRET_FIELD_TEXT_RE, `$1${REDACTED_EVENT_VALUE}$2`)
.replace(ESCAPED_JSON_SECRET_FIELD_TEXT_RE, `$1${REDACTED_EVENT_VALUE}$2`),
REDACTED_EVENT_VALUE,
);
}

View file

@ -72,6 +72,12 @@ import { redactCurrentUserValue } from "../log-redaction.js";
import { renderOrgChartSvg, renderOrgChartPng, type OrgNode, type OrgChartStyle, ORG_CHART_STYLES } from "./org-chart-svg.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { runClaudeLogin } from "@paperclipai/adapter-claude-local/server";
import {
DEFAULT_ACPX_LOCAL_AGENT,
DEFAULT_ACPX_LOCAL_MODE,
DEFAULT_ACPX_LOCAL_NON_INTERACTIVE_PERMISSIONS,
DEFAULT_ACPX_LOCAL_PERMISSION_MODE,
} from "@paperclipai/adapter-acpx-local";
import {
DEFAULT_CODEX_LOCAL_BYPASS_APPROVALS_AND_SANDBOX,
DEFAULT_CODEX_LOCAL_MODEL,
@ -110,6 +116,7 @@ export function agentRoutes(
// Legacy hardcoded maps — used as fallback when adapter module does not
// declare capability flags explicitly.
const DEFAULT_INSTRUCTIONS_PATH_KEYS: Record<string, string> = {
acpx_local: "instructionsFilePath",
claude_local: "instructionsFilePath",
codex_local: "instructionsFilePath",
droid_local: "instructionsFilePath",
@ -826,6 +833,21 @@ export function agentRoutes(
adapterConfig: Record<string, unknown>,
): Record<string, unknown> {
const next = { ...adapterConfig };
if (adapterType === "acpx_local") {
if (!asNonEmptyString(next.agent)) {
next.agent = DEFAULT_ACPX_LOCAL_AGENT;
}
if (!asNonEmptyString(next.mode)) {
next.mode = DEFAULT_ACPX_LOCAL_MODE;
}
if (!asNonEmptyString(next.permissionMode)) {
next.permissionMode = DEFAULT_ACPX_LOCAL_PERMISSION_MODE;
}
if (!asNonEmptyString(next.nonInteractivePermissions)) {
next.nonInteractivePermissions = DEFAULT_ACPX_LOCAL_NON_INTERACTIVE_PERMISSIONS;
}
return ensureGatewayDeviceKey(adapterType, next);
}
if (adapterType === "codex_local") {
if (!asNonEmptyString(next.model)) {
next.model = DEFAULT_CODEX_LOCAL_MODEL;

View file

@ -34,6 +34,7 @@ export async function resolveEnvironmentExecutionTarget(input: {
if (input.environment.driver === "sandbox") {
if (
input.adapterType !== "acpx_local" &&
input.adapterType !== "codex_local" &&
input.adapterType !== "claude_local" &&
input.adapterType !== "gemini_local" &&
@ -106,6 +107,7 @@ export async function resolveEnvironmentExecutionTarget(input: {
if (
(
input.adapterType !== "codex_local" &&
input.adapterType !== "acpx_local" &&
input.adapterType !== "claude_local" &&
input.adapterType !== "gemini_local" &&
input.adapterType !== "opencode_local" &&

View file

@ -121,6 +121,7 @@ import { recoveryService } from "./recovery/service.js";
import { productivityReviewService } from "./productivity-review.js";
import { withAgentStartLock } from "./agent-start-lock.js";
import { redactCurrentUserText, redactCurrentUserValue } from "../log-redaction.js";
import { redactEventPayload } from "../redaction.js";
import {
hasSessionCompactionThresholds,
resolveSessionCompactionPolicy,
@ -3118,9 +3119,10 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
const boundedPayload = event.payload
? boundHeartbeatRunEventPayloadForStorage(event.payload)
: event.payload;
const sanitizedPayload = boundedPayload
? redactCurrentUserValue(boundedPayload, currentUserRedactionOptions)
: boundedPayload;
const secretSanitizedPayload = boundedPayload ? redactEventPayload(boundedPayload) : boundedPayload;
const sanitizedPayload = secretSanitizedPayload
? redactCurrentUserValue(secretSanitizedPayload, currentUserRedactionOptions)
: secretSanitizedPayload;
await db.insert(heartbeatRunEvents).values({
companyId: run.companyId,