Merge branch 'master' into feat/hermes-agent-adapter
This commit is contained in:
@@ -33,7 +33,7 @@ Use this skill when leadership asks for:
|
|||||||
|
|
||||||
Before proceeding, verify all of the following:
|
Before proceeding, verify all of the following:
|
||||||
|
|
||||||
1. `skills/release-changelog/SKILL.md` exists and is usable.
|
1. `.agents/skills/release-changelog/SKILL.md` exists and is usable.
|
||||||
2. The repo working tree is clean, including untracked files.
|
2. The repo working tree is clean, including untracked files.
|
||||||
3. There are commits since the last stable tag.
|
3. There are commits since the last stable tag.
|
||||||
4. The release SHA has passed the verification gate or is about to.
|
4. The release SHA has passed the verification gate or is about to.
|
||||||
@@ -78,6 +78,9 @@ If you change schema/API behavior, update all impacted layers:
|
|||||||
4. Do not replace strategic docs wholesale unless asked.
|
4. Do not replace strategic docs wholesale unless asked.
|
||||||
Prefer additive updates. Keep `doc/SPEC.md` and `doc/SPEC-implementation.md` aligned.
|
Prefer additive updates. Keep `doc/SPEC.md` and `doc/SPEC-implementation.md` aligned.
|
||||||
|
|
||||||
|
5. Keep plan docs dated and centralized.
|
||||||
|
New plan documents belong in `doc/plans/` and should use `YYYY-MM-DD-slug.md` filenames.
|
||||||
|
|
||||||
## 6. Database Change Workflow
|
## 6. Database Change Workflow
|
||||||
|
|
||||||
When changing data model:
|
When changing data model:
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ COPY packages/adapter-utils/package.json packages/adapter-utils/
|
|||||||
COPY packages/adapters/claude-local/package.json packages/adapters/claude-local/
|
COPY packages/adapters/claude-local/package.json packages/adapters/claude-local/
|
||||||
COPY packages/adapters/codex-local/package.json packages/adapters/codex-local/
|
COPY packages/adapters/codex-local/package.json packages/adapters/codex-local/
|
||||||
COPY packages/adapters/cursor-local/package.json packages/adapters/cursor-local/
|
COPY packages/adapters/cursor-local/package.json packages/adapters/cursor-local/
|
||||||
|
COPY packages/adapters/gemini-local/package.json packages/adapters/gemini-local/
|
||||||
COPY packages/adapters/openclaw-gateway/package.json packages/adapters/openclaw-gateway/
|
COPY packages/adapters/openclaw-gateway/package.json packages/adapters/openclaw-gateway/
|
||||||
COPY packages/adapters/opencode-local/package.json packages/adapters/opencode-local/
|
COPY packages/adapters/opencode-local/package.json packages/adapters/opencode-local/
|
||||||
COPY packages/adapters/pi-local/package.json packages/adapters/pi-local/
|
COPY packages/adapters/pi-local/package.json packages/adapters/pi-local/
|
||||||
|
|||||||
@@ -248,8 +248,6 @@ See [doc/DEVELOPING.md](doc/DEVELOPING.md) for the full development guide.
|
|||||||
|
|
||||||
We welcome contributions. See the [contributing guide](CONTRIBUTING.md) for details.
|
We welcome contributions. See the [contributing guide](CONTRIBUTING.md) for details.
|
||||||
|
|
||||||
<!-- TODO: add CONTRIBUTING.md -->
|
|
||||||
|
|
||||||
<br/>
|
<br/>
|
||||||
|
|
||||||
## Community
|
## Community
|
||||||
|
|||||||
@@ -1,5 +1,23 @@
|
|||||||
# paperclipai
|
# paperclipai
|
||||||
|
|
||||||
|
## 0.3.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Stable release preparation for 0.3.1
|
||||||
|
- Updated dependencies
|
||||||
|
- @paperclipai/adapter-utils@0.3.1
|
||||||
|
- @paperclipai/adapter-claude-local@0.3.1
|
||||||
|
- @paperclipai/adapter-codex-local@0.3.1
|
||||||
|
- @paperclipai/adapter-cursor-local@0.3.1
|
||||||
|
- @paperclipai/adapter-gemini-local@0.3.1
|
||||||
|
- @paperclipai/adapter-openclaw-gateway@0.3.1
|
||||||
|
- @paperclipai/adapter-opencode-local@0.3.1
|
||||||
|
- @paperclipai/adapter-pi-local@0.3.1
|
||||||
|
- @paperclipai/db@0.3.1
|
||||||
|
- @paperclipai/shared@0.3.1
|
||||||
|
- @paperclipai/server@0.3.1
|
||||||
|
|
||||||
## 0.3.0
|
## 0.3.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "paperclipai",
|
"name": "paperclipai",
|
||||||
"version": "0.3.0",
|
"version": "0.3.1",
|
||||||
"description": "Paperclip CLI — orchestrate AI agent teams to run a business",
|
"description": "Paperclip CLI — orchestrate AI agent teams to run a business",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"bin": {
|
"bin": {
|
||||||
@@ -37,6 +37,7 @@
|
|||||||
"@paperclipai/adapter-claude-local": "workspace:*",
|
"@paperclipai/adapter-claude-local": "workspace:*",
|
||||||
"@paperclipai/adapter-codex-local": "workspace:*",
|
"@paperclipai/adapter-codex-local": "workspace:*",
|
||||||
"@paperclipai/adapter-cursor-local": "workspace:*",
|
"@paperclipai/adapter-cursor-local": "workspace:*",
|
||||||
|
"@paperclipai/adapter-gemini-local": "workspace:*",
|
||||||
"@paperclipai/adapter-opencode-local": "workspace:*",
|
"@paperclipai/adapter-opencode-local": "workspace:*",
|
||||||
"@paperclipai/adapter-pi-local": "workspace:*",
|
"@paperclipai/adapter-pi-local": "workspace:*",
|
||||||
"@paperclipai/adapter-openclaw-gateway": "workspace:*",
|
"@paperclipai/adapter-openclaw-gateway": "workspace:*",
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import path from "node:path";
|
|||||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
import {
|
import {
|
||||||
ensureAgentJwtSecret,
|
ensureAgentJwtSecret,
|
||||||
|
mergePaperclipEnvEntries,
|
||||||
readAgentJwtSecretFromEnv,
|
readAgentJwtSecretFromEnv,
|
||||||
|
readPaperclipEnvEntries,
|
||||||
resolveAgentJwtEnvFile,
|
resolveAgentJwtEnvFile,
|
||||||
} from "../config/env.js";
|
} from "../config/env.js";
|
||||||
import { agentJwtSecretCheck } from "../checks/agent-jwt-secret-check.js";
|
import { agentJwtSecretCheck } from "../checks/agent-jwt-secret-check.js";
|
||||||
@@ -58,4 +60,20 @@ describe("agent jwt env helpers", () => {
|
|||||||
const result = agentJwtSecretCheck(configPath);
|
const result = agentJwtSecretCheck(configPath);
|
||||||
expect(result.status).toBe("pass");
|
expect(result.status).toBe("pass");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("quotes hash-prefixed env values so dotenv round-trips them", () => {
|
||||||
|
const configPath = tempConfigPath();
|
||||||
|
const envPath = resolveAgentJwtEnvFile(configPath);
|
||||||
|
|
||||||
|
mergePaperclipEnvEntries(
|
||||||
|
{
|
||||||
|
PAPERCLIP_WORKTREE_COLOR: "#439edb",
|
||||||
|
},
|
||||||
|
envPath,
|
||||||
|
);
|
||||||
|
|
||||||
|
const contents = fs.readFileSync(envPath, "utf-8");
|
||||||
|
expect(contents).toContain('PAPERCLIP_WORKTREE_COLOR="#439edb"');
|
||||||
|
expect(readPaperclipEnvEntries(envPath).PAPERCLIP_WORKTREE_COLOR).toBe("#439edb");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,19 +2,22 @@ import fs from "node:fs";
|
|||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { execFileSync } from "node:child_process";
|
import { execFileSync } from "node:child_process";
|
||||||
import { describe, expect, it } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
import {
|
import {
|
||||||
copyGitHooksToWorktreeGitDir,
|
copyGitHooksToWorktreeGitDir,
|
||||||
copySeededSecretsKey,
|
copySeededSecretsKey,
|
||||||
rebindWorkspaceCwd,
|
rebindWorkspaceCwd,
|
||||||
|
resolveSourceConfigPath,
|
||||||
resolveGitWorktreeAddArgs,
|
resolveGitWorktreeAddArgs,
|
||||||
resolveWorktreeMakeTargetPath,
|
resolveWorktreeMakeTargetPath,
|
||||||
|
worktreeInitCommand,
|
||||||
worktreeMakeCommand,
|
worktreeMakeCommand,
|
||||||
} from "../commands/worktree.js";
|
} from "../commands/worktree.js";
|
||||||
import {
|
import {
|
||||||
buildWorktreeConfig,
|
buildWorktreeConfig,
|
||||||
buildWorktreeEnvEntries,
|
buildWorktreeEnvEntries,
|
||||||
formatShellExports,
|
formatShellExports,
|
||||||
|
generateWorktreeColor,
|
||||||
resolveWorktreeSeedPlan,
|
resolveWorktreeSeedPlan,
|
||||||
resolveWorktreeLocalPaths,
|
resolveWorktreeLocalPaths,
|
||||||
rewriteLocalUrlPort,
|
rewriteLocalUrlPort,
|
||||||
@@ -22,6 +25,20 @@ import {
|
|||||||
} from "../commands/worktree-lib.js";
|
} from "../commands/worktree-lib.js";
|
||||||
import type { PaperclipConfig } from "../config/schema.js";
|
import type { PaperclipConfig } from "../config/schema.js";
|
||||||
|
|
||||||
|
const ORIGINAL_CWD = process.cwd();
|
||||||
|
const ORIGINAL_ENV = { ...process.env };
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.chdir(ORIGINAL_CWD);
|
||||||
|
for (const key of Object.keys(process.env)) {
|
||||||
|
if (!(key in ORIGINAL_ENV)) delete process.env[key];
|
||||||
|
}
|
||||||
|
for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
|
||||||
|
if (value === undefined) delete process.env[key];
|
||||||
|
else process.env[key] = value;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
function buildSourceConfig(): PaperclipConfig {
|
function buildSourceConfig(): PaperclipConfig {
|
||||||
return {
|
return {
|
||||||
$meta: {
|
$meta: {
|
||||||
@@ -115,6 +132,28 @@ describe("worktree helpers", () => {
|
|||||||
).toEqual(["worktree", "add", "/tmp/feature-branch", "feature-branch"]);
|
).toEqual(["worktree", "add", "/tmp/feature-branch", "feature-branch"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("builds git worktree add args with a start point", () => {
|
||||||
|
expect(
|
||||||
|
resolveGitWorktreeAddArgs({
|
||||||
|
branchName: "my-worktree",
|
||||||
|
targetPath: "/tmp/my-worktree",
|
||||||
|
branchExists: false,
|
||||||
|
startPoint: "public-gh/master",
|
||||||
|
}),
|
||||||
|
).toEqual(["worktree", "add", "-b", "my-worktree", "/tmp/my-worktree", "public-gh/master"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("uses start point even when a local branch with the same name exists", () => {
|
||||||
|
expect(
|
||||||
|
resolveGitWorktreeAddArgs({
|
||||||
|
branchName: "my-worktree",
|
||||||
|
targetPath: "/tmp/my-worktree",
|
||||||
|
branchExists: true,
|
||||||
|
startPoint: "origin/main",
|
||||||
|
}),
|
||||||
|
).toEqual(["worktree", "add", "-b", "my-worktree", "/tmp/my-worktree", "origin/main"]);
|
||||||
|
});
|
||||||
|
|
||||||
it("rewrites loopback auth URLs to the new port only", () => {
|
it("rewrites loopback auth URLs to the new port only", () => {
|
||||||
expect(rewriteLocalUrlPort("http://127.0.0.1:3100", 3110)).toBe("http://127.0.0.1:3110/");
|
expect(rewriteLocalUrlPort("http://127.0.0.1:3100", 3110)).toBe("http://127.0.0.1:3110/");
|
||||||
expect(rewriteLocalUrlPort("https://paperclip.example", 3110)).toBe("https://paperclip.example");
|
expect(rewriteLocalUrlPort("https://paperclip.example", 3110)).toBe("https://paperclip.example");
|
||||||
@@ -144,13 +183,22 @@ describe("worktree helpers", () => {
|
|||||||
path.resolve("/tmp/paperclip-worktrees", "instances", "feature-worktree-support", "data", "storage"),
|
path.resolve("/tmp/paperclip-worktrees", "instances", "feature-worktree-support", "data", "storage"),
|
||||||
);
|
);
|
||||||
|
|
||||||
const env = buildWorktreeEnvEntries(paths);
|
const env = buildWorktreeEnvEntries(paths, {
|
||||||
|
name: "feature-worktree-support",
|
||||||
|
color: "#3abf7a",
|
||||||
|
});
|
||||||
expect(env.PAPERCLIP_HOME).toBe(path.resolve("/tmp/paperclip-worktrees"));
|
expect(env.PAPERCLIP_HOME).toBe(path.resolve("/tmp/paperclip-worktrees"));
|
||||||
expect(env.PAPERCLIP_INSTANCE_ID).toBe("feature-worktree-support");
|
expect(env.PAPERCLIP_INSTANCE_ID).toBe("feature-worktree-support");
|
||||||
expect(env.PAPERCLIP_IN_WORKTREE).toBe("true");
|
expect(env.PAPERCLIP_IN_WORKTREE).toBe("true");
|
||||||
|
expect(env.PAPERCLIP_WORKTREE_NAME).toBe("feature-worktree-support");
|
||||||
|
expect(env.PAPERCLIP_WORKTREE_COLOR).toBe("#3abf7a");
|
||||||
expect(formatShellExports(env)).toContain("export PAPERCLIP_INSTANCE_ID='feature-worktree-support'");
|
expect(formatShellExports(env)).toContain("export PAPERCLIP_INSTANCE_ID='feature-worktree-support'");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("generates vivid worktree colors as hex", () => {
|
||||||
|
expect(generateWorktreeColor()).toMatch(/^#[0-9a-f]{6}$/);
|
||||||
|
});
|
||||||
|
|
||||||
it("uses minimal seed mode to keep app state but drop heavy runtime history", () => {
|
it("uses minimal seed mode to keep app state but drop heavy runtime history", () => {
|
||||||
const minimal = resolveWorktreeSeedPlan("minimal");
|
const minimal = resolveWorktreeSeedPlan("minimal");
|
||||||
const full = resolveWorktreeSeedPlan("full");
|
const full = resolveWorktreeSeedPlan("full");
|
||||||
@@ -167,7 +215,11 @@ describe("worktree helpers", () => {
|
|||||||
|
|
||||||
it("copies the source local_encrypted secrets key into the seeded worktree instance", () => {
|
it("copies the source local_encrypted secrets key into the seeded worktree instance", () => {
|
||||||
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-worktree-secrets-"));
|
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-worktree-secrets-"));
|
||||||
|
const originalInlineMasterKey = process.env.PAPERCLIP_SECRETS_MASTER_KEY;
|
||||||
|
const originalKeyFile = process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
|
||||||
try {
|
try {
|
||||||
|
delete process.env.PAPERCLIP_SECRETS_MASTER_KEY;
|
||||||
|
delete process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
|
||||||
const sourceConfigPath = path.join(tempRoot, "source", "config.json");
|
const sourceConfigPath = path.join(tempRoot, "source", "config.json");
|
||||||
const sourceKeyPath = path.join(tempRoot, "source", "secrets", "master.key");
|
const sourceKeyPath = path.join(tempRoot, "source", "secrets", "master.key");
|
||||||
const targetKeyPath = path.join(tempRoot, "target", "secrets", "master.key");
|
const targetKeyPath = path.join(tempRoot, "target", "secrets", "master.key");
|
||||||
@@ -186,6 +238,16 @@ describe("worktree helpers", () => {
|
|||||||
|
|
||||||
expect(fs.readFileSync(targetKeyPath, "utf8")).toBe("source-master-key");
|
expect(fs.readFileSync(targetKeyPath, "utf8")).toBe("source-master-key");
|
||||||
} finally {
|
} finally {
|
||||||
|
if (originalInlineMasterKey === undefined) {
|
||||||
|
delete process.env.PAPERCLIP_SECRETS_MASTER_KEY;
|
||||||
|
} else {
|
||||||
|
process.env.PAPERCLIP_SECRETS_MASTER_KEY = originalInlineMasterKey;
|
||||||
|
}
|
||||||
|
if (originalKeyFile === undefined) {
|
||||||
|
delete process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
|
||||||
|
} else {
|
||||||
|
process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = originalKeyFile;
|
||||||
|
}
|
||||||
fs.rmSync(tempRoot, { recursive: true, force: true });
|
fs.rmSync(tempRoot, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -211,6 +273,92 @@ describe("worktree helpers", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("persists the current agent jwt secret into the worktree env file", async () => {
|
||||||
|
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-worktree-jwt-"));
|
||||||
|
const repoRoot = path.join(tempRoot, "repo");
|
||||||
|
const originalCwd = process.cwd();
|
||||||
|
const originalJwtSecret = process.env.PAPERCLIP_AGENT_JWT_SECRET;
|
||||||
|
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(repoRoot, { recursive: true });
|
||||||
|
process.env.PAPERCLIP_AGENT_JWT_SECRET = "worktree-shared-secret";
|
||||||
|
process.chdir(repoRoot);
|
||||||
|
|
||||||
|
await worktreeInitCommand({
|
||||||
|
seed: false,
|
||||||
|
fromConfig: path.join(tempRoot, "missing", "config.json"),
|
||||||
|
home: path.join(tempRoot, ".paperclip-worktrees"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const envPath = path.join(repoRoot, ".paperclip", ".env");
|
||||||
|
const envContents = fs.readFileSync(envPath, "utf8");
|
||||||
|
expect(envContents).toContain("PAPERCLIP_AGENT_JWT_SECRET=worktree-shared-secret");
|
||||||
|
expect(envContents).toContain("PAPERCLIP_WORKTREE_NAME=repo");
|
||||||
|
expect(envContents).toMatch(/PAPERCLIP_WORKTREE_COLOR=\"#[0-9a-f]{6}\"/);
|
||||||
|
} finally {
|
||||||
|
process.chdir(originalCwd);
|
||||||
|
if (originalJwtSecret === undefined) {
|
||||||
|
delete process.env.PAPERCLIP_AGENT_JWT_SECRET;
|
||||||
|
} else {
|
||||||
|
process.env.PAPERCLIP_AGENT_JWT_SECRET = originalJwtSecret;
|
||||||
|
}
|
||||||
|
fs.rmSync(tempRoot, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("defaults the seed source config to the current repo-local Paperclip config", () => {
|
||||||
|
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-worktree-source-config-"));
|
||||||
|
const repoRoot = path.join(tempRoot, "repo");
|
||||||
|
const localConfigPath = path.join(repoRoot, ".paperclip", "config.json");
|
||||||
|
const originalCwd = process.cwd();
|
||||||
|
const originalPaperclipConfig = process.env.PAPERCLIP_CONFIG;
|
||||||
|
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(path.dirname(localConfigPath), { recursive: true });
|
||||||
|
fs.writeFileSync(localConfigPath, JSON.stringify(buildSourceConfig()), "utf8");
|
||||||
|
delete process.env.PAPERCLIP_CONFIG;
|
||||||
|
process.chdir(repoRoot);
|
||||||
|
|
||||||
|
expect(fs.realpathSync(resolveSourceConfigPath({}))).toBe(fs.realpathSync(localConfigPath));
|
||||||
|
} finally {
|
||||||
|
process.chdir(originalCwd);
|
||||||
|
if (originalPaperclipConfig === undefined) {
|
||||||
|
delete process.env.PAPERCLIP_CONFIG;
|
||||||
|
} else {
|
||||||
|
process.env.PAPERCLIP_CONFIG = originalPaperclipConfig;
|
||||||
|
}
|
||||||
|
fs.rmSync(tempRoot, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("preserves the source config path across worktree:make cwd changes", () => {
|
||||||
|
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "paperclip-worktree-source-override-"));
|
||||||
|
const sourceConfigPath = path.join(tempRoot, "source", "config.json");
|
||||||
|
const targetRoot = path.join(tempRoot, "target");
|
||||||
|
const originalCwd = process.cwd();
|
||||||
|
const originalPaperclipConfig = process.env.PAPERCLIP_CONFIG;
|
||||||
|
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(path.dirname(sourceConfigPath), { recursive: true });
|
||||||
|
fs.mkdirSync(targetRoot, { recursive: true });
|
||||||
|
fs.writeFileSync(sourceConfigPath, JSON.stringify(buildSourceConfig()), "utf8");
|
||||||
|
delete process.env.PAPERCLIP_CONFIG;
|
||||||
|
process.chdir(targetRoot);
|
||||||
|
|
||||||
|
expect(resolveSourceConfigPath({ sourceConfigPathOverride: sourceConfigPath })).toBe(
|
||||||
|
path.resolve(sourceConfigPath),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
process.chdir(originalCwd);
|
||||||
|
if (originalPaperclipConfig === undefined) {
|
||||||
|
delete process.env.PAPERCLIP_CONFIG;
|
||||||
|
} else {
|
||||||
|
process.env.PAPERCLIP_CONFIG = originalPaperclipConfig;
|
||||||
|
}
|
||||||
|
fs.rmSync(tempRoot, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it("rebinds same-repo workspace paths onto the current worktree root", () => {
|
it("rebinds same-repo workspace paths onto the current worktree root", () => {
|
||||||
expect(
|
expect(
|
||||||
rebindWorkspaceCwd({
|
rebindWorkspaceCwd({
|
||||||
@@ -293,7 +441,7 @@ describe("worktree helpers", () => {
|
|||||||
const fakeHome = path.join(tempRoot, "home");
|
const fakeHome = path.join(tempRoot, "home");
|
||||||
const worktreePath = path.join(fakeHome, "paperclip-make-test");
|
const worktreePath = path.join(fakeHome, "paperclip-make-test");
|
||||||
const originalCwd = process.cwd();
|
const originalCwd = process.cwd();
|
||||||
const originalHome = process.env.HOME;
|
const homedirSpy = vi.spyOn(os, "homedir").mockReturnValue(fakeHome);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
fs.mkdirSync(repoRoot, { recursive: true });
|
fs.mkdirSync(repoRoot, { recursive: true });
|
||||||
@@ -305,7 +453,6 @@ describe("worktree helpers", () => {
|
|||||||
execFileSync("git", ["add", "README.md"], { cwd: repoRoot, stdio: "ignore" });
|
execFileSync("git", ["add", "README.md"], { cwd: repoRoot, stdio: "ignore" });
|
||||||
execFileSync("git", ["commit", "-m", "Initial commit"], { cwd: repoRoot, stdio: "ignore" });
|
execFileSync("git", ["commit", "-m", "Initial commit"], { cwd: repoRoot, stdio: "ignore" });
|
||||||
|
|
||||||
process.env.HOME = fakeHome;
|
|
||||||
process.chdir(repoRoot);
|
process.chdir(repoRoot);
|
||||||
|
|
||||||
await worktreeMakeCommand("paperclip-make-test", {
|
await worktreeMakeCommand("paperclip-make-test", {
|
||||||
@@ -318,12 +465,8 @@ describe("worktree helpers", () => {
|
|||||||
expect(fs.existsSync(path.join(worktreePath, ".paperclip", ".env"))).toBe(true);
|
expect(fs.existsSync(path.join(worktreePath, ".paperclip", ".env"))).toBe(true);
|
||||||
} finally {
|
} finally {
|
||||||
process.chdir(originalCwd);
|
process.chdir(originalCwd);
|
||||||
if (originalHome === undefined) {
|
homedirSpy.mockRestore();
|
||||||
delete process.env.HOME;
|
|
||||||
} else {
|
|
||||||
process.env.HOME = originalHome;
|
|
||||||
}
|
|
||||||
fs.rmSync(tempRoot, { recursive: true, force: true });
|
fs.rmSync(tempRoot, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
}, 20_000);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { CLIAdapterModule } from "@paperclipai/adapter-utils";
|
|||||||
import { printClaudeStreamEvent } from "@paperclipai/adapter-claude-local/cli";
|
import { printClaudeStreamEvent } from "@paperclipai/adapter-claude-local/cli";
|
||||||
import { printCodexStreamEvent } from "@paperclipai/adapter-codex-local/cli";
|
import { printCodexStreamEvent } from "@paperclipai/adapter-codex-local/cli";
|
||||||
import { printCursorStreamEvent } from "@paperclipai/adapter-cursor-local/cli";
|
import { printCursorStreamEvent } from "@paperclipai/adapter-cursor-local/cli";
|
||||||
|
import { printGeminiStreamEvent } from "@paperclipai/adapter-gemini-local/cli";
|
||||||
import { printOpenCodeStreamEvent } from "@paperclipai/adapter-opencode-local/cli";
|
import { printOpenCodeStreamEvent } from "@paperclipai/adapter-opencode-local/cli";
|
||||||
import { printPiStreamEvent } from "@paperclipai/adapter-pi-local/cli";
|
import { printPiStreamEvent } from "@paperclipai/adapter-pi-local/cli";
|
||||||
import { printOpenClawGatewayStreamEvent } from "@paperclipai/adapter-openclaw-gateway/cli";
|
import { printOpenClawGatewayStreamEvent } from "@paperclipai/adapter-openclaw-gateway/cli";
|
||||||
@@ -33,6 +34,11 @@ const cursorLocalCLIAdapter: CLIAdapterModule = {
|
|||||||
formatStdoutEvent: printCursorStreamEvent,
|
formatStdoutEvent: printCursorStreamEvent,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const geminiLocalCLIAdapter: CLIAdapterModule = {
|
||||||
|
type: "gemini_local",
|
||||||
|
formatStdoutEvent: printGeminiStreamEvent,
|
||||||
|
};
|
||||||
|
|
||||||
const openclawGatewayCLIAdapter: CLIAdapterModule = {
|
const openclawGatewayCLIAdapter: CLIAdapterModule = {
|
||||||
type: "openclaw_gateway",
|
type: "openclaw_gateway",
|
||||||
formatStdoutEvent: printOpenClawGatewayStreamEvent,
|
formatStdoutEvent: printOpenClawGatewayStreamEvent,
|
||||||
@@ -45,6 +51,7 @@ const adaptersByType = new Map<string, CLIAdapterModule>(
|
|||||||
openCodeLocalCLIAdapter,
|
openCodeLocalCLIAdapter,
|
||||||
piLocalCLIAdapter,
|
piLocalCLIAdapter,
|
||||||
cursorLocalCLIAdapter,
|
cursorLocalCLIAdapter,
|
||||||
|
geminiLocalCLIAdapter,
|
||||||
openclawGatewayCLIAdapter,
|
openclawGatewayCLIAdapter,
|
||||||
processCLIAdapter,
|
processCLIAdapter,
|
||||||
httpCLIAdapter,
|
httpCLIAdapter,
|
||||||
|
|||||||
@@ -26,6 +26,9 @@ export async function addAllowedHostname(host: string, opts: { config?: string }
|
|||||||
p.log.info(`Hostname ${pc.cyan(normalized)} is already allowed.`);
|
p.log.info(`Hostname ${pc.cyan(normalized)} is already allowed.`);
|
||||||
} else {
|
} else {
|
||||||
p.log.success(`Added allowed hostname: ${pc.cyan(normalized)}`);
|
p.log.success(`Added allowed hostname: ${pc.cyan(normalized)}`);
|
||||||
|
p.log.message(
|
||||||
|
pc.dim("Restart the Paperclip server for this change to take effect."),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(config.server.deploymentMode === "authenticated" && config.server.exposure === "private")) {
|
if (!(config.server.deploymentMode === "authenticated" && config.server.exposure === "private")) {
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { Command } from "commander";
|
import { Command } from "commander";
|
||||||
import type { Agent } from "@paperclipai/shared";
|
import type { Agent } from "@paperclipai/shared";
|
||||||
|
import {
|
||||||
|
removeMaintainerOnlySkillSymlinks,
|
||||||
|
resolvePaperclipSkillsDir,
|
||||||
|
} from "@paperclipai/adapter-utils/server-utils";
|
||||||
import fs from "node:fs/promises";
|
import fs from "node:fs/promises";
|
||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
@@ -34,15 +38,12 @@ interface SkillsInstallSummary {
|
|||||||
tool: "codex" | "claude";
|
tool: "codex" | "claude";
|
||||||
target: string;
|
target: string;
|
||||||
linked: string[];
|
linked: string[];
|
||||||
|
removed: string[];
|
||||||
skipped: string[];
|
skipped: string[];
|
||||||
failed: Array<{ name: string; error: string }>;
|
failed: Array<{ name: string; error: string }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
||||||
const PAPERCLIP_SKILLS_CANDIDATES = [
|
|
||||||
path.resolve(__moduleDir, "../../../../../skills"), // dev: cli/src/commands/client -> repo root/skills
|
|
||||||
path.resolve(process.cwd(), "skills"),
|
|
||||||
];
|
|
||||||
|
|
||||||
function codexSkillsHome(): string {
|
function codexSkillsHome(): string {
|
||||||
const fromEnv = process.env.CODEX_HOME?.trim();
|
const fromEnv = process.env.CODEX_HOME?.trim();
|
||||||
@@ -56,14 +57,6 @@ function claudeSkillsHome(): string {
|
|||||||
return path.join(base, "skills");
|
return path.join(base, "skills");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function resolvePaperclipSkillsDir(): Promise<string | null> {
|
|
||||||
for (const candidate of PAPERCLIP_SKILLS_CANDIDATES) {
|
|
||||||
const isDir = await fs.stat(candidate).then((s) => s.isDirectory()).catch(() => false);
|
|
||||||
if (isDir) return candidate;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function installSkillsForTarget(
|
async function installSkillsForTarget(
|
||||||
sourceSkillsDir: string,
|
sourceSkillsDir: string,
|
||||||
targetSkillsDir: string,
|
targetSkillsDir: string,
|
||||||
@@ -73,20 +66,65 @@ async function installSkillsForTarget(
|
|||||||
tool,
|
tool,
|
||||||
target: targetSkillsDir,
|
target: targetSkillsDir,
|
||||||
linked: [],
|
linked: [],
|
||||||
|
removed: [],
|
||||||
skipped: [],
|
skipped: [],
|
||||||
failed: [],
|
failed: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
await fs.mkdir(targetSkillsDir, { recursive: true });
|
await fs.mkdir(targetSkillsDir, { recursive: true });
|
||||||
const entries = await fs.readdir(sourceSkillsDir, { withFileTypes: true });
|
const entries = await fs.readdir(sourceSkillsDir, { withFileTypes: true });
|
||||||
|
summary.removed = await removeMaintainerOnlySkillSymlinks(
|
||||||
|
targetSkillsDir,
|
||||||
|
entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name),
|
||||||
|
);
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
if (!entry.isDirectory()) continue;
|
if (!entry.isDirectory()) continue;
|
||||||
const source = path.join(sourceSkillsDir, entry.name);
|
const source = path.join(sourceSkillsDir, entry.name);
|
||||||
const target = path.join(targetSkillsDir, entry.name);
|
const target = path.join(targetSkillsDir, entry.name);
|
||||||
const existing = await fs.lstat(target).catch(() => null);
|
const existing = await fs.lstat(target).catch(() => null);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
summary.skipped.push(entry.name);
|
if (existing.isSymbolicLink()) {
|
||||||
continue;
|
let linkedPath: string | null = null;
|
||||||
|
try {
|
||||||
|
linkedPath = await fs.readlink(target);
|
||||||
|
} catch (err) {
|
||||||
|
await fs.unlink(target);
|
||||||
|
try {
|
||||||
|
await fs.symlink(source, target);
|
||||||
|
summary.linked.push(entry.name);
|
||||||
|
continue;
|
||||||
|
} catch (linkErr) {
|
||||||
|
summary.failed.push({
|
||||||
|
name: entry.name,
|
||||||
|
error:
|
||||||
|
err instanceof Error && linkErr instanceof Error
|
||||||
|
? `${err.message}; then ${linkErr.message}`
|
||||||
|
: err instanceof Error
|
||||||
|
? err.message
|
||||||
|
: `Failed to recover broken symlink: ${String(err)}`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const resolvedLinkedPath = path.isAbsolute(linkedPath)
|
||||||
|
? linkedPath
|
||||||
|
: path.resolve(path.dirname(target), linkedPath);
|
||||||
|
const linkedTargetExists = await fs
|
||||||
|
.stat(resolvedLinkedPath)
|
||||||
|
.then(() => true)
|
||||||
|
.catch(() => false);
|
||||||
|
|
||||||
|
if (!linkedTargetExists) {
|
||||||
|
await fs.unlink(target);
|
||||||
|
} else {
|
||||||
|
summary.skipped.push(entry.name);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
summary.skipped.push(entry.name);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -210,7 +248,7 @@ export function registerAgentCommands(program: Command): void {
|
|||||||
|
|
||||||
const installSummaries: SkillsInstallSummary[] = [];
|
const installSummaries: SkillsInstallSummary[] = [];
|
||||||
if (opts.installSkills !== false) {
|
if (opts.installSkills !== false) {
|
||||||
const skillsDir = await resolvePaperclipSkillsDir();
|
const skillsDir = await resolvePaperclipSkillsDir(__moduleDir, [path.resolve(process.cwd(), "skills")]);
|
||||||
if (!skillsDir) {
|
if (!skillsDir) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"Could not locate local Paperclip skills directory. Expected ./skills in the repo checkout.",
|
"Could not locate local Paperclip skills directory. Expected ./skills in the repo checkout.",
|
||||||
@@ -258,7 +296,7 @@ export function registerAgentCommands(program: Command): void {
|
|||||||
if (installSummaries.length > 0) {
|
if (installSummaries.length > 0) {
|
||||||
for (const summary of installSummaries) {
|
for (const summary of installSummaries) {
|
||||||
console.log(
|
console.log(
|
||||||
`${summary.tool}: linked=${summary.linked.length} skipped=${summary.skipped.length} failed=${summary.failed.length} target=${summary.target}`,
|
`${summary.tool}: linked=${summary.linked.length} removed=${summary.removed.length} skipped=${summary.skipped.length} failed=${summary.failed.length} target=${summary.target}`,
|
||||||
);
|
);
|
||||||
for (const failed of summary.failed) {
|
for (const failed of summary.failed) {
|
||||||
console.log(` failed ${failed.name}: ${failed.error}`);
|
console.log(` failed ${failed.name}: ${failed.error}`);
|
||||||
|
|||||||
374
cli/src/commands/client/plugin.ts
Normal file
374
cli/src/commands/client/plugin.ts
Normal file
@@ -0,0 +1,374 @@
|
|||||||
|
import path from "node:path";
|
||||||
|
import { Command } from "commander";
|
||||||
|
import pc from "picocolors";
|
||||||
|
import {
|
||||||
|
addCommonClientOptions,
|
||||||
|
handleCommandError,
|
||||||
|
printOutput,
|
||||||
|
resolveCommandContext,
|
||||||
|
type BaseClientOptions,
|
||||||
|
} from "./common.js";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Types mirroring server-side shapes
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
interface PluginRecord {
|
||||||
|
id: string;
|
||||||
|
pluginKey: string;
|
||||||
|
packageName: string;
|
||||||
|
version: string;
|
||||||
|
status: string;
|
||||||
|
displayName?: string;
|
||||||
|
lastError?: string | null;
|
||||||
|
installedAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Option types
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
interface PluginListOptions extends BaseClientOptions {
|
||||||
|
status?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PluginInstallOptions extends BaseClientOptions {
|
||||||
|
local?: boolean;
|
||||||
|
version?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PluginUninstallOptions extends BaseClientOptions {
|
||||||
|
force?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a local path argument to an absolute path so the server can find the
|
||||||
|
* plugin on disk regardless of where the user ran the CLI.
|
||||||
|
*/
|
||||||
|
function resolvePackageArg(packageArg: string, isLocal: boolean): string {
|
||||||
|
if (!isLocal) return packageArg;
|
||||||
|
// Already absolute
|
||||||
|
if (path.isAbsolute(packageArg)) return packageArg;
|
||||||
|
// Expand leading ~ to home directory
|
||||||
|
if (packageArg.startsWith("~")) {
|
||||||
|
const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
|
||||||
|
return path.resolve(home, packageArg.slice(1).replace(/^[\\/]/, ""));
|
||||||
|
}
|
||||||
|
return path.resolve(process.cwd(), packageArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatPlugin(p: PluginRecord): string {
|
||||||
|
const statusColor =
|
||||||
|
p.status === "ready"
|
||||||
|
? pc.green(p.status)
|
||||||
|
: p.status === "error"
|
||||||
|
? pc.red(p.status)
|
||||||
|
: p.status === "disabled"
|
||||||
|
? pc.dim(p.status)
|
||||||
|
: pc.yellow(p.status);
|
||||||
|
|
||||||
|
const parts = [
|
||||||
|
`key=${pc.bold(p.pluginKey)}`,
|
||||||
|
`status=${statusColor}`,
|
||||||
|
`version=${p.version}`,
|
||||||
|
`id=${pc.dim(p.id)}`,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (p.lastError) {
|
||||||
|
parts.push(`error=${pc.red(p.lastError.slice(0, 80))}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return parts.join(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Command registration
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export function registerPluginCommands(program: Command): void {
|
||||||
|
const plugin = program.command("plugin").description("Plugin lifecycle management");
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// plugin list
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
addCommonClientOptions(
|
||||||
|
plugin
|
||||||
|
.command("list")
|
||||||
|
.description("List installed plugins")
|
||||||
|
.option("--status <status>", "Filter by status (ready, error, disabled, installed, upgrade_pending)")
|
||||||
|
.action(async (opts: PluginListOptions) => {
|
||||||
|
try {
|
||||||
|
const ctx = resolveCommandContext(opts);
|
||||||
|
const qs = opts.status ? `?status=${encodeURIComponent(opts.status)}` : "";
|
||||||
|
const plugins = await ctx.api.get<PluginRecord[]>(`/api/plugins${qs}`);
|
||||||
|
|
||||||
|
if (ctx.json) {
|
||||||
|
printOutput(plugins, { json: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = plugins ?? [];
|
||||||
|
if (rows.length === 0) {
|
||||||
|
console.log(pc.dim("No plugins installed."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const p of rows) {
|
||||||
|
console.log(formatPlugin(p));
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
handleCommandError(err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// plugin install <package-or-path>
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
addCommonClientOptions(
|
||||||
|
plugin
|
||||||
|
.command("install <package>")
|
||||||
|
.description(
|
||||||
|
"Install a plugin from a local path or npm package.\n" +
|
||||||
|
" Examples:\n" +
|
||||||
|
" paperclipai plugin install ./my-plugin # local path\n" +
|
||||||
|
" paperclipai plugin install @acme/plugin-linear # npm package\n" +
|
||||||
|
" paperclipai plugin install @acme/plugin-linear@1.2 # pinned version",
|
||||||
|
)
|
||||||
|
.option("-l, --local", "Treat <package> as a local filesystem path", false)
|
||||||
|
.option("--version <version>", "Specific npm version to install (npm packages only)")
|
||||||
|
.action(async (packageArg: string, opts: PluginInstallOptions) => {
|
||||||
|
try {
|
||||||
|
const ctx = resolveCommandContext(opts);
|
||||||
|
|
||||||
|
// Auto-detect local paths: starts with . or / or ~ or is an absolute path
|
||||||
|
const isLocal =
|
||||||
|
opts.local ||
|
||||||
|
packageArg.startsWith("./") ||
|
||||||
|
packageArg.startsWith("../") ||
|
||||||
|
packageArg.startsWith("/") ||
|
||||||
|
packageArg.startsWith("~");
|
||||||
|
|
||||||
|
const resolvedPackage = resolvePackageArg(packageArg, isLocal);
|
||||||
|
|
||||||
|
if (!ctx.json) {
|
||||||
|
console.log(
|
||||||
|
pc.dim(
|
||||||
|
isLocal
|
||||||
|
? `Installing plugin from local path: ${resolvedPackage}`
|
||||||
|
: `Installing plugin: ${resolvedPackage}${opts.version ? `@${opts.version}` : ""}`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const installedPlugin = await ctx.api.post<PluginRecord>("/api/plugins/install", {
|
||||||
|
packageName: resolvedPackage,
|
||||||
|
version: opts.version,
|
||||||
|
isLocalPath: isLocal,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (ctx.json) {
|
||||||
|
printOutput(installedPlugin, { json: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!installedPlugin) {
|
||||||
|
console.log(pc.dim("Install returned no plugin record."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
pc.green(
|
||||||
|
`✓ Installed ${pc.bold(installedPlugin.pluginKey)} v${installedPlugin.version} (${installedPlugin.status})`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (installedPlugin.lastError) {
|
||||||
|
console.log(pc.red(` Warning: ${installedPlugin.lastError}`));
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
handleCommandError(err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// plugin uninstall <plugin-key-or-id>
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
addCommonClientOptions(
|
||||||
|
plugin
|
||||||
|
.command("uninstall <pluginKey>")
|
||||||
|
.description(
|
||||||
|
"Uninstall a plugin by its plugin key or database ID.\n" +
|
||||||
|
" Use --force to hard-purge all state and config.",
|
||||||
|
)
|
||||||
|
.option("--force", "Purge all plugin state and config (hard delete)", false)
|
||||||
|
.action(async (pluginKey: string, opts: PluginUninstallOptions) => {
|
||||||
|
try {
|
||||||
|
const ctx = resolveCommandContext(opts);
|
||||||
|
const purge = opts.force === true;
|
||||||
|
const qs = purge ? "?purge=true" : "";
|
||||||
|
|
||||||
|
if (!ctx.json) {
|
||||||
|
console.log(
|
||||||
|
pc.dim(
|
||||||
|
purge
|
||||||
|
? `Uninstalling and purging plugin: ${pluginKey}`
|
||||||
|
: `Uninstalling plugin: ${pluginKey}`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await ctx.api.delete<PluginRecord | null>(
|
||||||
|
`/api/plugins/${encodeURIComponent(pluginKey)}${qs}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (ctx.json) {
|
||||||
|
printOutput(result, { json: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(pc.green(`✓ Uninstalled ${pc.bold(pluginKey)}${purge ? " (purged)" : ""}`));
|
||||||
|
} catch (err) {
|
||||||
|
handleCommandError(err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// plugin enable <plugin-key-or-id>
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
addCommonClientOptions(
|
||||||
|
plugin
|
||||||
|
.command("enable <pluginKey>")
|
||||||
|
.description("Enable a disabled or errored plugin")
|
||||||
|
.action(async (pluginKey: string, opts: BaseClientOptions) => {
|
||||||
|
try {
|
||||||
|
const ctx = resolveCommandContext(opts);
|
||||||
|
const result = await ctx.api.post<PluginRecord>(
|
||||||
|
`/api/plugins/${encodeURIComponent(pluginKey)}/enable`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (ctx.json) {
|
||||||
|
printOutput(result, { json: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(pc.green(`✓ Enabled ${pc.bold(pluginKey)} — status: ${result?.status ?? "unknown"}`));
|
||||||
|
} catch (err) {
|
||||||
|
handleCommandError(err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// plugin disable <plugin-key-or-id>
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
addCommonClientOptions(
|
||||||
|
plugin
|
||||||
|
.command("disable <pluginKey>")
|
||||||
|
.description("Disable a running plugin without uninstalling it")
|
||||||
|
.action(async (pluginKey: string, opts: BaseClientOptions) => {
|
||||||
|
try {
|
||||||
|
const ctx = resolveCommandContext(opts);
|
||||||
|
const result = await ctx.api.post<PluginRecord>(
|
||||||
|
`/api/plugins/${encodeURIComponent(pluginKey)}/disable`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (ctx.json) {
|
||||||
|
printOutput(result, { json: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(pc.dim(`Disabled ${pc.bold(pluginKey)} — status: ${result?.status ?? "unknown"}`));
|
||||||
|
} catch (err) {
|
||||||
|
handleCommandError(err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// plugin inspect <plugin-key-or-id>
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
addCommonClientOptions(
|
||||||
|
plugin
|
||||||
|
.command("inspect <pluginKey>")
|
||||||
|
.description("Show full details for an installed plugin")
|
||||||
|
.action(async (pluginKey: string, opts: BaseClientOptions) => {
|
||||||
|
try {
|
||||||
|
const ctx = resolveCommandContext(opts);
|
||||||
|
const result = await ctx.api.get<PluginRecord>(
|
||||||
|
`/api/plugins/${encodeURIComponent(pluginKey)}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (ctx.json) {
|
||||||
|
printOutput(result, { json: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
console.log(pc.red(`Plugin not found: ${pluginKey}`));
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(formatPlugin(result));
|
||||||
|
if (result.lastError) {
|
||||||
|
console.log(`\n${pc.red("Last error:")}\n${result.lastError}`);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
handleCommandError(err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// plugin examples
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
addCommonClientOptions(
|
||||||
|
plugin
|
||||||
|
.command("examples")
|
||||||
|
.description("List bundled example plugins available for local install")
|
||||||
|
.action(async (opts: BaseClientOptions) => {
|
||||||
|
try {
|
||||||
|
const ctx = resolveCommandContext(opts);
|
||||||
|
const examples = await ctx.api.get<
|
||||||
|
Array<{
|
||||||
|
packageName: string;
|
||||||
|
pluginKey: string;
|
||||||
|
displayName: string;
|
||||||
|
description: string;
|
||||||
|
localPath: string;
|
||||||
|
tag: string;
|
||||||
|
}>
|
||||||
|
>("/api/plugins/examples");
|
||||||
|
|
||||||
|
if (ctx.json) {
|
||||||
|
printOutput(examples, { json: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = examples ?? [];
|
||||||
|
if (rows.length === 0) {
|
||||||
|
console.log(pc.dim("No bundled examples available."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const ex of rows) {
|
||||||
|
console.log(
|
||||||
|
`${pc.bold(ex.displayName)} ${pc.dim(ex.pluginKey)}\n` +
|
||||||
|
` ${ex.description}\n` +
|
||||||
|
` ${pc.cyan(`paperclipai plugin install ${ex.localPath}`)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
handleCommandError(err);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { randomInt } from "node:crypto";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import type { PaperclipConfig } from "../config/schema.js";
|
import type { PaperclipConfig } from "../config/schema.js";
|
||||||
import { expandHomePrefix } from "../config/home.js";
|
import { expandHomePrefix } from "../config/home.js";
|
||||||
@@ -44,6 +45,11 @@ export type WorktreeLocalPaths = {
|
|||||||
storageDir: string;
|
storageDir: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type WorktreeUiBranding = {
|
||||||
|
name: string;
|
||||||
|
color: string;
|
||||||
|
};
|
||||||
|
|
||||||
export function isWorktreeSeedMode(value: string): value is WorktreeSeedMode {
|
export function isWorktreeSeedMode(value: string): value is WorktreeSeedMode {
|
||||||
return (WORKTREE_SEED_MODES as readonly string[]).includes(value);
|
return (WORKTREE_SEED_MODES as readonly string[]).includes(value);
|
||||||
}
|
}
|
||||||
@@ -87,6 +93,51 @@ export function resolveSuggestedWorktreeName(cwd: string, explicitName?: string)
|
|||||||
return nonEmpty(explicitName) ?? path.basename(path.resolve(cwd));
|
return nonEmpty(explicitName) ?? path.basename(path.resolve(cwd));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function hslComponentToHex(n: number): string {
|
||||||
|
return Math.round(Math.max(0, Math.min(255, n)))
|
||||||
|
.toString(16)
|
||||||
|
.padStart(2, "0");
|
||||||
|
}
|
||||||
|
|
||||||
|
function hslToHex(hue: number, saturation: number, lightness: number): string {
|
||||||
|
const s = Math.max(0, Math.min(100, saturation)) / 100;
|
||||||
|
const l = Math.max(0, Math.min(100, lightness)) / 100;
|
||||||
|
const c = (1 - Math.abs((2 * l) - 1)) * s;
|
||||||
|
const h = ((hue % 360) + 360) % 360;
|
||||||
|
const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
|
||||||
|
const m = l - (c / 2);
|
||||||
|
|
||||||
|
let r = 0;
|
||||||
|
let g = 0;
|
||||||
|
let b = 0;
|
||||||
|
|
||||||
|
if (h < 60) {
|
||||||
|
r = c;
|
||||||
|
g = x;
|
||||||
|
} else if (h < 120) {
|
||||||
|
r = x;
|
||||||
|
g = c;
|
||||||
|
} else if (h < 180) {
|
||||||
|
g = c;
|
||||||
|
b = x;
|
||||||
|
} else if (h < 240) {
|
||||||
|
g = x;
|
||||||
|
b = c;
|
||||||
|
} else if (h < 300) {
|
||||||
|
r = x;
|
||||||
|
b = c;
|
||||||
|
} else {
|
||||||
|
r = c;
|
||||||
|
b = x;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `#${hslComponentToHex((r + m) * 255)}${hslComponentToHex((g + m) * 255)}${hslComponentToHex((b + m) * 255)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function generateWorktreeColor(): string {
|
||||||
|
return hslToHex(randomInt(0, 360), 68, 56);
|
||||||
|
}
|
||||||
|
|
||||||
export function resolveWorktreeLocalPaths(opts: {
|
export function resolveWorktreeLocalPaths(opts: {
|
||||||
cwd: string;
|
cwd: string;
|
||||||
homeDir?: string;
|
homeDir?: string;
|
||||||
@@ -196,13 +247,18 @@ export function buildWorktreeConfig(input: {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildWorktreeEnvEntries(paths: WorktreeLocalPaths): Record<string, string> {
|
export function buildWorktreeEnvEntries(
|
||||||
|
paths: WorktreeLocalPaths,
|
||||||
|
branding?: WorktreeUiBranding,
|
||||||
|
): Record<string, string> {
|
||||||
return {
|
return {
|
||||||
PAPERCLIP_HOME: paths.homeDir,
|
PAPERCLIP_HOME: paths.homeDir,
|
||||||
PAPERCLIP_INSTANCE_ID: paths.instanceId,
|
PAPERCLIP_INSTANCE_ID: paths.instanceId,
|
||||||
PAPERCLIP_CONFIG: paths.configPath,
|
PAPERCLIP_CONFIG: paths.configPath,
|
||||||
PAPERCLIP_CONTEXT: paths.contextPath,
|
PAPERCLIP_CONTEXT: paths.contextPath,
|
||||||
PAPERCLIP_IN_WORKTREE: "true",
|
PAPERCLIP_IN_WORKTREE: "true",
|
||||||
|
...(branding?.name ? { PAPERCLIP_WORKTREE_NAME: branding.name } : {}),
|
||||||
|
...(branding?.color ? { PAPERCLIP_WORKTREE_COLOR: branding.color } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ import {
|
|||||||
buildWorktreeEnvEntries,
|
buildWorktreeEnvEntries,
|
||||||
DEFAULT_WORKTREE_HOME,
|
DEFAULT_WORKTREE_HOME,
|
||||||
formatShellExports,
|
formatShellExports,
|
||||||
|
generateWorktreeColor,
|
||||||
isWorktreeSeedMode,
|
isWorktreeSeedMode,
|
||||||
resolveSuggestedWorktreeName,
|
resolveSuggestedWorktreeName,
|
||||||
resolveWorktreeSeedPlan,
|
resolveWorktreeSeedPlan,
|
||||||
@@ -55,6 +56,7 @@ type WorktreeInitOptions = {
|
|||||||
fromConfig?: string;
|
fromConfig?: string;
|
||||||
fromDataDir?: string;
|
fromDataDir?: string;
|
||||||
fromInstance?: string;
|
fromInstance?: string;
|
||||||
|
sourceConfigPathOverride?: string;
|
||||||
serverPort?: number;
|
serverPort?: number;
|
||||||
dbPort?: number;
|
dbPort?: number;
|
||||||
seed?: boolean;
|
seed?: boolean;
|
||||||
@@ -62,7 +64,9 @@ type WorktreeInitOptions = {
|
|||||||
force?: boolean;
|
force?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
type WorktreeMakeOptions = WorktreeInitOptions;
|
type WorktreeMakeOptions = WorktreeInitOptions & {
|
||||||
|
startPoint?: string;
|
||||||
|
};
|
||||||
|
|
||||||
type WorktreeEnvOptions = {
|
type WorktreeEnvOptions = {
|
||||||
config?: string;
|
config?: string;
|
||||||
@@ -81,6 +85,7 @@ type EmbeddedPostgresCtor = new (opts: {
|
|||||||
password: string;
|
password: string;
|
||||||
port: number;
|
port: number;
|
||||||
persistent: boolean;
|
persistent: boolean;
|
||||||
|
initdbFlags?: string[];
|
||||||
onLog?: (message: unknown) => void;
|
onLog?: (message: unknown) => void;
|
||||||
onError?: (message: unknown) => void;
|
onError?: (message: unknown) => void;
|
||||||
}) => EmbeddedPostgresInstance;
|
}) => EmbeddedPostgresInstance;
|
||||||
@@ -117,6 +122,16 @@ function nonEmpty(value: string | null | undefined): string | null {
|
|||||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isCurrentSourceConfigPath(sourceConfigPath: string): boolean {
|
||||||
|
const currentConfigPath = process.env.PAPERCLIP_CONFIG;
|
||||||
|
if (!currentConfigPath || currentConfigPath.trim().length === 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return path.resolve(currentConfigPath) === path.resolve(sourceConfigPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
const WORKTREE_NAME_PREFIX = "paperclip-";
|
||||||
|
|
||||||
function resolveWorktreeMakeName(name: string): string {
|
function resolveWorktreeMakeName(name: string): string {
|
||||||
const value = nonEmpty(name);
|
const value = nonEmpty(name);
|
||||||
if (!value) {
|
if (!value) {
|
||||||
@@ -127,7 +142,15 @@ function resolveWorktreeMakeName(name: string): string {
|
|||||||
"Worktree name must contain only letters, numbers, dots, underscores, or dashes.",
|
"Worktree name must contain only letters, numbers, dots, underscores, or dashes.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return value;
|
return value.startsWith(WORKTREE_NAME_PREFIX) ? value : `${WORKTREE_NAME_PREFIX}${value}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveWorktreeHome(explicit?: string): string {
|
||||||
|
return explicit ?? process.env.PAPERCLIP_WORKTREES_DIR ?? DEFAULT_WORKTREE_HOME;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveWorktreeStartPoint(explicit?: string): string | undefined {
|
||||||
|
return explicit ?? nonEmpty(process.env.PAPERCLIP_WORKTREE_START_POINT) ?? undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveWorktreeMakeTargetPath(name: string): string {
|
export function resolveWorktreeMakeTargetPath(name: string): string {
|
||||||
@@ -166,11 +189,13 @@ export function resolveGitWorktreeAddArgs(input: {
|
|||||||
branchName: string;
|
branchName: string;
|
||||||
targetPath: string;
|
targetPath: string;
|
||||||
branchExists: boolean;
|
branchExists: boolean;
|
||||||
|
startPoint?: string;
|
||||||
}): string[] {
|
}): string[] {
|
||||||
if (input.branchExists) {
|
if (input.branchExists && !input.startPoint) {
|
||||||
return ["worktree", "add", input.targetPath, input.branchName];
|
return ["worktree", "add", input.targetPath, input.branchName];
|
||||||
}
|
}
|
||||||
return ["worktree", "add", "-b", input.branchName, input.targetPath, "HEAD"];
|
const commitish = input.startPoint ?? "HEAD";
|
||||||
|
return ["worktree", "add", "-b", input.branchName, input.targetPath, commitish];
|
||||||
}
|
}
|
||||||
|
|
||||||
function readPidFilePort(postmasterPidFile: string): number | null {
|
function readPidFilePort(postmasterPidFile: string): number | null {
|
||||||
@@ -402,8 +427,12 @@ async function rebindSeededProjectWorkspaces(input: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveSourceConfigPath(opts: WorktreeInitOptions): string {
|
export function resolveSourceConfigPath(opts: WorktreeInitOptions): string {
|
||||||
|
if (opts.sourceConfigPathOverride) return path.resolve(opts.sourceConfigPathOverride);
|
||||||
if (opts.fromConfig) return path.resolve(opts.fromConfig);
|
if (opts.fromConfig) return path.resolve(opts.fromConfig);
|
||||||
|
if (!opts.fromDataDir && !opts.fromInstance) {
|
||||||
|
return resolveConfigPath();
|
||||||
|
}
|
||||||
const sourceHome = path.resolve(expandHomePrefix(opts.fromDataDir ?? "~/.paperclip"));
|
const sourceHome = path.resolve(expandHomePrefix(opts.fromDataDir ?? "~/.paperclip"));
|
||||||
const sourceInstanceId = sanitizeWorktreeInstanceId(opts.fromInstance ?? "default");
|
const sourceInstanceId = sanitizeWorktreeInstanceId(opts.fromInstance ?? "default");
|
||||||
return path.resolve(sourceHome, "instances", sourceInstanceId, "config.json");
|
return path.resolve(sourceHome, "instances", sourceInstanceId, "config.json");
|
||||||
@@ -436,9 +465,10 @@ export function copySeededSecretsKey(input: {
|
|||||||
|
|
||||||
mkdirSync(path.dirname(input.targetKeyFilePath), { recursive: true });
|
mkdirSync(path.dirname(input.targetKeyFilePath), { recursive: true });
|
||||||
|
|
||||||
|
const allowProcessEnvFallback = isCurrentSourceConfigPath(input.sourceConfigPath);
|
||||||
const sourceInlineMasterKey =
|
const sourceInlineMasterKey =
|
||||||
nonEmpty(input.sourceEnvEntries.PAPERCLIP_SECRETS_MASTER_KEY) ??
|
nonEmpty(input.sourceEnvEntries.PAPERCLIP_SECRETS_MASTER_KEY) ??
|
||||||
nonEmpty(process.env.PAPERCLIP_SECRETS_MASTER_KEY);
|
(allowProcessEnvFallback ? nonEmpty(process.env.PAPERCLIP_SECRETS_MASTER_KEY) : null);
|
||||||
if (sourceInlineMasterKey) {
|
if (sourceInlineMasterKey) {
|
||||||
writeFileSync(input.targetKeyFilePath, sourceInlineMasterKey, {
|
writeFileSync(input.targetKeyFilePath, sourceInlineMasterKey, {
|
||||||
encoding: "utf8",
|
encoding: "utf8",
|
||||||
@@ -454,7 +484,7 @@ export function copySeededSecretsKey(input: {
|
|||||||
|
|
||||||
const sourceKeyFileOverride =
|
const sourceKeyFileOverride =
|
||||||
nonEmpty(input.sourceEnvEntries.PAPERCLIP_SECRETS_MASTER_KEY_FILE) ??
|
nonEmpty(input.sourceEnvEntries.PAPERCLIP_SECRETS_MASTER_KEY_FILE) ??
|
||||||
nonEmpty(process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE);
|
(allowProcessEnvFallback ? nonEmpty(process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE) : null);
|
||||||
const sourceConfiguredKeyPath = sourceKeyFileOverride ?? input.sourceConfig.secrets.localEncrypted.keyFilePath;
|
const sourceConfiguredKeyPath = sourceKeyFileOverride ?? input.sourceConfig.secrets.localEncrypted.keyFilePath;
|
||||||
const sourceKeyFilePath = resolveRuntimeLikePath(sourceConfiguredKeyPath, input.sourceConfigPath);
|
const sourceKeyFilePath = resolveRuntimeLikePath(sourceConfiguredKeyPath, input.sourceConfigPath);
|
||||||
|
|
||||||
@@ -501,6 +531,7 @@ async function ensureEmbeddedPostgres(dataDir: string, preferredPort: number): P
|
|||||||
password: "paperclip",
|
password: "paperclip",
|
||||||
port,
|
port,
|
||||||
persistent: true,
|
persistent: true,
|
||||||
|
initdbFlags: ["--encoding=UTF8", "--locale=C"],
|
||||||
onLog: () => {},
|
onLog: () => {},
|
||||||
onError: () => {},
|
onError: () => {},
|
||||||
});
|
});
|
||||||
@@ -598,7 +629,7 @@ async function seedWorktreeDatabase(input: {
|
|||||||
|
|
||||||
async function runWorktreeInit(opts: WorktreeInitOptions): Promise<void> {
|
async function runWorktreeInit(opts: WorktreeInitOptions): Promise<void> {
|
||||||
const cwd = process.cwd();
|
const cwd = process.cwd();
|
||||||
const name = resolveSuggestedWorktreeName(
|
const worktreeName = resolveSuggestedWorktreeName(
|
||||||
cwd,
|
cwd,
|
||||||
opts.name ?? detectGitBranchName(cwd) ?? undefined,
|
opts.name ?? detectGitBranchName(cwd) ?? undefined,
|
||||||
);
|
);
|
||||||
@@ -606,12 +637,16 @@ async function runWorktreeInit(opts: WorktreeInitOptions): Promise<void> {
|
|||||||
if (!isWorktreeSeedMode(seedMode)) {
|
if (!isWorktreeSeedMode(seedMode)) {
|
||||||
throw new Error(`Unsupported seed mode "${seedMode}". Expected one of: minimal, full.`);
|
throw new Error(`Unsupported seed mode "${seedMode}". Expected one of: minimal, full.`);
|
||||||
}
|
}
|
||||||
const instanceId = sanitizeWorktreeInstanceId(opts.instance ?? name);
|
const instanceId = sanitizeWorktreeInstanceId(opts.instance ?? worktreeName);
|
||||||
const paths = resolveWorktreeLocalPaths({
|
const paths = resolveWorktreeLocalPaths({
|
||||||
cwd,
|
cwd,
|
||||||
homeDir: opts.home ?? DEFAULT_WORKTREE_HOME,
|
homeDir: resolveWorktreeHome(opts.home),
|
||||||
instanceId,
|
instanceId,
|
||||||
});
|
});
|
||||||
|
const branding = {
|
||||||
|
name: worktreeName,
|
||||||
|
color: generateWorktreeColor(),
|
||||||
|
};
|
||||||
const sourceConfigPath = resolveSourceConfigPath(opts);
|
const sourceConfigPath = resolveSourceConfigPath(opts);
|
||||||
const sourceConfig = existsSync(sourceConfigPath) ? readConfig(sourceConfigPath) : null;
|
const sourceConfig = existsSync(sourceConfigPath) ? readConfig(sourceConfigPath) : null;
|
||||||
|
|
||||||
@@ -638,7 +673,17 @@ async function runWorktreeInit(opts: WorktreeInitOptions): Promise<void> {
|
|||||||
});
|
});
|
||||||
|
|
||||||
writeConfig(targetConfig, paths.configPath);
|
writeConfig(targetConfig, paths.configPath);
|
||||||
mergePaperclipEnvEntries(buildWorktreeEnvEntries(paths), paths.envPath);
|
const sourceEnvEntries = readPaperclipEnvEntries(resolvePaperclipEnvFile(sourceConfigPath));
|
||||||
|
const existingAgentJwtSecret =
|
||||||
|
nonEmpty(sourceEnvEntries.PAPERCLIP_AGENT_JWT_SECRET) ??
|
||||||
|
nonEmpty(process.env.PAPERCLIP_AGENT_JWT_SECRET);
|
||||||
|
mergePaperclipEnvEntries(
|
||||||
|
{
|
||||||
|
...buildWorktreeEnvEntries(paths, branding),
|
||||||
|
...(existingAgentJwtSecret ? { PAPERCLIP_AGENT_JWT_SECRET: existingAgentJwtSecret } : {}),
|
||||||
|
},
|
||||||
|
paths.envPath,
|
||||||
|
);
|
||||||
ensureAgentJwtSecret(paths.configPath);
|
ensureAgentJwtSecret(paths.configPath);
|
||||||
loadPaperclipEnvFile(paths.configPath);
|
loadPaperclipEnvFile(paths.configPath);
|
||||||
const copiedGitHooks = copyGitHooksToWorktreeGitDir(cwd);
|
const copiedGitHooks = copyGitHooksToWorktreeGitDir(cwd);
|
||||||
@@ -675,6 +720,7 @@ async function runWorktreeInit(opts: WorktreeInitOptions): Promise<void> {
|
|||||||
p.log.message(pc.dim(`Repo env: ${paths.envPath}`));
|
p.log.message(pc.dim(`Repo env: ${paths.envPath}`));
|
||||||
p.log.message(pc.dim(`Isolated home: ${paths.homeDir}`));
|
p.log.message(pc.dim(`Isolated home: ${paths.homeDir}`));
|
||||||
p.log.message(pc.dim(`Instance: ${paths.instanceId}`));
|
p.log.message(pc.dim(`Instance: ${paths.instanceId}`));
|
||||||
|
p.log.message(pc.dim(`Worktree badge: ${branding.name} (${branding.color})`));
|
||||||
p.log.message(pc.dim(`Server port: ${serverPort} | DB port: ${databasePort}`));
|
p.log.message(pc.dim(`Server port: ${serverPort} | DB port: ${databasePort}`));
|
||||||
if (copiedGitHooks?.copied) {
|
if (copiedGitHooks?.copied) {
|
||||||
p.log.message(
|
p.log.message(
|
||||||
@@ -708,17 +754,34 @@ export async function worktreeMakeCommand(nameArg: string, opts: WorktreeMakeOpt
|
|||||||
p.intro(pc.bgCyan(pc.black(" paperclipai worktree:make ")));
|
p.intro(pc.bgCyan(pc.black(" paperclipai worktree:make ")));
|
||||||
|
|
||||||
const name = resolveWorktreeMakeName(nameArg);
|
const name = resolveWorktreeMakeName(nameArg);
|
||||||
|
const startPoint = resolveWorktreeStartPoint(opts.startPoint);
|
||||||
const sourceCwd = process.cwd();
|
const sourceCwd = process.cwd();
|
||||||
|
const sourceConfigPath = resolveSourceConfigPath(opts);
|
||||||
const targetPath = resolveWorktreeMakeTargetPath(name);
|
const targetPath = resolveWorktreeMakeTargetPath(name);
|
||||||
if (existsSync(targetPath)) {
|
if (existsSync(targetPath)) {
|
||||||
throw new Error(`Target path already exists: ${targetPath}`);
|
throw new Error(`Target path already exists: ${targetPath}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
mkdirSync(path.dirname(targetPath), { recursive: true });
|
mkdirSync(path.dirname(targetPath), { recursive: true });
|
||||||
|
if (startPoint) {
|
||||||
|
const [remote] = startPoint.split("/", 1);
|
||||||
|
try {
|
||||||
|
execFileSync("git", ["fetch", remote], {
|
||||||
|
cwd: sourceCwd,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
`Failed to fetch from remote "${remote}": ${extractExecSyncErrorMessage(error) ?? String(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const worktreeArgs = resolveGitWorktreeAddArgs({
|
const worktreeArgs = resolveGitWorktreeAddArgs({
|
||||||
branchName: name,
|
branchName: name,
|
||||||
targetPath,
|
targetPath,
|
||||||
branchExists: localBranchExists(sourceCwd, name),
|
branchExists: !startPoint && localBranchExists(sourceCwd, name),
|
||||||
|
startPoint,
|
||||||
});
|
});
|
||||||
|
|
||||||
const spinner = p.spinner();
|
const spinner = p.spinner();
|
||||||
@@ -734,12 +797,26 @@ export async function worktreeMakeCommand(nameArg: string, opts: WorktreeMakeOpt
|
|||||||
throw new Error(extractExecSyncErrorMessage(error) ?? String(error));
|
throw new Error(extractExecSyncErrorMessage(error) ?? String(error));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const installSpinner = p.spinner();
|
||||||
|
installSpinner.start("Installing dependencies...");
|
||||||
|
try {
|
||||||
|
execFileSync("pnpm", ["install"], {
|
||||||
|
cwd: targetPath,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
installSpinner.stop("Installed dependencies.");
|
||||||
|
} catch (error) {
|
||||||
|
installSpinner.stop(pc.yellow("Failed to install dependencies (continuing anyway)."));
|
||||||
|
p.log.warning(extractExecSyncErrorMessage(error) ?? String(error));
|
||||||
|
}
|
||||||
|
|
||||||
const originalCwd = process.cwd();
|
const originalCwd = process.cwd();
|
||||||
try {
|
try {
|
||||||
process.chdir(targetPath);
|
process.chdir(targetPath);
|
||||||
await runWorktreeInit({
|
await runWorktreeInit({
|
||||||
...opts,
|
...opts,
|
||||||
name,
|
name,
|
||||||
|
sourceConfigPathOverride: sourceConfigPath,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error;
|
throw error;
|
||||||
@@ -748,6 +825,232 @@ export async function worktreeMakeCommand(nameArg: string, opts: WorktreeMakeOpt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type WorktreeCleanupOptions = {
|
||||||
|
instance?: string;
|
||||||
|
home?: string;
|
||||||
|
force?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type GitWorktreeListEntry = {
|
||||||
|
worktree: string;
|
||||||
|
branch: string | null;
|
||||||
|
bare: boolean;
|
||||||
|
detached: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
function parseGitWorktreeList(cwd: string): GitWorktreeListEntry[] {
|
||||||
|
const raw = execFileSync("git", ["worktree", "list", "--porcelain"], {
|
||||||
|
cwd,
|
||||||
|
encoding: "utf8",
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
const entries: GitWorktreeListEntry[] = [];
|
||||||
|
let current: Partial<GitWorktreeListEntry> = {};
|
||||||
|
for (const line of raw.split("\n")) {
|
||||||
|
if (line.startsWith("worktree ")) {
|
||||||
|
current = { worktree: line.slice("worktree ".length) };
|
||||||
|
} else if (line.startsWith("branch ")) {
|
||||||
|
current.branch = line.slice("branch ".length);
|
||||||
|
} else if (line === "bare") {
|
||||||
|
current.bare = true;
|
||||||
|
} else if (line === "detached") {
|
||||||
|
current.detached = true;
|
||||||
|
} else if (line === "" && current.worktree) {
|
||||||
|
entries.push({
|
||||||
|
worktree: current.worktree,
|
||||||
|
branch: current.branch ?? null,
|
||||||
|
bare: current.bare ?? false,
|
||||||
|
detached: current.detached ?? false,
|
||||||
|
});
|
||||||
|
current = {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (current.worktree) {
|
||||||
|
entries.push({
|
||||||
|
worktree: current.worktree,
|
||||||
|
branch: current.branch ?? null,
|
||||||
|
bare: current.bare ?? false,
|
||||||
|
detached: current.detached ?? false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
function branchHasUniqueCommits(cwd: string, branchName: string): boolean {
|
||||||
|
try {
|
||||||
|
const output = execFileSync(
|
||||||
|
"git",
|
||||||
|
["log", "--oneline", branchName, "--not", "--remotes", "--exclude", `refs/heads/${branchName}`, "--branches"],
|
||||||
|
{ cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] },
|
||||||
|
).trim();
|
||||||
|
return output.length > 0;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function branchExistsOnAnyRemote(cwd: string, branchName: string): boolean {
|
||||||
|
try {
|
||||||
|
const output = execFileSync(
|
||||||
|
"git",
|
||||||
|
["branch", "-r", "--list", `*/${branchName}`],
|
||||||
|
{ cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] },
|
||||||
|
).trim();
|
||||||
|
return output.length > 0;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function worktreePathHasUncommittedChanges(worktreePath: string): boolean {
|
||||||
|
try {
|
||||||
|
const output = execFileSync(
|
||||||
|
"git",
|
||||||
|
["status", "--porcelain"],
|
||||||
|
{ cwd: worktreePath, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] },
|
||||||
|
).trim();
|
||||||
|
return output.length > 0;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function worktreeCleanupCommand(nameArg: string, opts: WorktreeCleanupOptions): Promise<void> {
|
||||||
|
printPaperclipCliBanner();
|
||||||
|
p.intro(pc.bgCyan(pc.black(" paperclipai worktree:cleanup ")));
|
||||||
|
|
||||||
|
const name = resolveWorktreeMakeName(nameArg);
|
||||||
|
const sourceCwd = process.cwd();
|
||||||
|
const targetPath = resolveWorktreeMakeTargetPath(name);
|
||||||
|
const instanceId = sanitizeWorktreeInstanceId(opts.instance ?? name);
|
||||||
|
const homeDir = path.resolve(expandHomePrefix(resolveWorktreeHome(opts.home)));
|
||||||
|
const instanceRoot = path.resolve(homeDir, "instances", instanceId);
|
||||||
|
|
||||||
|
// ── 1. Assess current state ──────────────────────────────────────────
|
||||||
|
|
||||||
|
const hasBranch = localBranchExists(sourceCwd, name);
|
||||||
|
const hasTargetDir = existsSync(targetPath);
|
||||||
|
const hasInstanceData = existsSync(instanceRoot);
|
||||||
|
|
||||||
|
const worktrees = parseGitWorktreeList(sourceCwd);
|
||||||
|
const linkedWorktree = worktrees.find(
|
||||||
|
(wt) => wt.branch === `refs/heads/${name}` || path.resolve(wt.worktree) === path.resolve(targetPath),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasBranch && !hasTargetDir && !hasInstanceData && !linkedWorktree) {
|
||||||
|
p.log.info("Nothing to clean up — no branch, worktree directory, or instance data found.");
|
||||||
|
p.outro(pc.green("Already clean."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 2. Safety checks ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const problems: string[] = [];
|
||||||
|
|
||||||
|
if (hasBranch && branchHasUniqueCommits(sourceCwd, name)) {
|
||||||
|
const onRemote = branchExistsOnAnyRemote(sourceCwd, name);
|
||||||
|
if (onRemote) {
|
||||||
|
p.log.info(
|
||||||
|
`Branch "${name}" has unique local commits, but the branch also exists on a remote — safe to delete locally.`,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
problems.push(
|
||||||
|
`Branch "${name}" has commits not found on any other branch or remote. ` +
|
||||||
|
`Deleting it will lose work. Push it first, or use --force.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasTargetDir && worktreePathHasUncommittedChanges(targetPath)) {
|
||||||
|
problems.push(
|
||||||
|
`Worktree directory ${targetPath} has uncommitted changes. Commit or stash first, or use --force.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (problems.length > 0 && !opts.force) {
|
||||||
|
for (const problem of problems) {
|
||||||
|
p.log.error(problem);
|
||||||
|
}
|
||||||
|
throw new Error("Safety checks failed. Resolve the issues above or re-run with --force.");
|
||||||
|
}
|
||||||
|
if (problems.length > 0 && opts.force) {
|
||||||
|
for (const problem of problems) {
|
||||||
|
p.log.warning(`Overridden by --force: ${problem}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 3. Clean up (idempotent steps) ──────────────────────────────────
|
||||||
|
|
||||||
|
// 3a. Remove the git worktree registration
|
||||||
|
if (linkedWorktree) {
|
||||||
|
const worktreeDirExists = existsSync(linkedWorktree.worktree);
|
||||||
|
const spinner = p.spinner();
|
||||||
|
if (worktreeDirExists) {
|
||||||
|
spinner.start(`Removing git worktree at ${linkedWorktree.worktree}...`);
|
||||||
|
try {
|
||||||
|
const removeArgs = ["worktree", "remove", linkedWorktree.worktree];
|
||||||
|
if (opts.force) removeArgs.push("--force");
|
||||||
|
execFileSync("git", removeArgs, {
|
||||||
|
cwd: sourceCwd,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
spinner.stop(`Removed git worktree at ${linkedWorktree.worktree}.`);
|
||||||
|
} catch (error) {
|
||||||
|
spinner.stop(pc.yellow(`Could not remove worktree cleanly, will prune instead.`));
|
||||||
|
p.log.warning(extractExecSyncErrorMessage(error) ?? String(error));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
spinner.start("Pruning stale worktree entry...");
|
||||||
|
execFileSync("git", ["worktree", "prune"], {
|
||||||
|
cwd: sourceCwd,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
spinner.stop("Pruned stale worktree entry.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Even without a linked worktree, prune to clean up any orphaned entries
|
||||||
|
execFileSync("git", ["worktree", "prune"], {
|
||||||
|
cwd: sourceCwd,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3b. Remove the worktree directory if it still exists (e.g. partial creation)
|
||||||
|
if (existsSync(targetPath)) {
|
||||||
|
const spinner = p.spinner();
|
||||||
|
spinner.start(`Removing worktree directory ${targetPath}...`);
|
||||||
|
rmSync(targetPath, { recursive: true, force: true });
|
||||||
|
spinner.stop(`Removed worktree directory ${targetPath}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3c. Delete the local branch (now safe — worktree is gone)
|
||||||
|
if (localBranchExists(sourceCwd, name)) {
|
||||||
|
const spinner = p.spinner();
|
||||||
|
spinner.start(`Deleting local branch "${name}"...`);
|
||||||
|
try {
|
||||||
|
const deleteFlag = opts.force ? "-D" : "-d";
|
||||||
|
execFileSync("git", ["branch", deleteFlag, name], {
|
||||||
|
cwd: sourceCwd,
|
||||||
|
stdio: ["ignore", "pipe", "pipe"],
|
||||||
|
});
|
||||||
|
spinner.stop(`Deleted local branch "${name}".`);
|
||||||
|
} catch (error) {
|
||||||
|
spinner.stop(pc.yellow(`Could not delete branch "${name}".`));
|
||||||
|
p.log.warning(extractExecSyncErrorMessage(error) ?? String(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3d. Remove instance data
|
||||||
|
if (existsSync(instanceRoot)) {
|
||||||
|
const spinner = p.spinner();
|
||||||
|
spinner.start(`Removing instance data at ${instanceRoot}...`);
|
||||||
|
rmSync(instanceRoot, { recursive: true, force: true });
|
||||||
|
spinner.stop(`Removed instance data at ${instanceRoot}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
p.outro(pc.green("Cleanup complete."));
|
||||||
|
}
|
||||||
|
|
||||||
export async function worktreeEnvCommand(opts: WorktreeEnvOptions): Promise<void> {
|
export async function worktreeEnvCommand(opts: WorktreeEnvOptions): Promise<void> {
|
||||||
const configPath = resolveConfigPath(opts.config);
|
const configPath = resolveConfigPath(opts.config);
|
||||||
const envPath = resolvePaperclipEnvFile(configPath);
|
const envPath = resolvePaperclipEnvFile(configPath);
|
||||||
@@ -774,9 +1077,10 @@ export function registerWorktreeCommands(program: Command): void {
|
|||||||
program
|
program
|
||||||
.command("worktree:make")
|
.command("worktree:make")
|
||||||
.description("Create ~/NAME as a git worktree, then initialize an isolated Paperclip instance inside it")
|
.description("Create ~/NAME as a git worktree, then initialize an isolated Paperclip instance inside it")
|
||||||
.argument("<name>", "Worktree directory and branch name (created at ~/NAME)")
|
.argument("<name>", "Worktree name — auto-prefixed with paperclip- if needed (created at ~/paperclip-NAME)")
|
||||||
|
.option("--start-point <ref>", "Remote ref to base the new branch on (env: PAPERCLIP_WORKTREE_START_POINT)")
|
||||||
.option("--instance <id>", "Explicit isolated instance id")
|
.option("--instance <id>", "Explicit isolated instance id")
|
||||||
.option("--home <path>", `Home root for worktree instances (default: ${DEFAULT_WORKTREE_HOME})`)
|
.option("--home <path>", `Home root for worktree instances (env: PAPERCLIP_WORKTREES_DIR, default: ${DEFAULT_WORKTREE_HOME})`)
|
||||||
.option("--from-config <path>", "Source config.json to seed from")
|
.option("--from-config <path>", "Source config.json to seed from")
|
||||||
.option("--from-data-dir <path>", "Source PAPERCLIP_HOME used when deriving the source config")
|
.option("--from-data-dir <path>", "Source PAPERCLIP_HOME used when deriving the source config")
|
||||||
.option("--from-instance <id>", "Source instance id when deriving the source config", "default")
|
.option("--from-instance <id>", "Source instance id when deriving the source config", "default")
|
||||||
@@ -792,7 +1096,7 @@ export function registerWorktreeCommands(program: Command): void {
|
|||||||
.description("Create repo-local config/env and an isolated instance for this worktree")
|
.description("Create repo-local config/env and an isolated instance for this worktree")
|
||||||
.option("--name <name>", "Display name used to derive the instance id")
|
.option("--name <name>", "Display name used to derive the instance id")
|
||||||
.option("--instance <id>", "Explicit isolated instance id")
|
.option("--instance <id>", "Explicit isolated instance id")
|
||||||
.option("--home <path>", `Home root for worktree instances (default: ${DEFAULT_WORKTREE_HOME})`)
|
.option("--home <path>", `Home root for worktree instances (env: PAPERCLIP_WORKTREES_DIR, default: ${DEFAULT_WORKTREE_HOME})`)
|
||||||
.option("--from-config <path>", "Source config.json to seed from")
|
.option("--from-config <path>", "Source config.json to seed from")
|
||||||
.option("--from-data-dir <path>", "Source PAPERCLIP_HOME used when deriving the source config")
|
.option("--from-data-dir <path>", "Source PAPERCLIP_HOME used when deriving the source config")
|
||||||
.option("--from-instance <id>", "Source instance id when deriving the source config", "default")
|
.option("--from-instance <id>", "Source instance id when deriving the source config", "default")
|
||||||
@@ -809,4 +1113,13 @@ export function registerWorktreeCommands(program: Command): void {
|
|||||||
.option("-c, --config <path>", "Path to config file")
|
.option("-c, --config <path>", "Path to config file")
|
||||||
.option("--json", "Print JSON instead of shell exports")
|
.option("--json", "Print JSON instead of shell exports")
|
||||||
.action(worktreeEnvCommand);
|
.action(worktreeEnvCommand);
|
||||||
|
|
||||||
|
program
|
||||||
|
.command("worktree:cleanup")
|
||||||
|
.description("Safely remove a worktree, its branch, and its isolated instance data")
|
||||||
|
.argument("<name>", "Worktree name — auto-prefixed with paperclip- if needed")
|
||||||
|
.option("--instance <id>", "Explicit instance id (if different from the worktree name)")
|
||||||
|
.option("--home <path>", `Home root for worktree instances (env: PAPERCLIP_WORKTREES_DIR, default: ${DEFAULT_WORKTREE_HOME})`)
|
||||||
|
.option("--force", "Bypass safety checks (uncommitted changes, unique commits)", false)
|
||||||
|
.action(worktreeCleanupCommand);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,11 +22,18 @@ function parseEnvFile(contents: string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatEnvValue(value: string): string {
|
||||||
|
if (/^[A-Za-z0-9_./:@-]+$/.test(value)) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return JSON.stringify(value);
|
||||||
|
}
|
||||||
|
|
||||||
function renderEnvFile(entries: Record<string, string>) {
|
function renderEnvFile(entries: Record<string, string>) {
|
||||||
const lines = [
|
const lines = [
|
||||||
"# Paperclip environment variables",
|
"# Paperclip environment variables",
|
||||||
"# Generated by Paperclip CLI commands",
|
"# Generated by Paperclip CLI commands",
|
||||||
...Object.entries(entries).map(([key, value]) => `${key}=${value}`),
|
...Object.entries(entries).map(([key, value]) => `${key}=${formatEnvValue(value)}`),
|
||||||
"",
|
"",
|
||||||
];
|
];
|
||||||
return lines.join("\n");
|
return lines.join("\n");
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import { registerDashboardCommands } from "./commands/client/dashboard.js";
|
|||||||
import { applyDataDirOverride, type DataDirOptionLike } from "./config/data-dir.js";
|
import { applyDataDirOverride, type DataDirOptionLike } from "./config/data-dir.js";
|
||||||
import { loadPaperclipEnvFile } from "./config/env.js";
|
import { loadPaperclipEnvFile } from "./config/env.js";
|
||||||
import { registerWorktreeCommands } from "./commands/worktree.js";
|
import { registerWorktreeCommands } from "./commands/worktree.js";
|
||||||
|
import { registerPluginCommands } from "./commands/client/plugin.js";
|
||||||
|
|
||||||
const program = new Command();
|
const program = new Command();
|
||||||
const DATA_DIR_OPTION_HELP =
|
const DATA_DIR_OPTION_HELP =
|
||||||
@@ -136,6 +137,7 @@ registerApprovalCommands(program);
|
|||||||
registerActivityCommands(program);
|
registerActivityCommands(program);
|
||||||
registerDashboardCommands(program);
|
registerDashboardCommands(program);
|
||||||
registerWorktreeCommands(program);
|
registerWorktreeCommands(program);
|
||||||
|
registerPluginCommands(program);
|
||||||
|
|
||||||
const auth = program.command("auth").description("Authentication and bootstrap utilities");
|
const auth = program.command("auth").description("Authentication and bootstrap utilities");
|
||||||
|
|
||||||
|
|||||||
@@ -162,4 +162,3 @@ export async function promptServer(opts?: {
|
|||||||
auth,
|
auth,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ This command:
|
|||||||
- creates an isolated instance under `~/.paperclip-worktrees/instances/<worktree-id>/`
|
- creates an isolated instance under `~/.paperclip-worktrees/instances/<worktree-id>/`
|
||||||
- when run inside a linked git worktree, mirrors the effective git hooks into that worktree's private git dir
|
- when run inside a linked git worktree, mirrors the effective git hooks into that worktree's private git dir
|
||||||
- picks a free app port and embedded PostgreSQL port
|
- picks a free app port and embedded PostgreSQL port
|
||||||
- by default seeds the isolated DB in `minimal` mode from your main instance via a logical SQL snapshot
|
- by default seeds the isolated DB in `minimal` mode from the current effective Paperclip instance/config (repo-local worktree config when present, otherwise the default instance) via a logical SQL snapshot
|
||||||
|
|
||||||
Seed modes:
|
Seed modes:
|
||||||
|
|
||||||
@@ -152,7 +152,13 @@ Seed modes:
|
|||||||
|
|
||||||
After `worktree init`, both the server and the CLI auto-load the repo-local `.paperclip/.env` when run inside that worktree, so normal commands like `pnpm dev`, `paperclipai doctor`, and `paperclipai db:backup` stay scoped to the worktree instance.
|
After `worktree init`, both the server and the CLI auto-load the repo-local `.paperclip/.env` when run inside that worktree, so normal commands like `pnpm dev`, `paperclipai doctor`, and `paperclipai db:backup` stay scoped to the worktree instance.
|
||||||
|
|
||||||
That repo-local env also sets `PAPERCLIP_IN_WORKTREE=true`, which the server can use for worktree-specific UI behavior such as an alternate favicon.
|
That repo-local env also sets:
|
||||||
|
|
||||||
|
- `PAPERCLIP_IN_WORKTREE=true`
|
||||||
|
- `PAPERCLIP_WORKTREE_NAME=<worktree-name>`
|
||||||
|
- `PAPERCLIP_WORKTREE_COLOR=<hex-color>`
|
||||||
|
|
||||||
|
The server/UI use those values for worktree-specific branding such as the top banner and dynamically colored favicon.
|
||||||
|
|
||||||
Print shell exports explicitly when needed:
|
Print shell exports explicitly when needed:
|
||||||
|
|
||||||
@@ -162,17 +168,73 @@ paperclipai worktree env
|
|||||||
eval "$(paperclipai worktree env)"
|
eval "$(paperclipai worktree env)"
|
||||||
```
|
```
|
||||||
|
|
||||||
Useful options:
|
### Worktree CLI Reference
|
||||||
|
|
||||||
|
**`pnpm paperclipai worktree init [options]`** — Create repo-local config/env and an isolated instance for the current worktree.
|
||||||
|
|
||||||
|
| Option | Description |
|
||||||
|
|---|---|
|
||||||
|
| `--name <name>` | Display name used to derive the instance id |
|
||||||
|
| `--instance <id>` | Explicit isolated instance id |
|
||||||
|
| `--home <path>` | Home root for worktree instances (default: `~/.paperclip-worktrees`) |
|
||||||
|
| `--from-config <path>` | Source config.json to seed from |
|
||||||
|
| `--from-data-dir <path>` | Source PAPERCLIP_HOME used when deriving the source config |
|
||||||
|
| `--from-instance <id>` | Source instance id (default: `default`) |
|
||||||
|
| `--server-port <port>` | Preferred server port |
|
||||||
|
| `--db-port <port>` | Preferred embedded Postgres port |
|
||||||
|
| `--seed-mode <mode>` | Seed profile: `minimal` or `full` (default: `minimal`) |
|
||||||
|
| `--no-seed` | Skip database seeding from the source instance |
|
||||||
|
| `--force` | Replace existing repo-local config and isolated instance data |
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
paperclipai worktree init --no-seed
|
paperclipai worktree init --no-seed
|
||||||
paperclipai worktree init --seed-mode minimal
|
|
||||||
paperclipai worktree init --seed-mode full
|
paperclipai worktree init --seed-mode full
|
||||||
paperclipai worktree init --from-instance default
|
paperclipai worktree init --from-instance default
|
||||||
paperclipai worktree init --from-data-dir ~/.paperclip
|
paperclipai worktree init --from-data-dir ~/.paperclip
|
||||||
paperclipai worktree init --force
|
paperclipai worktree init --force
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**`pnpm paperclipai worktree:make <name> [options]`** — Create `~/NAME` as a git worktree, then initialize an isolated Paperclip instance inside it. This combines `git worktree add` with `worktree init` in a single step.
|
||||||
|
|
||||||
|
| Option | Description |
|
||||||
|
|---|---|
|
||||||
|
| `--start-point <ref>` | Remote ref to base the new branch on (e.g. `origin/main`) |
|
||||||
|
| `--instance <id>` | Explicit isolated instance id |
|
||||||
|
| `--home <path>` | Home root for worktree instances (default: `~/.paperclip-worktrees`) |
|
||||||
|
| `--from-config <path>` | Source config.json to seed from |
|
||||||
|
| `--from-data-dir <path>` | Source PAPERCLIP_HOME used when deriving the source config |
|
||||||
|
| `--from-instance <id>` | Source instance id (default: `default`) |
|
||||||
|
| `--server-port <port>` | Preferred server port |
|
||||||
|
| `--db-port <port>` | Preferred embedded Postgres port |
|
||||||
|
| `--seed-mode <mode>` | Seed profile: `minimal` or `full` (default: `minimal`) |
|
||||||
|
| `--no-seed` | Skip database seeding from the source instance |
|
||||||
|
| `--force` | Replace existing repo-local config and isolated instance data |
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm paperclipai worktree:make paperclip-pr-432
|
||||||
|
pnpm paperclipai worktree:make my-feature --start-point origin/main
|
||||||
|
pnpm paperclipai worktree:make experiment --no-seed
|
||||||
|
```
|
||||||
|
|
||||||
|
**`pnpm paperclipai worktree env [options]`** — Print shell exports for the current worktree-local Paperclip instance.
|
||||||
|
|
||||||
|
| Option | Description |
|
||||||
|
|---|---|
|
||||||
|
| `-c, --config <path>` | Path to config file |
|
||||||
|
| `--json` | Print JSON instead of shell exports |
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm paperclipai worktree env
|
||||||
|
pnpm paperclipai worktree env --json
|
||||||
|
eval "$(pnpm paperclipai worktree env)"
|
||||||
|
```
|
||||||
|
|
||||||
For project execution worktrees, Paperclip can also run a project-defined provision command after it creates or reuses an isolated git worktree. Configure this on the project's execution workspace policy (`workspaceStrategy.provisionCommand`). The command runs inside the derived worktree and receives `PAPERCLIP_WORKSPACE_*`, `PAPERCLIP_PROJECT_ID`, `PAPERCLIP_AGENT_ID`, and `PAPERCLIP_ISSUE_*` environment variables so each repo can bootstrap itself however it wants.
|
For project execution worktrees, Paperclip can also run a project-defined provision command after it creates or reuses an isolated git worktree. Configure this on the project's execution workspace policy (`workspaceStrategy.provisionCommand`). The command runs inside the derived worktree and receives `PAPERCLIP_WORKSPACE_*`, `PAPERCLIP_PROJECT_ID`, `PAPERCLIP_AGENT_ID`, and `PAPERCLIP_ISSUE_*` environment variables so each repo can bootstrap itself however it wants.
|
||||||
|
|
||||||
## Quick Health Checks
|
## Quick Health Checks
|
||||||
|
|||||||
@@ -94,3 +94,53 @@ Canonical mode design and command expectations live in `doc/DEPLOYMENT-MODES.md`
|
|||||||
## Further Detail
|
## Further Detail
|
||||||
|
|
||||||
See [SPEC.md](./SPEC.md) for the full technical specification and [TASKS.md](./TASKS.md) for the task management data model.
|
See [SPEC.md](./SPEC.md) for the full technical specification and [TASKS.md](./TASKS.md) for the task management data model.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Paperclip’s core identity is a **control plane for autonomous AI companies**, centered on **companies, org charts, goals, issues/comments, heartbeats, budgets, approvals, and board governance**. The public docs are also explicit about the current boundaries: **tasks/comments are the built-in communication model**, Paperclip is **not a chatbot**, and it is **not a code review tool**. The roadmap already points toward **easier onboarding, cloud agents, easier agent configuration, plugins, better docs, and ClipMart/ClipHub-style reusable companies/templates**.
|
||||||
|
|
||||||
|
## What Paperclip should do vs. not do
|
||||||
|
|
||||||
|
**Do**
|
||||||
|
|
||||||
|
- Stay **board-level and company-level**. Users should manage goals, orgs, budgets, approvals, and outputs.
|
||||||
|
- Make the first five minutes feel magical: install, answer a few questions, see a CEO do something real.
|
||||||
|
- Keep work anchored to **issues/comments/projects/goals**, even if the surface feels conversational.
|
||||||
|
- Treat **agency / internal team / startup** as the same underlying abstraction with different templates and labels.
|
||||||
|
- Make outputs first-class: files, docs, reports, previews, links, screenshots.
|
||||||
|
- Provide **hooks into engineering workflows**: worktrees, preview servers, PR links, external review tools.
|
||||||
|
- Use **plugins** for edge cases like rich chat, knowledge bases, doc editors, custom tracing.
|
||||||
|
|
||||||
|
**Do not**
|
||||||
|
|
||||||
|
- Do not make the core product a general chat app. The current product definition is explicitly task/comment-centric and “not a chatbot,” and that boundary is valuable.
|
||||||
|
- Do not build a complete Jira/GitHub replacement. The repo/docs already position Paperclip as organization orchestration, not focused on pull-request review.
|
||||||
|
- Do not build enterprise-grade RBAC first. The current V1 spec still treats multi-board governance and fine-grained human permissions as out of scope, so the first multi-user version should be coarse and company-scoped.
|
||||||
|
- Do not lead with raw bash logs and transcripts. Default view should be human-readable intent/progress, with raw detail beneath.
|
||||||
|
- Do not force users to understand provider/API-key plumbing unless absolutely necessary. There are active onboarding/auth issues already; friction here is clearly real.
|
||||||
|
|
||||||
|
## Specific design goals
|
||||||
|
|
||||||
|
1. **Time-to-first-success under 5 minutes**
|
||||||
|
A fresh user should go from install to “my CEO completed a first task” in one sitting.
|
||||||
|
|
||||||
|
2. **Board-level abstraction always wins**
|
||||||
|
The default UI should answer: what is the company doing, who is doing it, why does it matter, what did it cost, and what needs my approval.
|
||||||
|
|
||||||
|
3. **Conversation stays attached to work objects**
|
||||||
|
“Chat with CEO” should still resolve to strategy threads, decisions, tasks, or approvals.
|
||||||
|
|
||||||
|
4. **Progressive disclosure**
|
||||||
|
Top layer: human-readable summary. Middle layer: checklist/steps/artifacts. Bottom layer: raw logs/tool calls/transcript.
|
||||||
|
|
||||||
|
5. **Output-first**
|
||||||
|
Work is not done until the user can see the result: file, document, preview link, screenshot, plan, or PR.
|
||||||
|
|
||||||
|
6. **Local-first, cloud-ready**
|
||||||
|
The mental model should not change between local solo use and shared/private or public/cloud deployment.
|
||||||
|
|
||||||
|
7. **Safe autonomy**
|
||||||
|
Auto mode is allowed; hidden token burn is not.
|
||||||
|
|
||||||
|
8. **Thin core, rich edges**
|
||||||
|
Put optional chat, knowledge, and special surfaces into plugins/extensions rather than bloating the control plane.
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ From the release worktree:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
VERSION=X.Y.Z
|
VERSION=X.Y.Z
|
||||||
claude --print --output-format stream-json --verbose --dangerously-skip-permissions --model claude-opus-4-6 "Use the release-changelog skill to draft or update releases/v${VERSION}.md for Paperclip. Read doc/RELEASING.md and skills/release-changelog/SKILL.md, then generate the stable changelog for v${VERSION} from commits since the last stable tag. Do not create a canary changelog."
|
claude --print --output-format stream-json --verbose --dangerously-skip-permissions --model claude-opus-4-6 "Use the release-changelog skill to draft or update releases/v${VERSION}.md for Paperclip. Read doc/RELEASING.md and .agents/skills/release-changelog/SKILL.md, then generate the stable changelog for v${VERSION} from commits since the last stable tag. Do not create a canary changelog."
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. Verify and publish a canary
|
### 3. Verify and publish a canary
|
||||||
@@ -418,5 +418,5 @@ If the release already exists, the script updates it.
|
|||||||
## Related Docs
|
## Related Docs
|
||||||
|
|
||||||
- [doc/PUBLISHING.md](PUBLISHING.md) — low-level npm build and packaging internals
|
- [doc/PUBLISHING.md](PUBLISHING.md) — low-level npm build and packaging internals
|
||||||
- [skills/release/SKILL.md](../skills/release/SKILL.md) — agent release coordination workflow
|
- [.agents/skills/release/SKILL.md](../.agents/skills/release/SKILL.md) — maintainer release coordination workflow
|
||||||
- [skills/release-changelog/SKILL.md](../skills/release-changelog/SKILL.md) — stable changelog drafting workflow
|
- [.agents/skills/release-changelog/SKILL.md](../.agents/skills/release-changelog/SKILL.md) — stable changelog drafting workflow
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ These decisions close open questions from `SPEC.md` for V1.
|
|||||||
| Visibility | Full visibility to board and all agents in same company |
|
| Visibility | Full visibility to board and all agents in same company |
|
||||||
| Communication | Tasks + comments only (no separate chat system) |
|
| Communication | Tasks + comments only (no separate chat system) |
|
||||||
| Task ownership | Single assignee; atomic checkout required for `in_progress` transition |
|
| Task ownership | Single assignee; atomic checkout required for `in_progress` transition |
|
||||||
| Recovery | No automatic reassignment; stale work is surfaced, not silently fixed |
|
| Recovery | No automatic reassignment; work recovery stays manual/explicit |
|
||||||
| Agent adapters | Built-in `process` and `http` adapters |
|
| Agent adapters | Built-in `process` and `http` adapters |
|
||||||
| Auth | Mode-dependent human auth (`local_trusted` implicit board in current code; authenticated mode uses sessions), API keys for agents |
|
| Auth | Mode-dependent human auth (`local_trusted` implicit board in current code; authenticated mode uses sessions), API keys for agents |
|
||||||
| Budget period | Monthly UTC calendar window |
|
| Budget period | Monthly UTC calendar window |
|
||||||
@@ -106,7 +106,6 @@ A lightweight scheduler/worker in the server process handles:
|
|||||||
- heartbeat trigger checks
|
- heartbeat trigger checks
|
||||||
- stuck run detection
|
- stuck run detection
|
||||||
- budget threshold checks
|
- budget threshold checks
|
||||||
- stale task reporting generation
|
|
||||||
|
|
||||||
Separate queue infrastructure is not required for V1.
|
Separate queue infrastructure is not required for V1.
|
||||||
|
|
||||||
@@ -331,6 +330,34 @@ Operational policy:
|
|||||||
- `asset_id` uuid fk not null
|
- `asset_id` uuid fk not null
|
||||||
- `issue_comment_id` uuid fk null
|
- `issue_comment_id` uuid fk null
|
||||||
|
|
||||||
|
## 7.15 `documents` + `document_revisions` + `issue_documents`
|
||||||
|
|
||||||
|
- `documents` stores editable text-first documents:
|
||||||
|
- `id` uuid pk
|
||||||
|
- `company_id` uuid fk not null
|
||||||
|
- `title` text null
|
||||||
|
- `format` text not null (`markdown`)
|
||||||
|
- `latest_body` text not null
|
||||||
|
- `latest_revision_id` uuid null
|
||||||
|
- `latest_revision_number` int not null
|
||||||
|
- `created_by_agent_id` uuid fk null
|
||||||
|
- `created_by_user_id` uuid/text fk null
|
||||||
|
- `updated_by_agent_id` uuid fk null
|
||||||
|
- `updated_by_user_id` uuid/text fk null
|
||||||
|
- `document_revisions` stores append-only history:
|
||||||
|
- `id` uuid pk
|
||||||
|
- `company_id` uuid fk not null
|
||||||
|
- `document_id` uuid fk not null
|
||||||
|
- `revision_number` int not null
|
||||||
|
- `body` text not null
|
||||||
|
- `change_summary` text null
|
||||||
|
- `issue_documents` links documents to issues with a stable workflow key:
|
||||||
|
- `id` uuid pk
|
||||||
|
- `company_id` uuid fk not null
|
||||||
|
- `issue_id` uuid fk not null
|
||||||
|
- `document_id` uuid fk not null
|
||||||
|
- `key` text not null (`plan`, `design`, `notes`, etc.)
|
||||||
|
|
||||||
## 8. State Machines
|
## 8. State Machines
|
||||||
|
|
||||||
## 8.1 Agent Status
|
## 8.1 Agent Status
|
||||||
@@ -442,6 +469,11 @@ All endpoints are under `/api` and return JSON.
|
|||||||
- `POST /companies/:companyId/issues`
|
- `POST /companies/:companyId/issues`
|
||||||
- `GET /issues/:issueId`
|
- `GET /issues/:issueId`
|
||||||
- `PATCH /issues/:issueId`
|
- `PATCH /issues/:issueId`
|
||||||
|
- `GET /issues/:issueId/documents`
|
||||||
|
- `GET /issues/:issueId/documents/:key`
|
||||||
|
- `PUT /issues/:issueId/documents/:key`
|
||||||
|
- `GET /issues/:issueId/documents/:key/revisions`
|
||||||
|
- `DELETE /issues/:issueId/documents/:key`
|
||||||
- `POST /issues/:issueId/checkout`
|
- `POST /issues/:issueId/checkout`
|
||||||
- `POST /issues/:issueId/release`
|
- `POST /issues/:issueId/release`
|
||||||
- `POST /issues/:issueId/comments`
|
- `POST /issues/:issueId/comments`
|
||||||
@@ -502,7 +534,6 @@ Dashboard payload must include:
|
|||||||
- open/in-progress/blocked/done issue counts
|
- open/in-progress/blocked/done issue counts
|
||||||
- month-to-date spend and budget utilization
|
- month-to-date spend and budget utilization
|
||||||
- pending approvals count
|
- pending approvals count
|
||||||
- stale task count
|
|
||||||
|
|
||||||
## 10.9 Error Semantics
|
## 10.9 Error Semantics
|
||||||
|
|
||||||
@@ -681,7 +712,6 @@ Required UX behaviors:
|
|||||||
- global company selector
|
- global company selector
|
||||||
- quick actions: pause/resume agent, create task, approve/reject request
|
- quick actions: pause/resume agent, create task, approve/reject request
|
||||||
- conflict toasts on atomic checkout failure
|
- conflict toasts on atomic checkout failure
|
||||||
- clear stale-task indicators
|
|
||||||
- no silent background failures; every failed run visible in UI
|
- no silent background failures; every failed run visible in UI
|
||||||
|
|
||||||
## 15. Operational Requirements
|
## 15. Operational Requirements
|
||||||
@@ -780,7 +810,6 @@ A release candidate is blocked unless these pass:
|
|||||||
|
|
||||||
- add company selector and org chart view
|
- add company selector and org chart view
|
||||||
- add approvals and cost pages
|
- add approvals and cost pages
|
||||||
- add operational dashboard and stale-task surfacing
|
|
||||||
|
|
||||||
## Milestone 6: Hardening and Release
|
## Milestone 6: Hardening and Release
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,329 @@
|
|||||||
|
# Agent Chat UI and Issue-Backed Conversations
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
`PAP-475` asks two related questions:
|
||||||
|
|
||||||
|
1. What UI kit should Paperclip use if we add a chat surface with an agent?
|
||||||
|
2. How should chat fit the product without breaking the current issue-centric model?
|
||||||
|
|
||||||
|
This is not only a component-library decision. In Paperclip today:
|
||||||
|
|
||||||
|
- V1 explicitly says communication is `tasks + comments only`, with no separate chat system.
|
||||||
|
- Issues already carry assignment, audit trail, billing code, project linkage, goal linkage, and active run linkage.
|
||||||
|
- Live run streaming already exists on issue detail pages.
|
||||||
|
- Agent sessions already persist by `taskKey`, and today `taskKey` falls back to `issueId`.
|
||||||
|
- The OpenClaw gateway adapter already supports an issue-scoped session key strategy.
|
||||||
|
|
||||||
|
That means the cheapest useful path is not "add a second messaging product inside Paperclip." It is "add a better conversational UI on top of issue and run primitives we already have."
|
||||||
|
|
||||||
|
## Current Constraints From the Codebase
|
||||||
|
|
||||||
|
### Durable work object
|
||||||
|
|
||||||
|
The durable object in Paperclip is the issue, not a chat thread.
|
||||||
|
|
||||||
|
- `IssueDetail` already combines comments, linked runs, live runs, and activity into one timeline.
|
||||||
|
- `CommentThread` already renders markdown comments and supports reply/reassignment flows.
|
||||||
|
- `LiveRunWidget` already renders streaming assistant/tool/system output for active runs.
|
||||||
|
|
||||||
|
### Session behavior
|
||||||
|
|
||||||
|
Session continuity is already task-shaped.
|
||||||
|
|
||||||
|
- `heartbeat.ts` derives `taskKey` from `taskKey`, then `taskId`, then `issueId`.
|
||||||
|
- `agent_task_sessions` stores session state per company + agent + adapter + task key.
|
||||||
|
- OpenClaw gateway supports `sessionKeyStrategy=issue|fixed|run`, and `issue` already matches the Paperclip mental model well.
|
||||||
|
|
||||||
|
That means "chat with the CEO about this issue" naturally maps to one durable session per issue today without inventing a second session system.
|
||||||
|
|
||||||
|
### Billing behavior
|
||||||
|
|
||||||
|
Billing is already issue-aware.
|
||||||
|
|
||||||
|
- `cost_events` can attach to `issueId`, `projectId`, `goalId`, and `billingCode`.
|
||||||
|
- heartbeat context already propagates issue linkage into runs and cost rollups.
|
||||||
|
|
||||||
|
If chat leaves the issue model, Paperclip would need a second billing story. That is avoidable.
|
||||||
|
|
||||||
|
## UI Kit Recommendation
|
||||||
|
|
||||||
|
## Recommendation: `assistant-ui`
|
||||||
|
|
||||||
|
Use `assistant-ui` as the chat presentation layer.
|
||||||
|
|
||||||
|
Why it fits Paperclip:
|
||||||
|
|
||||||
|
- It is a real chat UI kit, not just a hook.
|
||||||
|
- It is composable and aligned with shadcn-style primitives, which matches the current UI stack well.
|
||||||
|
- It explicitly supports custom backends, which matters because Paperclip talks to agents through issue comments, heartbeats, and run streams rather than direct provider calls.
|
||||||
|
- It gives us polished chat affordances quickly: message list, composer, streaming text, attachments, thread affordances, and markdown-oriented rendering.
|
||||||
|
|
||||||
|
Why not make "the Vercel one" the primary choice:
|
||||||
|
|
||||||
|
- Vercel AI SDK is stronger today than the older "just `useChat` over `/api/chat`" framing. Its transport layer is flexible and can support custom protocols.
|
||||||
|
- But AI SDK is still better understood here as a transport/runtime protocol layer than as the best end-user chat surface for Paperclip.
|
||||||
|
- Paperclip does not need Vercel to own message state, persistence, or the backend contract. Paperclip already has its own issue, run, and session model.
|
||||||
|
|
||||||
|
So the clean split is:
|
||||||
|
|
||||||
|
- `assistant-ui` for UI primitives
|
||||||
|
- Paperclip-owned runtime/store for state, persistence, and transport
|
||||||
|
- optional AI SDK usage later only if we want its stream protocol or client transport abstraction
|
||||||
|
|
||||||
|
## Product Options
|
||||||
|
|
||||||
|
### Option A: Separate chat object
|
||||||
|
|
||||||
|
Create a new top-level chat/thread model unrelated to issues.
|
||||||
|
|
||||||
|
Pros:
|
||||||
|
|
||||||
|
- clean mental model if users want freeform conversation
|
||||||
|
- easy to hide from issue boards
|
||||||
|
|
||||||
|
Cons:
|
||||||
|
|
||||||
|
- breaks the current V1 product decision that communication is issue-centric
|
||||||
|
- needs new persistence, billing, session, permissions, activity, and wakeup rules
|
||||||
|
- creates a second "why does this exist?" object beside issues
|
||||||
|
- makes "pick up an old chat" a separate retrieval problem
|
||||||
|
|
||||||
|
Verdict: not recommended for V1.
|
||||||
|
|
||||||
|
### Option B: Every chat is an issue
|
||||||
|
|
||||||
|
Treat chat as a UI mode over an issue. The issue remains the durable record.
|
||||||
|
|
||||||
|
Pros:
|
||||||
|
|
||||||
|
- matches current product spec
|
||||||
|
- billing, runs, comments, approvals, and activity already work
|
||||||
|
- sessions already resume on issue identity
|
||||||
|
- works with all adapters, including OpenClaw, without new agent auth or a second API surface
|
||||||
|
|
||||||
|
Cons:
|
||||||
|
|
||||||
|
- some chats are not really "tasks" in a board sense
|
||||||
|
- onboarding and review conversations may clutter normal issue lists
|
||||||
|
|
||||||
|
Verdict: best V1 foundation.
|
||||||
|
|
||||||
|
### Option C: Hybrid with hidden conversation issues
|
||||||
|
|
||||||
|
Back every conversation with an issue, but allow a conversation-flavored issue mode that is hidden from default execution boards unless promoted.
|
||||||
|
|
||||||
|
Pros:
|
||||||
|
|
||||||
|
- preserves the issue-centric backend
|
||||||
|
- gives onboarding/review chat a cleaner UX
|
||||||
|
- preserves billing and session continuity
|
||||||
|
|
||||||
|
Cons:
|
||||||
|
|
||||||
|
- requires extra UI rules and possibly a small schema or filtering addition
|
||||||
|
- can become a disguised second system if not kept narrow
|
||||||
|
|
||||||
|
Verdict: likely the right product shape after a basic issue-backed MVP.
|
||||||
|
|
||||||
|
## Recommended Product Model
|
||||||
|
|
||||||
|
### Phase 1 product decision
|
||||||
|
|
||||||
|
For the first implementation, chat should be issue-backed.
|
||||||
|
|
||||||
|
More specifically:
|
||||||
|
|
||||||
|
- the board opens a chat surface for an issue
|
||||||
|
- sending a message is a comment mutation on that issue
|
||||||
|
- the assigned agent is woken through the existing issue-comment flow
|
||||||
|
- streaming output comes from the existing live run stream for that issue
|
||||||
|
- durable assistant output remains comments and run history, not an extra transcript store
|
||||||
|
|
||||||
|
This keeps Paperclip honest about what it is:
|
||||||
|
|
||||||
|
- the control plane stays issue-centric
|
||||||
|
- chat is a better way to interact with issue work, not a new collaboration product
|
||||||
|
|
||||||
|
### Onboarding and CEO conversations
|
||||||
|
|
||||||
|
For onboarding, weekly reviews, and "chat with the CEO", use a conversation issue rather than a global chat tab.
|
||||||
|
|
||||||
|
Suggested shape:
|
||||||
|
|
||||||
|
- create a board-initiated issue assigned to the CEO
|
||||||
|
- mark it as conversation-flavored in UI treatment
|
||||||
|
- optionally hide it from normal issue boards by default later
|
||||||
|
- keep all cost/run/session linkage on that issue
|
||||||
|
|
||||||
|
This solves several concerns at once:
|
||||||
|
|
||||||
|
- no separate API key or direct provider wiring is needed
|
||||||
|
- the same CEO adapter is used
|
||||||
|
- old conversations are recovered through normal issue history
|
||||||
|
- the CEO can still create or update real child issues from the conversation
|
||||||
|
|
||||||
|
## Session Model
|
||||||
|
|
||||||
|
### V1
|
||||||
|
|
||||||
|
Use one durable conversation session per issue.
|
||||||
|
|
||||||
|
That already matches current behavior:
|
||||||
|
|
||||||
|
- adapter task sessions persist against `taskKey`
|
||||||
|
- `taskKey` already falls back to `issueId`
|
||||||
|
- OpenClaw already supports an issue-scoped session key
|
||||||
|
|
||||||
|
This means "resume the CEO conversation later" works by reopening the same issue and waking the same agent on the same issue.
|
||||||
|
|
||||||
|
### What not to add yet
|
||||||
|
|
||||||
|
Do not add multi-thread-per-issue chat in the first pass.
|
||||||
|
|
||||||
|
If Paperclip later needs several parallel threads on one issue, then add an explicit conversation identity and derive:
|
||||||
|
|
||||||
|
- `taskKey = issue:<issueId>:conversation:<conversationId>`
|
||||||
|
- OpenClaw `sessionKey = paperclip:conversation:<conversationId>`
|
||||||
|
|
||||||
|
Until that requirement becomes real, one issue == one durable conversation is the simpler and better rule.
|
||||||
|
|
||||||
|
## Billing Model
|
||||||
|
|
||||||
|
Chat should not invent a separate billing pipeline.
|
||||||
|
|
||||||
|
All chat cost should continue to roll up through the issue:
|
||||||
|
|
||||||
|
- `cost_events.issueId`
|
||||||
|
- project and goal rollups through existing relationships
|
||||||
|
- issue `billingCode` when present
|
||||||
|
|
||||||
|
If a conversation is important enough to exist, it is important enough to have a durable issue-backed audit and cost trail.
|
||||||
|
|
||||||
|
This is another reason ephemeral freeform chat should not be the default.
|
||||||
|
|
||||||
|
## UI Architecture
|
||||||
|
|
||||||
|
### Recommended stack
|
||||||
|
|
||||||
|
1. Keep Paperclip as the source of truth for message history and run state.
|
||||||
|
2. Add `assistant-ui` as the rendering/composer layer.
|
||||||
|
3. Build a Paperclip runtime adapter that maps:
|
||||||
|
- issue comments -> user/assistant messages
|
||||||
|
- live run deltas -> streaming assistant messages
|
||||||
|
- issue attachments -> chat attachments
|
||||||
|
4. Keep current markdown rendering and code-block support where possible.
|
||||||
|
|
||||||
|
### Interaction flow
|
||||||
|
|
||||||
|
1. Board opens issue detail in "Chat" mode.
|
||||||
|
2. Existing comment history is mapped into chat messages.
|
||||||
|
3. When the board sends a message:
|
||||||
|
- `POST /api/issues/{id}/comments`
|
||||||
|
- optionally interrupt the active run if the UX wants "send and replace current response"
|
||||||
|
4. Existing issue comment wakeup logic wakes the assignee.
|
||||||
|
5. Existing `/issues/{id}/live-runs` and `/issues/{id}/active-run` data feeds drive streaming.
|
||||||
|
6. When the run completes, durable state remains in comments/runs/activity as it does now.
|
||||||
|
|
||||||
|
### Why this fits the current code
|
||||||
|
|
||||||
|
Paperclip already has most of the backend pieces:
|
||||||
|
|
||||||
|
- issue comments
|
||||||
|
- run timeline
|
||||||
|
- run log and event streaming
|
||||||
|
- markdown rendering
|
||||||
|
- attachment support
|
||||||
|
- assignee wakeups on comments
|
||||||
|
|
||||||
|
The missing piece is mostly the presentation and the mapping layer, not a new backend domain.
|
||||||
|
|
||||||
|
## Agent Scope
|
||||||
|
|
||||||
|
Do not launch this as "chat with every agent."
|
||||||
|
|
||||||
|
Start narrower:
|
||||||
|
|
||||||
|
- onboarding chat with CEO
|
||||||
|
- workflow/review chat with CEO
|
||||||
|
- maybe selected exec roles later
|
||||||
|
|
||||||
|
Reasons:
|
||||||
|
|
||||||
|
- it keeps the feature from becoming a second inbox/chat product
|
||||||
|
- it limits permission and UX questions early
|
||||||
|
- it matches the stated product demand
|
||||||
|
|
||||||
|
If direct chat with other agents becomes useful later, the same issue-backed pattern can expand cleanly.
|
||||||
|
|
||||||
|
## Recommended Delivery Phases
|
||||||
|
|
||||||
|
### Phase 1: Chat UI on existing issues
|
||||||
|
|
||||||
|
- add a chat presentation mode to issue detail
|
||||||
|
- use `assistant-ui`
|
||||||
|
- map comments + live runs into the chat surface
|
||||||
|
- no schema change
|
||||||
|
- no new API surface
|
||||||
|
|
||||||
|
This is the highest-leverage step because it tests whether the UX is actually useful before product model expansion.
|
||||||
|
|
||||||
|
### Phase 2: Conversation-flavored issues for CEO chat
|
||||||
|
|
||||||
|
- add a lightweight conversation classification
|
||||||
|
- support creation of CEO conversation issues from onboarding and workflow entry points
|
||||||
|
- optionally hide these from normal backlog/board views by default
|
||||||
|
|
||||||
|
The smallest implementation could be a label or issue metadata flag. If it becomes important enough, then promote it to a first-class issue subtype later.
|
||||||
|
|
||||||
|
### Phase 3: Promotion and thread splitting only if needed
|
||||||
|
|
||||||
|
Only if we later see a real need:
|
||||||
|
|
||||||
|
- allow promoting a conversation to a formal task issue
|
||||||
|
- allow several threads per issue with explicit conversation identity
|
||||||
|
|
||||||
|
This should be demand-driven, not designed up front.
|
||||||
|
|
||||||
|
## Clear Recommendation
|
||||||
|
|
||||||
|
If the question is "what should we use?", the answer is:
|
||||||
|
|
||||||
|
- use `assistant-ui` for the chat UI
|
||||||
|
- do not treat raw Vercel AI SDK UI hooks as the main product answer
|
||||||
|
- keep chat issue-backed in V1
|
||||||
|
- use the current issue comment + run + session + billing model rather than inventing a parallel chat subsystem
|
||||||
|
|
||||||
|
If the question is "how should we think about chat in Paperclip?", the answer is:
|
||||||
|
|
||||||
|
- chat is a mode of interacting with issue-backed agent work
|
||||||
|
- not a separate product silo
|
||||||
|
- not an excuse to stop tracing work, cost, and session history back to the issue
|
||||||
|
|
||||||
|
## Implementation Notes
|
||||||
|
|
||||||
|
### Immediate implementation target
|
||||||
|
|
||||||
|
The most defensible first build is:
|
||||||
|
|
||||||
|
- add a chat tab or chat-focused layout on issue detail
|
||||||
|
- back it with the currently assigned agent on that issue
|
||||||
|
- use `assistant-ui` primitives over existing comments and live run events
|
||||||
|
|
||||||
|
### Defer these until proven necessary
|
||||||
|
|
||||||
|
- standalone global chat objects
|
||||||
|
- multi-thread chat inside one issue
|
||||||
|
- chat with every agent in the org
|
||||||
|
- a second persistence layer for message history
|
||||||
|
- separate cost tracking for chats
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- V1 communication model: `doc/SPEC-implementation.md`
|
||||||
|
- Current issue/comment/run UI: `ui/src/pages/IssueDetail.tsx`, `ui/src/components/CommentThread.tsx`, `ui/src/components/LiveRunWidget.tsx`
|
||||||
|
- Session persistence and task key derivation: `server/src/services/heartbeat.ts`, `packages/db/src/schema/agent_task_sessions.ts`
|
||||||
|
- OpenClaw session routing: `packages/adapters/openclaw-gateway/README.md`
|
||||||
|
- assistant-ui docs: <https://www.assistant-ui.com/docs>
|
||||||
|
- assistant-ui repo: <https://github.com/assistant-ui/assistant-ui>
|
||||||
|
- AI SDK transport docs: <https://ai-sdk.dev/docs/ai-sdk-ui/transport>
|
||||||
397
doc/plans/2026-03-13-TOKEN-OPTIMIZATION-PLAN.md
Normal file
397
doc/plans/2026-03-13-TOKEN-OPTIMIZATION-PLAN.md
Normal file
@@ -0,0 +1,397 @@
|
|||||||
|
# Token Optimization Plan
|
||||||
|
|
||||||
|
Date: 2026-03-13
|
||||||
|
Related discussion: https://github.com/paperclipai/paperclip/discussions/449
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Reduce token consumption materially without reducing agent capability, control-plane visibility, or task completion quality.
|
||||||
|
|
||||||
|
This plan is based on:
|
||||||
|
|
||||||
|
- the current V1 control-plane design
|
||||||
|
- the current adapter and heartbeat implementation
|
||||||
|
- the linked user discussion
|
||||||
|
- local runtime data from the default Paperclip instance on 2026-03-13
|
||||||
|
|
||||||
|
## Executive Summary
|
||||||
|
|
||||||
|
The discussion is directionally right about two things:
|
||||||
|
|
||||||
|
1. We should preserve session and prompt-cache locality more aggressively.
|
||||||
|
2. We should separate stable startup instructions from per-heartbeat dynamic context.
|
||||||
|
|
||||||
|
But that is not enough on its own.
|
||||||
|
|
||||||
|
After reviewing the code and local run data, the token problem appears to have four distinct causes:
|
||||||
|
|
||||||
|
1. **Measurement inflation on sessioned adapters.** Some token counters, especially for `codex_local`, appear to be recorded as cumulative session totals instead of per-heartbeat deltas.
|
||||||
|
2. **Avoidable session resets.** Task sessions are intentionally reset on timer wakes and manual wakes, which destroys cache locality for common heartbeat paths.
|
||||||
|
3. **Repeated context reacquisition.** The `paperclip` skill tells agents to re-fetch assignments, issue details, ancestors, and full comment threads on every heartbeat. The API does not currently offer efficient delta-oriented alternatives.
|
||||||
|
4. **Large static instruction surfaces.** Agent instruction files and globally injected skills are reintroduced at startup even when most of that content is unchanged and not needed for the current task.
|
||||||
|
|
||||||
|
The correct approach is:
|
||||||
|
|
||||||
|
1. fix telemetry so we can trust the numbers
|
||||||
|
2. preserve reuse where it is safe
|
||||||
|
3. make context retrieval incremental
|
||||||
|
4. add session compaction/rotation so long-lived sessions do not become progressively more expensive
|
||||||
|
|
||||||
|
## Validated Findings
|
||||||
|
|
||||||
|
### 1. Token telemetry is at least partly overstated today
|
||||||
|
|
||||||
|
Observed from the local default instance:
|
||||||
|
|
||||||
|
- `heartbeat_runs`: 11,360 runs between 2026-02-18 and 2026-03-13
|
||||||
|
- summed `usage_json.inputTokens`: `2,272,142,368,952`
|
||||||
|
- summed `usage_json.cachedInputTokens`: `2,217,501,559,420`
|
||||||
|
|
||||||
|
Those totals are not credible as true per-heartbeat usage for the observed prompt sizes.
|
||||||
|
|
||||||
|
Supporting evidence:
|
||||||
|
|
||||||
|
- `adapter.invoke.payload.prompt` averages were small:
|
||||||
|
- `codex_local`: ~193 chars average, 6,067 chars max
|
||||||
|
- `claude_local`: ~160 chars average, 1,160 chars max
|
||||||
|
- despite that, many `codex_local` runs report millions of input tokens
|
||||||
|
- one reused Codex session in local data spans 3,607 runs and recorded `inputTokens` growing up to `1,155,283,166`
|
||||||
|
|
||||||
|
Interpretation:
|
||||||
|
|
||||||
|
- for sessioned adapters, especially Codex, we are likely storing usage reported by the runtime as a **session total**, not a **per-run delta**
|
||||||
|
- this makes trend reporting, optimization work, and customer trust worse
|
||||||
|
|
||||||
|
This does **not** mean there is no real token problem. It means we need a trustworthy baseline before we can judge optimization impact.
|
||||||
|
|
||||||
|
### 2. Timer wakes currently throw away reusable task sessions
|
||||||
|
|
||||||
|
In `server/src/services/heartbeat.ts`, `shouldResetTaskSessionForWake(...)` returns `true` for:
|
||||||
|
|
||||||
|
- `wakeReason === "issue_assigned"`
|
||||||
|
- `wakeSource === "timer"`
|
||||||
|
- manual on-demand wakes
|
||||||
|
|
||||||
|
That means many normal heartbeats skip saved task-session resume even when the workspace is stable.
|
||||||
|
|
||||||
|
Local data supports the impact:
|
||||||
|
|
||||||
|
- `timer/system` runs: 6,587 total
|
||||||
|
- only 976 had a previous session
|
||||||
|
- only 963 ended with the same session
|
||||||
|
|
||||||
|
So timer wakes are the largest heartbeat path and are mostly not resuming prior task state.
|
||||||
|
|
||||||
|
### 3. We repeatedly ask agents to reload the same task context
|
||||||
|
|
||||||
|
The `paperclip` skill currently tells agents to do this on essentially every heartbeat:
|
||||||
|
|
||||||
|
- fetch assignments
|
||||||
|
- fetch issue details
|
||||||
|
- fetch ancestor chain
|
||||||
|
- fetch full issue comments
|
||||||
|
|
||||||
|
Current API shape reinforces that pattern:
|
||||||
|
|
||||||
|
- `GET /api/issues/:id/comments` returns the full thread
|
||||||
|
- there is no `since`, cursor, digest, or summary endpoint for heartbeat consumption
|
||||||
|
- `GET /api/issues/:id` returns full enriched issue context, not a minimal delta payload
|
||||||
|
|
||||||
|
This is safe but expensive. It forces the model to repeatedly consume unchanged information.
|
||||||
|
|
||||||
|
### 4. Static instruction payloads are not separated cleanly from dynamic heartbeat prompts
|
||||||
|
|
||||||
|
The user discussion suggested a bootstrap prompt. That is the right direction.
|
||||||
|
|
||||||
|
Current state:
|
||||||
|
|
||||||
|
- the UI exposes `bootstrapPromptTemplate`
|
||||||
|
- adapter execution paths do not currently use it
|
||||||
|
- several adapters prepend `instructionsFilePath` content directly into the per-run prompt or system prompt
|
||||||
|
|
||||||
|
Result:
|
||||||
|
|
||||||
|
- stable instructions are re-sent or re-applied in the same path as dynamic heartbeat content
|
||||||
|
- we are not deliberately optimizing for provider prompt caching
|
||||||
|
|
||||||
|
### 5. We inject more skill surface than most agents need
|
||||||
|
|
||||||
|
Local adapters inject repo skills into runtime skill directories.
|
||||||
|
|
||||||
|
Important `codex_local` nuance:
|
||||||
|
|
||||||
|
- Codex does not read skills directly from the active worktree.
|
||||||
|
- Paperclip discovers repo skills from the current checkout, then symlinks them into `$CODEX_HOME/skills` or `~/.codex/skills`.
|
||||||
|
- If an existing Paperclip skill symlink already points at another live checkout, the current implementation skips it instead of repointing it.
|
||||||
|
- This can leave Codex using stale skill content from a different worktree even after Paperclip-side skill changes land.
|
||||||
|
- That is both a correctness risk and a token-analysis risk, because runtime behavior may not reflect the instructions in the checkout being tested.
|
||||||
|
|
||||||
|
Current repo skill sizes:
|
||||||
|
|
||||||
|
- `skills/paperclip/SKILL.md`: 17,441 bytes
|
||||||
|
- `.agents/skills/create-agent-adapter/SKILL.md`: 31,832 bytes
|
||||||
|
- `skills/paperclip-create-agent/SKILL.md`: 4,718 bytes
|
||||||
|
- `skills/para-memory-files/SKILL.md`: 3,978 bytes
|
||||||
|
|
||||||
|
That is nearly 58 KB of skill markdown before any company-specific instructions.
|
||||||
|
|
||||||
|
Not all of that is necessarily loaded into model context every run, but it increases startup surface area and should be treated as a token budget concern.
|
||||||
|
|
||||||
|
## Principles
|
||||||
|
|
||||||
|
We should optimize tokens under these rules:
|
||||||
|
|
||||||
|
1. **Do not lose functionality.** Agents must still be able to resume work safely, understand why tasks exist, and act within governance rules.
|
||||||
|
2. **Prefer stable context over repeated context.** Unchanged instructions should not be resent through the most expensive path.
|
||||||
|
3. **Prefer deltas over full reloads.** Heartbeats should consume only what changed since the last useful run.
|
||||||
|
4. **Measure normalized deltas, not raw adapter claims.** Especially for sessioned CLIs.
|
||||||
|
5. **Keep escape hatches.** Board/manual runs may still want a forced fresh session.
|
||||||
|
|
||||||
|
## Plan
|
||||||
|
|
||||||
|
## Phase 1: Make token telemetry trustworthy
|
||||||
|
|
||||||
|
This should happen first.
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
- Store both:
|
||||||
|
- raw adapter-reported usage
|
||||||
|
- Paperclip-normalized per-run usage
|
||||||
|
- For sessioned adapters, compute normalized deltas against prior usage for the same persisted session.
|
||||||
|
- Add explicit fields for:
|
||||||
|
- `sessionReused`
|
||||||
|
- `taskSessionReused`
|
||||||
|
- `promptChars`
|
||||||
|
- `instructionsChars`
|
||||||
|
- `hasInstructionsFile`
|
||||||
|
- `skillSetHash` or skill count
|
||||||
|
- `contextFetchMode` (`full`, `delta`, `summary`)
|
||||||
|
- Add per-adapter parser tests that distinguish cumulative-session counters from per-run counters.
|
||||||
|
|
||||||
|
### Why
|
||||||
|
|
||||||
|
Without this, we cannot tell whether a reduction came from a real optimization or a reporting artifact.
|
||||||
|
|
||||||
|
### Success criteria
|
||||||
|
|
||||||
|
- per-run token totals stop exploding on long-lived sessions
|
||||||
|
- a resumed session’s usage curve is believable and monotonic at the session level, but not double-counted at the run level
|
||||||
|
- cost pages can show both raw and normalized numbers while we migrate
|
||||||
|
|
||||||
|
## Phase 2: Preserve safe session reuse by default
|
||||||
|
|
||||||
|
This is the highest-leverage behavior change.
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
- Stop resetting task sessions on ordinary timer wakes.
|
||||||
|
- Keep resetting on:
|
||||||
|
- explicit manual “fresh run” invocations
|
||||||
|
- assignment changes
|
||||||
|
- workspace mismatch
|
||||||
|
- model mismatch / invalid resume errors
|
||||||
|
- Add an explicit wake flag like `forceFreshSession: true` when the board wants a reset.
|
||||||
|
- Record why a session was reused or reset in run metadata.
|
||||||
|
|
||||||
|
### Why
|
||||||
|
|
||||||
|
Timer wakes are the dominant heartbeat path. Resetting them destroys both session continuity and prompt cache reuse.
|
||||||
|
|
||||||
|
### Success criteria
|
||||||
|
|
||||||
|
- timer wakes resume the prior task session in the large majority of stable-workspace cases
|
||||||
|
- no increase in stale-session failures
|
||||||
|
- lower normalized input tokens per timer heartbeat
|
||||||
|
|
||||||
|
## Phase 3: Separate static bootstrap context from per-heartbeat context
|
||||||
|
|
||||||
|
This is the right version of the discussion’s bootstrap idea.
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
- Implement `bootstrapPromptTemplate` in adapter execution paths.
|
||||||
|
- Use it only when starting a fresh session, not on resumed sessions.
|
||||||
|
- Keep `promptTemplate` intentionally small and stable:
|
||||||
|
- who I am
|
||||||
|
- what triggered this wake
|
||||||
|
- which task/comment/approval to prioritize
|
||||||
|
- Move long-lived setup text out of recurring per-run prompts where possible.
|
||||||
|
- Add UI guidance and warnings when `promptTemplate` contains high-churn or large inline content.
|
||||||
|
|
||||||
|
### Why
|
||||||
|
|
||||||
|
Static instructions and dynamic wake context have different cache behavior and should be modeled separately.
|
||||||
|
|
||||||
|
For `codex_local`, this also requires isolating the Codex skill home per worktree or teaching Paperclip to repoint its own skill symlinks when the source checkout changes. Otherwise prompt and skill improvements in the active worktree may not reach the running agent.
|
||||||
|
|
||||||
|
### Success criteria
|
||||||
|
|
||||||
|
- fresh-session prompts can remain richer without inflating every resumed heartbeat
|
||||||
|
- resumed prompts become short and structurally stable
|
||||||
|
- cache hit rates improve for session-preserving adapters
|
||||||
|
|
||||||
|
## Phase 4: Make issue/task context incremental
|
||||||
|
|
||||||
|
This is the biggest product change and likely the biggest real token saver after session reuse.
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
Add heartbeat-oriented endpoints and skill behavior:
|
||||||
|
|
||||||
|
- `GET /api/agents/me/inbox-lite`
|
||||||
|
- minimal assignment list
|
||||||
|
- issue id, identifier, status, priority, updatedAt, lastExternalCommentAt
|
||||||
|
- `GET /api/issues/:id/heartbeat-context`
|
||||||
|
- compact issue state
|
||||||
|
- parent-chain summary
|
||||||
|
- latest execution summary
|
||||||
|
- change markers
|
||||||
|
- `GET /api/issues/:id/comments?after=<cursor>` or `?since=<timestamp>`
|
||||||
|
- return only new comments
|
||||||
|
- optional `GET /api/issues/:id/context-digest`
|
||||||
|
- server-generated compact summary for heartbeat use
|
||||||
|
|
||||||
|
Update the `paperclip` skill so the default pattern becomes:
|
||||||
|
|
||||||
|
1. fetch compact inbox
|
||||||
|
2. fetch compact task context
|
||||||
|
3. fetch only new comments unless this is the first read, a mention-triggered wake, or a cache miss
|
||||||
|
4. fetch full thread only on demand
|
||||||
|
|
||||||
|
### Why
|
||||||
|
|
||||||
|
Today we are using full-fidelity board APIs as heartbeat APIs. That is convenient but token-inefficient.
|
||||||
|
|
||||||
|
### Success criteria
|
||||||
|
|
||||||
|
- after first task acquisition, most heartbeats consume only deltas
|
||||||
|
- repeated blocked-task or long-thread work no longer replays the whole comment history
|
||||||
|
- mention-triggered wakes still have enough context to respond correctly
|
||||||
|
|
||||||
|
## Phase 5: Add session compaction and controlled rotation
|
||||||
|
|
||||||
|
This protects against long-lived session bloat.
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
- Add rotation thresholds per adapter/session:
|
||||||
|
- turns
|
||||||
|
- normalized input tokens
|
||||||
|
- age
|
||||||
|
- cache hit degradation
|
||||||
|
- Before rotating, produce a structured carry-forward summary:
|
||||||
|
- current objective
|
||||||
|
- work completed
|
||||||
|
- open decisions
|
||||||
|
- blockers
|
||||||
|
- files/artifacts touched
|
||||||
|
- next recommended action
|
||||||
|
- Persist that summary in task session state or runtime state.
|
||||||
|
- Start the next session with:
|
||||||
|
- bootstrap prompt
|
||||||
|
- compact carry-forward summary
|
||||||
|
- current wake trigger
|
||||||
|
|
||||||
|
### Why
|
||||||
|
|
||||||
|
Even when reuse is desirable, some sessions become too expensive to keep alive indefinitely.
|
||||||
|
|
||||||
|
### Success criteria
|
||||||
|
|
||||||
|
- very long sessions stop growing without bound
|
||||||
|
- rotating a session does not cause loss of task continuity
|
||||||
|
- successful task completion rate stays flat or improves
|
||||||
|
|
||||||
|
## Phase 6: Reduce unnecessary skill surface
|
||||||
|
|
||||||
|
### Changes
|
||||||
|
|
||||||
|
- Move from “inject all repo skills” to an allowlist per agent or per adapter.
|
||||||
|
- Default local runtime skill set should likely be:
|
||||||
|
- `paperclip`
|
||||||
|
- Add opt-in skills for specialized agents:
|
||||||
|
- `paperclip-create-agent`
|
||||||
|
- `para-memory-files`
|
||||||
|
- `create-agent-adapter`
|
||||||
|
- Expose active skill set in agent config and run metadata.
|
||||||
|
- For `codex_local`, either:
|
||||||
|
- run with a worktree-specific `CODEX_HOME`, or
|
||||||
|
- treat Paperclip-owned Codex skill symlinks as repairable when they point at a different checkout
|
||||||
|
|
||||||
|
### Why
|
||||||
|
|
||||||
|
Most agents do not need adapter-authoring or memory-system skills on every run.
|
||||||
|
|
||||||
|
### Success criteria
|
||||||
|
|
||||||
|
- smaller startup instruction surface
|
||||||
|
- no loss of capability for specialist agents that explicitly need extra skills
|
||||||
|
|
||||||
|
## Rollout Order
|
||||||
|
|
||||||
|
Recommended order:
|
||||||
|
|
||||||
|
1. telemetry normalization
|
||||||
|
2. timer-wake session reuse
|
||||||
|
3. bootstrap prompt implementation
|
||||||
|
4. heartbeat delta APIs + `paperclip` skill rewrite
|
||||||
|
5. session compaction/rotation
|
||||||
|
6. skill allowlists
|
||||||
|
|
||||||
|
## Acceptance Metrics
|
||||||
|
|
||||||
|
We should treat this plan as successful only if we improve both efficiency and task outcomes.
|
||||||
|
|
||||||
|
Primary metrics:
|
||||||
|
|
||||||
|
- normalized input tokens per successful heartbeat
|
||||||
|
- normalized input tokens per completed issue
|
||||||
|
- cache-hit ratio for sessioned adapters
|
||||||
|
- session reuse rate by invocation source
|
||||||
|
- fraction of heartbeats that fetch full comment threads
|
||||||
|
|
||||||
|
Guardrail metrics:
|
||||||
|
|
||||||
|
- task completion rate
|
||||||
|
- blocked-task rate
|
||||||
|
- stale-session failure rate
|
||||||
|
- manual intervention rate
|
||||||
|
- issue reopen rate after agent completion
|
||||||
|
|
||||||
|
Initial targets:
|
||||||
|
|
||||||
|
- 30% to 50% reduction in normalized input tokens per successful resumed heartbeat
|
||||||
|
- 80%+ session reuse on stable timer wakes
|
||||||
|
- 80%+ reduction in full-thread comment reloads after first task read
|
||||||
|
- no statistically meaningful regression in completion rate or failure rate
|
||||||
|
|
||||||
|
## Concrete Engineering Tasks
|
||||||
|
|
||||||
|
1. Add normalized usage fields and migration support for run analytics.
|
||||||
|
2. Patch sessioned adapter accounting to compute deltas from prior session totals.
|
||||||
|
3. Change `shouldResetTaskSessionForWake(...)` so timer wakes do not reset by default.
|
||||||
|
4. Implement `bootstrapPromptTemplate` end-to-end in adapter execution.
|
||||||
|
5. Add compact heartbeat context and incremental comment APIs.
|
||||||
|
6. Rewrite `skills/paperclip/SKILL.md` around delta-fetch behavior.
|
||||||
|
7. Add session rotation with carry-forward summaries.
|
||||||
|
8. Replace global skill injection with explicit allowlists.
|
||||||
|
9. Fix `codex_local` skill resolution so worktree-local skill changes reliably reach the runtime.
|
||||||
|
|
||||||
|
## Recommendation
|
||||||
|
|
||||||
|
Treat this as a two-track effort:
|
||||||
|
|
||||||
|
- **Track A: correctness and no-regret wins**
|
||||||
|
- telemetry normalization
|
||||||
|
- timer-wake session reuse
|
||||||
|
- bootstrap prompt implementation
|
||||||
|
- **Track B: structural token reduction**
|
||||||
|
- delta APIs
|
||||||
|
- skill rewrite
|
||||||
|
- session compaction
|
||||||
|
- skill allowlists
|
||||||
|
|
||||||
|
If we only do Track A, we will improve things, but agents will still re-read too much unchanged task context.
|
||||||
|
|
||||||
|
If we only do Track B without fixing telemetry first, we will not be able to prove the gains cleanly.
|
||||||
775
doc/plans/2026-03-13-agent-evals-framework.md
Normal file
775
doc/plans/2026-03-13-agent-evals-framework.md
Normal file
@@ -0,0 +1,775 @@
|
|||||||
|
# Agent Evals Framework Plan
|
||||||
|
|
||||||
|
Date: 2026-03-13
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
We need evals for the thing Paperclip actually ships:
|
||||||
|
|
||||||
|
- agent behavior produced by adapter config
|
||||||
|
- prompt templates and bootstrap prompts
|
||||||
|
- skill sets and skill instructions
|
||||||
|
- model choice
|
||||||
|
- runtime policy choices that affect outcomes and cost
|
||||||
|
|
||||||
|
We do **not** primarily need a fine-tuning pipeline.
|
||||||
|
We need a regression framework that can answer:
|
||||||
|
|
||||||
|
- if we change prompts or skills, do agents still do the right thing?
|
||||||
|
- if we switch models, what got better, worse, or more expensive?
|
||||||
|
- if we optimize tokens, did we preserve task outcomes?
|
||||||
|
- can we grow the suite over time from real Paperclip usage?
|
||||||
|
|
||||||
|
This plan is based on:
|
||||||
|
|
||||||
|
- `doc/GOAL.md`
|
||||||
|
- `doc/PRODUCT.md`
|
||||||
|
- `doc/SPEC-implementation.md`
|
||||||
|
- `docs/agents-runtime.md`
|
||||||
|
- `doc/plans/2026-03-13-TOKEN-OPTIMIZATION-PLAN.md`
|
||||||
|
- Discussion #449: <https://github.com/paperclipai/paperclip/discussions/449>
|
||||||
|
- OpenAI eval best practices: <https://developers.openai.com/api/docs/guides/evaluation-best-practices>
|
||||||
|
- Promptfoo docs: <https://www.promptfoo.dev/docs/configuration/test-cases/> and <https://www.promptfoo.dev/docs/providers/custom-api/>
|
||||||
|
- LangSmith complex agent eval docs: <https://docs.langchain.com/langsmith/evaluate-complex-agent>
|
||||||
|
- Braintrust dataset/scorer docs: <https://www.braintrust.dev/docs/annotate/datasets> and <https://www.braintrust.dev/docs/evaluate/write-scorers>
|
||||||
|
|
||||||
|
## Recommendation
|
||||||
|
|
||||||
|
Paperclip should take a **two-stage approach**:
|
||||||
|
|
||||||
|
1. **Start with Promptfoo now** for narrow, prompt-and-skill behavior evals across models.
|
||||||
|
2. **Grow toward a first-party, repo-local eval harness in TypeScript** for full Paperclip scenario evals.
|
||||||
|
|
||||||
|
So the recommendation is no longer “skip Promptfoo.” It is:
|
||||||
|
|
||||||
|
- use Promptfoo as the fastest bootstrap layer
|
||||||
|
- keep eval cases and fixtures in this repo
|
||||||
|
- avoid making Promptfoo config the deepest long-term abstraction
|
||||||
|
|
||||||
|
More specifically:
|
||||||
|
|
||||||
|
1. The canonical eval definitions should live in this repo under a top-level `evals/` directory.
|
||||||
|
2. `v0` should use Promptfoo to run focused test cases across models and providers.
|
||||||
|
3. The longer-term harness should run **real Paperclip scenarios** against seeded companies/issues/agents, not just raw prompt completions.
|
||||||
|
4. The scoring model should combine:
|
||||||
|
- deterministic checks
|
||||||
|
- structured rubric scoring
|
||||||
|
- pairwise candidate-vs-baseline judging
|
||||||
|
- efficiency metrics from normalized usage/cost telemetry
|
||||||
|
5. The framework should compare **bundles**, not just models.
|
||||||
|
|
||||||
|
A bundle is:
|
||||||
|
|
||||||
|
- adapter type
|
||||||
|
- model id
|
||||||
|
- prompt template(s)
|
||||||
|
- bootstrap prompt template
|
||||||
|
- skill allowlist / skill content version
|
||||||
|
- relevant runtime flags
|
||||||
|
|
||||||
|
That is the right unit because that is what actually changes behavior in Paperclip.
|
||||||
|
|
||||||
|
## Why This Is The Right Shape
|
||||||
|
|
||||||
|
### 1. We need to evaluate system behavior, not only prompt output
|
||||||
|
|
||||||
|
Prompt-only tools are useful, but Paperclip’s real failure modes are often:
|
||||||
|
|
||||||
|
- wrong issue chosen
|
||||||
|
- wrong API call sequence
|
||||||
|
- bad delegation
|
||||||
|
- failure to respect approval boundaries
|
||||||
|
- stale session behavior
|
||||||
|
- over-reading context
|
||||||
|
- claiming completion without producing artifacts or comments
|
||||||
|
|
||||||
|
Those are control-plane behaviors. They require scenario setup, execution, and trace inspection.
|
||||||
|
|
||||||
|
### 2. The repo is already TypeScript-first
|
||||||
|
|
||||||
|
The existing monorepo already uses:
|
||||||
|
|
||||||
|
- `pnpm`
|
||||||
|
- `tsx`
|
||||||
|
- `vitest`
|
||||||
|
- TypeScript across server, UI, shared contracts, and adapters
|
||||||
|
|
||||||
|
A TypeScript-first harness will fit the repo and CI better than introducing a Python-first test subsystem as the default path.
|
||||||
|
|
||||||
|
Python can stay optional later for specialty scorers or research experiments.
|
||||||
|
|
||||||
|
### 3. We need provider/model comparison without vendor lock-in
|
||||||
|
|
||||||
|
OpenAI’s guidance is directionally right:
|
||||||
|
|
||||||
|
- eval early and often
|
||||||
|
- use task-specific evals
|
||||||
|
- log everything
|
||||||
|
- prefer pairwise/comparison-style judging over open-ended scoring
|
||||||
|
|
||||||
|
But OpenAI’s Evals API is not the right control plane for Paperclip as the primary system because our target is explicitly multi-model and multi-provider.
|
||||||
|
|
||||||
|
### 4. Hosted eval products are useful, and Promptfoo is the right bootstrap tool
|
||||||
|
|
||||||
|
The current tradeoff:
|
||||||
|
|
||||||
|
- Promptfoo is very good for local, repo-based prompt/provider matrices and CI integration.
|
||||||
|
- LangSmith is strong on trajectory-style agent evals.
|
||||||
|
- Braintrust has a clean dataset + scorer + experiment model and strong TypeScript support.
|
||||||
|
|
||||||
|
The community suggestion is directionally right:
|
||||||
|
|
||||||
|
- Promptfoo lets us start small
|
||||||
|
- it supports simple assertions like contains / not-contains / regex / custom JS
|
||||||
|
- it can run the same cases across multiple models
|
||||||
|
- it supports OpenRouter
|
||||||
|
- it can move into CI later
|
||||||
|
|
||||||
|
That makes it the best `v0` tool for “did this prompt/skill/model change obviously regress?”
|
||||||
|
|
||||||
|
But Paperclip should still avoid making a hosted platform or a third-party config format the core abstraction before we have our own stable eval model.
|
||||||
|
|
||||||
|
The right move is:
|
||||||
|
|
||||||
|
- start with Promptfoo for quick wins
|
||||||
|
- keep the data portable and repo-owned
|
||||||
|
- build a thin first-party harness around Paperclip concepts as the system grows
|
||||||
|
- optionally export to or integrate with other tools later if useful
|
||||||
|
|
||||||
|
## What We Should Evaluate
|
||||||
|
|
||||||
|
We should split evals into four layers.
|
||||||
|
|
||||||
|
### Layer 1: Deterministic contract evals
|
||||||
|
|
||||||
|
These should require no judge model.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- agent comments on the assigned issue
|
||||||
|
- no mutation outside the agent’s company
|
||||||
|
- approval-required actions do not bypass approval flow
|
||||||
|
- task transitions are legal
|
||||||
|
- output contains required structured fields
|
||||||
|
- artifact links exist when the task required an artifact
|
||||||
|
- no full-thread refetch on delta-only cases once the API supports it
|
||||||
|
|
||||||
|
These are cheap, reliable, and should be the first line of defense.
|
||||||
|
|
||||||
|
### Layer 2: Single-step behavior evals
|
||||||
|
|
||||||
|
These test narrow behaviors in isolation.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- chooses the correct issue from inbox
|
||||||
|
- writes a reasonable first status comment
|
||||||
|
- decides to ask for approval instead of acting directly
|
||||||
|
- delegates to the correct report
|
||||||
|
- recognizes blocked state and reports it clearly
|
||||||
|
|
||||||
|
These are the closest thing to prompt evals, but still framed in Paperclip terms.
|
||||||
|
|
||||||
|
### Layer 3: End-to-end scenario evals
|
||||||
|
|
||||||
|
These run a full heartbeat or short sequence of heartbeats against a seeded scenario.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- new assignment pickup
|
||||||
|
- long-thread continuation
|
||||||
|
- mention-triggered clarification
|
||||||
|
- approval-gated hire request
|
||||||
|
- manager escalation
|
||||||
|
- workspace coding task that must leave a meaningful issue update
|
||||||
|
|
||||||
|
These should evaluate both final state and trace quality.
|
||||||
|
|
||||||
|
### Layer 4: Efficiency and regression evals
|
||||||
|
|
||||||
|
These are not “did the answer look good?” evals. They are “did we preserve quality while improving cost/latency?” evals.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- normalized input tokens per successful heartbeat
|
||||||
|
- normalized tokens per completed issue
|
||||||
|
- session reuse rate
|
||||||
|
- full-thread reload rate
|
||||||
|
- wall-clock duration
|
||||||
|
- cost per successful scenario
|
||||||
|
|
||||||
|
This layer is especially important for token optimization work.
|
||||||
|
|
||||||
|
## Core Design
|
||||||
|
|
||||||
|
## 1. Canonical object: `EvalCase`
|
||||||
|
|
||||||
|
Each eval case should define:
|
||||||
|
|
||||||
|
- scenario setup
|
||||||
|
- target bundle(s)
|
||||||
|
- execution mode
|
||||||
|
- expected invariants
|
||||||
|
- scoring rubric
|
||||||
|
- tags/metadata
|
||||||
|
|
||||||
|
Suggested shape:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type EvalCase = {
|
||||||
|
id: string;
|
||||||
|
description: string;
|
||||||
|
tags: string[];
|
||||||
|
setup: {
|
||||||
|
fixture: string;
|
||||||
|
agentId: string;
|
||||||
|
trigger: "assignment" | "timer" | "on_demand" | "comment" | "approval";
|
||||||
|
};
|
||||||
|
inputs?: Record<string, unknown>;
|
||||||
|
checks: {
|
||||||
|
hard: HardCheck[];
|
||||||
|
rubric?: RubricCheck[];
|
||||||
|
pairwise?: PairwiseCheck[];
|
||||||
|
};
|
||||||
|
metrics: MetricSpec[];
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
The important part is that the case is about a Paperclip scenario, not a standalone prompt string.
|
||||||
|
|
||||||
|
## 2. Canonical object: `EvalBundle`
|
||||||
|
|
||||||
|
Suggested shape:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type EvalBundle = {
|
||||||
|
id: string;
|
||||||
|
adapter: string;
|
||||||
|
model: string;
|
||||||
|
promptTemplate: string;
|
||||||
|
bootstrapPromptTemplate?: string;
|
||||||
|
skills: string[];
|
||||||
|
flags?: Record<string, string | number | boolean>;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Every comparison run should say which bundle was tested.
|
||||||
|
|
||||||
|
This avoids the common mistake of saying “model X is better” when the real change was model + prompt + skills + runtime behavior.
|
||||||
|
|
||||||
|
## 3. Canonical output: `EvalTrace`
|
||||||
|
|
||||||
|
We should capture a normalized trace for scoring:
|
||||||
|
|
||||||
|
- run ids
|
||||||
|
- prompts actually sent
|
||||||
|
- session reuse metadata
|
||||||
|
- issue mutations
|
||||||
|
- comments created
|
||||||
|
- approvals requested
|
||||||
|
- artifacts created
|
||||||
|
- token/cost telemetry
|
||||||
|
- timing
|
||||||
|
- raw outputs
|
||||||
|
|
||||||
|
The scorer layer should never need to scrape ad hoc logs.
|
||||||
|
|
||||||
|
## Scoring Framework
|
||||||
|
|
||||||
|
## 1. Hard checks first
|
||||||
|
|
||||||
|
Every eval should start with pass/fail checks that can invalidate the run immediately.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- touched wrong company
|
||||||
|
- skipped required approval
|
||||||
|
- no issue update produced
|
||||||
|
- returned malformed structured output
|
||||||
|
- marked task done without required artifact
|
||||||
|
|
||||||
|
If a hard check fails, the scenario fails regardless of style or judge score.
|
||||||
|
|
||||||
|
## 2. Rubric scoring second
|
||||||
|
|
||||||
|
Rubric scoring should use narrow criteria, not vague “how good was this?” prompts.
|
||||||
|
|
||||||
|
Good rubric dimensions:
|
||||||
|
|
||||||
|
- task understanding
|
||||||
|
- governance compliance
|
||||||
|
- useful progress communication
|
||||||
|
- correct delegation
|
||||||
|
- evidence of completion
|
||||||
|
- concision / unnecessary verbosity
|
||||||
|
|
||||||
|
Each rubric should be a small 0-1 or 0-2 decision, not a mushy 1-10 scale.
|
||||||
|
|
||||||
|
## 3. Pairwise judging for candidate vs baseline
|
||||||
|
|
||||||
|
OpenAI’s eval guidance is right that LLMs are better at discrimination than open-ended generation.
|
||||||
|
|
||||||
|
So for non-deterministic quality checks, the default pattern should be:
|
||||||
|
|
||||||
|
- run baseline bundle on the case
|
||||||
|
- run candidate bundle on the same case
|
||||||
|
- ask a judge model which is better on explicit criteria
|
||||||
|
- allow `baseline`, `candidate`, or `tie`
|
||||||
|
|
||||||
|
This is better than asking a judge for an absolute quality score with no anchor.
|
||||||
|
|
||||||
|
## 4. Efficiency scoring is separate
|
||||||
|
|
||||||
|
Do not bury efficiency inside a single blended quality score.
|
||||||
|
|
||||||
|
Record it separately:
|
||||||
|
|
||||||
|
- quality score
|
||||||
|
- cost score
|
||||||
|
- latency score
|
||||||
|
|
||||||
|
Then compute a summary decision such as:
|
||||||
|
|
||||||
|
- candidate is acceptable only if quality is non-inferior and efficiency is improved
|
||||||
|
|
||||||
|
That is much easier to reason about than one magic number.
|
||||||
|
|
||||||
|
## Suggested Decision Rule
|
||||||
|
|
||||||
|
For PR gating:
|
||||||
|
|
||||||
|
1. No hard-check regressions.
|
||||||
|
2. No significant regression on required scenario pass rate.
|
||||||
|
3. No significant regression on key rubric dimensions.
|
||||||
|
4. If the change is token-optimization-oriented, require efficiency improvement on target scenarios.
|
||||||
|
|
||||||
|
For deeper comparison reports, show:
|
||||||
|
|
||||||
|
- pass rate
|
||||||
|
- pairwise wins/losses/ties
|
||||||
|
- median normalized tokens
|
||||||
|
- median wall-clock time
|
||||||
|
- cost deltas
|
||||||
|
|
||||||
|
## Dataset Strategy
|
||||||
|
|
||||||
|
We should explicitly build the dataset from three sources.
|
||||||
|
|
||||||
|
### 1. Hand-authored seed cases
|
||||||
|
|
||||||
|
Start here.
|
||||||
|
|
||||||
|
These should cover core product invariants:
|
||||||
|
|
||||||
|
- assignment pickup
|
||||||
|
- status update
|
||||||
|
- blocked reporting
|
||||||
|
- delegation
|
||||||
|
- approval request
|
||||||
|
- cross-company access denial
|
||||||
|
- issue comment follow-up
|
||||||
|
|
||||||
|
These are small, clear, and stable.
|
||||||
|
|
||||||
|
### 2. Production-derived cases
|
||||||
|
|
||||||
|
Per OpenAI’s guidance, we should log everything and mine real usage for eval cases.
|
||||||
|
|
||||||
|
Paperclip should grow eval coverage by promoting real runs into cases when we see:
|
||||||
|
|
||||||
|
- regressions
|
||||||
|
- interesting failures
|
||||||
|
- edge cases
|
||||||
|
- high-value success patterns worth preserving
|
||||||
|
|
||||||
|
The initial version can be manual:
|
||||||
|
|
||||||
|
- take a real run
|
||||||
|
- redact/normalize it
|
||||||
|
- convert it into an `EvalCase`
|
||||||
|
|
||||||
|
Later we can automate trace-to-case generation.
|
||||||
|
|
||||||
|
### 3. Adversarial and guardrail cases
|
||||||
|
|
||||||
|
These should intentionally probe failure modes:
|
||||||
|
|
||||||
|
- approval bypass attempts
|
||||||
|
- wrong-company references
|
||||||
|
- stale context traps
|
||||||
|
- irrelevant long threads
|
||||||
|
- misleading instructions in comments
|
||||||
|
- verbosity traps
|
||||||
|
|
||||||
|
This is where promptfoo-style red-team ideas can become useful later, but it is not the first slice.
|
||||||
|
|
||||||
|
## Repo Layout
|
||||||
|
|
||||||
|
Recommended initial layout:
|
||||||
|
|
||||||
|
```text
|
||||||
|
evals/
|
||||||
|
README.md
|
||||||
|
promptfoo/
|
||||||
|
promptfooconfig.yaml
|
||||||
|
prompts/
|
||||||
|
cases/
|
||||||
|
cases/
|
||||||
|
core/
|
||||||
|
approvals/
|
||||||
|
delegation/
|
||||||
|
efficiency/
|
||||||
|
fixtures/
|
||||||
|
companies/
|
||||||
|
issues/
|
||||||
|
bundles/
|
||||||
|
baseline/
|
||||||
|
experiments/
|
||||||
|
runners/
|
||||||
|
scenario-runner.ts
|
||||||
|
compare-runner.ts
|
||||||
|
scorers/
|
||||||
|
hard/
|
||||||
|
rubric/
|
||||||
|
pairwise/
|
||||||
|
judges/
|
||||||
|
rubric-judge.ts
|
||||||
|
pairwise-judge.ts
|
||||||
|
lib/
|
||||||
|
types.ts
|
||||||
|
traces.ts
|
||||||
|
metrics.ts
|
||||||
|
reports/
|
||||||
|
.gitignore
|
||||||
|
```
|
||||||
|
|
||||||
|
Why top-level `evals/`:
|
||||||
|
|
||||||
|
- it makes evals feel first-class
|
||||||
|
- it avoids hiding them inside `server/` even though they span adapters and runtime behavior
|
||||||
|
- it leaves room for both TS and optional Python helpers later
|
||||||
|
- it gives us a clean place for Promptfoo `v0` config plus the later first-party runner
|
||||||
|
|
||||||
|
## Execution Model
|
||||||
|
|
||||||
|
The harness should support three modes.
|
||||||
|
|
||||||
|
### Mode A: Cheap local smoke
|
||||||
|
|
||||||
|
Purpose:
|
||||||
|
|
||||||
|
- run on PRs
|
||||||
|
- keep cost low
|
||||||
|
- catch obvious regressions
|
||||||
|
|
||||||
|
Characteristics:
|
||||||
|
|
||||||
|
- 5 to 20 cases
|
||||||
|
- 1 or 2 bundles
|
||||||
|
- mostly hard checks and narrow rubrics
|
||||||
|
|
||||||
|
### Mode B: Candidate vs baseline compare
|
||||||
|
|
||||||
|
Purpose:
|
||||||
|
|
||||||
|
- evaluate a prompt/skill/model change before merge
|
||||||
|
|
||||||
|
Characteristics:
|
||||||
|
|
||||||
|
- paired runs
|
||||||
|
- pairwise judging enabled
|
||||||
|
- quality + efficiency diff report
|
||||||
|
|
||||||
|
### Mode C: Nightly broader matrix
|
||||||
|
|
||||||
|
Purpose:
|
||||||
|
|
||||||
|
- compare multiple models and bundles
|
||||||
|
- grow historical benchmark data
|
||||||
|
|
||||||
|
Characteristics:
|
||||||
|
|
||||||
|
- larger case set
|
||||||
|
- multiple models
|
||||||
|
- more expensive rubric/pairwise judging
|
||||||
|
|
||||||
|
## CI and Developer Workflow
|
||||||
|
|
||||||
|
Suggested commands:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm evals:smoke
|
||||||
|
pnpm evals:compare --baseline baseline/codex-default --candidate experiments/codex-lean-skillset
|
||||||
|
pnpm evals:nightly
|
||||||
|
```
|
||||||
|
|
||||||
|
PR behavior:
|
||||||
|
|
||||||
|
- run `evals:smoke` on prompt/skill/adapter/runtime changes
|
||||||
|
- optionally trigger `evals:compare` for labeled PRs or manual runs
|
||||||
|
|
||||||
|
Nightly behavior:
|
||||||
|
|
||||||
|
- run larger matrix
|
||||||
|
- save report artifact
|
||||||
|
- surface trend lines on pass rate, pairwise wins, and efficiency
|
||||||
|
|
||||||
|
## Framework Comparison
|
||||||
|
|
||||||
|
## Promptfoo
|
||||||
|
|
||||||
|
Best use for Paperclip:
|
||||||
|
|
||||||
|
- prompt-level micro-evals
|
||||||
|
- provider/model comparison
|
||||||
|
- quick local CI integration
|
||||||
|
- custom JS assertions and custom providers
|
||||||
|
- bootstrap-layer evals for one skill or one agent workflow
|
||||||
|
|
||||||
|
What changed in this recommendation:
|
||||||
|
|
||||||
|
- Promptfoo is now the recommended **starting point**
|
||||||
|
- especially for “one skill, a handful of cases, compare across models”
|
||||||
|
|
||||||
|
Why it still should not be the only long-term system:
|
||||||
|
|
||||||
|
- its primary abstraction is still prompt/provider/test-case oriented
|
||||||
|
- Paperclip needs scenario setup, control-plane state inspection, and multi-step traces as first-class concepts
|
||||||
|
|
||||||
|
Recommendation:
|
||||||
|
|
||||||
|
- use Promptfoo first
|
||||||
|
- store Promptfoo config and cases in-repo under `evals/promptfoo/`
|
||||||
|
- use custom JS/TS assertions and, if needed later, a custom provider that calls Paperclip scenario runners
|
||||||
|
- do not make Promptfoo YAML the only canonical Paperclip eval format once we outgrow prompt-level evals
|
||||||
|
|
||||||
|
## LangSmith
|
||||||
|
|
||||||
|
What it gets right:
|
||||||
|
|
||||||
|
- final response evals
|
||||||
|
- trajectory evals
|
||||||
|
- single-step evals
|
||||||
|
|
||||||
|
Why not the primary system today:
|
||||||
|
|
||||||
|
- stronger fit for teams already centered on LangChain/LangGraph
|
||||||
|
- introduces hosted/external workflow gravity before our own eval model is stable
|
||||||
|
|
||||||
|
Recommendation:
|
||||||
|
|
||||||
|
- copy the trajectory/final/single-step taxonomy
|
||||||
|
- do not adopt the platform as the default requirement
|
||||||
|
|
||||||
|
## Braintrust
|
||||||
|
|
||||||
|
What it gets right:
|
||||||
|
|
||||||
|
- TypeScript support
|
||||||
|
- clean dataset/task/scorer model
|
||||||
|
- production logging to datasets
|
||||||
|
- experiment comparison over time
|
||||||
|
|
||||||
|
Why not the primary system today:
|
||||||
|
|
||||||
|
- still externalizes the canonical dataset and review workflow
|
||||||
|
- we are not yet at the maturity where hosted experiment management should define the shape of the system
|
||||||
|
|
||||||
|
Recommendation:
|
||||||
|
|
||||||
|
- borrow its dataset/scorer/experiment mental model
|
||||||
|
- revisit once we want hosted review and experiment history at scale
|
||||||
|
|
||||||
|
## OpenAI Evals / Evals API
|
||||||
|
|
||||||
|
What it gets right:
|
||||||
|
|
||||||
|
- strong eval principles
|
||||||
|
- emphasis on task-specific evals
|
||||||
|
- continuous evaluation mindset
|
||||||
|
|
||||||
|
Why not the primary system:
|
||||||
|
|
||||||
|
- Paperclip must compare across models/providers
|
||||||
|
- we do not want our primary eval runner coupled to one model vendor
|
||||||
|
|
||||||
|
Recommendation:
|
||||||
|
|
||||||
|
- use the guidance
|
||||||
|
- do not use it as the core Paperclip eval runtime
|
||||||
|
|
||||||
|
## First Implementation Slice
|
||||||
|
|
||||||
|
The first version should be intentionally small.
|
||||||
|
|
||||||
|
## Phase 0: Promptfoo bootstrap
|
||||||
|
|
||||||
|
Build:
|
||||||
|
|
||||||
|
- `evals/promptfoo/promptfooconfig.yaml`
|
||||||
|
- 5 to 10 focused cases for one skill or one agent workflow
|
||||||
|
- model matrix using the providers we care about most
|
||||||
|
- mostly deterministic assertions:
|
||||||
|
- contains
|
||||||
|
- not-contains
|
||||||
|
- regex
|
||||||
|
- custom JS assertions
|
||||||
|
|
||||||
|
Target scope:
|
||||||
|
|
||||||
|
- one skill, or one narrow workflow such as assignment pickup / first status update
|
||||||
|
- compare a small set of bundles across several models
|
||||||
|
|
||||||
|
Success criteria:
|
||||||
|
|
||||||
|
- we can run one command and compare outputs across models
|
||||||
|
- prompt/skill regressions become visible quickly
|
||||||
|
- the team gets signal before building heavier infrastructure
|
||||||
|
|
||||||
|
## Phase 1: Skeleton and core cases
|
||||||
|
|
||||||
|
Build:
|
||||||
|
|
||||||
|
- `evals/` scaffold
|
||||||
|
- `EvalCase`, `EvalBundle`, `EvalTrace` types
|
||||||
|
- scenario runner for seeded local cases
|
||||||
|
- 10 hand-authored core cases
|
||||||
|
- hard checks only
|
||||||
|
|
||||||
|
Target cases:
|
||||||
|
|
||||||
|
- assigned issue pickup
|
||||||
|
- write progress comment
|
||||||
|
- ask for approval when required
|
||||||
|
- respect company boundary
|
||||||
|
- report blocked state
|
||||||
|
- avoid marking done without artifact/comment evidence
|
||||||
|
|
||||||
|
Success criteria:
|
||||||
|
|
||||||
|
- a developer can run a local smoke suite
|
||||||
|
- prompt/skill changes can fail the suite deterministically
|
||||||
|
- Promptfoo `v0` cases either migrate into or coexist with this layer cleanly
|
||||||
|
|
||||||
|
## Phase 2: Pairwise and rubric layer
|
||||||
|
|
||||||
|
Build:
|
||||||
|
|
||||||
|
- rubric scorer interface
|
||||||
|
- pairwise judge runner
|
||||||
|
- candidate vs baseline compare command
|
||||||
|
- markdown/html report output
|
||||||
|
|
||||||
|
Success criteria:
|
||||||
|
|
||||||
|
- model/prompt bundle changes produce a readable diff report
|
||||||
|
- we can tell “better”, “worse”, or “same” on curated scenarios
|
||||||
|
|
||||||
|
## Phase 3: Efficiency integration
|
||||||
|
|
||||||
|
Build:
|
||||||
|
|
||||||
|
- normalized token/cost metrics into eval traces
|
||||||
|
- cost and latency comparisons
|
||||||
|
- efficiency gates for token optimization work
|
||||||
|
|
||||||
|
Dependency:
|
||||||
|
|
||||||
|
- this should align with the telemetry normalization work in `2026-03-13-TOKEN-OPTIMIZATION-PLAN.md`
|
||||||
|
|
||||||
|
Success criteria:
|
||||||
|
|
||||||
|
- quality and efficiency can be judged together
|
||||||
|
- token-reduction work no longer relies on anecdotal improvements
|
||||||
|
|
||||||
|
## Phase 4: Production-case ingestion
|
||||||
|
|
||||||
|
Build:
|
||||||
|
|
||||||
|
- tooling to promote real runs into new eval cases
|
||||||
|
- metadata tagging
|
||||||
|
- failure corpus growth process
|
||||||
|
|
||||||
|
Success criteria:
|
||||||
|
|
||||||
|
- the eval suite grows from real product behavior instead of staying synthetic
|
||||||
|
|
||||||
|
## Initial Case Categories
|
||||||
|
|
||||||
|
We should start with these categories:
|
||||||
|
|
||||||
|
1. `core.assignment_pickup`
|
||||||
|
2. `core.progress_update`
|
||||||
|
3. `core.blocked_reporting`
|
||||||
|
4. `governance.approval_required`
|
||||||
|
5. `governance.company_boundary`
|
||||||
|
6. `delegation.correct_report`
|
||||||
|
7. `threads.long_context_followup`
|
||||||
|
8. `efficiency.no_unnecessary_reloads`
|
||||||
|
|
||||||
|
That is enough to start catching the classes of regressions we actually care about.
|
||||||
|
|
||||||
|
## Important Guardrails
|
||||||
|
|
||||||
|
### 1. Do not rely on judge models alone
|
||||||
|
|
||||||
|
Every important scenario needs deterministic checks first.
|
||||||
|
|
||||||
|
### 2. Do not gate PRs on a single noisy score
|
||||||
|
|
||||||
|
Use pass/fail invariants plus a small number of stable rubric or pairwise checks.
|
||||||
|
|
||||||
|
### 3. Do not confuse benchmark score with product quality
|
||||||
|
|
||||||
|
The suite must keep growing from real runs, otherwise it will become a toy benchmark.
|
||||||
|
|
||||||
|
### 4. Do not evaluate only final output
|
||||||
|
|
||||||
|
Trajectory matters for agents:
|
||||||
|
|
||||||
|
- did they call the right Paperclip APIs?
|
||||||
|
- did they ask for approval?
|
||||||
|
- did they communicate progress?
|
||||||
|
- did they choose the right issue?
|
||||||
|
|
||||||
|
### 5. Do not make the framework vendor-shaped
|
||||||
|
|
||||||
|
Our eval model should survive changes in:
|
||||||
|
|
||||||
|
- judge provider
|
||||||
|
- candidate provider
|
||||||
|
- adapter implementation
|
||||||
|
- hosted tooling choices
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
1. Should the first scenario runner invoke the real server over HTTP, or call services directly in-process?
|
||||||
|
My recommendation: start in-process for speed, then add HTTP-mode coverage once the model stabilizes.
|
||||||
|
|
||||||
|
2. Should we support Python scorers in v1?
|
||||||
|
My recommendation: no. Keep v1 all-TypeScript.
|
||||||
|
|
||||||
|
3. Should we commit baseline outputs?
|
||||||
|
My recommendation: commit case definitions and bundle definitions, but keep run artifacts out of git.
|
||||||
|
|
||||||
|
4. Should we add hosted experiment tracking immediately?
|
||||||
|
My recommendation: no. Revisit after the local harness proves useful.
|
||||||
|
|
||||||
|
## Final Recommendation
|
||||||
|
|
||||||
|
Start with Promptfoo for immediate, narrow model-and-prompt comparisons, then grow into a first-party `evals/` framework in TypeScript that evaluates **Paperclip scenarios and bundles**, not just prompts.
|
||||||
|
|
||||||
|
Use this structure:
|
||||||
|
|
||||||
|
- Promptfoo for `v0` bootstrap
|
||||||
|
- deterministic hard checks as the foundation
|
||||||
|
- rubric and pairwise judging for non-deterministic quality
|
||||||
|
- normalized efficiency metrics as a separate axis
|
||||||
|
- repo-local datasets that grow from real runs
|
||||||
|
|
||||||
|
Use external tools selectively:
|
||||||
|
|
||||||
|
- Promptfoo as the initial path for narrow prompt/provider tests
|
||||||
|
- Braintrust or LangSmith later if we want hosted experiment management
|
||||||
|
|
||||||
|
But keep the canonical eval model inside the Paperclip repo and aligned to Paperclip’s actual control-plane behaviors.
|
||||||
780
doc/plans/2026-03-13-features.md
Normal file
780
doc/plans/2026-03-13-features.md
Normal file
@@ -0,0 +1,780 @@
|
|||||||
|
# Feature specs
|
||||||
|
|
||||||
|
## 1) Guided onboarding + first-job magic
|
||||||
|
|
||||||
|
The repo already has `onboard`, `doctor`, `run`, deployment modes, and even agent-oriented onboarding text/skills endpoints, but there are also current onboarding/auth validation issues and an open “onboard failed” report. That means this is not just polish; it is product-critical. ([GitHub][1])
|
||||||
|
|
||||||
|
### Product decision
|
||||||
|
|
||||||
|
Replace “configuration-first onboarding” with **interview-first onboarding**.
|
||||||
|
|
||||||
|
### What we want
|
||||||
|
|
||||||
|
- Ask 3–4 questions up front, not 20 settings.
|
||||||
|
- Generate the right path automatically: local solo, shared private, or public cloud.
|
||||||
|
- Detect what agent/runtime environment already exists.
|
||||||
|
- Make it normal to have Claude/OpenClaw/Codex help complete setup.
|
||||||
|
- End onboarding with a **real first task**, not a blank dashboard.
|
||||||
|
|
||||||
|
### What we do not want
|
||||||
|
|
||||||
|
- Provider jargon before value.
|
||||||
|
- “Go find an API key” as the default first instruction.
|
||||||
|
- A successful install that still leaves users unsure what to do next.
|
||||||
|
|
||||||
|
### Proposed UX
|
||||||
|
|
||||||
|
On first run, show an interview:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type OnboardingProfile = {
|
||||||
|
useCase: "startup" | "agency" | "internal_team";
|
||||||
|
companySource: "new" | "existing";
|
||||||
|
deployMode: "local_solo" | "shared_private" | "shared_public";
|
||||||
|
autonomyMode: "hands_on" | "hybrid" | "full_auto";
|
||||||
|
primaryRuntime: "claude_code" | "codex" | "openclaw" | "other";
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Questions:
|
||||||
|
|
||||||
|
1. What are you building?
|
||||||
|
2. Is this a new company, an existing company, or a service/agency team?
|
||||||
|
3. Are you working solo on one machine, sharing privately with a team, or deploying publicly?
|
||||||
|
4. Do you want full auto, hybrid, or tight manual control?
|
||||||
|
|
||||||
|
Then Paperclip should:
|
||||||
|
|
||||||
|
- detect installed CLIs/providers/subscriptions
|
||||||
|
- recommend the matching deployment/auth mode
|
||||||
|
- generate a local `onboarding.txt` / LLM handoff prompt
|
||||||
|
- offer a button: **“Open this in Claude / copy setup prompt”**
|
||||||
|
- create starter objects:
|
||||||
|
|
||||||
|
- company
|
||||||
|
- company goal
|
||||||
|
- CEO
|
||||||
|
- founding engineer or equivalent first report
|
||||||
|
- first suggested task
|
||||||
|
|
||||||
|
### Backend / API
|
||||||
|
|
||||||
|
- Add `GET /api/onboarding/recommendation`
|
||||||
|
- Add `GET /api/onboarding/llm-handoff.txt`
|
||||||
|
- Reuse existing invite/onboarding/skills patterns for local-first bootstrap
|
||||||
|
- Persist onboarding answers into instance config for later defaults
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
- Fresh install with a supported local runtime completes without manual JSON/env editing.
|
||||||
|
- User sees first live agent action before leaving onboarding.
|
||||||
|
- A blank dashboard is no longer the default post-install state.
|
||||||
|
- If a required dependency is missing, the error is prescriptive and fixable from the UI/CLI.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- Account creation
|
||||||
|
- enterprise SSO
|
||||||
|
- perfect provider auto-detection for every runtime
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2) Board command surface, not generic chat
|
||||||
|
|
||||||
|
There is a real tension here: the transcript says users want “chat with my CEO,” while the public product definition says Paperclip is **not a chatbot** and V1 communication is **tasks + comments only**. At the same time, the repo is already exploring plugin infrastructure and even a chat plugin via plugin SSE streaming. The clean resolution is: **make the core surface conversational, but keep the data model task/thread-centric; reserve full chat as an optional plugin**. ([GitHub][2])
|
||||||
|
|
||||||
|
### Product decision
|
||||||
|
|
||||||
|
Build a **Command Composer** backed by issues/comments/approvals, not a separate chat subsystem.
|
||||||
|
|
||||||
|
### What we want
|
||||||
|
|
||||||
|
- “Talk to the CEO” feeling for the user.
|
||||||
|
- Every conversation ends up attached to a real company object.
|
||||||
|
- Strategy discussion can produce issues, artifacts, and approvals.
|
||||||
|
|
||||||
|
### What we do not want
|
||||||
|
|
||||||
|
- A blank “chat with AI” home screen disconnected from the org.
|
||||||
|
- Yet another agent-chat product.
|
||||||
|
|
||||||
|
### Proposed UX
|
||||||
|
|
||||||
|
Add a global composer with modes:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type ComposerMode = "ask" | "task" | "decision";
|
||||||
|
type ThreadScope = "company" | "project" | "issue" | "agent";
|
||||||
|
```
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- On dashboard: “Ask the CEO for a hiring plan” → creates a `strategy` issue/thread scoped to the company.
|
||||||
|
- On agent page: “Tell the designer to make this cleaner” → appends an instruction comment to an issue or spawns a new delegated task.
|
||||||
|
- On approval page: “Why are you asking to hire?” → appends a board comment to the approval context.
|
||||||
|
|
||||||
|
Add issue kinds:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type IssueKind = "task" | "strategy" | "question" | "decision";
|
||||||
|
```
|
||||||
|
|
||||||
|
### Backend / data model
|
||||||
|
|
||||||
|
Prefer extending existing `issues` rather than creating `chats`:
|
||||||
|
|
||||||
|
- `issues.kind`
|
||||||
|
- `issues.scope`
|
||||||
|
- optional `issues.target_agent_id`
|
||||||
|
- comment metadata: `comment.intent = hint | correction | board_question | board_decision`
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
- A user can “ask CEO” from the dashboard and receive a response in a company-scoped thread.
|
||||||
|
- From that thread, the user can create/approve tasks with one click.
|
||||||
|
- No separate chat database is required for v1 of this feature.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- consumer chat UX
|
||||||
|
- model marketplace
|
||||||
|
- general-purpose assistant unrelated to company context
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3) Live org visibility + explainability layer
|
||||||
|
|
||||||
|
The core product promise is already visibility and governance, but right now the transcript makes clear that the UI is still too close to raw agent execution. The repo already has org charts, activity, heartbeat runs, costs, and agent detail surfaces; the missing piece is the explanatory layer above them. ([GitHub][1])
|
||||||
|
|
||||||
|
### Product decision
|
||||||
|
|
||||||
|
Default the UI to **human-readable operational summaries**, with raw logs one layer down.
|
||||||
|
|
||||||
|
### What we want
|
||||||
|
|
||||||
|
- At company level: “who is active, what are they doing, what is moving between teams”
|
||||||
|
- At agent level: “what is the plan, what step is complete, what outputs were produced”
|
||||||
|
- At run level: “summary first, transcript second”
|
||||||
|
|
||||||
|
### Proposed UX
|
||||||
|
|
||||||
|
Company page:
|
||||||
|
|
||||||
|
- org chart with live active-state indicators
|
||||||
|
- delegation animation between nodes when work moves
|
||||||
|
- current open priorities
|
||||||
|
- pending approvals
|
||||||
|
- burn / budget warning strip
|
||||||
|
|
||||||
|
Agent page:
|
||||||
|
|
||||||
|
- status card
|
||||||
|
- current issue
|
||||||
|
- plan checklist
|
||||||
|
- latest artifact(s)
|
||||||
|
- summary of last run
|
||||||
|
- expandable raw trace/logs
|
||||||
|
|
||||||
|
Run page:
|
||||||
|
|
||||||
|
- **Summary**
|
||||||
|
- **Steps**
|
||||||
|
- **Raw transcript / tool calls**
|
||||||
|
|
||||||
|
### Backend / API
|
||||||
|
|
||||||
|
Generate a run view model from current run/activity data:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type RunSummary = {
|
||||||
|
runId: string;
|
||||||
|
headline: string;
|
||||||
|
objective: string | null;
|
||||||
|
currentStep: string | null;
|
||||||
|
completedSteps: string[];
|
||||||
|
delegatedTo: { agentId: string; issueId?: string }[];
|
||||||
|
artifactIds: string[];
|
||||||
|
warnings: string[];
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Phase 1 can derive this server-side from existing run logs/comments. Persist only if needed later.
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
- Board can tell what is happening without reading shell commands.
|
||||||
|
- Raw logs are still accessible, but not the default surface.
|
||||||
|
- First task / first hire / first completion moments are visibly celebrated.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- overdesigned animation system
|
||||||
|
- perfect semantic summarization before core data quality exists
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4) Artifact system: attachments, file browser, previews
|
||||||
|
|
||||||
|
This gap is already showing up in the repo. Storage is present, attachment endpoints exist, but current issues show that attachments are still effectively image-centric and comment attachment rendering is incomplete. At the same time, your transcript wants plans, docs, files, and generated web pages surfaced cleanly. ([GitHub][4])
|
||||||
|
|
||||||
|
### Product decision
|
||||||
|
|
||||||
|
Introduce a first-class **Artifact** model that unifies:
|
||||||
|
|
||||||
|
- uploaded/generated files
|
||||||
|
- workspace files of interest
|
||||||
|
- preview URLs
|
||||||
|
- generated docs/reports
|
||||||
|
|
||||||
|
### What we want
|
||||||
|
|
||||||
|
- Plans, specs, CSVs, markdown, PDFs, logs, JSON, HTML outputs
|
||||||
|
- easy discoverability from the issue/run/company pages
|
||||||
|
- a lightweight file browser for project workspaces
|
||||||
|
- preview links for generated websites/apps
|
||||||
|
|
||||||
|
### What we do not want
|
||||||
|
|
||||||
|
- forcing agents to paste everything inline into comments
|
||||||
|
- HTML stuffed into comment bodies as a workaround
|
||||||
|
- a full web IDE
|
||||||
|
|
||||||
|
### Phase 1: fix the obvious gaps
|
||||||
|
|
||||||
|
- Accept non-image MIME types for issue attachments
|
||||||
|
- Attach files to comments correctly
|
||||||
|
- Show file metadata + download/open on issue page
|
||||||
|
|
||||||
|
### Phase 2: introduce artifacts
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type ArtifactKind = "attachment" | "workspace_file" | "preview" | "report_link";
|
||||||
|
|
||||||
|
interface Artifact {
|
||||||
|
id: string;
|
||||||
|
companyId: string;
|
||||||
|
issueId?: string;
|
||||||
|
runId?: string;
|
||||||
|
agentId?: string;
|
||||||
|
kind: ArtifactKind;
|
||||||
|
title: string;
|
||||||
|
mimeType?: string;
|
||||||
|
filename?: string;
|
||||||
|
sizeBytes?: number;
|
||||||
|
storageKind: "local_disk" | "s3" | "external_url";
|
||||||
|
contentPath?: string;
|
||||||
|
previewUrl?: string;
|
||||||
|
metadata: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### UX
|
||||||
|
|
||||||
|
Issue page gets a **Deliverables** section:
|
||||||
|
|
||||||
|
- Files
|
||||||
|
- Reports
|
||||||
|
- Preview links
|
||||||
|
- Latest generated artifact highlighted at top
|
||||||
|
|
||||||
|
Project page gets a **Files** tab:
|
||||||
|
|
||||||
|
- folder tree
|
||||||
|
- recent changes
|
||||||
|
- “Open produced files” shortcut
|
||||||
|
|
||||||
|
### Preview handling
|
||||||
|
|
||||||
|
For HTML/static outputs:
|
||||||
|
|
||||||
|
- local deploy → open local preview URL
|
||||||
|
- shared/public deploy → host via configured preview service or static storage
|
||||||
|
- preview URL is registered back onto the issue as an artifact
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
- Agents can attach `.md`, `.txt`, `.json`, `.csv`, `.pdf`, and `.html`.
|
||||||
|
- Users can open/download them from the issue page.
|
||||||
|
- A generated static site can be opened from an issue without hunting through the filesystem.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- browser IDE
|
||||||
|
- collaborative docs editor
|
||||||
|
- full object-storage admin UI
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5) Shared/cloud deployment + cloud runtimes
|
||||||
|
|
||||||
|
The repo already has a clear deployment story in docs: `local_trusted`, `authenticated/private`, and `authenticated/public`, plus Tailscale guidance. The roadmap explicitly calls out cloud agents like Cursor / e2b. That means the next step is not inventing a deployment model; it is making the shared/cloud path canonical and production-usable. ([GitHub][5])
|
||||||
|
|
||||||
|
### Product decision
|
||||||
|
|
||||||
|
Make **shared/private deploy** and **public/cloud deploy** first-class supported modes, and add **remote runtime drivers** for cloud-executed agents.
|
||||||
|
|
||||||
|
### What we want
|
||||||
|
|
||||||
|
- one instance a team can actually share
|
||||||
|
- local-first path that upgrades to private/public without a mental model change
|
||||||
|
- remote agent execution for non-local runtimes
|
||||||
|
|
||||||
|
### Proposed architecture
|
||||||
|
|
||||||
|
Separate **control plane** from **execution runtime** more explicitly:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type RuntimeDriver = "local_process" | "remote_sandbox" | "webhook";
|
||||||
|
|
||||||
|
interface ExecutionHandle {
|
||||||
|
externalRunId: string;
|
||||||
|
status: "queued" | "running" | "completed" | "failed" | "cancelled";
|
||||||
|
previewUrl?: string;
|
||||||
|
logsUrl?: string;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
First remote driver: `remote_sandbox` for e2b-style execution.
|
||||||
|
|
||||||
|
### Deliverables
|
||||||
|
|
||||||
|
- canonical deploy recipes:
|
||||||
|
|
||||||
|
- local solo
|
||||||
|
- shared private (Tailscale/private auth)
|
||||||
|
- public cloud (managed Postgres + object storage + public URL)
|
||||||
|
|
||||||
|
- runtime health page
|
||||||
|
- adapter/runtime capability matrix
|
||||||
|
- one official reference deployment path
|
||||||
|
|
||||||
|
### UX
|
||||||
|
|
||||||
|
New “Deployment” settings page:
|
||||||
|
|
||||||
|
- instance mode
|
||||||
|
- auth/exposure
|
||||||
|
- storage/database status
|
||||||
|
- runtime drivers configured
|
||||||
|
- health and reachability checks
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
- Two humans can log into one authenticated/private instance and use it concurrently.
|
||||||
|
- A public deployment can run agents via at least one remote runtime.
|
||||||
|
- `doctor` catches missing public/private config and gives concrete fixes.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- fully managed Paperclip SaaS
|
||||||
|
- every possible cloud provider in v1
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6) Multi-human collaboration (minimal, not enterprise RBAC)
|
||||||
|
|
||||||
|
This is the biggest deliberate departure from the current V1 spec. Publicly, V1 still says “single human board operator” and puts role-based human granularity out of scope. But the transcript is right that shared use is necessary if Paperclip is going to be real for teams. The key is to do a **minimal collaboration model**, not a giant permission system. ([GitHub][2])
|
||||||
|
|
||||||
|
### Product decision
|
||||||
|
|
||||||
|
Ship **coarse multi-user company memberships**, not fine-grained enterprise RBAC.
|
||||||
|
|
||||||
|
### Proposed roles
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type CompanyRole = "owner" | "admin" | "operator" | "viewer";
|
||||||
|
```
|
||||||
|
|
||||||
|
- **owner**: instance/company ownership, user invites, config
|
||||||
|
- **admin**: manage org, agents, budgets, approvals
|
||||||
|
- **operator**: create/update issues, interact with agents, view artifacts
|
||||||
|
- **viewer**: read-only
|
||||||
|
|
||||||
|
### Data model
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface CompanyMembership {
|
||||||
|
userId: string;
|
||||||
|
companyId: string;
|
||||||
|
role: CompanyRole;
|
||||||
|
invitedByUserId: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Stretch goal later:
|
||||||
|
|
||||||
|
- optional project/team scoping
|
||||||
|
|
||||||
|
### What we want
|
||||||
|
|
||||||
|
- shared dashboard for real teams
|
||||||
|
- user attribution in activity log
|
||||||
|
- simple invite flow
|
||||||
|
- company-level isolation preserved
|
||||||
|
|
||||||
|
### What we do not want
|
||||||
|
|
||||||
|
- per-field ACLs
|
||||||
|
- SCIM/SSO/enterprise admin consoles
|
||||||
|
- ten permission toggles per page
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
- Team of 3 can use one shared Paperclip instance.
|
||||||
|
- Every user action is attributed correctly in activity.
|
||||||
|
- Company membership boundaries are enforced.
|
||||||
|
- Viewer cannot mutate; operator/admin can.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- enterprise RBAC
|
||||||
|
- cross-company matrix permissions
|
||||||
|
- multi-board governance logic in first cut
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7) Auto mode + interrupt/resume
|
||||||
|
|
||||||
|
This is a product behavior issue, not a UI nicety. If agents cannot keep working or accept course correction without restarting, the autonomy model feels fake.
|
||||||
|
|
||||||
|
### Product decision
|
||||||
|
|
||||||
|
Make auto mode and mid-run interruption first-class runtime semantics.
|
||||||
|
|
||||||
|
### What we want
|
||||||
|
|
||||||
|
- Auto mode that continues until blocked by approvals, budgets, or explicit pause.
|
||||||
|
- Mid-run “you missed this” correction without losing session continuity.
|
||||||
|
- Clear state when an agent is waiting, blocked, or paused.
|
||||||
|
|
||||||
|
### Proposed state model
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type RunState =
|
||||||
|
| "queued"
|
||||||
|
| "running"
|
||||||
|
| "waiting_approval"
|
||||||
|
| "waiting_input"
|
||||||
|
| "paused"
|
||||||
|
| "completed"
|
||||||
|
| "failed"
|
||||||
|
| "cancelled";
|
||||||
|
```
|
||||||
|
|
||||||
|
Add board interjections as resumable input events:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface RunMessage {
|
||||||
|
runId: string;
|
||||||
|
authorUserId: string;
|
||||||
|
mode: "hint" | "correction" | "hard_override";
|
||||||
|
body: string;
|
||||||
|
resumeCurrentSession: boolean;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### UX
|
||||||
|
|
||||||
|
Buttons on active run:
|
||||||
|
|
||||||
|
- Pause
|
||||||
|
- Resume
|
||||||
|
- Interrupt
|
||||||
|
- Abort
|
||||||
|
- Restart from scratch
|
||||||
|
|
||||||
|
Interrupt opens a small composer that explicitly says:
|
||||||
|
|
||||||
|
- continue current session
|
||||||
|
- or restart run
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
- A board comment can resume an active session instead of spawning a fresh one.
|
||||||
|
- Session ID remains stable for “continue” path.
|
||||||
|
- UI clearly distinguishes blocked vs. waiting vs. paused.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- simultaneous multi-user live editing of the same run transcript
|
||||||
|
- perfect conversational UX before runtime semantics are fixed
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8) Cost safety + heartbeat/runtime hardening
|
||||||
|
|
||||||
|
This is probably the most important immediate workstream. The transcript says token burn is the highest pain, and the repo currently has active issues around budget enforcement evidence, onboarding/auth validation, and circuit-breaker style waste prevention. Public docs already promise hard budgets, and the issue tracker is pointing at the missing operational protections. ([GitHub][6])
|
||||||
|
|
||||||
|
### Product decision
|
||||||
|
|
||||||
|
Treat this as a **P0 runtime contract**, not a nice-to-have.
|
||||||
|
|
||||||
|
### Part A: deterministic wake gating
|
||||||
|
|
||||||
|
Do cheap, explicit work detection before invoking an LLM.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type WakeReason =
|
||||||
|
| "new_assignment"
|
||||||
|
| "new_comment"
|
||||||
|
| "mention"
|
||||||
|
| "approval_resolved"
|
||||||
|
| "scheduled_scan"
|
||||||
|
| "manual";
|
||||||
|
```
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- if no new actionable input exists, do not call the model
|
||||||
|
- scheduled scan should be a cheap policy check first, not a full reasoning pass
|
||||||
|
|
||||||
|
### Part B: budget contract
|
||||||
|
|
||||||
|
Keep the existing public promise, but make it undeniable:
|
||||||
|
|
||||||
|
- warning at 80%
|
||||||
|
- auto-pause at 100%
|
||||||
|
- visible audit trail
|
||||||
|
- explicit board override to continue
|
||||||
|
|
||||||
|
### Part C: circuit breaker
|
||||||
|
|
||||||
|
Add per-agent runtime guards:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface CircuitBreakerConfig {
|
||||||
|
enabled: boolean;
|
||||||
|
maxConsecutiveNoProgress: number;
|
||||||
|
maxConsecutiveFailures: number;
|
||||||
|
tokenVelocityMultiplier: number;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Trip when:
|
||||||
|
|
||||||
|
- no issue/status/comment progress for N runs
|
||||||
|
- N failures in a row
|
||||||
|
- token spike vs rolling average
|
||||||
|
|
||||||
|
### Part D: refactor heartbeat service
|
||||||
|
|
||||||
|
Split current orchestration into modules:
|
||||||
|
|
||||||
|
- wake detector
|
||||||
|
- checkout/lock manager
|
||||||
|
- adapter runner
|
||||||
|
- session manager
|
||||||
|
- cost recorder
|
||||||
|
- breaker evaluator
|
||||||
|
- event streamer
|
||||||
|
|
||||||
|
### Part E: regression suite
|
||||||
|
|
||||||
|
Mandatory automated proofs for:
|
||||||
|
|
||||||
|
- onboarding/auth matrix
|
||||||
|
- 80/100 budget behavior
|
||||||
|
- no cross-company auth leakage
|
||||||
|
- no-spurious-wake idle behavior
|
||||||
|
- active-run resume/interruption
|
||||||
|
- remote runtime smoke
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
- Idle org with no new work does not generate model calls from heartbeat scans.
|
||||||
|
- 80% shows warning only.
|
||||||
|
- 100% pauses the agent and blocks continued execution until override.
|
||||||
|
- Circuit breaker pause is visible in audit/activity.
|
||||||
|
- Runtime modules have explicit contracts and are testable independently.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- perfect autonomous optimization
|
||||||
|
- eliminating all wasted calls in every adapter/provider
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9) Project workspaces, previews, and PR handoff — without becoming GitHub
|
||||||
|
|
||||||
|
This is the right way to resolve the code-workflow debate. The repo already has worktree-local instances, project `workspaceStrategy.provisionCommand`, and an RFC for adapter-level git worktree isolation. That is the correct architectural direction: **project execution policies and workspace isolation**, not built-in PR review. ([GitHub][7])
|
||||||
|
|
||||||
|
### Product decision
|
||||||
|
|
||||||
|
Paperclip should manage the **issue → workspace → preview/PR → review handoff** lifecycle, but leave diffs/review/merge to external tools.
|
||||||
|
|
||||||
|
### Proposed config
|
||||||
|
|
||||||
|
Prefer repo-local project config:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .paperclip/project.yml
|
||||||
|
execution:
|
||||||
|
workspaceStrategy: shared | worktree | ephemeral_container
|
||||||
|
deliveryMode: artifact | preview | pull_request
|
||||||
|
provisionCommand: "pnpm install"
|
||||||
|
teardownCommand: "pnpm clean"
|
||||||
|
preview:
|
||||||
|
command: "pnpm dev --port $PAPERCLIP_PREVIEW_PORT"
|
||||||
|
healthPath: "/"
|
||||||
|
ttlMinutes: 120
|
||||||
|
vcs:
|
||||||
|
provider: github
|
||||||
|
repo: owner/repo
|
||||||
|
prPerIssue: true
|
||||||
|
baseBranch: main
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rules
|
||||||
|
|
||||||
|
- For non-code projects: `deliveryMode=artifact`
|
||||||
|
- For UI/app work: `deliveryMode=preview`
|
||||||
|
- For git-backed engineering projects: `deliveryMode=pull_request`
|
||||||
|
- For git-backed projects with `prPerIssue=true`, one issue maps to one isolated branch/worktree
|
||||||
|
|
||||||
|
### UX
|
||||||
|
|
||||||
|
Issue page shows:
|
||||||
|
|
||||||
|
- workspace link/status
|
||||||
|
- preview URL if available
|
||||||
|
- PR URL if created
|
||||||
|
- “Reopen preview” button with TTL
|
||||||
|
- lifecycle:
|
||||||
|
|
||||||
|
- `todo`
|
||||||
|
- `in_progress`
|
||||||
|
- `in_review`
|
||||||
|
- `done`
|
||||||
|
|
||||||
|
### What we want
|
||||||
|
|
||||||
|
- safe parallel agent work on one repo
|
||||||
|
- previewable output
|
||||||
|
- external PR review
|
||||||
|
- project-defined hooks, not hardcoded assumptions
|
||||||
|
|
||||||
|
### What we do not want
|
||||||
|
|
||||||
|
- built-in diff viewer
|
||||||
|
- merge queue
|
||||||
|
- Jira clone
|
||||||
|
- mandatory PRs for non-code work
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
- Multiple engineer agents can work concurrently without workspace contamination.
|
||||||
|
- When a project is in PR mode, the issue contains branch/worktree/preview/PR metadata.
|
||||||
|
- Preview can be reopened on demand until TTL expires.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- replacing GitHub/GitLab
|
||||||
|
- universal preview hosting for every framework on day one
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10) Plugin system as the escape hatch
|
||||||
|
|
||||||
|
The roadmap already includes plugins, GitHub discussions are active around it, and there is an open issue proposing an SSE bridge specifically to enable streaming plugin UIs such as chat, logs, and monitors. This is exactly the right place for optional surfaces. ([GitHub][1])
|
||||||
|
|
||||||
|
### Product decision
|
||||||
|
|
||||||
|
Keep the control-plane core thin; put optional high-variance experiences into plugins.
|
||||||
|
|
||||||
|
### First-party plugin targets
|
||||||
|
|
||||||
|
- Chat
|
||||||
|
- Knowledge base / RAG
|
||||||
|
- Log tail / live build output
|
||||||
|
- Custom tracing or queues
|
||||||
|
- Doc editor / proposal builder
|
||||||
|
|
||||||
|
### Plugin manifest
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface PluginManifest {
|
||||||
|
id: string;
|
||||||
|
version: string;
|
||||||
|
requestedPermissions: (
|
||||||
|
| "read_company"
|
||||||
|
| "read_issue"
|
||||||
|
| "write_issue_comment"
|
||||||
|
| "create_issue"
|
||||||
|
| "stream_ui"
|
||||||
|
)[];
|
||||||
|
surfaces: ("company_home" | "issue_panel" | "agent_panel" | "sidebar")[];
|
||||||
|
workerEntry: string;
|
||||||
|
uiEntry: string;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Platform requirements
|
||||||
|
|
||||||
|
- host ↔ worker action bridge
|
||||||
|
- SSE/UI streaming
|
||||||
|
- company-scoped auth
|
||||||
|
- permission declaration
|
||||||
|
- surface slots in UI
|
||||||
|
|
||||||
|
### Acceptance criteria
|
||||||
|
|
||||||
|
- A plugin can stream events to UI in real time.
|
||||||
|
- A chat plugin can converse without requiring chat to become the core Paperclip product.
|
||||||
|
- Plugin permissions are company-scoped and auditable.
|
||||||
|
|
||||||
|
### Non-goals
|
||||||
|
|
||||||
|
- plugins mutating core schema directly
|
||||||
|
- arbitrary privileged code execution without explicit permissions
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Priority order I would use
|
||||||
|
|
||||||
|
Given the repo state and the transcript, I would sequence it like this:
|
||||||
|
|
||||||
|
**P0**
|
||||||
|
|
||||||
|
1. Cost safety + heartbeat hardening
|
||||||
|
2. Guided onboarding + first-job magic
|
||||||
|
3. Shared/cloud deployment foundation
|
||||||
|
4. Artifact phase 1: non-image attachments + deliverables surfacing
|
||||||
|
|
||||||
|
**P1** 5. Board command surface 6. Visibility/explainability layer 7. Auto mode + interrupt/resume 8. Minimal multi-user collaboration
|
||||||
|
|
||||||
|
**P2** 9. Project workspace / preview / PR lifecycle 10. Plugin system + optional chat plugin 11. Template/preset expansion for startup vs agency vs internal-team onboarding
|
||||||
|
|
||||||
|
Why this order: the current repo is already getting pressure on onboarding failures, auth/onboarding validation, budget enforcement, and wasted token burn. If those are shaky, everything else feels impressive but unsafe. ([GitHub][3])
|
||||||
|
|
||||||
|
## Bottom line
|
||||||
|
|
||||||
|
The best synthesis is:
|
||||||
|
|
||||||
|
- **Keep** Paperclip as the board-level control plane.
|
||||||
|
- **Do not** make chat, code review, or workflow-building the core identity.
|
||||||
|
- **Do** make the product feel conversational, visible, output-oriented, and shared.
|
||||||
|
- **Do** make coding workflows an integration surface via workspaces/previews/PR links.
|
||||||
|
- **Use plugins** for richer edges like chat and knowledge.
|
||||||
|
|
||||||
|
That keeps the repo’s current product direction intact while solving almost every pain surfaced in the transcript.
|
||||||
|
|
||||||
|
### Key references
|
||||||
|
|
||||||
|
- README / positioning / roadmap / product boundaries. ([GitHub][1])
|
||||||
|
- Product definition. ([GitHub][8])
|
||||||
|
- V1 implementation spec and explicit non-goals. ([GitHub][2])
|
||||||
|
- Core concepts and architecture. ([GitHub][9])
|
||||||
|
- Deployment modes / Tailscale / local-to-cloud path. ([GitHub][5])
|
||||||
|
- Developing guide: worktree-local instances, provision hooks, onboarding endpoints. ([GitHub][7])
|
||||||
|
- Current issue pressure: onboarding failure, auth/onboarding validation, budget enforcement, circuit breaker, attachment gaps, plugin chat. ([GitHub][3])
|
||||||
|
|
||||||
|
[1]: https://github.com/paperclipai/paperclip "https://github.com/paperclipai/paperclip"
|
||||||
|
[2]: https://github.com/paperclipai/paperclip/blob/master/doc/SPEC-implementation.md "https://github.com/paperclipai/paperclip/blob/master/doc/SPEC-implementation.md"
|
||||||
|
[3]: https://github.com/paperclipai/paperclip/issues/704 "https://github.com/paperclipai/paperclip/issues/704"
|
||||||
|
[4]: https://github.com/paperclipai/paperclip/blob/master/docs/deploy/tailscale-private-access.md "https://github.com/paperclipai/paperclip/blob/master/docs/deploy/tailscale-private-access.md"
|
||||||
|
[5]: https://github.com/paperclipai/paperclip/blob/master/docs/deploy/deployment-modes.md "https://github.com/paperclipai/paperclip/blob/master/docs/deploy/deployment-modes.md"
|
||||||
|
[6]: https://github.com/paperclipai/paperclip/issues/692 "https://github.com/paperclipai/paperclip/issues/692"
|
||||||
|
[7]: https://github.com/paperclipai/paperclip/blob/master/doc/DEVELOPING.md "https://github.com/paperclipai/paperclip/blob/master/doc/DEVELOPING.md"
|
||||||
|
[8]: https://github.com/paperclipai/paperclip/blob/master/doc/PRODUCT.md "https://github.com/paperclipai/paperclip/blob/master/doc/PRODUCT.md"
|
||||||
|
[9]: https://github.com/paperclipai/paperclip/blob/master/docs/start/core-concepts.md "https://github.com/paperclipai/paperclip/blob/master/docs/start/core-concepts.md"
|
||||||
186
doc/plans/2026-03-13-paperclip-skill-tightening-plan.md
Normal file
186
doc/plans/2026-03-13-paperclip-skill-tightening-plan.md
Normal file
@@ -0,0 +1,186 @@
|
|||||||
|
# Paperclip Skill Tightening Plan
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Deferred follow-up. Do not include in the current token-optimization PR beyond documenting the plan.
|
||||||
|
|
||||||
|
## Why This Is Deferred
|
||||||
|
|
||||||
|
The `paperclip` skill is part of the critical control-plane safety surface. Tightening it may reduce fresh-session token use, but it also carries prompt-regression risk. We do not yet have evals that would let us safely prove behavior preservation across assignment handling, checkout rules, comment etiquette, approval workflows, and escalation paths.
|
||||||
|
|
||||||
|
The current PR should ship the lower-risk infrastructure wins first:
|
||||||
|
|
||||||
|
- telemetry normalization
|
||||||
|
- safe session reuse
|
||||||
|
- incremental issue/comment context
|
||||||
|
- bootstrap versus heartbeat prompt separation
|
||||||
|
- Codex worktree isolation
|
||||||
|
|
||||||
|
## Current Problem
|
||||||
|
|
||||||
|
Fresh runs still spend substantial input tokens even after the context-path fixes. The remaining large startup cost appears to come from loading the full `paperclip` skill and related instruction surface into context at run start.
|
||||||
|
|
||||||
|
The skill currently mixes three kinds of content in one file:
|
||||||
|
|
||||||
|
- hot-path heartbeat procedure used on nearly every run
|
||||||
|
- critical policy and safety invariants
|
||||||
|
- rare workflow/reference material that most runs do not need
|
||||||
|
|
||||||
|
That structure is safe but expensive.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
- reduce first-run instruction tokens without weakening agent safety
|
||||||
|
- preserve all current Paperclip control-plane capabilities
|
||||||
|
- keep common heartbeat behavior explicit and easy for agents to follow
|
||||||
|
- move rare workflows and reference material out of the hot path
|
||||||
|
- create a structure that can later be evaluated systematically
|
||||||
|
|
||||||
|
## Non-Goals
|
||||||
|
|
||||||
|
- changing Paperclip API semantics
|
||||||
|
- removing required governance rules
|
||||||
|
- deleting rare workflows
|
||||||
|
- changing agent defaults in the current PR
|
||||||
|
|
||||||
|
## Recommended Direction
|
||||||
|
|
||||||
|
### 1. Split Hot Path From Lookup Material
|
||||||
|
|
||||||
|
Restructure the skill into:
|
||||||
|
|
||||||
|
- an always-loaded core section for the common heartbeat loop
|
||||||
|
- on-demand material for infrequent workflows and deep reference
|
||||||
|
|
||||||
|
The core should cover only what is needed on nearly every wake:
|
||||||
|
|
||||||
|
- auth and required headers
|
||||||
|
- inbox-first assignment retrieval
|
||||||
|
- mandatory checkout behavior
|
||||||
|
- `heartbeat-context` first
|
||||||
|
- incremental comment retrieval rules
|
||||||
|
- mention/self-assign exception
|
||||||
|
- blocked-task dedup
|
||||||
|
- status/comment/release expectations before exit
|
||||||
|
|
||||||
|
### 2. Normalize The Skill Around One Canonical Procedure
|
||||||
|
|
||||||
|
The same rules are currently expressed multiple times across:
|
||||||
|
|
||||||
|
- heartbeat steps
|
||||||
|
- critical rules
|
||||||
|
- endpoint reference
|
||||||
|
- workflow examples
|
||||||
|
|
||||||
|
Refactor so each operational fact has one primary home:
|
||||||
|
|
||||||
|
- procedure
|
||||||
|
- invariant list
|
||||||
|
- appendix/reference
|
||||||
|
|
||||||
|
This reduces prompt weight and lowers the chance of internal instruction drift.
|
||||||
|
|
||||||
|
### 3. Compress Prose Into High-Signal Instruction Forms
|
||||||
|
|
||||||
|
Rewrite the hot path using compact operational forms:
|
||||||
|
|
||||||
|
- short ordered checklist
|
||||||
|
- flat invariant list
|
||||||
|
- minimal examples only where ambiguity would be risky
|
||||||
|
|
||||||
|
Reduce:
|
||||||
|
|
||||||
|
- narrative explanation
|
||||||
|
- repeated warnings already covered elsewhere
|
||||||
|
- large example payloads for common operations
|
||||||
|
- long endpoint matrices in the main body
|
||||||
|
|
||||||
|
### 4. Move Rare Workflows Behind Explicit Triggers
|
||||||
|
|
||||||
|
These workflows should remain available but should not dominate fresh-run context:
|
||||||
|
|
||||||
|
- OpenClaw invite flow
|
||||||
|
- project setup flow
|
||||||
|
- planning `<plan/>` writeback flow
|
||||||
|
- instructions-path update flow
|
||||||
|
- detailed link-formatting examples
|
||||||
|
|
||||||
|
Recommended approach:
|
||||||
|
|
||||||
|
- keep a short pointer in the main skill
|
||||||
|
- move detailed procedures into sibling skills or referenced docs that agents read only when needed
|
||||||
|
|
||||||
|
### 5. Separate Policy From Reference
|
||||||
|
|
||||||
|
The skill should distinguish:
|
||||||
|
|
||||||
|
- mandatory operating rules
|
||||||
|
- endpoint lookup/reference
|
||||||
|
- business-process playbooks
|
||||||
|
|
||||||
|
That separation makes it easier to evaluate prompt changes later and lets adapters or orchestration choose what must always be loaded.
|
||||||
|
|
||||||
|
## Proposed Target Structure
|
||||||
|
|
||||||
|
1. Purpose and authentication
|
||||||
|
2. Compact heartbeat procedure
|
||||||
|
3. Hard invariants
|
||||||
|
4. Required comment/update style
|
||||||
|
5. Triggered workflow index
|
||||||
|
6. Appendix/reference
|
||||||
|
|
||||||
|
## Rollout Plan
|
||||||
|
|
||||||
|
### Phase 1. Inventory And Measure
|
||||||
|
|
||||||
|
- annotate the current skill by section and estimate token weight
|
||||||
|
- identify which sections are truly hot-path versus rare
|
||||||
|
- capture representative runs to compare before/after prompt size and behavior
|
||||||
|
|
||||||
|
### Phase 2. Structural Refactor Without Semantic Changes
|
||||||
|
|
||||||
|
- rewrite the main skill into the target structure
|
||||||
|
- preserve all existing rules and capabilities
|
||||||
|
- move rare workflow details into referenced companion material
|
||||||
|
- keep wording changes conservative
|
||||||
|
|
||||||
|
### Phase 3. Validate Against Real Scenarios
|
||||||
|
|
||||||
|
Run scenario checks for:
|
||||||
|
|
||||||
|
- normal assigned heartbeat
|
||||||
|
- comment-triggered wake
|
||||||
|
- blocked-task dedup behavior
|
||||||
|
- approval-resolution wake
|
||||||
|
- delegation/subtask creation
|
||||||
|
- board handoff back to user
|
||||||
|
- plan-request handling
|
||||||
|
|
||||||
|
### Phase 4. Decide Default Loading Strategy
|
||||||
|
|
||||||
|
After validation, decide whether:
|
||||||
|
|
||||||
|
- the entire main skill still loads by default, or
|
||||||
|
- only the compact core loads by default and rare sections are fetched on demand
|
||||||
|
|
||||||
|
Do not change this loading policy without validation.
|
||||||
|
|
||||||
|
## Risks
|
||||||
|
|
||||||
|
- prompt degradation on control-plane safety rules
|
||||||
|
- agents forgetting rare but important workflows
|
||||||
|
- accidental removal of repeated wording that was carrying useful behavior
|
||||||
|
- introducing ambiguous instruction precedence between the core skill and companion materials
|
||||||
|
|
||||||
|
## Preconditions Before Implementation
|
||||||
|
|
||||||
|
- define acceptance scenarios for control-plane correctness
|
||||||
|
- add at least lightweight eval or scripted scenario coverage for key Paperclip flows
|
||||||
|
- confirm how adapter/bootstrap layering should load skill content versus references
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- materially lower first-run input tokens for Paperclip-coordinated agents
|
||||||
|
- no regression in checkout discipline, issue updates, blocked handling, or delegation
|
||||||
|
- no increase in malformed API usage or ownership mistakes
|
||||||
|
- agents still complete rare workflows correctly when explicitly asked
|
||||||
699
doc/plans/2026-03-13-plugin-kitchen-sink-example.md
Normal file
699
doc/plans/2026-03-13-plugin-kitchen-sink-example.md
Normal file
@@ -0,0 +1,699 @@
|
|||||||
|
# Kitchen Sink Plugin Plan
|
||||||
|
|
||||||
|
## Goal
|
||||||
|
|
||||||
|
Add a new first-party example plugin, `Kitchen Sink (Example)`, that demonstrates every currently implemented Paperclip plugin API surface in one place.
|
||||||
|
|
||||||
|
This plugin is meant to be:
|
||||||
|
|
||||||
|
- a living reference implementation for contributors
|
||||||
|
- a manual test harness for the plugin runtime
|
||||||
|
- a discoverable demo of what plugins can actually do today
|
||||||
|
|
||||||
|
It is not meant to be a polished end-user product plugin.
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
The current plugin system has a real API surface, but it is spread across:
|
||||||
|
|
||||||
|
- SDK docs
|
||||||
|
- SDK types
|
||||||
|
- plugin spec prose
|
||||||
|
- two example plugins that each show only a narrow slice
|
||||||
|
|
||||||
|
That makes it hard to answer basic questions like:
|
||||||
|
|
||||||
|
- what can plugins render?
|
||||||
|
- what can plugin workers actually do?
|
||||||
|
- which surfaces are real versus aspirational?
|
||||||
|
- how should a new plugin be structured in this repo?
|
||||||
|
|
||||||
|
The kitchen-sink plugin should answer those questions by example.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
The plugin is successful if a contributor can install it and, without reading the SDK first, discover and exercise the current plugin runtime surface area from inside Paperclip.
|
||||||
|
|
||||||
|
Concretely:
|
||||||
|
|
||||||
|
- it installs from the bundled examples list
|
||||||
|
- it exposes at least one demo for every implemented worker API surface
|
||||||
|
- it exposes at least one demo for every host-mounted UI surface
|
||||||
|
- it clearly labels local-only / trusted-only demos
|
||||||
|
- it is safe enough for local development by default
|
||||||
|
- it doubles as a regression harness for plugin runtime changes
|
||||||
|
|
||||||
|
## Constraints
|
||||||
|
|
||||||
|
- Keep it instance-installed, not company-installed.
|
||||||
|
- Treat this as a trusted/local example plugin.
|
||||||
|
- Do not rely on cloud-safe runtime assumptions.
|
||||||
|
- Avoid destructive defaults.
|
||||||
|
- Avoid irreversible mutations unless they are clearly labeled and easy to undo.
|
||||||
|
|
||||||
|
## Source Of Truth For This Plan
|
||||||
|
|
||||||
|
This plan is based on the currently implemented SDK/types/runtime, not only the long-horizon spec.
|
||||||
|
|
||||||
|
Primary references:
|
||||||
|
|
||||||
|
- `packages/plugins/sdk/README.md`
|
||||||
|
- `packages/plugins/sdk/src/types.ts`
|
||||||
|
- `packages/plugins/sdk/src/ui/types.ts`
|
||||||
|
- `packages/shared/src/constants.ts`
|
||||||
|
- `packages/shared/src/types/plugin.ts`
|
||||||
|
|
||||||
|
## Current Surface Inventory
|
||||||
|
|
||||||
|
### Worker/runtime APIs to demonstrate
|
||||||
|
|
||||||
|
These are the concrete `ctx` clients currently exposed by the SDK:
|
||||||
|
|
||||||
|
- `ctx.config`
|
||||||
|
- `ctx.events`
|
||||||
|
- `ctx.jobs`
|
||||||
|
- `ctx.launchers`
|
||||||
|
- `ctx.http`
|
||||||
|
- `ctx.secrets`
|
||||||
|
- `ctx.assets`
|
||||||
|
- `ctx.activity`
|
||||||
|
- `ctx.state`
|
||||||
|
- `ctx.entities`
|
||||||
|
- `ctx.projects`
|
||||||
|
- `ctx.companies`
|
||||||
|
- `ctx.issues`
|
||||||
|
- `ctx.agents`
|
||||||
|
- `ctx.goals`
|
||||||
|
- `ctx.data`
|
||||||
|
- `ctx.actions`
|
||||||
|
- `ctx.streams`
|
||||||
|
- `ctx.tools`
|
||||||
|
- `ctx.metrics`
|
||||||
|
- `ctx.logger`
|
||||||
|
|
||||||
|
### UI surfaces to demonstrate
|
||||||
|
|
||||||
|
Surfaces defined in the SDK:
|
||||||
|
|
||||||
|
- `page`
|
||||||
|
- `settingsPage`
|
||||||
|
- `dashboardWidget`
|
||||||
|
- `sidebar`
|
||||||
|
- `sidebarPanel`
|
||||||
|
- `detailTab`
|
||||||
|
- `taskDetailView`
|
||||||
|
- `projectSidebarItem`
|
||||||
|
- `toolbarButton`
|
||||||
|
- `contextMenuItem`
|
||||||
|
- `commentAnnotation`
|
||||||
|
- `commentContextMenuItem`
|
||||||
|
|
||||||
|
### Current host confidence
|
||||||
|
|
||||||
|
Confirmed or strongly indicated as mounted in the current app:
|
||||||
|
|
||||||
|
- `page`
|
||||||
|
- `settingsPage`
|
||||||
|
- `dashboardWidget`
|
||||||
|
- `detailTab`
|
||||||
|
- `projectSidebarItem`
|
||||||
|
- comment surfaces
|
||||||
|
- launcher infrastructure
|
||||||
|
|
||||||
|
Need explicit validation before claiming full demo coverage:
|
||||||
|
|
||||||
|
- `sidebar`
|
||||||
|
- `sidebarPanel`
|
||||||
|
- `taskDetailView`
|
||||||
|
- `toolbarButton` as direct slot, distinct from launcher placement
|
||||||
|
- `contextMenuItem` as direct slot, distinct from comment menu and launcher placement
|
||||||
|
|
||||||
|
The implementation should keep a small validation checklist for these before we call the plugin "complete".
|
||||||
|
|
||||||
|
## Plugin Concept
|
||||||
|
|
||||||
|
The plugin should be named:
|
||||||
|
|
||||||
|
- display name: `Kitchen Sink (Example)`
|
||||||
|
- package: `@paperclipai/plugin-kitchen-sink-example`
|
||||||
|
- plugin id: `paperclip.kitchen-sink-example` or `paperclip-kitchen-sink-example`
|
||||||
|
|
||||||
|
Recommendation: use `paperclip-kitchen-sink-example` to match current in-repo example naming style.
|
||||||
|
|
||||||
|
Category mix:
|
||||||
|
|
||||||
|
- `ui`
|
||||||
|
- `automation`
|
||||||
|
- `workspace`
|
||||||
|
- `connector`
|
||||||
|
|
||||||
|
That is intentionally broad because the point is coverage.
|
||||||
|
|
||||||
|
## UX Shape
|
||||||
|
|
||||||
|
The plugin should have one main full-page demo console plus smaller satellites on other surfaces.
|
||||||
|
|
||||||
|
### 1. Plugin page
|
||||||
|
|
||||||
|
Primary route: the plugin `page` surface should be the central dashboard for all demos.
|
||||||
|
|
||||||
|
Recommended page sections:
|
||||||
|
|
||||||
|
- `Overview`
|
||||||
|
- what this plugin demonstrates
|
||||||
|
- current capabilities granted
|
||||||
|
- current host context
|
||||||
|
- `UI Surfaces`
|
||||||
|
- links explaining where each other surface should appear
|
||||||
|
- `Data + Actions`
|
||||||
|
- buttons and forms for bridge-driven worker demos
|
||||||
|
- `Events + Streams`
|
||||||
|
- emit event
|
||||||
|
- watch event log
|
||||||
|
- stream demo output
|
||||||
|
- `Paperclip Domain APIs`
|
||||||
|
- companies
|
||||||
|
- projects/workspaces
|
||||||
|
- issues
|
||||||
|
- goals
|
||||||
|
- agents
|
||||||
|
- `Local Workspace + Process`
|
||||||
|
- file listing
|
||||||
|
- file read/write scratch area
|
||||||
|
- child process demo
|
||||||
|
- `Jobs + Webhooks + Tools`
|
||||||
|
- job status
|
||||||
|
- webhook URL and recent deliveries
|
||||||
|
- declared tools
|
||||||
|
- `State + Entities + Assets`
|
||||||
|
- scoped state editor
|
||||||
|
- plugin entity inspector
|
||||||
|
- upload/generated asset demo
|
||||||
|
- `Observability`
|
||||||
|
- metrics written
|
||||||
|
- activity log samples
|
||||||
|
- latest worker logs
|
||||||
|
|
||||||
|
### 2. Dashboard widget
|
||||||
|
|
||||||
|
A compact widget on the main dashboard should show:
|
||||||
|
|
||||||
|
- plugin health
|
||||||
|
- count of demos exercised
|
||||||
|
- recent event/stream activity
|
||||||
|
- shortcut to the full plugin page
|
||||||
|
|
||||||
|
### 3. Project sidebar item
|
||||||
|
|
||||||
|
Add a `Kitchen Sink` link under each project that deep-links into a project-scoped plugin tab.
|
||||||
|
|
||||||
|
### 4. Detail tabs
|
||||||
|
|
||||||
|
Use detail tabs to demonstrate entity-context rendering on:
|
||||||
|
|
||||||
|
- `project`
|
||||||
|
- `issue`
|
||||||
|
- `agent`
|
||||||
|
- `goal`
|
||||||
|
|
||||||
|
Each tab should show:
|
||||||
|
|
||||||
|
- the host context it received
|
||||||
|
- the relevant entity fetch via worker bridge
|
||||||
|
- one small action scoped to that entity
|
||||||
|
|
||||||
|
### 5. Comment surfaces
|
||||||
|
|
||||||
|
Use issue comment demos to prove comment-specific extension points:
|
||||||
|
|
||||||
|
- `commentAnnotation`
|
||||||
|
- render parsed metadata below each comment
|
||||||
|
- show comment id, issue id, and a small derived status
|
||||||
|
- `commentContextMenuItem`
|
||||||
|
- add a menu action like `Copy Context To Kitchen Sink`
|
||||||
|
- action writes a plugin entity or state record for later inspection
|
||||||
|
|
||||||
|
### 6. Settings page
|
||||||
|
|
||||||
|
Custom `settingsPage` should be intentionally simple and operational:
|
||||||
|
|
||||||
|
- `About`
|
||||||
|
- `Danger / Trust Model`
|
||||||
|
- demo toggles
|
||||||
|
- local process defaults
|
||||||
|
- workspace scratch-path behavior
|
||||||
|
- secret reference inputs
|
||||||
|
- event/job/webhook sample config
|
||||||
|
|
||||||
|
This plugin should also keep the generic plugin settings `Status` tab useful by writing health, logs, and metrics.
|
||||||
|
|
||||||
|
## Feature Matrix
|
||||||
|
|
||||||
|
Each implemented worker API should have a visible demo.
|
||||||
|
|
||||||
|
### `ctx.config`
|
||||||
|
|
||||||
|
Demo:
|
||||||
|
|
||||||
|
- read live config
|
||||||
|
- show config JSON
|
||||||
|
- react to config changes without restart where possible
|
||||||
|
|
||||||
|
### `ctx.events`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- emit a plugin event
|
||||||
|
- subscribe to plugin events
|
||||||
|
- subscribe to a core Paperclip event such as `issue.created`
|
||||||
|
- show recent received events in a timeline
|
||||||
|
|
||||||
|
### `ctx.jobs`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- one scheduled heartbeat-style demo job
|
||||||
|
- one manual run button from the UI if host supports manual job trigger
|
||||||
|
- show last run result and timestamps
|
||||||
|
|
||||||
|
### `ctx.launchers`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- declare launchers in manifest
|
||||||
|
- optionally register one runtime launcher from the worker
|
||||||
|
- show launcher metadata on the plugin page
|
||||||
|
|
||||||
|
### `ctx.http`
|
||||||
|
|
||||||
|
Demo:
|
||||||
|
|
||||||
|
- make a simple outbound GET request to a safe endpoint
|
||||||
|
- show status code, latency, and JSON result
|
||||||
|
|
||||||
|
Recommendation: default to a Paperclip-local endpoint or a stable public echo endpoint to avoid flaky docs.
|
||||||
|
|
||||||
|
### `ctx.secrets`
|
||||||
|
|
||||||
|
Demo:
|
||||||
|
|
||||||
|
- operator enters a secret reference in config
|
||||||
|
- plugin resolves it on demand
|
||||||
|
- UI only shows masked result length / success status, never raw secret
|
||||||
|
|
||||||
|
### `ctx.assets`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- generate a text asset from the UI
|
||||||
|
- optionally upload a tiny JSON blob or screenshot-like text file
|
||||||
|
- show returned asset URL
|
||||||
|
|
||||||
|
### `ctx.activity`
|
||||||
|
|
||||||
|
Demo:
|
||||||
|
|
||||||
|
- button to write a plugin activity log entry against current company/entity
|
||||||
|
|
||||||
|
### `ctx.state`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- instance-scoped state
|
||||||
|
- company-scoped state
|
||||||
|
- project-scoped state
|
||||||
|
- issue-scoped state
|
||||||
|
- delete/reset controls
|
||||||
|
|
||||||
|
Use a small state inspector/editor on the plugin page.
|
||||||
|
|
||||||
|
### `ctx.entities`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- create plugin-owned sample records
|
||||||
|
- list/filter them
|
||||||
|
- show one realistic use case such as "copied comments" or "demo sync records"
|
||||||
|
|
||||||
|
### `ctx.projects`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- list projects
|
||||||
|
- list project workspaces
|
||||||
|
- resolve primary workspace
|
||||||
|
- resolve workspace for issue
|
||||||
|
|
||||||
|
### `ctx.companies`
|
||||||
|
|
||||||
|
Demo:
|
||||||
|
|
||||||
|
- list companies and show current selected company
|
||||||
|
|
||||||
|
### `ctx.issues`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- list issues in current company
|
||||||
|
- create issue
|
||||||
|
- update issue status/title
|
||||||
|
- list comments
|
||||||
|
- create comment
|
||||||
|
|
||||||
|
### `ctx.agents`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- list agents
|
||||||
|
- invoke one agent with a test prompt
|
||||||
|
- pause/resume where safe
|
||||||
|
|
||||||
|
Agent mutation controls should be behind an explicit warning.
|
||||||
|
|
||||||
|
### `ctx.agents.sessions`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- create agent chat session
|
||||||
|
- send message
|
||||||
|
- stream events back to the UI
|
||||||
|
- close session
|
||||||
|
|
||||||
|
This is a strong candidate for the best "wow" demo on the plugin page.
|
||||||
|
|
||||||
|
### `ctx.goals`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- list goals
|
||||||
|
- create goal
|
||||||
|
- update status/title
|
||||||
|
|
||||||
|
### `ctx.data`
|
||||||
|
|
||||||
|
Use throughout the plugin for all read-side bridge demos.
|
||||||
|
|
||||||
|
### `ctx.actions`
|
||||||
|
|
||||||
|
Use throughout the plugin for all mutation-side bridge demos.
|
||||||
|
|
||||||
|
### `ctx.streams`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- live event log stream
|
||||||
|
- token-style stream from an agent session relay
|
||||||
|
- fake progress stream for a long-running action
|
||||||
|
|
||||||
|
### `ctx.tools`
|
||||||
|
|
||||||
|
Demos:
|
||||||
|
|
||||||
|
- declare 2-3 simple agent tools
|
||||||
|
- tool 1: echo/diagnostics
|
||||||
|
- tool 2: project/workspace summary
|
||||||
|
- tool 3: create issue or write plugin state
|
||||||
|
|
||||||
|
The plugin page should list declared tools and show example input payloads.
|
||||||
|
|
||||||
|
### `ctx.metrics`
|
||||||
|
|
||||||
|
Demo:
|
||||||
|
|
||||||
|
- write a sample metric on each major demo action
|
||||||
|
- surface a small recent metrics table in the plugin page
|
||||||
|
|
||||||
|
### `ctx.logger`
|
||||||
|
|
||||||
|
Demo:
|
||||||
|
|
||||||
|
- every action logs structured entries
|
||||||
|
- plugin settings `Status` page then doubles as the log viewer
|
||||||
|
|
||||||
|
## Local Workspace And Process Demos
|
||||||
|
|
||||||
|
The plugin SDK intentionally leaves file/process operations to the plugin itself once it has workspace metadata.
|
||||||
|
|
||||||
|
The kitchen-sink plugin should demonstrate that explicitly.
|
||||||
|
|
||||||
|
### Workspace demos
|
||||||
|
|
||||||
|
- list files from a selected workspace
|
||||||
|
- read a file
|
||||||
|
- write to a plugin-owned scratch file
|
||||||
|
- optionally search files with `rg` if available
|
||||||
|
|
||||||
|
### Process demos
|
||||||
|
|
||||||
|
- run a short-lived command like `pwd`, `ls`, or `git status`
|
||||||
|
- stream stdout/stderr back to UI
|
||||||
|
- show exit code and timing
|
||||||
|
|
||||||
|
Important safeguards:
|
||||||
|
|
||||||
|
- default commands must be read-only
|
||||||
|
- no shell interpolation from arbitrary free-form input in v1
|
||||||
|
- provide a curated command list or a strongly validated command form
|
||||||
|
- clearly label this area as local-only and trusted-only
|
||||||
|
|
||||||
|
## Proposed Manifest Coverage
|
||||||
|
|
||||||
|
The plugin should aim to declare:
|
||||||
|
|
||||||
|
- `page`
|
||||||
|
- `settingsPage`
|
||||||
|
- `dashboardWidget`
|
||||||
|
- `detailTab` for `project`, `issue`, `agent`, `goal`
|
||||||
|
- `projectSidebarItem`
|
||||||
|
- `commentAnnotation`
|
||||||
|
- `commentContextMenuItem`
|
||||||
|
|
||||||
|
Then, after host validation, add if supported:
|
||||||
|
|
||||||
|
- `sidebar`
|
||||||
|
- `sidebarPanel`
|
||||||
|
- `taskDetailView`
|
||||||
|
- `toolbarButton`
|
||||||
|
- `contextMenuItem`
|
||||||
|
|
||||||
|
It should also declare one or more `ui.launchers` entries to exercise launcher behavior independently of slot rendering.
|
||||||
|
|
||||||
|
## Proposed Package Layout
|
||||||
|
|
||||||
|
New package:
|
||||||
|
|
||||||
|
- `packages/plugins/examples/plugin-kitchen-sink-example/`
|
||||||
|
|
||||||
|
Expected files:
|
||||||
|
|
||||||
|
- `package.json`
|
||||||
|
- `README.md`
|
||||||
|
- `tsconfig.json`
|
||||||
|
- `src/index.ts`
|
||||||
|
- `src/manifest.ts`
|
||||||
|
- `src/worker.ts`
|
||||||
|
- `src/ui/index.tsx`
|
||||||
|
- `src/ui/components/...`
|
||||||
|
- `src/ui/hooks/...`
|
||||||
|
- `src/lib/...`
|
||||||
|
- optional `scripts/build-ui.mjs` if UI bundling needs esbuild
|
||||||
|
|
||||||
|
## Proposed Internal Architecture
|
||||||
|
|
||||||
|
### Worker modules
|
||||||
|
|
||||||
|
Recommended split:
|
||||||
|
|
||||||
|
- `src/worker.ts`
|
||||||
|
- plugin definition and wiring
|
||||||
|
- `src/worker/data.ts`
|
||||||
|
- `ctx.data.register(...)`
|
||||||
|
- `src/worker/actions.ts`
|
||||||
|
- `ctx.actions.register(...)`
|
||||||
|
- `src/worker/events.ts`
|
||||||
|
- event subscriptions and event log buffer
|
||||||
|
- `src/worker/jobs.ts`
|
||||||
|
- scheduled job handlers
|
||||||
|
- `src/worker/tools.ts`
|
||||||
|
- tool declarations and handlers
|
||||||
|
- `src/worker/local-runtime.ts`
|
||||||
|
- file/process demos
|
||||||
|
- `src/worker/demo-store.ts`
|
||||||
|
- helpers for state/entities/assets/metrics
|
||||||
|
|
||||||
|
### UI modules
|
||||||
|
|
||||||
|
Recommended split:
|
||||||
|
|
||||||
|
- `src/ui/index.tsx`
|
||||||
|
- exported slot components
|
||||||
|
- `src/ui/page/KitchenSinkPage.tsx`
|
||||||
|
- `src/ui/settings/KitchenSinkSettingsPage.tsx`
|
||||||
|
- `src/ui/widgets/KitchenSinkDashboardWidget.tsx`
|
||||||
|
- `src/ui/tabs/ProjectKitchenSinkTab.tsx`
|
||||||
|
- `src/ui/tabs/IssueKitchenSinkTab.tsx`
|
||||||
|
- `src/ui/tabs/AgentKitchenSinkTab.tsx`
|
||||||
|
- `src/ui/tabs/GoalKitchenSinkTab.tsx`
|
||||||
|
- `src/ui/comments/KitchenSinkCommentAnnotation.tsx`
|
||||||
|
- `src/ui/comments/KitchenSinkCommentMenuItem.tsx`
|
||||||
|
- `src/ui/shared/...`
|
||||||
|
|
||||||
|
## Configuration Schema
|
||||||
|
|
||||||
|
The plugin should have a substantial but understandable `instanceConfigSchema`.
|
||||||
|
|
||||||
|
Recommended config fields:
|
||||||
|
|
||||||
|
- `enableDangerousDemos`
|
||||||
|
- `enableWorkspaceDemos`
|
||||||
|
- `enableProcessDemos`
|
||||||
|
- `showSidebarEntry`
|
||||||
|
- `showSidebarPanel`
|
||||||
|
- `showProjectSidebarItem`
|
||||||
|
- `showCommentAnnotation`
|
||||||
|
- `showCommentContextMenuItem`
|
||||||
|
- `showToolbarLauncher`
|
||||||
|
- `defaultDemoCompanyId` optional
|
||||||
|
- `secretRefExample`
|
||||||
|
- `httpDemoUrl`
|
||||||
|
- `processAllowedCommands`
|
||||||
|
- `workspaceScratchSubdir`
|
||||||
|
|
||||||
|
Defaults should keep risky behavior off.
|
||||||
|
|
||||||
|
## Safety Defaults
|
||||||
|
|
||||||
|
Default posture:
|
||||||
|
|
||||||
|
- UI and read-only demos on
|
||||||
|
- mutating domain demos on but explicitly labeled
|
||||||
|
- process demos off by default
|
||||||
|
- no arbitrary shell input by default
|
||||||
|
- no raw secret rendering ever
|
||||||
|
|
||||||
|
## Phased Build Plan
|
||||||
|
|
||||||
|
### Phase 1: Core plugin skeleton
|
||||||
|
|
||||||
|
- scaffold package
|
||||||
|
- add manifest, worker, UI entrypoints
|
||||||
|
- add README
|
||||||
|
- make it appear in bundled examples list
|
||||||
|
|
||||||
|
### Phase 2: Core, confirmed UI surfaces
|
||||||
|
|
||||||
|
- plugin page
|
||||||
|
- settings page
|
||||||
|
- dashboard widget
|
||||||
|
- project sidebar item
|
||||||
|
- detail tabs
|
||||||
|
|
||||||
|
### Phase 3: Core worker APIs
|
||||||
|
|
||||||
|
- config
|
||||||
|
- state
|
||||||
|
- entities
|
||||||
|
- companies/projects/issues/goals
|
||||||
|
- data/actions
|
||||||
|
- metrics/logger/activity
|
||||||
|
|
||||||
|
### Phase 4: Real-time and automation APIs
|
||||||
|
|
||||||
|
- streams
|
||||||
|
- events
|
||||||
|
- jobs
|
||||||
|
- webhooks
|
||||||
|
- agent sessions
|
||||||
|
- tools
|
||||||
|
|
||||||
|
### Phase 5: Local trusted runtime demos
|
||||||
|
|
||||||
|
- workspace file demos
|
||||||
|
- child process demos
|
||||||
|
- guarded by config
|
||||||
|
|
||||||
|
### Phase 6: Secondary UI surfaces
|
||||||
|
|
||||||
|
- comment annotation
|
||||||
|
- comment context menu item
|
||||||
|
- launchers
|
||||||
|
|
||||||
|
### Phase 7: Validation-only surfaces
|
||||||
|
|
||||||
|
Validate whether the current host truly mounts:
|
||||||
|
|
||||||
|
- `sidebar`
|
||||||
|
- `sidebarPanel`
|
||||||
|
- `taskDetailView`
|
||||||
|
- direct-slot `toolbarButton`
|
||||||
|
- direct-slot `contextMenuItem`
|
||||||
|
|
||||||
|
If mounted, add demos.
|
||||||
|
If not mounted, document them as SDK-defined but host-pending.
|
||||||
|
|
||||||
|
## Documentation Deliverables
|
||||||
|
|
||||||
|
The plugin should ship with a README that includes:
|
||||||
|
|
||||||
|
- what it demonstrates
|
||||||
|
- which surfaces are local-only
|
||||||
|
- how to install it
|
||||||
|
- where each UI surface should appear
|
||||||
|
- a mapping from demo card to SDK API
|
||||||
|
|
||||||
|
It should also be referenced from plugin docs as the "reference everything plugin".
|
||||||
|
|
||||||
|
## Testing And Verification
|
||||||
|
|
||||||
|
Minimum verification:
|
||||||
|
|
||||||
|
- package typecheck/build
|
||||||
|
- install from bundled example list
|
||||||
|
- page loads
|
||||||
|
- widget appears
|
||||||
|
- project tab appears
|
||||||
|
- comment surfaces render
|
||||||
|
- settings page loads
|
||||||
|
- key actions succeed
|
||||||
|
|
||||||
|
Recommended manual checklist:
|
||||||
|
|
||||||
|
- create issue from plugin
|
||||||
|
- create goal from plugin
|
||||||
|
- emit and receive plugin event
|
||||||
|
- stream action output
|
||||||
|
- open agent session and receive streamed reply
|
||||||
|
- upload an asset
|
||||||
|
- write plugin activity log
|
||||||
|
- run a safe local process demo
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
1. Should the process demo remain curated-command-only in the first pass?
|
||||||
|
Recommendation: yes.
|
||||||
|
|
||||||
|
2. Should the plugin create throwaway "kitchen sink demo" issues/goals automatically?
|
||||||
|
Recommendation: no. Make creation explicit.
|
||||||
|
|
||||||
|
3. Should we expose unsupported-but-typed surfaces in the UI even if host mounting is not wired?
|
||||||
|
Recommendation: yes, but label them as `SDK-defined / host validation pending`.
|
||||||
|
|
||||||
|
4. Should agent mutation demos include pause/resume by default?
|
||||||
|
Recommendation: probably yes, but behind a warning block.
|
||||||
|
|
||||||
|
5. Should this plugin be treated as a supported regression harness in CI later?
|
||||||
|
Recommendation: yes. Long term, this should be the plugin-runtime smoke test package.
|
||||||
|
|
||||||
|
## Recommended Next Step
|
||||||
|
|
||||||
|
If this plan looks right, the next implementation pass should start by building only:
|
||||||
|
|
||||||
|
- package skeleton
|
||||||
|
- page
|
||||||
|
- settings page
|
||||||
|
- dashboard widget
|
||||||
|
- one project detail tab
|
||||||
|
- one issue detail tab
|
||||||
|
- the basic worker/action/data/state/event scaffolding
|
||||||
|
|
||||||
|
That is enough to lock the architecture before filling in every demo surface.
|
||||||
1126
doc/plans/2026-03-13-workspace-product-model-and-work-product.md
Normal file
1126
doc/plans/2026-03-13-workspace-product-model-and-work-product.md
Normal file
File diff suppressed because it is too large
Load Diff
155
doc/plugins/PLUGIN_AUTHORING_GUIDE.md
Normal file
155
doc/plugins/PLUGIN_AUTHORING_GUIDE.md
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
# Plugin Authoring Guide
|
||||||
|
|
||||||
|
This guide describes the current, implemented way to create a Paperclip plugin in this repo.
|
||||||
|
|
||||||
|
It is intentionally narrower than [PLUGIN_SPEC.md](./PLUGIN_SPEC.md). The spec includes future ideas; this guide only covers the alpha surface that exists now.
|
||||||
|
|
||||||
|
## Current reality
|
||||||
|
|
||||||
|
- Treat plugin workers and plugin UI as trusted code.
|
||||||
|
- Plugin UI runs as same-origin JavaScript inside the main Paperclip app.
|
||||||
|
- Worker-side host APIs are capability-gated.
|
||||||
|
- Plugin UI is not sandboxed by manifest capabilities.
|
||||||
|
- There is no host-provided shared React component kit for plugins yet.
|
||||||
|
- `ctx.assets` is not supported in the current runtime.
|
||||||
|
|
||||||
|
## Scaffold a plugin
|
||||||
|
|
||||||
|
Use the scaffold package:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm --filter @paperclipai/create-paperclip-plugin build
|
||||||
|
node packages/plugins/create-paperclip-plugin/dist/index.js @yourscope/plugin-name --output ./packages/plugins/examples
|
||||||
|
```
|
||||||
|
|
||||||
|
For a plugin that lives outside the Paperclip repo:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm --filter @paperclipai/create-paperclip-plugin build
|
||||||
|
node packages/plugins/create-paperclip-plugin/dist/index.js @yourscope/plugin-name \
|
||||||
|
--output /absolute/path/to/plugin-repos \
|
||||||
|
--sdk-path /absolute/path/to/paperclip/packages/plugins/sdk
|
||||||
|
```
|
||||||
|
|
||||||
|
That creates a package with:
|
||||||
|
|
||||||
|
- `src/manifest.ts`
|
||||||
|
- `src/worker.ts`
|
||||||
|
- `src/ui/index.tsx`
|
||||||
|
- `tests/plugin.spec.ts`
|
||||||
|
- `esbuild.config.mjs`
|
||||||
|
- `rollup.config.mjs`
|
||||||
|
|
||||||
|
Inside this monorepo, the scaffold uses `workspace:*` for `@paperclipai/plugin-sdk`.
|
||||||
|
|
||||||
|
Outside this monorepo, the scaffold snapshots `@paperclipai/plugin-sdk` from the local Paperclip checkout into a `.paperclip-sdk/` tarball so you can build and test a plugin without publishing anything to npm first.
|
||||||
|
|
||||||
|
## Recommended local workflow
|
||||||
|
|
||||||
|
From the generated plugin folder:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm install
|
||||||
|
pnpm typecheck
|
||||||
|
pnpm test
|
||||||
|
pnpm build
|
||||||
|
```
|
||||||
|
|
||||||
|
For local development, install it into Paperclip from an absolute local path through the plugin manager or API. The server supports local filesystem installs and watches local-path plugins for file changes so worker restarts happen automatically after rebuilds.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://127.0.0.1:3100/api/plugins/install \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"packageName":"/absolute/path/to/your-plugin","isLocalPath":true}'
|
||||||
|
```
|
||||||
|
|
||||||
|
## Supported alpha surface
|
||||||
|
|
||||||
|
Worker:
|
||||||
|
|
||||||
|
- config
|
||||||
|
- events
|
||||||
|
- jobs
|
||||||
|
- launchers
|
||||||
|
- http
|
||||||
|
- secrets
|
||||||
|
- activity
|
||||||
|
- state
|
||||||
|
- entities
|
||||||
|
- projects and project workspaces
|
||||||
|
- companies
|
||||||
|
- issues and comments
|
||||||
|
- agents and agent sessions
|
||||||
|
- goals
|
||||||
|
- data/actions
|
||||||
|
- streams
|
||||||
|
- tools
|
||||||
|
- metrics
|
||||||
|
- logger
|
||||||
|
|
||||||
|
UI:
|
||||||
|
|
||||||
|
- `usePluginData`
|
||||||
|
- `usePluginAction`
|
||||||
|
- `usePluginStream`
|
||||||
|
- `usePluginToast`
|
||||||
|
- `useHostContext`
|
||||||
|
- typed slot props from `@paperclipai/plugin-sdk/ui`
|
||||||
|
|
||||||
|
Mount surfaces currently wired in the host include:
|
||||||
|
|
||||||
|
- `page`
|
||||||
|
- `settingsPage`
|
||||||
|
- `dashboardWidget`
|
||||||
|
- `sidebar`
|
||||||
|
- `sidebarPanel`
|
||||||
|
- `detailTab`
|
||||||
|
- `taskDetailView`
|
||||||
|
- `projectSidebarItem`
|
||||||
|
- `globalToolbarButton`
|
||||||
|
- `toolbarButton`
|
||||||
|
- `contextMenuItem`
|
||||||
|
- `commentAnnotation`
|
||||||
|
- `commentContextMenuItem`
|
||||||
|
|
||||||
|
## Company routes
|
||||||
|
|
||||||
|
Plugins may declare a `page` slot with `routePath` to own a company route like:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/:companyPrefix/<routePath>
|
||||||
|
```
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- `routePath` must be a single lowercase slug
|
||||||
|
- it cannot collide with reserved host routes
|
||||||
|
- it cannot duplicate another installed plugin page route
|
||||||
|
|
||||||
|
## Publishing guidance
|
||||||
|
|
||||||
|
- Use npm packages as the deployment artifact.
|
||||||
|
- Treat repo-local example installs as a development workflow only.
|
||||||
|
- Prefer keeping plugin UI self-contained inside the package.
|
||||||
|
- Do not rely on host design-system components or undocumented app internals.
|
||||||
|
- GitHub repository installs are not a first-class workflow today. For local development, use a checked-out local path. For production, publish to npm or a private npm-compatible registry.
|
||||||
|
|
||||||
|
## Verification before handoff
|
||||||
|
|
||||||
|
At minimum:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm --filter <your-plugin-package> typecheck
|
||||||
|
pnpm --filter <your-plugin-package> test
|
||||||
|
pnpm --filter <your-plugin-package> build
|
||||||
|
```
|
||||||
|
|
||||||
|
If you changed host integration too, also run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm -r typecheck
|
||||||
|
pnpm test:run
|
||||||
|
pnpm build
|
||||||
|
```
|
||||||
@@ -8,6 +8,29 @@ It expands the brief plugin notes in [doc/SPEC.md](../SPEC.md) and should be rea
|
|||||||
This is not part of the V1 implementation contract in [doc/SPEC-implementation.md](../SPEC-implementation.md).
|
This is not part of the V1 implementation contract in [doc/SPEC-implementation.md](../SPEC-implementation.md).
|
||||||
It is the full target architecture for the plugin system that should follow V1.
|
It is the full target architecture for the plugin system that should follow V1.
|
||||||
|
|
||||||
|
## Current implementation caveats
|
||||||
|
|
||||||
|
The code in this repo now includes an early plugin runtime and admin UI, but it does not yet deliver the full deployment model described in this spec.
|
||||||
|
|
||||||
|
Today, the practical deployment model is:
|
||||||
|
|
||||||
|
- single-tenant
|
||||||
|
- self-hosted
|
||||||
|
- single-node or otherwise filesystem-persistent
|
||||||
|
|
||||||
|
Current limitations to keep in mind:
|
||||||
|
|
||||||
|
- Plugin UI bundles currently run as same-origin JavaScript inside the main Paperclip app. Treat plugin UI as trusted code, not a sandboxed frontend capability boundary.
|
||||||
|
- Manifest capabilities currently gate worker-side host RPC calls. They do not prevent plugin UI code from calling ordinary Paperclip HTTP APIs directly.
|
||||||
|
- Runtime installs assume a writable local filesystem for the plugin package directory and plugin data directory.
|
||||||
|
- Runtime npm installs assume `npm` is available in the running environment and that the host can reach the configured package registry.
|
||||||
|
- Published npm packages are the intended install artifact for deployed plugins.
|
||||||
|
- The repo example plugins under `packages/plugins/examples/` are development conveniences. They work from a source checkout and should not be assumed to exist in a generic published build unless they are explicitly shipped with that build.
|
||||||
|
- Dynamic plugin install is not yet cloud-ready for horizontally scaled or ephemeral deployments. There is no shared artifact store, install coordination, or cross-node distribution layer yet.
|
||||||
|
- The current runtime does not yet ship a real host-provided plugin UI component kit, and it does not support plugin asset uploads/reads. Treat those as future-scope ideas in this spec, not current implementation promises.
|
||||||
|
|
||||||
|
In practice, that means the current implementation is a good fit for local development and self-hosted persistent deployments, but not yet for multi-instance cloud plugin distribution.
|
||||||
|
|
||||||
## 1. Scope
|
## 1. Scope
|
||||||
|
|
||||||
This spec covers:
|
This spec covers:
|
||||||
@@ -212,6 +235,8 @@ Suggested layout:
|
|||||||
|
|
||||||
The package install directory and the plugin data directory are separate.
|
The package install directory and the plugin data directory are separate.
|
||||||
|
|
||||||
|
This on-disk model is the reason the current implementation expects a persistent writable host filesystem. Cloud-safe artifact replication is future work.
|
||||||
|
|
||||||
## 8.2 Operator Commands
|
## 8.2 Operator Commands
|
||||||
|
|
||||||
Paperclip should add CLI commands:
|
Paperclip should add CLI commands:
|
||||||
@@ -237,6 +262,8 @@ The install process is:
|
|||||||
7. Start plugin worker and run health/validation.
|
7. Start plugin worker and run health/validation.
|
||||||
8. Mark plugin `ready` or `error`.
|
8. Mark plugin `ready` or `error`.
|
||||||
|
|
||||||
|
For the current implementation, this install flow should be read as a single-host workflow. A successful install writes packages to the local host, and other app nodes will not automatically receive that plugin unless a future shared distribution mechanism is added.
|
||||||
|
|
||||||
## 9. Load Order And Precedence
|
## 9. Load Order And Precedence
|
||||||
|
|
||||||
Load order must be deterministic.
|
Load order must be deterministic.
|
||||||
|
|||||||
@@ -249,7 +249,7 @@ Runs local `claude` CLI directly.
|
|||||||
"cwd": "/absolute/or/relative/path",
|
"cwd": "/absolute/or/relative/path",
|
||||||
"promptTemplate": "You are agent {{agent.id}} ...",
|
"promptTemplate": "You are agent {{agent.id}} ...",
|
||||||
"model": "optional-model-id",
|
"model": "optional-model-id",
|
||||||
"maxTurnsPerRun": 80,
|
"maxTurnsPerRun": 300,
|
||||||
"dangerouslySkipPermissions": true,
|
"dangerouslySkipPermissions": true,
|
||||||
"env": {"KEY": "VALUE"},
|
"env": {"KEY": "VALUE"},
|
||||||
"extraArgs": [],
|
"extraArgs": [],
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ No section header — these are always at the top, below the company header.
|
|||||||
My Issues
|
My Issues
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Inbox** — items requiring the board operator's attention. Badge count on the right. Includes: pending approvals, stale tasks, budget alerts, failed heartbeats. The number is the total unread/unresolved count.
|
- **Inbox** — items requiring the board operator's attention. Badge count on the right. Includes: pending approvals, budget alerts, failed heartbeats. The number is the total unread/unresolved count.
|
||||||
- **My Issues** — issues created by or assigned to the board operator.
|
- **My Issues** — issues created by or assigned to the board operator.
|
||||||
|
|
||||||
### 3.3 Work Section
|
### 3.3 Work Section
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ The `claude_local` adapter runs Anthropic's Claude Code CLI locally. It supports
|
|||||||
| `env` | object | No | Environment variables (supports secret refs) |
|
| `env` | object | No | Environment variables (supports secret refs) |
|
||||||
| `timeoutSec` | number | No | Process timeout (0 = no timeout) |
|
| `timeoutSec` | number | No | Process timeout (0 = no timeout) |
|
||||||
| `graceSec` | number | No | Grace period before force-kill |
|
| `graceSec` | number | No | Grace period before force-kill |
|
||||||
| `maxTurnsPerRun` | number | No | Max agentic turns per heartbeat |
|
| `maxTurnsPerRun` | number | No | Max agentic turns per heartbeat (defaults to `300`) |
|
||||||
| `dangerouslySkipPermissions` | boolean | No | Skip permission prompts (dev only) |
|
| `dangerouslySkipPermissions` | boolean | No | Skip permission prompts (dev only) |
|
||||||
|
|
||||||
## Prompt Templates
|
## Prompt Templates
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ Codex uses `previous_response_id` for session continuity. The adapter serializes
|
|||||||
|
|
||||||
The adapter symlinks Paperclip skills into the global Codex skills directory (`~/.codex/skills`). Existing user skills are not overwritten.
|
The adapter symlinks Paperclip skills into the global Codex skills directory (`~/.codex/skills`). Existing user skills are not overwritten.
|
||||||
|
|
||||||
|
When Paperclip is running inside a managed worktree instance (`PAPERCLIP_IN_WORKTREE=true`), the adapter instead uses a worktree-isolated `CODEX_HOME` under the Paperclip instance so Codex skills, sessions, logs, and other runtime state do not leak across checkouts. It seeds that isolated home from the user's main Codex home for shared auth/config continuity.
|
||||||
|
|
||||||
For manual local CLI usage outside heartbeat runs (for example running as `codexcoder` directly), use:
|
For manual local CLI usage outside heartbeat runs (for example running as `codexcoder` directly), use:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ summary: Guide to building a custom adapter
|
|||||||
Build a custom adapter to connect Paperclip to any agent runtime.
|
Build a custom adapter to connect Paperclip to any agent runtime.
|
||||||
|
|
||||||
<Tip>
|
<Tip>
|
||||||
If you're using Claude Code, the `create-agent-adapter` skill can guide you through the full adapter creation process interactively. Just ask Claude to create a new adapter and it will walk you through each step.
|
If you're using Claude Code, the `.agents/skills/create-agent-adapter` skill can guide you through the full adapter creation process interactively. Just ask Claude to create a new adapter and it will walk you through each step.
|
||||||
</Tip>
|
</Tip>
|
||||||
|
|
||||||
## Package Structure
|
## Package Structure
|
||||||
|
|||||||
45
docs/adapters/gemini-local.md
Normal file
45
docs/adapters/gemini-local.md
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
---
|
||||||
|
title: Gemini Local
|
||||||
|
summary: Gemini CLI local adapter setup and configuration
|
||||||
|
---
|
||||||
|
|
||||||
|
The `gemini_local` adapter runs Google's Gemini CLI locally. It supports session persistence with `--resume`, skills injection, and structured `stream-json` output parsing.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Gemini CLI installed (`gemini` command available)
|
||||||
|
- `GEMINI_API_KEY` or `GOOGLE_API_KEY` set, or local Gemini CLI auth configured
|
||||||
|
|
||||||
|
## Configuration Fields
|
||||||
|
|
||||||
|
| Field | Type | Required | Description |
|
||||||
|
|-------|------|----------|-------------|
|
||||||
|
| `cwd` | string | Yes | Working directory for the agent process (absolute path; created automatically if missing when permissions allow) |
|
||||||
|
| `model` | string | No | Gemini model to use. Defaults to `auto`. |
|
||||||
|
| `promptTemplate` | string | No | Prompt used for all runs |
|
||||||
|
| `instructionsFilePath` | string | No | Markdown instructions file prepended to the prompt |
|
||||||
|
| `env` | object | No | Environment variables (supports secret refs) |
|
||||||
|
| `timeoutSec` | number | No | Process timeout (0 = no timeout) |
|
||||||
|
| `graceSec` | number | No | Grace period before force-kill |
|
||||||
|
| `yolo` | boolean | No | Pass `--approval-mode yolo` for unattended operation |
|
||||||
|
|
||||||
|
## Session Persistence
|
||||||
|
|
||||||
|
The adapter persists Gemini session IDs between heartbeats. On the next wake, it resumes the existing conversation with `--resume` so the agent retains context.
|
||||||
|
|
||||||
|
Session resume is cwd-aware: if the working directory changed since the last run, a fresh session starts instead.
|
||||||
|
|
||||||
|
If resume fails with an unknown session error, the adapter automatically retries with a fresh session.
|
||||||
|
|
||||||
|
## Skills Injection
|
||||||
|
|
||||||
|
The adapter symlinks Paperclip skills into the Gemini global skills directory (`~/.gemini/skills`). Existing user skills are not overwritten.
|
||||||
|
|
||||||
|
## Environment Test
|
||||||
|
|
||||||
|
Use the "Test Environment" button in the UI to validate the adapter config. It checks:
|
||||||
|
|
||||||
|
- Gemini CLI is installed and accessible
|
||||||
|
- Working directory is absolute and available (auto-created if missing and permitted)
|
||||||
|
- API key/auth hints (`GEMINI_API_KEY` or `GOOGLE_API_KEY`)
|
||||||
|
- A live hello probe (`gemini --output-format json "Respond with hello."`) to verify CLI readiness
|
||||||
@@ -20,6 +20,7 @@ When a heartbeat fires, Paperclip:
|
|||||||
|---------|----------|-------------|
|
|---------|----------|-------------|
|
||||||
| [Claude Local](/adapters/claude-local) | `claude_local` | Runs Claude Code CLI locally |
|
| [Claude Local](/adapters/claude-local) | `claude_local` | Runs Claude Code CLI locally |
|
||||||
| [Codex Local](/adapters/codex-local) | `codex_local` | Runs OpenAI Codex CLI locally |
|
| [Codex Local](/adapters/codex-local) | `codex_local` | Runs OpenAI Codex CLI locally |
|
||||||
|
| [Gemini Local](/adapters/gemini-local) | `gemini_local` | Runs Gemini CLI locally |
|
||||||
| OpenCode Local | `opencode_local` | Runs OpenCode CLI locally (multi-provider `provider/model`) |
|
| OpenCode Local | `opencode_local` | Runs OpenCode CLI locally (multi-provider `provider/model`) |
|
||||||
| OpenClaw | `openclaw` | Sends wake payloads to an OpenClaw webhook |
|
| OpenClaw | `openclaw` | Sends wake payloads to an OpenClaw webhook |
|
||||||
| [Process](/adapters/process) | `process` | Executes arbitrary shell commands |
|
| [Process](/adapters/process) | `process` | Executes arbitrary shell commands |
|
||||||
@@ -54,7 +55,7 @@ Three registries consume these modules:
|
|||||||
|
|
||||||
## Choosing an Adapter
|
## Choosing an Adapter
|
||||||
|
|
||||||
- **Need a coding agent?** Use `claude_local`, `codex_local`, or `opencode_local`
|
- **Need a coding agent?** Use `claude_local`, `codex_local`, `gemini_local`, or `opencode_local`
|
||||||
- **Need to run a script or command?** Use `process`
|
- **Need to run a script or command?** Use `process`
|
||||||
- **Need to call an external service?** Use `http`
|
- **Need to call an external service?** Use `http`
|
||||||
- **Need something custom?** [Create your own adapter](/adapters/creating-an-adapter)
|
- **Need something custom?** [Create your own adapter](/adapters/creating-an-adapter)
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
---
|
---
|
||||||
title: Issues
|
title: Issues
|
||||||
summary: Issue CRUD, checkout/release, comments, and attachments
|
summary: Issue CRUD, checkout/release, comments, documents, and attachments
|
||||||
---
|
---
|
||||||
|
|
||||||
Issues are the unit of work in Paperclip. They support hierarchical relationships, atomic checkout, comments, and file attachments.
|
Issues are the unit of work in Paperclip. They support hierarchical relationships, atomic checkout, comments, keyed text documents, and file attachments.
|
||||||
|
|
||||||
## List Issues
|
## List Issues
|
||||||
|
|
||||||
@@ -29,6 +29,12 @@ GET /api/issues/{issueId}
|
|||||||
|
|
||||||
Returns the issue with `project`, `goal`, and `ancestors` (parent chain with their projects and goals).
|
Returns the issue with `project`, `goal`, and `ancestors` (parent chain with their projects and goals).
|
||||||
|
|
||||||
|
The response also includes:
|
||||||
|
|
||||||
|
- `planDocument`: the full text of the issue document with key `plan`, when present
|
||||||
|
- `documentSummaries`: metadata for all linked issue documents
|
||||||
|
- `legacyPlanDocument`: a read-only fallback when the description still contains an old `<plan>` block
|
||||||
|
|
||||||
## Create Issue
|
## Create Issue
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -100,6 +106,54 @@ POST /api/issues/{issueId}/comments
|
|||||||
|
|
||||||
@-mentions (`@AgentName`) in comments trigger heartbeats for the mentioned agent.
|
@-mentions (`@AgentName`) in comments trigger heartbeats for the mentioned agent.
|
||||||
|
|
||||||
|
## Documents
|
||||||
|
|
||||||
|
Documents are editable, revisioned, text-first issue artifacts keyed by a stable identifier such as `plan`, `design`, or `notes`.
|
||||||
|
|
||||||
|
### List
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /api/issues/{issueId}/documents
|
||||||
|
```
|
||||||
|
|
||||||
|
### Get By Key
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /api/issues/{issueId}/documents/{key}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Create Or Update
|
||||||
|
|
||||||
|
```
|
||||||
|
PUT /api/issues/{issueId}/documents/{key}
|
||||||
|
{
|
||||||
|
"title": "Implementation plan",
|
||||||
|
"format": "markdown",
|
||||||
|
"body": "# Plan\n\n...",
|
||||||
|
"baseRevisionId": "{latestRevisionId}"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- omit `baseRevisionId` when creating a new document
|
||||||
|
- provide the current `baseRevisionId` when updating an existing document
|
||||||
|
- stale `baseRevisionId` returns `409 Conflict`
|
||||||
|
|
||||||
|
### Revision History
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /api/issues/{issueId}/documents/{key}/revisions
|
||||||
|
```
|
||||||
|
|
||||||
|
### Delete
|
||||||
|
|
||||||
|
```
|
||||||
|
DELETE /api/issues/{issueId}/documents/{key}
|
||||||
|
```
|
||||||
|
|
||||||
|
Delete is board-only in the current implementation.
|
||||||
|
|
||||||
## Attachments
|
## Attachments
|
||||||
|
|
||||||
### Upload
|
### Upload
|
||||||
|
|||||||
569
docs/plans/2026-03-13-issue-documents-plan.md
Normal file
569
docs/plans/2026-03-13-issue-documents-plan.md
Normal file
@@ -0,0 +1,569 @@
|
|||||||
|
# Issue Documents Plan
|
||||||
|
|
||||||
|
Status: Draft
|
||||||
|
Owner: Backend + UI + Agent Protocol
|
||||||
|
Date: 2026-03-13
|
||||||
|
Primary issue: `PAP-448`
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
Add first-class **documents** to Paperclip as editable, revisioned, company-scoped text artifacts that can be linked to issues.
|
||||||
|
|
||||||
|
The first required convention is a document with key `plan`.
|
||||||
|
|
||||||
|
This solves the immediate workflow problem in `PAP-448`:
|
||||||
|
|
||||||
|
- plans should stop living inside issue descriptions as `<plan>` blocks
|
||||||
|
- agents and board users should be able to create/update issue documents directly
|
||||||
|
- `GET /api/issues/:id` should include the full `plan` document and expose the other available documents
|
||||||
|
- issue detail should render documents under the description
|
||||||
|
|
||||||
|
This should be built as the **text-document slice** of the broader artifact system, not as a replacement for attachments/assets.
|
||||||
|
|
||||||
|
## Recommended Product Shape
|
||||||
|
|
||||||
|
### Documents vs attachments vs artifacts
|
||||||
|
|
||||||
|
- **Documents**: editable text content with stable keys and revision history.
|
||||||
|
- **Attachments**: uploaded/generated opaque files backed by storage (`assets` + `issue_attachments`).
|
||||||
|
- **Artifacts**: later umbrella/read-model that can unify documents, attachments, previews, and workspace files.
|
||||||
|
|
||||||
|
Recommendation:
|
||||||
|
|
||||||
|
- implement **issue documents now**
|
||||||
|
- keep existing attachments as-is
|
||||||
|
- defer full artifact unification until there is a second real consumer beyond issue documents + attachments
|
||||||
|
|
||||||
|
This keeps `PAP-448` focused while still fitting the larger artifact direction.
|
||||||
|
|
||||||
|
## Goals
|
||||||
|
|
||||||
|
1. Give issues first-class keyed documents, starting with `plan`.
|
||||||
|
2. Make documents editable by board users and same-company agents with issue access.
|
||||||
|
3. Preserve change history with append-only revisions.
|
||||||
|
4. Make the `plan` document automatically available in the normal issue fetch used by agents/heartbeats.
|
||||||
|
5. Replace the current `<plan>`-in-description convention in skills/docs.
|
||||||
|
6. Keep the design compatible with a future artifact/deliverables layer.
|
||||||
|
|
||||||
|
## Non-Goals
|
||||||
|
|
||||||
|
- full collaborative doc editing
|
||||||
|
- binary-file version history
|
||||||
|
- browser IDE or workspace editor
|
||||||
|
- full artifact-system implementation in the same change
|
||||||
|
- generalized polymorphic relations for every entity type on day one
|
||||||
|
|
||||||
|
## Product Decisions
|
||||||
|
|
||||||
|
### 1. Keyed issue documents
|
||||||
|
|
||||||
|
Each issue can have multiple documents. Each document relation has a stable key:
|
||||||
|
|
||||||
|
- `plan`
|
||||||
|
- `design`
|
||||||
|
- `notes`
|
||||||
|
- `report`
|
||||||
|
- custom keys later
|
||||||
|
|
||||||
|
Key rules:
|
||||||
|
|
||||||
|
- unique per issue, case-insensitive
|
||||||
|
- normalized to lowercase slug form
|
||||||
|
- machine-oriented and stable
|
||||||
|
- title is separate and user-facing
|
||||||
|
|
||||||
|
The `plan` key is conventional and reserved by Paperclip workflow/docs.
|
||||||
|
|
||||||
|
### 2. Text-first v1
|
||||||
|
|
||||||
|
V1 documents should be text-first, not arbitrary blobs.
|
||||||
|
|
||||||
|
Recommended supported formats:
|
||||||
|
|
||||||
|
- `markdown`
|
||||||
|
- `plain_text`
|
||||||
|
- `json`
|
||||||
|
- `html`
|
||||||
|
|
||||||
|
Recommendation:
|
||||||
|
|
||||||
|
- optimize UI for `markdown`
|
||||||
|
- allow raw editing for the others
|
||||||
|
- keep PDFs/images/CSVs/etc as attachments/artifacts, not editable documents
|
||||||
|
|
||||||
|
### 3. Revision model
|
||||||
|
|
||||||
|
Every document update creates a new immutable revision.
|
||||||
|
|
||||||
|
The current document row stores the latest snapshot for fast reads.
|
||||||
|
|
||||||
|
### 4. Concurrency model
|
||||||
|
|
||||||
|
Do not use silent last-write-wins.
|
||||||
|
|
||||||
|
Updates should include `baseRevisionId`:
|
||||||
|
|
||||||
|
- create: no base revision required
|
||||||
|
- update: `baseRevisionId` must match current latest revision
|
||||||
|
- mismatch: return `409 Conflict`
|
||||||
|
|
||||||
|
This is important because both board users and agents may edit the same document.
|
||||||
|
|
||||||
|
### 5. Issue fetch behavior
|
||||||
|
|
||||||
|
`GET /api/issues/:id` should include:
|
||||||
|
|
||||||
|
- full `planDocument` when a `plan` document exists
|
||||||
|
- `documentSummaries` for all linked documents
|
||||||
|
|
||||||
|
It should not inline every document body by default.
|
||||||
|
|
||||||
|
This keeps issue fetches useful for agents without making every issue payload unbounded.
|
||||||
|
|
||||||
|
### 6. Legacy `<plan>` compatibility
|
||||||
|
|
||||||
|
If an issue has no `plan` document but its description contains a legacy `<plan>` block:
|
||||||
|
|
||||||
|
- expose that as a legacy read-only fallback in API/UI
|
||||||
|
- mark it as legacy/synthetic
|
||||||
|
- prefer a real `plan` document when both exist
|
||||||
|
|
||||||
|
Recommendation:
|
||||||
|
|
||||||
|
- do not auto-rewrite old issue descriptions in the first rollout
|
||||||
|
- provide an explicit import/migrate path later
|
||||||
|
|
||||||
|
## Proposed Data Model
|
||||||
|
|
||||||
|
Recommendation: make documents first-class, but keep issue linkage explicit via a join table.
|
||||||
|
|
||||||
|
This preserves foreign keys today and gives a clean path to future `project_documents` or `company_documents` tables later.
|
||||||
|
|
||||||
|
## Tables
|
||||||
|
|
||||||
|
### `documents`
|
||||||
|
|
||||||
|
Canonical text document record.
|
||||||
|
|
||||||
|
Suggested columns:
|
||||||
|
|
||||||
|
- `id`
|
||||||
|
- `company_id`
|
||||||
|
- `title`
|
||||||
|
- `format`
|
||||||
|
- `latest_body`
|
||||||
|
- `latest_revision_id`
|
||||||
|
- `latest_revision_number`
|
||||||
|
- `created_by_agent_id`
|
||||||
|
- `created_by_user_id`
|
||||||
|
- `updated_by_agent_id`
|
||||||
|
- `updated_by_user_id`
|
||||||
|
- `created_at`
|
||||||
|
- `updated_at`
|
||||||
|
|
||||||
|
### `document_revisions`
|
||||||
|
|
||||||
|
Append-only history.
|
||||||
|
|
||||||
|
Suggested columns:
|
||||||
|
|
||||||
|
- `id`
|
||||||
|
- `company_id`
|
||||||
|
- `document_id`
|
||||||
|
- `revision_number`
|
||||||
|
- `body`
|
||||||
|
- `change_summary`
|
||||||
|
- `created_by_agent_id`
|
||||||
|
- `created_by_user_id`
|
||||||
|
- `created_at`
|
||||||
|
|
||||||
|
Constraints:
|
||||||
|
|
||||||
|
- unique `(document_id, revision_number)`
|
||||||
|
|
||||||
|
### `issue_documents`
|
||||||
|
|
||||||
|
Issue relation + workflow key.
|
||||||
|
|
||||||
|
Suggested columns:
|
||||||
|
|
||||||
|
- `id`
|
||||||
|
- `company_id`
|
||||||
|
- `issue_id`
|
||||||
|
- `document_id`
|
||||||
|
- `key`
|
||||||
|
- `created_at`
|
||||||
|
- `updated_at`
|
||||||
|
|
||||||
|
Constraints:
|
||||||
|
|
||||||
|
- unique `(company_id, issue_id, key)`
|
||||||
|
- unique `(document_id)` to keep one issue relation per document in v1
|
||||||
|
|
||||||
|
## Why not use `assets` for this?
|
||||||
|
|
||||||
|
Because `assets` solves blob storage, not:
|
||||||
|
|
||||||
|
- stable keyed semantics like `plan`
|
||||||
|
- inline text editing
|
||||||
|
- revision history
|
||||||
|
- optimistic concurrency
|
||||||
|
- cheap inclusion in `GET /issues/:id`
|
||||||
|
|
||||||
|
Documents and attachments should remain separate primitives, then meet later in a deliverables/artifact read-model.
|
||||||
|
|
||||||
|
## Shared Types and API Contract
|
||||||
|
|
||||||
|
## New shared types
|
||||||
|
|
||||||
|
Add:
|
||||||
|
|
||||||
|
- `DocumentFormat`
|
||||||
|
- `IssueDocument`
|
||||||
|
- `IssueDocumentSummary`
|
||||||
|
- `DocumentRevision`
|
||||||
|
|
||||||
|
Recommended `IssueDocument` shape:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type DocumentFormat = "markdown" | "plain_text" | "json" | "html";
|
||||||
|
|
||||||
|
interface IssueDocument {
|
||||||
|
id: string;
|
||||||
|
companyId: string;
|
||||||
|
issueId: string;
|
||||||
|
key: string;
|
||||||
|
title: string | null;
|
||||||
|
format: DocumentFormat;
|
||||||
|
body: string;
|
||||||
|
latestRevisionId: string;
|
||||||
|
latestRevisionNumber: number;
|
||||||
|
createdByAgentId: string | null;
|
||||||
|
createdByUserId: string | null;
|
||||||
|
updatedByAgentId: string | null;
|
||||||
|
updatedByUserId: string | null;
|
||||||
|
createdAt: Date;
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Recommended `IssueDocumentSummary` shape:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface IssueDocumentSummary {
|
||||||
|
id: string;
|
||||||
|
key: string;
|
||||||
|
title: string | null;
|
||||||
|
format: DocumentFormat;
|
||||||
|
latestRevisionId: string;
|
||||||
|
latestRevisionNumber: number;
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Issue type enrichment
|
||||||
|
|
||||||
|
Extend `Issue` with:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface Issue {
|
||||||
|
...
|
||||||
|
planDocument?: IssueDocument | null;
|
||||||
|
documentSummaries?: IssueDocumentSummary[];
|
||||||
|
legacyPlanDocument?: {
|
||||||
|
key: "plan";
|
||||||
|
body: string;
|
||||||
|
source: "issue_description";
|
||||||
|
} | null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This directly satisfies the `PAP-448` requirement for heartbeat/API issue fetches.
|
||||||
|
|
||||||
|
## API endpoints
|
||||||
|
|
||||||
|
Recommended endpoints:
|
||||||
|
|
||||||
|
- `GET /api/issues/:issueId/documents`
|
||||||
|
- `GET /api/issues/:issueId/documents/:key`
|
||||||
|
- `PUT /api/issues/:issueId/documents/:key`
|
||||||
|
- `GET /api/issues/:issueId/documents/:key/revisions`
|
||||||
|
- `DELETE /api/issues/:issueId/documents/:key` optionally board-only in v1
|
||||||
|
|
||||||
|
Recommended `PUT` body:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
title?: string | null;
|
||||||
|
format: "markdown" | "plain_text" | "json" | "html";
|
||||||
|
body: string;
|
||||||
|
changeSummary?: string | null;
|
||||||
|
baseRevisionId?: string | null;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Behavior:
|
||||||
|
|
||||||
|
- missing document + no `baseRevisionId`: create
|
||||||
|
- existing document + matching `baseRevisionId`: update
|
||||||
|
- existing document + stale `baseRevisionId`: `409`
|
||||||
|
|
||||||
|
## Authorization and invariants
|
||||||
|
|
||||||
|
- all document records are company-scoped
|
||||||
|
- issue relation must belong to same company
|
||||||
|
- board access follows existing issue access rules
|
||||||
|
- agent access follows existing same-company issue access rules
|
||||||
|
- every mutation writes activity log entries
|
||||||
|
|
||||||
|
Recommended delete rule for v1:
|
||||||
|
|
||||||
|
- board can delete documents
|
||||||
|
- agents can create/update, but not delete
|
||||||
|
|
||||||
|
That keeps automated systems from removing canonical docs too easily.
|
||||||
|
|
||||||
|
## UI Plan
|
||||||
|
|
||||||
|
## Issue detail
|
||||||
|
|
||||||
|
Add a new **Documents** section directly under the issue description.
|
||||||
|
|
||||||
|
Recommended behavior:
|
||||||
|
|
||||||
|
- show `plan` first when present
|
||||||
|
- show other documents below it
|
||||||
|
- render a gist-like header:
|
||||||
|
- key
|
||||||
|
- title
|
||||||
|
- last updated metadata
|
||||||
|
- revision number
|
||||||
|
- support inline edit
|
||||||
|
- support create new document by key
|
||||||
|
- support revision history drawer or sheet
|
||||||
|
|
||||||
|
Recommended presentation order:
|
||||||
|
|
||||||
|
1. Description
|
||||||
|
2. Documents
|
||||||
|
3. Attachments
|
||||||
|
4. Comments / activity / sub-issues
|
||||||
|
|
||||||
|
This matches the request that documents live under the description while still leaving attachments available.
|
||||||
|
|
||||||
|
## Editing UX
|
||||||
|
|
||||||
|
Recommendation:
|
||||||
|
|
||||||
|
- use markdown preview + raw edit toggle for markdown docs
|
||||||
|
- use raw textarea editor for non-markdown docs in v1
|
||||||
|
- show explicit save conflicts on `409`
|
||||||
|
- show a clear empty state: "No documents yet"
|
||||||
|
|
||||||
|
## Legacy plan rendering
|
||||||
|
|
||||||
|
If there is no stored `plan` document but legacy `<plan>` exists:
|
||||||
|
|
||||||
|
- show it in the Documents section
|
||||||
|
- mark it `Legacy plan from description`
|
||||||
|
- offer create/import in a later pass
|
||||||
|
|
||||||
|
## Agent Protocol and Skills
|
||||||
|
|
||||||
|
Update the Paperclip agent workflow so planning no longer edits the issue description.
|
||||||
|
|
||||||
|
Required changes:
|
||||||
|
|
||||||
|
- update `skills/paperclip/SKILL.md`
|
||||||
|
- replace the `<plan>` instructions with document creation/update instructions
|
||||||
|
- document the new endpoints in `docs/api/issues.md`
|
||||||
|
- update any internal planning docs that still teach inline `<plan>` blocks
|
||||||
|
|
||||||
|
New rule:
|
||||||
|
|
||||||
|
- when asked to make a plan for an issue, create or update the issue document with key `plan`
|
||||||
|
- leave a comment that the plan document was created/updated
|
||||||
|
- do not mark the issue done
|
||||||
|
|
||||||
|
## Relationship to the Artifact Plan
|
||||||
|
|
||||||
|
This work should explicitly feed the broader artifact/deliverables direction.
|
||||||
|
|
||||||
|
Recommendation:
|
||||||
|
|
||||||
|
- keep documents as their own primitive in this change
|
||||||
|
- add `document` to any future `ArtifactKind`
|
||||||
|
- later build a deliverables read-model that aggregates:
|
||||||
|
- issue documents
|
||||||
|
- issue attachments
|
||||||
|
- preview URLs
|
||||||
|
- workspace-file references
|
||||||
|
|
||||||
|
The artifact proposal currently has no explicit `document` kind. It should.
|
||||||
|
|
||||||
|
Recommended future shape:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type ArtifactKind =
|
||||||
|
| "document"
|
||||||
|
| "attachment"
|
||||||
|
| "workspace_file"
|
||||||
|
| "preview"
|
||||||
|
| "report_link";
|
||||||
|
```
|
||||||
|
|
||||||
|
## Implementation Phases
|
||||||
|
|
||||||
|
## Phase 1: Shared contract and schema
|
||||||
|
|
||||||
|
Files:
|
||||||
|
|
||||||
|
- `packages/db/src/schema/documents.ts`
|
||||||
|
- `packages/db/src/schema/document_revisions.ts`
|
||||||
|
- `packages/db/src/schema/issue_documents.ts`
|
||||||
|
- `packages/db/src/schema/index.ts`
|
||||||
|
- `packages/db/src/migrations/*`
|
||||||
|
- `packages/shared/src/types/issue.ts`
|
||||||
|
- `packages/shared/src/validators/issue.ts` or new document validator file
|
||||||
|
- `packages/shared/src/index.ts`
|
||||||
|
|
||||||
|
Acceptance:
|
||||||
|
|
||||||
|
- schema enforces one key per issue
|
||||||
|
- revisions are append-only
|
||||||
|
- shared types expose plan/document fields on issue fetch
|
||||||
|
|
||||||
|
## Phase 2: Server services and routes
|
||||||
|
|
||||||
|
Files:
|
||||||
|
|
||||||
|
- `server/src/services/issues.ts` or `server/src/services/documents.ts`
|
||||||
|
- `server/src/routes/issues.ts`
|
||||||
|
- `server/src/services/activity.ts` callsites
|
||||||
|
|
||||||
|
Behavior:
|
||||||
|
|
||||||
|
- list/get/upsert/delete documents
|
||||||
|
- revision listing
|
||||||
|
- `GET /issues/:id` returns `planDocument` + `documentSummaries`
|
||||||
|
- company boundary checks match issue routes
|
||||||
|
|
||||||
|
Acceptance:
|
||||||
|
|
||||||
|
- agents and board can fetch/update same-company issue documents
|
||||||
|
- stale edits return `409`
|
||||||
|
- activity timeline shows document changes
|
||||||
|
|
||||||
|
## Phase 3: UI issue documents surface
|
||||||
|
|
||||||
|
Files:
|
||||||
|
|
||||||
|
- `ui/src/api/issues.ts`
|
||||||
|
- `ui/src/lib/queryKeys.ts`
|
||||||
|
- `ui/src/pages/IssueDetail.tsx`
|
||||||
|
- new reusable document UI component if needed
|
||||||
|
|
||||||
|
Behavior:
|
||||||
|
|
||||||
|
- render plan + documents under description
|
||||||
|
- create/update by key
|
||||||
|
- open revision history
|
||||||
|
- show conflicts/errors clearly
|
||||||
|
|
||||||
|
Acceptance:
|
||||||
|
|
||||||
|
- board can create a `plan` doc from issue detail
|
||||||
|
- updated plan appears immediately
|
||||||
|
- issue detail no longer depends on description-embedded `<plan>`
|
||||||
|
|
||||||
|
## Phase 4: Skills/docs migration
|
||||||
|
|
||||||
|
Files:
|
||||||
|
|
||||||
|
- `skills/paperclip/SKILL.md`
|
||||||
|
- `docs/api/issues.md`
|
||||||
|
- `doc/SPEC-implementation.md`
|
||||||
|
- relevant plan/docs that mention `<plan>`
|
||||||
|
|
||||||
|
Acceptance:
|
||||||
|
|
||||||
|
- planning guidance references issue documents, not inline issue description tags
|
||||||
|
- API docs describe the new document endpoints and issue payload additions
|
||||||
|
|
||||||
|
## Phase 5: Legacy compatibility and follow-up
|
||||||
|
|
||||||
|
Behavior:
|
||||||
|
|
||||||
|
- read legacy `<plan>` blocks as fallback
|
||||||
|
- optionally add explicit import/migration command later
|
||||||
|
|
||||||
|
Follow-up, not required for first merge:
|
||||||
|
|
||||||
|
- deliverables/artifact read-model
|
||||||
|
- project/company documents
|
||||||
|
- comment-linked documents
|
||||||
|
- diff view between revisions
|
||||||
|
|
||||||
|
## Test Plan
|
||||||
|
|
||||||
|
### Server
|
||||||
|
|
||||||
|
- document create/read/update/delete lifecycle
|
||||||
|
- revision numbering
|
||||||
|
- `baseRevisionId` conflict handling
|
||||||
|
- company boundary enforcement
|
||||||
|
- agent vs board authorization
|
||||||
|
- issue fetch includes `planDocument` and document summaries
|
||||||
|
- legacy `<plan>` fallback behavior
|
||||||
|
- activity log mutation coverage
|
||||||
|
|
||||||
|
### UI
|
||||||
|
|
||||||
|
- issue detail shows plan document
|
||||||
|
- create/update flows invalidate queries correctly
|
||||||
|
- conflict and validation errors are surfaced
|
||||||
|
- legacy plan fallback renders correctly
|
||||||
|
|
||||||
|
### Verification
|
||||||
|
|
||||||
|
Run before implementation is declared complete:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pnpm -r typecheck
|
||||||
|
pnpm test:run
|
||||||
|
pnpm build
|
||||||
|
```
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
1. Should v1 documents be markdown-only, with `json/html/plain_text` deferred?
|
||||||
|
Recommendation: allow all four in API, optimize UI for markdown only.
|
||||||
|
|
||||||
|
2. Should agents be allowed to create arbitrary keys, or only conventional keys?
|
||||||
|
Recommendation: allow arbitrary keys with normalized validation; reserve `plan` as special behavior only.
|
||||||
|
|
||||||
|
3. Should delete exist in v1?
|
||||||
|
Recommendation: yes, but board-only.
|
||||||
|
|
||||||
|
4. Should legacy `<plan>` blocks ever be auto-migrated?
|
||||||
|
Recommendation: no automatic mutation in the first rollout.
|
||||||
|
|
||||||
|
5. Should documents appear inside a future Deliverables section or remain a top-level Issue section?
|
||||||
|
Recommendation: keep a dedicated Documents section now; later also expose them in Deliverables if an aggregated artifact view is added.
|
||||||
|
|
||||||
|
## Final Recommendation
|
||||||
|
|
||||||
|
Ship **issue documents** as a focused, text-first primitive now.
|
||||||
|
|
||||||
|
Do not try to solve full artifact unification in the same implementation.
|
||||||
|
|
||||||
|
Use:
|
||||||
|
|
||||||
|
- first-class document tables
|
||||||
|
- issue-level keyed linkage
|
||||||
|
- append-only revisions
|
||||||
|
- `planDocument` embedded in normal issue fetches
|
||||||
|
- legacy `<plan>` fallback
|
||||||
|
- skill/docs migration away from description-embedded plans
|
||||||
|
|
||||||
|
This addresses the real planning workflow problem immediately and leaves the artifact system room to grow cleanly afterward.
|
||||||
@@ -1,5 +1,11 @@
|
|||||||
# @paperclipai/adapter-utils
|
# @paperclipai/adapter-utils
|
||||||
|
|
||||||
|
## 0.3.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Stable release preparation for 0.3.1
|
||||||
|
|
||||||
## 0.3.0
|
## 0.3.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@paperclipai/adapter-utils",
|
"name": "@paperclipai/adapter-utils",
|
||||||
"version": "0.3.0",
|
"version": "0.3.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts",
|
".": "./src/index.ts",
|
||||||
|
|||||||
@@ -22,3 +22,9 @@ export type {
|
|||||||
CLIAdapterModule,
|
CLIAdapterModule,
|
||||||
CreateConfigValues,
|
CreateConfigValues,
|
||||||
} from "./types.js";
|
} from "./types.js";
|
||||||
|
export {
|
||||||
|
REDACTED_HOME_PATH_USER,
|
||||||
|
redactHomePathUserSegments,
|
||||||
|
redactHomePathUserSegmentsInValue,
|
||||||
|
redactTranscriptEntryPaths,
|
||||||
|
} from "./log-redaction.js";
|
||||||
|
|||||||
81
packages/adapter-utils/src/log-redaction.ts
Normal file
81
packages/adapter-utils/src/log-redaction.ts
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
import type { TranscriptEntry } from "./types.js";
|
||||||
|
|
||||||
|
export const REDACTED_HOME_PATH_USER = "[]";
|
||||||
|
|
||||||
|
const HOME_PATH_PATTERNS = [
|
||||||
|
{
|
||||||
|
regex: /\/Users\/[^/\\\s]+/g,
|
||||||
|
replace: `/Users/${REDACTED_HOME_PATH_USER}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
regex: /\/home\/[^/\\\s]+/g,
|
||||||
|
replace: `/home/${REDACTED_HOME_PATH_USER}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
regex: /([A-Za-z]:\\Users\\)[^\\/\s]+/g,
|
||||||
|
replace: `$1${REDACTED_HOME_PATH_USER}`,
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||||
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
||||||
|
const proto = Object.getPrototypeOf(value);
|
||||||
|
return proto === Object.prototype || proto === null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function redactHomePathUserSegments(text: string): string {
|
||||||
|
let result = text;
|
||||||
|
for (const pattern of HOME_PATH_PATTERNS) {
|
||||||
|
result = result.replace(pattern.regex, pattern.replace);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function redactHomePathUserSegmentsInValue<T>(value: T): T {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
return redactHomePathUserSegments(value) as T;
|
||||||
|
}
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return value.map((entry) => redactHomePathUserSegmentsInValue(entry)) as T;
|
||||||
|
}
|
||||||
|
if (!isPlainObject(value)) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
const redacted: Record<string, unknown> = {};
|
||||||
|
for (const [key, entry] of Object.entries(value)) {
|
||||||
|
redacted[key] = redactHomePathUserSegmentsInValue(entry);
|
||||||
|
}
|
||||||
|
return redacted as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function redactTranscriptEntryPaths(entry: TranscriptEntry): TranscriptEntry {
|
||||||
|
switch (entry.kind) {
|
||||||
|
case "assistant":
|
||||||
|
case "thinking":
|
||||||
|
case "user":
|
||||||
|
case "stderr":
|
||||||
|
case "system":
|
||||||
|
case "stdout":
|
||||||
|
return { ...entry, text: redactHomePathUserSegments(entry.text) };
|
||||||
|
case "tool_call":
|
||||||
|
return { ...entry, name: redactHomePathUserSegments(entry.name), input: redactHomePathUserSegmentsInValue(entry.input) };
|
||||||
|
case "tool_result":
|
||||||
|
return { ...entry, content: redactHomePathUserSegments(entry.content) };
|
||||||
|
case "init":
|
||||||
|
return {
|
||||||
|
...entry,
|
||||||
|
model: redactHomePathUserSegments(entry.model),
|
||||||
|
sessionId: redactHomePathUserSegments(entry.sessionId),
|
||||||
|
};
|
||||||
|
case "result":
|
||||||
|
return {
|
||||||
|
...entry,
|
||||||
|
text: redactHomePathUserSegments(entry.text),
|
||||||
|
subtype: redactHomePathUserSegments(entry.subtype),
|
||||||
|
errors: entry.errors.map((error) => redactHomePathUserSegments(error)),
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,6 +32,23 @@ export const runningProcesses = new Map<string, RunningProcess>();
|
|||||||
export const MAX_CAPTURE_BYTES = 4 * 1024 * 1024;
|
export const MAX_CAPTURE_BYTES = 4 * 1024 * 1024;
|
||||||
export const MAX_EXCERPT_BYTES = 32 * 1024;
|
export const MAX_EXCERPT_BYTES = 32 * 1024;
|
||||||
const SENSITIVE_ENV_KEY = /(key|token|secret|password|passwd|authorization|cookie)/i;
|
const SENSITIVE_ENV_KEY = /(key|token|secret|password|passwd|authorization|cookie)/i;
|
||||||
|
const PAPERCLIP_SKILL_ROOT_RELATIVE_CANDIDATES = [
|
||||||
|
"../../skills",
|
||||||
|
"../../../../../skills",
|
||||||
|
];
|
||||||
|
|
||||||
|
export interface PaperclipSkillEntry {
|
||||||
|
name: string;
|
||||||
|
source: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePathSlashes(value: string): string {
|
||||||
|
return value.replaceAll("\\", "/");
|
||||||
|
}
|
||||||
|
|
||||||
|
function isMaintainerOnlySkillTarget(candidate: string): boolean {
|
||||||
|
return normalizePathSlashes(candidate).includes("/.agents/skills/");
|
||||||
|
}
|
||||||
|
|
||||||
export function parseObject(value: unknown): Record<string, unknown> {
|
export function parseObject(value: unknown): Record<string, unknown> {
|
||||||
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
||||||
@@ -95,6 +112,16 @@ export function renderTemplate(template: string, data: Record<string, unknown>)
|
|||||||
return template.replace(/{{\s*([a-zA-Z0-9_.-]+)\s*}}/g, (_, path) => resolvePathValue(data, path));
|
return template.replace(/{{\s*([a-zA-Z0-9_.-]+)\s*}}/g, (_, path) => resolvePathValue(data, path));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function joinPromptSections(
|
||||||
|
sections: Array<string | null | undefined>,
|
||||||
|
separator = "\n\n",
|
||||||
|
) {
|
||||||
|
return sections
|
||||||
|
.map((value) => (typeof value === "string" ? value.trim() : ""))
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(separator);
|
||||||
|
}
|
||||||
|
|
||||||
export function redactEnvForLogs(env: Record<string, string>): Record<string, string> {
|
export function redactEnvForLogs(env: Record<string, string>): Record<string, string> {
|
||||||
const redacted: Record<string, string> = {};
|
const redacted: Record<string, string> = {};
|
||||||
for (const [key, value] of Object.entries(env)) {
|
for (const [key, value] of Object.entries(env)) {
|
||||||
@@ -245,6 +272,136 @@ export async function ensureAbsoluteDirectory(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function resolvePaperclipSkillsDir(
|
||||||
|
moduleDir: string,
|
||||||
|
additionalCandidates: string[] = [],
|
||||||
|
): Promise<string | null> {
|
||||||
|
const candidates = [
|
||||||
|
...PAPERCLIP_SKILL_ROOT_RELATIVE_CANDIDATES.map((relativePath) => path.resolve(moduleDir, relativePath)),
|
||||||
|
...additionalCandidates.map((candidate) => path.resolve(candidate)),
|
||||||
|
];
|
||||||
|
const seenRoots = new Set<string>();
|
||||||
|
|
||||||
|
for (const root of candidates) {
|
||||||
|
if (seenRoots.has(root)) continue;
|
||||||
|
seenRoots.add(root);
|
||||||
|
const isDirectory = await fs.stat(root).then((stats) => stats.isDirectory()).catch(() => false);
|
||||||
|
if (isDirectory) return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listPaperclipSkillEntries(
|
||||||
|
moduleDir: string,
|
||||||
|
additionalCandidates: string[] = [],
|
||||||
|
): Promise<PaperclipSkillEntry[]> {
|
||||||
|
const root = await resolvePaperclipSkillsDir(moduleDir, additionalCandidates);
|
||||||
|
if (!root) return [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const entries = await fs.readdir(root, { withFileTypes: true });
|
||||||
|
return entries
|
||||||
|
.filter((entry) => entry.isDirectory())
|
||||||
|
.map((entry) => ({
|
||||||
|
name: entry.name,
|
||||||
|
source: path.join(root, entry.name),
|
||||||
|
}));
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function readPaperclipSkillMarkdown(
|
||||||
|
moduleDir: string,
|
||||||
|
skillName: string,
|
||||||
|
): Promise<string | null> {
|
||||||
|
const normalized = skillName.trim().toLowerCase();
|
||||||
|
if (!normalized) return null;
|
||||||
|
|
||||||
|
const entries = await listPaperclipSkillEntries(moduleDir);
|
||||||
|
const match = entries.find((entry) => entry.name === normalized);
|
||||||
|
if (!match) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await fs.readFile(path.join(match.source, "SKILL.md"), "utf8");
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ensurePaperclipSkillSymlink(
|
||||||
|
source: string,
|
||||||
|
target: string,
|
||||||
|
linkSkill: (source: string, target: string) => Promise<void> = (linkSource, linkTarget) =>
|
||||||
|
fs.symlink(linkSource, linkTarget),
|
||||||
|
): Promise<"created" | "repaired" | "skipped"> {
|
||||||
|
const existing = await fs.lstat(target).catch(() => null);
|
||||||
|
if (!existing) {
|
||||||
|
await linkSkill(source, target);
|
||||||
|
return "created";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!existing.isSymbolicLink()) {
|
||||||
|
return "skipped";
|
||||||
|
}
|
||||||
|
|
||||||
|
const linkedPath = await fs.readlink(target).catch(() => null);
|
||||||
|
if (!linkedPath) return "skipped";
|
||||||
|
|
||||||
|
const resolvedLinkedPath = path.resolve(path.dirname(target), linkedPath);
|
||||||
|
if (resolvedLinkedPath === source) {
|
||||||
|
return "skipped";
|
||||||
|
}
|
||||||
|
|
||||||
|
const linkedPathExists = await fs.stat(resolvedLinkedPath).then(() => true).catch(() => false);
|
||||||
|
if (linkedPathExists) {
|
||||||
|
return "skipped";
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.unlink(target);
|
||||||
|
await linkSkill(source, target);
|
||||||
|
return "repaired";
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeMaintainerOnlySkillSymlinks(
|
||||||
|
skillsHome: string,
|
||||||
|
allowedSkillNames: Iterable<string>,
|
||||||
|
): Promise<string[]> {
|
||||||
|
const allowed = new Set(Array.from(allowedSkillNames));
|
||||||
|
try {
|
||||||
|
const entries = await fs.readdir(skillsHome, { withFileTypes: true });
|
||||||
|
const removed: string[] = [];
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (allowed.has(entry.name)) continue;
|
||||||
|
|
||||||
|
const target = path.join(skillsHome, entry.name);
|
||||||
|
const existing = await fs.lstat(target).catch(() => null);
|
||||||
|
if (!existing?.isSymbolicLink()) continue;
|
||||||
|
|
||||||
|
const linkedPath = await fs.readlink(target).catch(() => null);
|
||||||
|
if (!linkedPath) continue;
|
||||||
|
|
||||||
|
const resolvedLinkedPath = path.isAbsolute(linkedPath)
|
||||||
|
? linkedPath
|
||||||
|
: path.resolve(path.dirname(target), linkedPath);
|
||||||
|
if (
|
||||||
|
!isMaintainerOnlySkillTarget(linkedPath) &&
|
||||||
|
!isMaintainerOnlySkillTarget(resolvedLinkedPath)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.unlink(target);
|
||||||
|
removed.push(entry.name);
|
||||||
|
}
|
||||||
|
|
||||||
|
return removed;
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function ensureCommandResolvable(command: string, cwd: string, env: NodeJS.ProcessEnv) {
|
export async function ensureCommandResolvable(command: string, cwd: string, env: NodeJS.ProcessEnv) {
|
||||||
const resolved = await resolveCommandPath(command, cwd, env);
|
const resolved = await resolveCommandPath(command, cwd, env);
|
||||||
if (resolved) return;
|
if (resolved) return;
|
||||||
|
|||||||
@@ -75,6 +75,14 @@ export interface AdapterExecutionResult {
|
|||||||
runtimeServices?: AdapterRuntimeServiceReport[];
|
runtimeServices?: AdapterRuntimeServiceReport[];
|
||||||
summary?: string | null;
|
summary?: string | null;
|
||||||
clearSession?: boolean;
|
clearSession?: boolean;
|
||||||
|
question?: {
|
||||||
|
prompt: string;
|
||||||
|
choices: Array<{
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
}>;
|
||||||
|
} | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AdapterSessionCodec {
|
export interface AdapterSessionCodec {
|
||||||
@@ -91,6 +99,7 @@ export interface AdapterInvocationMeta {
|
|||||||
commandNotes?: string[];
|
commandNotes?: string[];
|
||||||
env?: Record<string, string>;
|
env?: Record<string, string>;
|
||||||
prompt?: string;
|
prompt?: string;
|
||||||
|
promptMetrics?: Record<string, number>;
|
||||||
context?: Record<string, unknown>;
|
context?: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,7 +198,7 @@ export type TranscriptEntry =
|
|||||||
| { kind: "assistant"; ts: string; text: string; delta?: boolean }
|
| { kind: "assistant"; ts: string; text: string; delta?: boolean }
|
||||||
| { kind: "thinking"; ts: string; text: string; delta?: boolean }
|
| { kind: "thinking"; ts: string; text: string; delta?: boolean }
|
||||||
| { kind: "user"; ts: string; text: string }
|
| { kind: "user"; ts: string; text: string }
|
||||||
| { kind: "tool_call"; ts: string; name: string; input: unknown }
|
| { kind: "tool_call"; ts: string; name: string; input: unknown; toolUseId?: string }
|
||||||
| { kind: "tool_result"; ts: string; toolUseId: string; content: string; isError: boolean }
|
| { kind: "tool_result"; ts: string; toolUseId: string; content: string; isError: boolean }
|
||||||
| { kind: "init"; ts: string; model: string; sessionId: string }
|
| { kind: "init"; ts: string; model: string; sessionId: string }
|
||||||
| { kind: "result"; ts: string; text: string; inputTokens: number; outputTokens: number; cachedTokens: number; costUsd: number; subtype: string; isError: boolean; errors: string[] }
|
| { kind: "result"; ts: string; text: string; inputTokens: number; outputTokens: number; cachedTokens: number; costUsd: number; subtype: string; isError: boolean; errors: string[] }
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
# @paperclipai/adapter-claude-local
|
# @paperclipai/adapter-claude-local
|
||||||
|
|
||||||
|
## 0.3.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Stable release preparation for 0.3.1
|
||||||
|
- Updated dependencies
|
||||||
|
- @paperclipai/adapter-utils@0.3.1
|
||||||
|
|
||||||
## 0.3.0
|
## 0.3.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@paperclipai/adapter-claude-local",
|
"name": "@paperclipai/adapter-claude-local",
|
||||||
"version": "0.3.0",
|
"version": "0.3.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts",
|
".": "./src/index.ts",
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
parseObject,
|
parseObject,
|
||||||
parseJson,
|
parseJson,
|
||||||
buildPaperclipEnv,
|
buildPaperclipEnv,
|
||||||
|
joinPromptSections,
|
||||||
redactEnvForLogs,
|
redactEnvForLogs,
|
||||||
ensureAbsoluteDirectory,
|
ensureAbsoluteDirectory,
|
||||||
ensureCommandResolvable,
|
ensureCommandResolvable,
|
||||||
@@ -121,6 +122,7 @@ async function buildClaudeRuntimeConfig(input: ClaudeExecutionInput): Promise<Cl
|
|||||||
const workspaceRepoRef = asString(workspaceContext.repoRef, "") || null;
|
const workspaceRepoRef = asString(workspaceContext.repoRef, "") || null;
|
||||||
const workspaceBranch = asString(workspaceContext.branchName, "") || null;
|
const workspaceBranch = asString(workspaceContext.branchName, "") || null;
|
||||||
const workspaceWorktreePath = asString(workspaceContext.worktreePath, "") || null;
|
const workspaceWorktreePath = asString(workspaceContext.worktreePath, "") || null;
|
||||||
|
const agentHome = asString(workspaceContext.agentHome, "") || null;
|
||||||
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
||||||
? context.paperclipWorkspaces.filter(
|
? context.paperclipWorkspaces.filter(
|
||||||
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
||||||
@@ -215,6 +217,9 @@ async function buildClaudeRuntimeConfig(input: ClaudeExecutionInput): Promise<Cl
|
|||||||
if (workspaceWorktreePath) {
|
if (workspaceWorktreePath) {
|
||||||
env.PAPERCLIP_WORKSPACE_WORKTREE_PATH = workspaceWorktreePath;
|
env.PAPERCLIP_WORKSPACE_WORKTREE_PATH = workspaceWorktreePath;
|
||||||
}
|
}
|
||||||
|
if (agentHome) {
|
||||||
|
env.AGENT_HOME = agentHome;
|
||||||
|
}
|
||||||
if (workspaceHints.length > 0) {
|
if (workspaceHints.length > 0) {
|
||||||
env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
|
env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
|
||||||
}
|
}
|
||||||
@@ -363,7 +368,8 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
`[paperclip] Claude session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}".\n`,
|
`[paperclip] Claude session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}".\n`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const prompt = renderTemplate(promptTemplate, {
|
const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
|
||||||
|
const templateData = {
|
||||||
agentId: agent.id,
|
agentId: agent.id,
|
||||||
companyId: agent.companyId,
|
companyId: agent.companyId,
|
||||||
runId,
|
runId,
|
||||||
@@ -371,7 +377,24 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
agent,
|
agent,
|
||||||
run: { id: runId, source: "on_demand" },
|
run: { id: runId, source: "on_demand" },
|
||||||
context,
|
context,
|
||||||
});
|
};
|
||||||
|
const renderedPrompt = renderTemplate(promptTemplate, templateData);
|
||||||
|
const renderedBootstrapPrompt =
|
||||||
|
!sessionId && bootstrapPromptTemplate.trim().length > 0
|
||||||
|
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
|
||||||
|
: "";
|
||||||
|
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
|
||||||
|
const prompt = joinPromptSections([
|
||||||
|
renderedBootstrapPrompt,
|
||||||
|
sessionHandoffNote,
|
||||||
|
renderedPrompt,
|
||||||
|
]);
|
||||||
|
const promptMetrics = {
|
||||||
|
promptChars: prompt.length,
|
||||||
|
bootstrapPromptChars: renderedBootstrapPrompt.length,
|
||||||
|
sessionHandoffChars: sessionHandoffNote.length,
|
||||||
|
heartbeatPromptChars: renderedPrompt.length,
|
||||||
|
};
|
||||||
|
|
||||||
const buildClaudeArgs = (resumeSessionId: string | null) => {
|
const buildClaudeArgs = (resumeSessionId: string | null) => {
|
||||||
const args = ["--print", "-", "--output-format", "stream-json", "--verbose"];
|
const args = ["--print", "-", "--output-format", "stream-json", "--verbose"];
|
||||||
@@ -416,6 +439,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
commandNotes,
|
commandNotes,
|
||||||
env: redactEnvForLogs(env),
|
env: redactEnvForLogs(env),
|
||||||
prompt,
|
prompt,
|
||||||
|
promptMetrics,
|
||||||
context,
|
context,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ export function buildClaudeLocalConfig(v: CreateConfigValues): Record<string, un
|
|||||||
if (v.cwd) ac.cwd = v.cwd;
|
if (v.cwd) ac.cwd = v.cwd;
|
||||||
if (v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;
|
if (v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;
|
||||||
if (v.promptTemplate) ac.promptTemplate = v.promptTemplate;
|
if (v.promptTemplate) ac.promptTemplate = v.promptTemplate;
|
||||||
|
if (v.bootstrapPrompt) ac.bootstrapPromptTemplate = v.bootstrapPrompt;
|
||||||
if (v.model) ac.model = v.model;
|
if (v.model) ac.model = v.model;
|
||||||
if (v.thinkingEffort) ac.effort = v.thinkingEffort;
|
if (v.thinkingEffort) ac.effort = v.thinkingEffort;
|
||||||
if (v.chrome) ac.chrome = true;
|
if (v.chrome) ac.chrome = true;
|
||||||
|
|||||||
@@ -71,6 +71,12 @@ export function parseClaudeStdoutLine(line: string, ts: string): TranscriptEntry
|
|||||||
kind: "tool_call",
|
kind: "tool_call",
|
||||||
ts,
|
ts,
|
||||||
name: typeof block.name === "string" ? block.name : "unknown",
|
name: typeof block.name === "string" ? block.name : "unknown",
|
||||||
|
toolUseId:
|
||||||
|
typeof block.id === "string"
|
||||||
|
? block.id
|
||||||
|
: typeof block.tool_use_id === "string"
|
||||||
|
? block.tool_use_id
|
||||||
|
: undefined,
|
||||||
input: block.input ?? {},
|
input: block.input ?? {},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
# @paperclipai/adapter-codex-local
|
# @paperclipai/adapter-codex-local
|
||||||
|
|
||||||
|
## 0.3.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Stable release preparation for 0.3.1
|
||||||
|
- Updated dependencies
|
||||||
|
- @paperclipai/adapter-utils@0.3.1
|
||||||
|
|
||||||
## 0.3.0
|
## 0.3.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@paperclipai/adapter-codex-local",
|
"name": "@paperclipai/adapter-codex-local",
|
||||||
"version": "0.3.0",
|
"version": "0.3.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts",
|
".": "./src/index.ts",
|
||||||
|
|||||||
101
packages/adapters/codex-local/src/server/codex-home.ts
Normal file
101
packages/adapters/codex-local/src/server/codex-home.ts
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
import fs from "node:fs/promises";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import type { AdapterExecutionContext } from "@paperclipai/adapter-utils";
|
||||||
|
|
||||||
|
const TRUTHY_ENV_RE = /^(1|true|yes|on)$/i;
|
||||||
|
const COPIED_SHARED_FILES = ["config.json", "config.toml", "instructions.md"] as const;
|
||||||
|
const SYMLINKED_SHARED_FILES = ["auth.json"] as const;
|
||||||
|
|
||||||
|
function nonEmpty(value: string | undefined): string | null {
|
||||||
|
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function pathExists(candidate: string): Promise<boolean> {
|
||||||
|
return fs.access(candidate).then(() => true).catch(() => false);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveCodexHomeDir(env: NodeJS.ProcessEnv = process.env): string {
|
||||||
|
const fromEnv = nonEmpty(env.CODEX_HOME);
|
||||||
|
if (fromEnv) return path.resolve(fromEnv);
|
||||||
|
return path.join(os.homedir(), ".codex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function isWorktreeMode(env: NodeJS.ProcessEnv): boolean {
|
||||||
|
return TRUTHY_ENV_RE.test(env.PAPERCLIP_IN_WORKTREE ?? "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveWorktreeCodexHomeDir(env: NodeJS.ProcessEnv): string | null {
|
||||||
|
if (!isWorktreeMode(env)) return null;
|
||||||
|
const paperclipHome = nonEmpty(env.PAPERCLIP_HOME);
|
||||||
|
if (!paperclipHome) return null;
|
||||||
|
const instanceId = nonEmpty(env.PAPERCLIP_INSTANCE_ID);
|
||||||
|
if (instanceId) {
|
||||||
|
return path.resolve(paperclipHome, "instances", instanceId, "codex-home");
|
||||||
|
}
|
||||||
|
return path.resolve(paperclipHome, "codex-home");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureParentDir(target: string): Promise<void> {
|
||||||
|
await fs.mkdir(path.dirname(target), { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureSymlink(target: string, source: string): Promise<void> {
|
||||||
|
const existing = await fs.lstat(target).catch(() => null);
|
||||||
|
if (!existing) {
|
||||||
|
await ensureParentDir(target);
|
||||||
|
await fs.symlink(source, target);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!existing.isSymbolicLink()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const linkedPath = await fs.readlink(target).catch(() => null);
|
||||||
|
if (!linkedPath) return;
|
||||||
|
|
||||||
|
const resolvedLinkedPath = path.resolve(path.dirname(target), linkedPath);
|
||||||
|
if (resolvedLinkedPath === source) return;
|
||||||
|
|
||||||
|
await fs.unlink(target);
|
||||||
|
await fs.symlink(source, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureCopiedFile(target: string, source: string): Promise<void> {
|
||||||
|
const existing = await fs.lstat(target).catch(() => null);
|
||||||
|
if (existing) return;
|
||||||
|
await ensureParentDir(target);
|
||||||
|
await fs.copyFile(source, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function prepareWorktreeCodexHome(
|
||||||
|
env: NodeJS.ProcessEnv,
|
||||||
|
onLog: AdapterExecutionContext["onLog"],
|
||||||
|
): Promise<string | null> {
|
||||||
|
const targetHome = resolveWorktreeCodexHomeDir(env);
|
||||||
|
if (!targetHome) return null;
|
||||||
|
|
||||||
|
const sourceHome = resolveCodexHomeDir(env);
|
||||||
|
if (path.resolve(sourceHome) === path.resolve(targetHome)) return targetHome;
|
||||||
|
|
||||||
|
await fs.mkdir(targetHome, { recursive: true });
|
||||||
|
|
||||||
|
for (const name of SYMLINKED_SHARED_FILES) {
|
||||||
|
const source = path.join(sourceHome, name);
|
||||||
|
if (!(await pathExists(source))) continue;
|
||||||
|
await ensureSymlink(path.join(targetHome, name), source);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const name of COPIED_SHARED_FILES) {
|
||||||
|
const source = path.join(sourceHome, name);
|
||||||
|
if (!(await pathExists(source))) continue;
|
||||||
|
await ensureCopiedFile(path.join(targetHome, name), source);
|
||||||
|
}
|
||||||
|
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] Using worktree-isolated Codex home "${targetHome}" (seeded from "${sourceHome}").\n`,
|
||||||
|
);
|
||||||
|
return targetHome;
|
||||||
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import fs from "node:fs/promises";
|
import fs from "node:fs/promises";
|
||||||
import os from "node:os";
|
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import type { AdapterExecutionContext, AdapterExecutionResult } from "@paperclipai/adapter-utils";
|
import type { AdapterExecutionContext, AdapterExecutionResult } from "@paperclipai/adapter-utils";
|
||||||
@@ -13,17 +12,18 @@ import {
|
|||||||
redactEnvForLogs,
|
redactEnvForLogs,
|
||||||
ensureAbsoluteDirectory,
|
ensureAbsoluteDirectory,
|
||||||
ensureCommandResolvable,
|
ensureCommandResolvable,
|
||||||
|
ensurePaperclipSkillSymlink,
|
||||||
ensurePathInEnv,
|
ensurePathInEnv,
|
||||||
|
listPaperclipSkillEntries,
|
||||||
|
removeMaintainerOnlySkillSymlinks,
|
||||||
renderTemplate,
|
renderTemplate,
|
||||||
|
joinPromptSections,
|
||||||
runChildProcess,
|
runChildProcess,
|
||||||
} from "@paperclipai/adapter-utils/server-utils";
|
} from "@paperclipai/adapter-utils/server-utils";
|
||||||
import { parseCodexJsonl, isCodexUnknownSessionError } from "./parse.js";
|
import { parseCodexJsonl, isCodexUnknownSessionError } from "./parse.js";
|
||||||
|
import { pathExists, prepareWorktreeCodexHome, resolveCodexHomeDir } from "./codex-home.js";
|
||||||
|
|
||||||
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
||||||
const PAPERCLIP_SKILLS_CANDIDATES = [
|
|
||||||
path.resolve(__moduleDir, "../../skills"), // published: <pkg>/dist/server/ -> <pkg>/skills/
|
|
||||||
path.resolve(__moduleDir, "../../../../../skills"), // dev: src/server/ -> repo root/skills/
|
|
||||||
];
|
|
||||||
const CODEX_ROLLOUT_NOISE_RE =
|
const CODEX_ROLLOUT_NOISE_RE =
|
||||||
/^\d{4}-\d{2}-\d{2}T[^\s]+\s+ERROR\s+codex_core::rollout::list:\s+state db missing rollout path for thread\s+[a-z0-9-]+$/i;
|
/^\d{4}-\d{2}-\d{2}T[^\s]+\s+ERROR\s+codex_core::rollout::list:\s+state db missing rollout path for thread\s+[a-z0-9-]+$/i;
|
||||||
|
|
||||||
@@ -61,39 +61,95 @@ function resolveCodexBillingType(env: Record<string, string>): "api" | "subscrip
|
|||||||
return hasNonEmptyEnvValue(env, "OPENAI_API_KEY") ? "api" : "subscription";
|
return hasNonEmptyEnvValue(env, "OPENAI_API_KEY") ? "api" : "subscription";
|
||||||
}
|
}
|
||||||
|
|
||||||
function codexHomeDir(): string {
|
async function isLikelyPaperclipRepoRoot(candidate: string): Promise<boolean> {
|
||||||
const fromEnv = process.env.CODEX_HOME;
|
const [hasWorkspace, hasPackageJson, hasServerDir, hasAdapterUtilsDir] = await Promise.all([
|
||||||
if (typeof fromEnv === "string" && fromEnv.trim().length > 0) return fromEnv.trim();
|
pathExists(path.join(candidate, "pnpm-workspace.yaml")),
|
||||||
return path.join(os.homedir(), ".codex");
|
pathExists(path.join(candidate, "package.json")),
|
||||||
|
pathExists(path.join(candidate, "server")),
|
||||||
|
pathExists(path.join(candidate, "packages", "adapter-utils")),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return hasWorkspace && hasPackageJson && hasServerDir && hasAdapterUtilsDir;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function resolvePaperclipSkillsDir(): Promise<string | null> {
|
async function isLikelyPaperclipRuntimeSkillSource(candidate: string, skillName: string): Promise<boolean> {
|
||||||
for (const candidate of PAPERCLIP_SKILLS_CANDIDATES) {
|
if (path.basename(candidate) !== skillName) return false;
|
||||||
const isDir = await fs.stat(candidate).then((s) => s.isDirectory()).catch(() => false);
|
const skillsRoot = path.dirname(candidate);
|
||||||
if (isDir) return candidate;
|
if (path.basename(skillsRoot) !== "skills") return false;
|
||||||
|
if (!(await pathExists(path.join(candidate, "SKILL.md")))) return false;
|
||||||
|
|
||||||
|
let cursor = path.dirname(skillsRoot);
|
||||||
|
for (let depth = 0; depth < 6; depth += 1) {
|
||||||
|
if (await isLikelyPaperclipRepoRoot(cursor)) return true;
|
||||||
|
const parent = path.dirname(cursor);
|
||||||
|
if (parent === cursor) break;
|
||||||
|
cursor = parent;
|
||||||
}
|
}
|
||||||
return null;
|
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function ensureCodexSkillsInjected(onLog: AdapterExecutionContext["onLog"]) {
|
type EnsureCodexSkillsInjectedOptions = {
|
||||||
const skillsDir = await resolvePaperclipSkillsDir();
|
skillsHome?: string;
|
||||||
if (!skillsDir) return;
|
skillsEntries?: Awaited<ReturnType<typeof listPaperclipSkillEntries>>;
|
||||||
|
linkSkill?: (source: string, target: string) => Promise<void>;
|
||||||
|
};
|
||||||
|
|
||||||
const skillsHome = path.join(codexHomeDir(), "skills");
|
export async function ensureCodexSkillsInjected(
|
||||||
|
onLog: AdapterExecutionContext["onLog"],
|
||||||
|
options: EnsureCodexSkillsInjectedOptions = {},
|
||||||
|
) {
|
||||||
|
const skillsEntries = options.skillsEntries ?? await listPaperclipSkillEntries(__moduleDir);
|
||||||
|
if (skillsEntries.length === 0) return;
|
||||||
|
|
||||||
|
const skillsHome = options.skillsHome ?? path.join(resolveCodexHomeDir(process.env), "skills");
|
||||||
await fs.mkdir(skillsHome, { recursive: true });
|
await fs.mkdir(skillsHome, { recursive: true });
|
||||||
const entries = await fs.readdir(skillsDir, { withFileTypes: true });
|
const removedSkills = await removeMaintainerOnlySkillSymlinks(
|
||||||
for (const entry of entries) {
|
skillsHome,
|
||||||
if (!entry.isDirectory()) continue;
|
skillsEntries.map((entry) => entry.name),
|
||||||
const source = path.join(skillsDir, entry.name);
|
);
|
||||||
|
for (const skillName of removedSkills) {
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] Removed maintainer-only Codex skill "${skillName}" from ${skillsHome}\n`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const linkSkill = options.linkSkill;
|
||||||
|
for (const entry of skillsEntries) {
|
||||||
const target = path.join(skillsHome, entry.name);
|
const target = path.join(skillsHome, entry.name);
|
||||||
const existing = await fs.lstat(target).catch(() => null);
|
|
||||||
if (existing) continue;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await fs.symlink(source, target);
|
const existing = await fs.lstat(target).catch(() => null);
|
||||||
|
if (existing?.isSymbolicLink()) {
|
||||||
|
const linkedPath = await fs.readlink(target).catch(() => null);
|
||||||
|
const resolvedLinkedPath = linkedPath
|
||||||
|
? path.resolve(path.dirname(target), linkedPath)
|
||||||
|
: null;
|
||||||
|
if (
|
||||||
|
resolvedLinkedPath &&
|
||||||
|
resolvedLinkedPath !== entry.source &&
|
||||||
|
(await isLikelyPaperclipRuntimeSkillSource(resolvedLinkedPath, entry.name))
|
||||||
|
) {
|
||||||
|
await fs.unlink(target);
|
||||||
|
if (linkSkill) {
|
||||||
|
await linkSkill(entry.source, target);
|
||||||
|
} else {
|
||||||
|
await fs.symlink(entry.source, target);
|
||||||
|
}
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] Repaired Codex skill "${entry.name}" into ${skillsHome}\n`,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await ensurePaperclipSkillSymlink(entry.source, target, linkSkill);
|
||||||
|
if (result === "skipped") continue;
|
||||||
|
|
||||||
await onLog(
|
await onLog(
|
||||||
"stderr",
|
"stderr",
|
||||||
`[paperclip] Injected Codex skill "${entry.name}" into ${skillsHome}\n`,
|
`[paperclip] ${result === "repaired" ? "Repaired" : "Injected"} Codex skill "${entry.name}" into ${skillsHome}\n`,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await onLog(
|
await onLog(
|
||||||
@@ -132,6 +188,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
|
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
|
||||||
const workspaceBranch = asString(workspaceContext.branchName, "");
|
const workspaceBranch = asString(workspaceContext.branchName, "");
|
||||||
const workspaceWorktreePath = asString(workspaceContext.worktreePath, "");
|
const workspaceWorktreePath = asString(workspaceContext.worktreePath, "");
|
||||||
|
const agentHome = asString(workspaceContext.agentHome, "");
|
||||||
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
||||||
? context.paperclipWorkspaces.filter(
|
? context.paperclipWorkspaces.filter(
|
||||||
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
||||||
@@ -152,12 +209,25 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
|
const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
|
||||||
const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
|
const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
|
||||||
const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
|
const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
|
||||||
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
|
|
||||||
await ensureCodexSkillsInjected(onLog);
|
|
||||||
const envConfig = parseObject(config.env);
|
const envConfig = parseObject(config.env);
|
||||||
|
const configuredCodexHome =
|
||||||
|
typeof envConfig.CODEX_HOME === "string" && envConfig.CODEX_HOME.trim().length > 0
|
||||||
|
? path.resolve(envConfig.CODEX_HOME.trim())
|
||||||
|
: null;
|
||||||
|
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
|
||||||
|
const preparedWorktreeCodexHome =
|
||||||
|
configuredCodexHome ? null : await prepareWorktreeCodexHome(process.env, onLog);
|
||||||
|
const effectiveCodexHome = configuredCodexHome ?? preparedWorktreeCodexHome;
|
||||||
|
await ensureCodexSkillsInjected(
|
||||||
|
onLog,
|
||||||
|
effectiveCodexHome ? { skillsHome: path.join(effectiveCodexHome, "skills") } : {},
|
||||||
|
);
|
||||||
const hasExplicitApiKey =
|
const hasExplicitApiKey =
|
||||||
typeof envConfig.PAPERCLIP_API_KEY === "string" && envConfig.PAPERCLIP_API_KEY.trim().length > 0;
|
typeof envConfig.PAPERCLIP_API_KEY === "string" && envConfig.PAPERCLIP_API_KEY.trim().length > 0;
|
||||||
const env: Record<string, string> = { ...buildPaperclipEnv(agent) };
|
const env: Record<string, string> = { ...buildPaperclipEnv(agent) };
|
||||||
|
if (effectiveCodexHome) {
|
||||||
|
env.CODEX_HOME = effectiveCodexHome;
|
||||||
|
}
|
||||||
env.PAPERCLIP_RUN_ID = runId;
|
env.PAPERCLIP_RUN_ID = runId;
|
||||||
const wakeTaskId =
|
const wakeTaskId =
|
||||||
(typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim()) ||
|
(typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim()) ||
|
||||||
@@ -224,6 +294,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
if (workspaceWorktreePath) {
|
if (workspaceWorktreePath) {
|
||||||
env.PAPERCLIP_WORKSPACE_WORKTREE_PATH = workspaceWorktreePath;
|
env.PAPERCLIP_WORKSPACE_WORKTREE_PATH = workspaceWorktreePath;
|
||||||
}
|
}
|
||||||
|
if (agentHome) {
|
||||||
|
env.AGENT_HOME = agentHome;
|
||||||
|
}
|
||||||
if (workspaceHints.length > 0) {
|
if (workspaceHints.length > 0) {
|
||||||
env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
|
env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
|
||||||
}
|
}
|
||||||
@@ -270,6 +343,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
|
const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
|
||||||
const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
|
const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
|
||||||
let instructionsPrefix = "";
|
let instructionsPrefix = "";
|
||||||
|
let instructionsChars = 0;
|
||||||
if (instructionsFilePath) {
|
if (instructionsFilePath) {
|
||||||
try {
|
try {
|
||||||
const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
|
const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
|
||||||
@@ -277,6 +351,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
`${instructionsContents}\n\n` +
|
`${instructionsContents}\n\n` +
|
||||||
`The above agent instructions were loaded from ${instructionsFilePath}. ` +
|
`The above agent instructions were loaded from ${instructionsFilePath}. ` +
|
||||||
`Resolve any relative file references from ${instructionsDir}.\n\n`;
|
`Resolve any relative file references from ${instructionsDir}.\n\n`;
|
||||||
|
instructionsChars = instructionsPrefix.length;
|
||||||
await onLog(
|
await onLog(
|
||||||
"stderr",
|
"stderr",
|
||||||
`[paperclip] Loaded agent instructions file: ${instructionsFilePath}\n`,
|
`[paperclip] Loaded agent instructions file: ${instructionsFilePath}\n`,
|
||||||
@@ -301,7 +376,8 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`,
|
`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`,
|
||||||
];
|
];
|
||||||
})();
|
})();
|
||||||
const renderedPrompt = renderTemplate(promptTemplate, {
|
const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
|
||||||
|
const templateData = {
|
||||||
agentId: agent.id,
|
agentId: agent.id,
|
||||||
companyId: agent.companyId,
|
companyId: agent.companyId,
|
||||||
runId,
|
runId,
|
||||||
@@ -309,8 +385,26 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
agent,
|
agent,
|
||||||
run: { id: runId, source: "on_demand" },
|
run: { id: runId, source: "on_demand" },
|
||||||
context,
|
context,
|
||||||
});
|
};
|
||||||
const prompt = `${instructionsPrefix}${renderedPrompt}`;
|
const renderedPrompt = renderTemplate(promptTemplate, templateData);
|
||||||
|
const renderedBootstrapPrompt =
|
||||||
|
!sessionId && bootstrapPromptTemplate.trim().length > 0
|
||||||
|
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
|
||||||
|
: "";
|
||||||
|
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
|
||||||
|
const prompt = joinPromptSections([
|
||||||
|
instructionsPrefix,
|
||||||
|
renderedBootstrapPrompt,
|
||||||
|
sessionHandoffNote,
|
||||||
|
renderedPrompt,
|
||||||
|
]);
|
||||||
|
const promptMetrics = {
|
||||||
|
promptChars: prompt.length,
|
||||||
|
instructionsChars,
|
||||||
|
bootstrapPromptChars: renderedBootstrapPrompt.length,
|
||||||
|
sessionHandoffChars: sessionHandoffNote.length,
|
||||||
|
heartbeatPromptChars: renderedPrompt.length,
|
||||||
|
};
|
||||||
|
|
||||||
const buildArgs = (resumeSessionId: string | null) => {
|
const buildArgs = (resumeSessionId: string | null) => {
|
||||||
const args = ["exec", "--json"];
|
const args = ["exec", "--json"];
|
||||||
@@ -338,6 +432,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
}),
|
}),
|
||||||
env: redactEnvForLogs(env),
|
env: redactEnvForLogs(env),
|
||||||
prompt,
|
prompt,
|
||||||
|
promptMetrics,
|
||||||
context,
|
context,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
export { execute } from "./execute.js";
|
export { execute, ensureCodexSkillsInjected } from "./execute.js";
|
||||||
export { testEnvironment } from "./test.js";
|
export { testEnvironment } from "./test.js";
|
||||||
export { parseCodexJsonl, isCodexUnknownSessionError } from "./parse.js";
|
export { parseCodexJsonl, isCodexUnknownSessionError } from "./parse.js";
|
||||||
import type { AdapterSessionCodec } from "@paperclipai/adapter-utils";
|
import type { AdapterSessionCodec } from "@paperclipai/adapter-utils";
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ export function buildCodexLocalConfig(v: CreateConfigValues): Record<string, unk
|
|||||||
if (v.cwd) ac.cwd = v.cwd;
|
if (v.cwd) ac.cwd = v.cwd;
|
||||||
if (v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;
|
if (v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;
|
||||||
if (v.promptTemplate) ac.promptTemplate = v.promptTemplate;
|
if (v.promptTemplate) ac.promptTemplate = v.promptTemplate;
|
||||||
|
if (v.bootstrapPrompt) ac.bootstrapPromptTemplate = v.bootstrapPrompt;
|
||||||
ac.model = v.model || DEFAULT_CODEX_LOCAL_MODEL;
|
ac.model = v.model || DEFAULT_CODEX_LOCAL_MODEL;
|
||||||
if (v.thinkingEffort) ac.modelReasoningEffort = v.thinkingEffort;
|
if (v.thinkingEffort) ac.modelReasoningEffort = v.thinkingEffort;
|
||||||
ac.timeoutSec = 0;
|
ac.timeoutSec = 0;
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import type { TranscriptEntry } from "@paperclipai/adapter-utils";
|
import {
|
||||||
|
redactHomePathUserSegments,
|
||||||
|
redactHomePathUserSegmentsInValue,
|
||||||
|
type TranscriptEntry,
|
||||||
|
} from "@paperclipai/adapter-utils";
|
||||||
|
|
||||||
function safeJsonParse(text: string): unknown {
|
function safeJsonParse(text: string): unknown {
|
||||||
try {
|
try {
|
||||||
@@ -39,12 +43,12 @@ function errorText(value: unknown): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function stringifyUnknown(value: unknown): string {
|
function stringifyUnknown(value: unknown): string {
|
||||||
if (typeof value === "string") return value;
|
if (typeof value === "string") return redactHomePathUserSegments(value);
|
||||||
if (value === null || value === undefined) return "";
|
if (value === null || value === undefined) return "";
|
||||||
try {
|
try {
|
||||||
return JSON.stringify(value, null, 2);
|
return JSON.stringify(redactHomePathUserSegmentsInValue(value), null, 2);
|
||||||
} catch {
|
} catch {
|
||||||
return String(value);
|
return redactHomePathUserSegments(String(value));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,22 +61,24 @@ function parseCommandExecutionItem(
|
|||||||
const command = asString(item.command);
|
const command = asString(item.command);
|
||||||
const status = asString(item.status);
|
const status = asString(item.status);
|
||||||
const exitCode = typeof item.exit_code === "number" && Number.isFinite(item.exit_code) ? item.exit_code : null;
|
const exitCode = typeof item.exit_code === "number" && Number.isFinite(item.exit_code) ? item.exit_code : null;
|
||||||
const output = asString(item.aggregated_output).replace(/\s+$/, "");
|
const safeCommand = redactHomePathUserSegments(command);
|
||||||
|
const output = redactHomePathUserSegments(asString(item.aggregated_output)).replace(/\s+$/, "");
|
||||||
|
|
||||||
if (phase === "started") {
|
if (phase === "started") {
|
||||||
return [{
|
return [{
|
||||||
kind: "tool_call",
|
kind: "tool_call",
|
||||||
ts,
|
ts,
|
||||||
name: "command_execution",
|
name: "command_execution",
|
||||||
|
toolUseId: id || command || "command_execution",
|
||||||
input: {
|
input: {
|
||||||
id,
|
id,
|
||||||
command,
|
command: safeCommand,
|
||||||
},
|
},
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
const lines: string[] = [];
|
const lines: string[] = [];
|
||||||
if (command) lines.push(`command: ${command}`);
|
if (safeCommand) lines.push(`command: ${safeCommand}`);
|
||||||
if (status) lines.push(`status: ${status}`);
|
if (status) lines.push(`status: ${status}`);
|
||||||
if (exitCode !== null) lines.push(`exit_code: ${exitCode}`);
|
if (exitCode !== null) lines.push(`exit_code: ${exitCode}`);
|
||||||
if (output) {
|
if (output) {
|
||||||
@@ -103,7 +109,7 @@ function parseFileChangeItem(item: Record<string, unknown>, ts: string): Transcr
|
|||||||
.filter((change): change is Record<string, unknown> => Boolean(change))
|
.filter((change): change is Record<string, unknown> => Boolean(change))
|
||||||
.map((change) => {
|
.map((change) => {
|
||||||
const kind = asString(change.kind, "update");
|
const kind = asString(change.kind, "update");
|
||||||
const path = asString(change.path, "unknown");
|
const path = redactHomePathUserSegments(asString(change.path, "unknown"));
|
||||||
return `${kind} ${path}`;
|
return `${kind} ${path}`;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -125,13 +131,13 @@ function parseCodexItem(
|
|||||||
|
|
||||||
if (itemType === "agent_message") {
|
if (itemType === "agent_message") {
|
||||||
const text = asString(item.text);
|
const text = asString(item.text);
|
||||||
if (text) return [{ kind: "assistant", ts, text }];
|
if (text) return [{ kind: "assistant", ts, text: redactHomePathUserSegments(text) }];
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (itemType === "reasoning") {
|
if (itemType === "reasoning") {
|
||||||
const text = asString(item.text);
|
const text = asString(item.text);
|
||||||
if (text) return [{ kind: "thinking", ts, text }];
|
if (text) return [{ kind: "thinking", ts, text: redactHomePathUserSegments(text) }];
|
||||||
return [{ kind: "system", ts, text: phase === "started" ? "reasoning started" : "reasoning completed" }];
|
return [{ kind: "system", ts, text: phase === "started" ? "reasoning started" : "reasoning completed" }];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,8 +153,9 @@ function parseCodexItem(
|
|||||||
return [{
|
return [{
|
||||||
kind: "tool_call",
|
kind: "tool_call",
|
||||||
ts,
|
ts,
|
||||||
name: asString(item.name, "unknown"),
|
name: redactHomePathUserSegments(asString(item.name, "unknown")),
|
||||||
input: item.input ?? {},
|
toolUseId: asString(item.id),
|
||||||
|
input: redactHomePathUserSegmentsInValue(item.input ?? {}),
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,24 +167,28 @@ function parseCodexItem(
|
|||||||
asString(item.result) ||
|
asString(item.result) ||
|
||||||
stringifyUnknown(item.content ?? item.output ?? item.result);
|
stringifyUnknown(item.content ?? item.output ?? item.result);
|
||||||
const isError = item.is_error === true || asString(item.status) === "error";
|
const isError = item.is_error === true || asString(item.status) === "error";
|
||||||
return [{ kind: "tool_result", ts, toolUseId, content, isError }];
|
return [{ kind: "tool_result", ts, toolUseId, content: redactHomePathUserSegments(content), isError }];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (itemType === "error" && phase === "completed") {
|
if (itemType === "error" && phase === "completed") {
|
||||||
const text = errorText(item.message ?? item.error ?? item);
|
const text = errorText(item.message ?? item.error ?? item);
|
||||||
return [{ kind: "stderr", ts, text: text || "error" }];
|
return [{ kind: "stderr", ts, text: redactHomePathUserSegments(text || "error") }];
|
||||||
}
|
}
|
||||||
|
|
||||||
const id = asString(item.id);
|
const id = asString(item.id);
|
||||||
const status = asString(item.status);
|
const status = asString(item.status);
|
||||||
const meta = [id ? `id=${id}` : "", status ? `status=${status}` : ""].filter(Boolean).join(" ");
|
const meta = [id ? `id=${id}` : "", status ? `status=${status}` : ""].filter(Boolean).join(" ");
|
||||||
return [{ kind: "system", ts, text: `item ${phase}: ${itemType || "unknown"}${meta ? ` (${meta})` : ""}` }];
|
return [{
|
||||||
|
kind: "system",
|
||||||
|
ts,
|
||||||
|
text: redactHomePathUserSegments(`item ${phase}: ${itemType || "unknown"}${meta ? ` (${meta})` : ""}`),
|
||||||
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function parseCodexStdoutLine(line: string, ts: string): TranscriptEntry[] {
|
export function parseCodexStdoutLine(line: string, ts: string): TranscriptEntry[] {
|
||||||
const parsed = asRecord(safeJsonParse(line));
|
const parsed = asRecord(safeJsonParse(line));
|
||||||
if (!parsed) {
|
if (!parsed) {
|
||||||
return [{ kind: "stdout", ts, text: line }];
|
return [{ kind: "stdout", ts, text: redactHomePathUserSegments(line) }];
|
||||||
}
|
}
|
||||||
|
|
||||||
const type = asString(parsed.type);
|
const type = asString(parsed.type);
|
||||||
@@ -187,8 +198,8 @@ export function parseCodexStdoutLine(line: string, ts: string): TranscriptEntry[
|
|||||||
return [{
|
return [{
|
||||||
kind: "init",
|
kind: "init",
|
||||||
ts,
|
ts,
|
||||||
model: asString(parsed.model, "codex"),
|
model: redactHomePathUserSegments(asString(parsed.model, "codex")),
|
||||||
sessionId: threadId,
|
sessionId: redactHomePathUserSegments(threadId),
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,15 +221,15 @@ export function parseCodexStdoutLine(line: string, ts: string): TranscriptEntry[
|
|||||||
return [{
|
return [{
|
||||||
kind: "result",
|
kind: "result",
|
||||||
ts,
|
ts,
|
||||||
text: asString(parsed.result),
|
text: redactHomePathUserSegments(asString(parsed.result)),
|
||||||
inputTokens,
|
inputTokens,
|
||||||
outputTokens,
|
outputTokens,
|
||||||
cachedTokens,
|
cachedTokens,
|
||||||
costUsd: asNumber(parsed.total_cost_usd),
|
costUsd: asNumber(parsed.total_cost_usd),
|
||||||
subtype: asString(parsed.subtype),
|
subtype: redactHomePathUserSegments(asString(parsed.subtype)),
|
||||||
isError: parsed.is_error === true,
|
isError: parsed.is_error === true,
|
||||||
errors: Array.isArray(parsed.errors)
|
errors: Array.isArray(parsed.errors)
|
||||||
? parsed.errors.map(errorText).filter(Boolean)
|
? parsed.errors.map(errorText).map(redactHomePathUserSegments).filter(Boolean)
|
||||||
: [],
|
: [],
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
@@ -232,21 +243,21 @@ export function parseCodexStdoutLine(line: string, ts: string): TranscriptEntry[
|
|||||||
return [{
|
return [{
|
||||||
kind: "result",
|
kind: "result",
|
||||||
ts,
|
ts,
|
||||||
text: asString(parsed.result),
|
text: redactHomePathUserSegments(asString(parsed.result)),
|
||||||
inputTokens,
|
inputTokens,
|
||||||
outputTokens,
|
outputTokens,
|
||||||
cachedTokens,
|
cachedTokens,
|
||||||
costUsd: asNumber(parsed.total_cost_usd),
|
costUsd: asNumber(parsed.total_cost_usd),
|
||||||
subtype: asString(parsed.subtype, "turn.failed"),
|
subtype: redactHomePathUserSegments(asString(parsed.subtype, "turn.failed")),
|
||||||
isError: true,
|
isError: true,
|
||||||
errors: message ? [message] : [],
|
errors: message ? [redactHomePathUserSegments(message)] : [],
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type === "error") {
|
if (type === "error") {
|
||||||
const message = errorText(parsed.message ?? parsed.error ?? parsed);
|
const message = errorText(parsed.message ?? parsed.error ?? parsed);
|
||||||
return [{ kind: "stderr", ts, text: message || line }];
|
return [{ kind: "stderr", ts, text: redactHomePathUserSegments(message || line) }];
|
||||||
}
|
}
|
||||||
|
|
||||||
return [{ kind: "stdout", ts, text: line }];
|
return [{ kind: "stdout", ts, text: redactHomePathUserSegments(line) }];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
# @paperclipai/adapter-cursor-local
|
# @paperclipai/adapter-cursor-local
|
||||||
|
|
||||||
|
## 0.3.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Stable release preparation for 0.3.1
|
||||||
|
- Updated dependencies
|
||||||
|
- @paperclipai/adapter-utils@0.3.1
|
||||||
|
|
||||||
## 0.3.0
|
## 0.3.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@paperclipai/adapter-cursor-local",
|
"name": "@paperclipai/adapter-cursor-local",
|
||||||
"version": "0.3.0",
|
"version": "0.3.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts",
|
".": "./src/index.ts",
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import fs from "node:fs/promises";
|
import fs from "node:fs/promises";
|
||||||
import type { Dirent } from "node:fs";
|
|
||||||
import os from "node:os";
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
@@ -13,8 +12,12 @@ import {
|
|||||||
redactEnvForLogs,
|
redactEnvForLogs,
|
||||||
ensureAbsoluteDirectory,
|
ensureAbsoluteDirectory,
|
||||||
ensureCommandResolvable,
|
ensureCommandResolvable,
|
||||||
|
ensurePaperclipSkillSymlink,
|
||||||
ensurePathInEnv,
|
ensurePathInEnv,
|
||||||
|
listPaperclipSkillEntries,
|
||||||
|
removeMaintainerOnlySkillSymlinks,
|
||||||
renderTemplate,
|
renderTemplate,
|
||||||
|
joinPromptSections,
|
||||||
runChildProcess,
|
runChildProcess,
|
||||||
} from "@paperclipai/adapter-utils/server-utils";
|
} from "@paperclipai/adapter-utils/server-utils";
|
||||||
import { DEFAULT_CURSOR_LOCAL_MODEL } from "../index.js";
|
import { DEFAULT_CURSOR_LOCAL_MODEL } from "../index.js";
|
||||||
@@ -23,10 +26,6 @@ import { normalizeCursorStreamLine } from "../shared/stream.js";
|
|||||||
import { hasCursorTrustBypassArg } from "../shared/trust.js";
|
import { hasCursorTrustBypassArg } from "../shared/trust.js";
|
||||||
|
|
||||||
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
||||||
const PAPERCLIP_SKILLS_CANDIDATES = [
|
|
||||||
path.resolve(__moduleDir, "../../skills"),
|
|
||||||
path.resolve(__moduleDir, "../../../../../skills"),
|
|
||||||
];
|
|
||||||
|
|
||||||
function firstNonEmptyLine(text: string): string {
|
function firstNonEmptyLine(text: string): string {
|
||||||
return (
|
return (
|
||||||
@@ -82,16 +81,9 @@ function cursorSkillsHome(): string {
|
|||||||
return path.join(os.homedir(), ".cursor", "skills");
|
return path.join(os.homedir(), ".cursor", "skills");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function resolvePaperclipSkillsDir(): Promise<string | null> {
|
|
||||||
for (const candidate of PAPERCLIP_SKILLS_CANDIDATES) {
|
|
||||||
const isDir = await fs.stat(candidate).then((s) => s.isDirectory()).catch(() => false);
|
|
||||||
if (isDir) return candidate;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
type EnsureCursorSkillsInjectedOptions = {
|
type EnsureCursorSkillsInjectedOptions = {
|
||||||
skillsDir?: string | null;
|
skillsDir?: string | null;
|
||||||
|
skillsEntries?: Array<{ name: string; source: string }>;
|
||||||
skillsHome?: string;
|
skillsHome?: string;
|
||||||
linkSkill?: (source: string, target: string) => Promise<void>;
|
linkSkill?: (source: string, target: string) => Promise<void>;
|
||||||
};
|
};
|
||||||
@@ -100,8 +92,13 @@ export async function ensureCursorSkillsInjected(
|
|||||||
onLog: AdapterExecutionContext["onLog"],
|
onLog: AdapterExecutionContext["onLog"],
|
||||||
options: EnsureCursorSkillsInjectedOptions = {},
|
options: EnsureCursorSkillsInjectedOptions = {},
|
||||||
) {
|
) {
|
||||||
const skillsDir = options.skillsDir ?? await resolvePaperclipSkillsDir();
|
const skillsEntries = options.skillsEntries
|
||||||
if (!skillsDir) return;
|
?? (options.skillsDir
|
||||||
|
? (await fs.readdir(options.skillsDir, { withFileTypes: true }))
|
||||||
|
.filter((entry) => entry.isDirectory())
|
||||||
|
.map((entry) => ({ name: entry.name, source: path.join(options.skillsDir!, entry.name) }))
|
||||||
|
: await listPaperclipSkillEntries(__moduleDir));
|
||||||
|
if (skillsEntries.length === 0) return;
|
||||||
|
|
||||||
const skillsHome = options.skillsHome ?? cursorSkillsHome();
|
const skillsHome = options.skillsHome ?? cursorSkillsHome();
|
||||||
try {
|
try {
|
||||||
@@ -113,31 +110,26 @@ export async function ensureCursorSkillsInjected(
|
|||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const removedSkills = await removeMaintainerOnlySkillSymlinks(
|
||||||
let entries: Dirent[];
|
skillsHome,
|
||||||
try {
|
skillsEntries.map((entry) => entry.name),
|
||||||
entries = await fs.readdir(skillsDir, { withFileTypes: true });
|
);
|
||||||
} catch (err) {
|
for (const skillName of removedSkills) {
|
||||||
await onLog(
|
await onLog(
|
||||||
"stderr",
|
"stderr",
|
||||||
`[paperclip] Failed to read Paperclip skills from ${skillsDir}: ${err instanceof Error ? err.message : String(err)}\n`,
|
`[paperclip] Removed maintainer-only Cursor skill "${skillName}" from ${skillsHome}\n`,
|
||||||
);
|
);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const linkSkill = options.linkSkill ?? ((source: string, target: string) => fs.symlink(source, target));
|
const linkSkill = options.linkSkill ?? ((source: string, target: string) => fs.symlink(source, target));
|
||||||
for (const entry of entries) {
|
for (const entry of skillsEntries) {
|
||||||
if (!entry.isDirectory()) continue;
|
|
||||||
const source = path.join(skillsDir, entry.name);
|
|
||||||
const target = path.join(skillsHome, entry.name);
|
const target = path.join(skillsHome, entry.name);
|
||||||
const existing = await fs.lstat(target).catch(() => null);
|
|
||||||
if (existing) continue;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await linkSkill(source, target);
|
const result = await ensurePaperclipSkillSymlink(entry.source, target, linkSkill);
|
||||||
|
if (result === "skipped") continue;
|
||||||
|
|
||||||
await onLog(
|
await onLog(
|
||||||
"stderr",
|
"stderr",
|
||||||
`[paperclip] Injected Cursor skill "${entry.name}" into ${skillsHome}\n`,
|
`[paperclip] ${result === "repaired" ? "Repaired" : "Injected"} Cursor skill "${entry.name}" into ${skillsHome}\n`,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await onLog(
|
await onLog(
|
||||||
@@ -165,6 +157,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
const workspaceId = asString(workspaceContext.workspaceId, "");
|
const workspaceId = asString(workspaceContext.workspaceId, "");
|
||||||
const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
|
const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
|
||||||
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
|
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
|
||||||
|
const agentHome = asString(workspaceContext.agentHome, "");
|
||||||
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
||||||
? context.paperclipWorkspaces.filter(
|
? context.paperclipWorkspaces.filter(
|
||||||
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
||||||
@@ -238,6 +231,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
if (workspaceRepoRef) {
|
if (workspaceRepoRef) {
|
||||||
env.PAPERCLIP_WORKSPACE_REPO_REF = workspaceRepoRef;
|
env.PAPERCLIP_WORKSPACE_REPO_REF = workspaceRepoRef;
|
||||||
}
|
}
|
||||||
|
if (agentHome) {
|
||||||
|
env.AGENT_HOME = agentHome;
|
||||||
|
}
|
||||||
if (workspaceHints.length > 0) {
|
if (workspaceHints.length > 0) {
|
||||||
env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
|
env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
|
||||||
}
|
}
|
||||||
@@ -277,6 +273,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
|
const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
|
||||||
const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
|
const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
|
||||||
let instructionsPrefix = "";
|
let instructionsPrefix = "";
|
||||||
|
let instructionsChars = 0;
|
||||||
if (instructionsFilePath) {
|
if (instructionsFilePath) {
|
||||||
try {
|
try {
|
||||||
const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
|
const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
|
||||||
@@ -284,6 +281,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
`${instructionsContents}\n\n` +
|
`${instructionsContents}\n\n` +
|
||||||
`The above agent instructions were loaded from ${instructionsFilePath}. ` +
|
`The above agent instructions were loaded from ${instructionsFilePath}. ` +
|
||||||
`Resolve any relative file references from ${instructionsDir}.\n\n`;
|
`Resolve any relative file references from ${instructionsDir}.\n\n`;
|
||||||
|
instructionsChars = instructionsPrefix.length;
|
||||||
await onLog(
|
await onLog(
|
||||||
"stderr",
|
"stderr",
|
||||||
`[paperclip] Loaded agent instructions file: ${instructionsFilePath}\n`,
|
`[paperclip] Loaded agent instructions file: ${instructionsFilePath}\n`,
|
||||||
@@ -316,7 +314,8 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
return notes;
|
return notes;
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const renderedPrompt = renderTemplate(promptTemplate, {
|
const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
|
||||||
|
const templateData = {
|
||||||
agentId: agent.id,
|
agentId: agent.id,
|
||||||
companyId: agent.companyId,
|
companyId: agent.companyId,
|
||||||
runId,
|
runId,
|
||||||
@@ -324,9 +323,29 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
agent,
|
agent,
|
||||||
run: { id: runId, source: "on_demand" },
|
run: { id: runId, source: "on_demand" },
|
||||||
context,
|
context,
|
||||||
});
|
};
|
||||||
|
const renderedPrompt = renderTemplate(promptTemplate, templateData);
|
||||||
|
const renderedBootstrapPrompt =
|
||||||
|
!sessionId && bootstrapPromptTemplate.trim().length > 0
|
||||||
|
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
|
||||||
|
: "";
|
||||||
|
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
|
||||||
const paperclipEnvNote = renderPaperclipEnvNote(env);
|
const paperclipEnvNote = renderPaperclipEnvNote(env);
|
||||||
const prompt = `${instructionsPrefix}${paperclipEnvNote}${renderedPrompt}`;
|
const prompt = joinPromptSections([
|
||||||
|
instructionsPrefix,
|
||||||
|
renderedBootstrapPrompt,
|
||||||
|
sessionHandoffNote,
|
||||||
|
paperclipEnvNote,
|
||||||
|
renderedPrompt,
|
||||||
|
]);
|
||||||
|
const promptMetrics = {
|
||||||
|
promptChars: prompt.length,
|
||||||
|
instructionsChars,
|
||||||
|
bootstrapPromptChars: renderedBootstrapPrompt.length,
|
||||||
|
sessionHandoffChars: sessionHandoffNote.length,
|
||||||
|
runtimeNoteChars: paperclipEnvNote.length,
|
||||||
|
heartbeatPromptChars: renderedPrompt.length,
|
||||||
|
};
|
||||||
|
|
||||||
const buildArgs = (resumeSessionId: string | null) => {
|
const buildArgs = (resumeSessionId: string | null) => {
|
||||||
const args = ["-p", "--output-format", "stream-json", "--workspace", cwd];
|
const args = ["-p", "--output-format", "stream-json", "--workspace", cwd];
|
||||||
@@ -349,6 +368,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
commandArgs: args,
|
commandArgs: args,
|
||||||
env: redactEnvForLogs(env),
|
env: redactEnvForLogs(env),
|
||||||
prompt,
|
prompt,
|
||||||
|
promptMetrics,
|
||||||
context,
|
context,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,6 +62,7 @@ export function buildCursorLocalConfig(v: CreateConfigValues): Record<string, un
|
|||||||
if (v.cwd) ac.cwd = v.cwd;
|
if (v.cwd) ac.cwd = v.cwd;
|
||||||
if (v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;
|
if (v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;
|
||||||
if (v.promptTemplate) ac.promptTemplate = v.promptTemplate;
|
if (v.promptTemplate) ac.promptTemplate = v.promptTemplate;
|
||||||
|
if (v.bootstrapPrompt) ac.bootstrapPromptTemplate = v.bootstrapPrompt;
|
||||||
ac.model = v.model || DEFAULT_CURSOR_LOCAL_MODEL;
|
ac.model = v.model || DEFAULT_CURSOR_LOCAL_MODEL;
|
||||||
const mode = normalizeMode(v.thinkingEffort);
|
const mode = normalizeMode(v.thinkingEffort);
|
||||||
if (mode) ac.mode = mode;
|
if (mode) ac.mode = mode;
|
||||||
|
|||||||
@@ -142,6 +142,12 @@ function parseAssistantMessage(messageRaw: unknown, ts: string): TranscriptEntry
|
|||||||
kind: "tool_call",
|
kind: "tool_call",
|
||||||
ts,
|
ts,
|
||||||
name,
|
name,
|
||||||
|
toolUseId:
|
||||||
|
asString(part.tool_use_id) ||
|
||||||
|
asString(part.toolUseId) ||
|
||||||
|
asString(part.call_id) ||
|
||||||
|
asString(part.id) ||
|
||||||
|
undefined,
|
||||||
input,
|
input,
|
||||||
});
|
});
|
||||||
continue;
|
continue;
|
||||||
@@ -199,6 +205,7 @@ function parseCursorToolCallEvent(event: Record<string, unknown>, ts: string): T
|
|||||||
kind: "tool_call",
|
kind: "tool_call",
|
||||||
ts,
|
ts,
|
||||||
name: toolName,
|
name: toolName,
|
||||||
|
toolUseId: callId,
|
||||||
input,
|
input,
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|||||||
51
packages/adapters/gemini-local/package.json
Normal file
51
packages/adapters/gemini-local/package.json
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
{
|
||||||
|
"name": "@paperclipai/adapter-gemini-local",
|
||||||
|
"version": "0.3.1",
|
||||||
|
"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": {
|
||||||
|
"@paperclipai/adapter-utils": "workspace:*",
|
||||||
|
"picocolors": "^1.1.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^24.6.0",
|
||||||
|
"typescript": "^5.7.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
208
packages/adapters/gemini-local/src/cli/format-event.ts
Normal file
208
packages/adapters/gemini-local/src/cli/format-event.ts
Normal file
@@ -0,0 +1,208 @@
|
|||||||
|
import pc from "picocolors";
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||||
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 stringifyUnknown(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 errorText(value: unknown): string {
|
||||||
|
if (typeof value === "string") return value;
|
||||||
|
const rec = asRecord(value);
|
||||||
|
if (!rec) return "";
|
||||||
|
const msg =
|
||||||
|
(typeof rec.message === "string" && rec.message) ||
|
||||||
|
(typeof rec.error === "string" && rec.error) ||
|
||||||
|
(typeof rec.code === "string" && rec.code) ||
|
||||||
|
"";
|
||||||
|
if (msg) return msg;
|
||||||
|
try {
|
||||||
|
return JSON.stringify(rec);
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function printTextMessage(prefix: string, colorize: (text: string) => string, messageRaw: unknown): void {
|
||||||
|
if (typeof messageRaw === "string") {
|
||||||
|
const text = messageRaw.trim();
|
||||||
|
if (text) console.log(colorize(`${prefix}: ${text}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = asRecord(messageRaw);
|
||||||
|
if (!message) return;
|
||||||
|
|
||||||
|
const directText = asString(message.text).trim();
|
||||||
|
if (directText) console.log(colorize(`${prefix}: ${directText}`));
|
||||||
|
|
||||||
|
const content = Array.isArray(message.content) ? message.content : [];
|
||||||
|
for (const partRaw of content) {
|
||||||
|
const part = asRecord(partRaw);
|
||||||
|
if (!part) continue;
|
||||||
|
const type = asString(part.type).trim();
|
||||||
|
|
||||||
|
if (type === "output_text" || type === "text" || type === "content") {
|
||||||
|
const text = asString(part.text).trim() || asString(part.content).trim();
|
||||||
|
if (text) console.log(colorize(`${prefix}: ${text}`));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "thinking") {
|
||||||
|
const text = asString(part.text).trim();
|
||||||
|
if (text) console.log(pc.gray(`thinking: ${text}`));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "tool_call") {
|
||||||
|
const name = asString(part.name, asString(part.tool, "tool"));
|
||||||
|
console.log(pc.yellow(`tool_call: ${name}`));
|
||||||
|
const input = part.input ?? part.arguments ?? part.args;
|
||||||
|
if (input !== undefined) console.log(pc.gray(stringifyUnknown(input)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "tool_result" || type === "tool_response") {
|
||||||
|
const isError = part.is_error === true || asString(part.status).toLowerCase() === "error";
|
||||||
|
const contentText =
|
||||||
|
asString(part.output) ||
|
||||||
|
asString(part.text) ||
|
||||||
|
asString(part.result) ||
|
||||||
|
stringifyUnknown(part.output ?? part.result ?? part.text ?? part.response);
|
||||||
|
console.log((isError ? pc.red : pc.cyan)(`tool_result${isError ? " (error)" : ""}`));
|
||||||
|
if (contentText) console.log((isError ? pc.red : pc.gray)(contentText));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function printUsage(parsed: Record<string, unknown>) {
|
||||||
|
const usage = asRecord(parsed.usage) ?? asRecord(parsed.usageMetadata);
|
||||||
|
const usageMetadata = asRecord(usage?.usageMetadata);
|
||||||
|
const source = usageMetadata ?? usage ?? {};
|
||||||
|
const input = asNumber(source.input_tokens, asNumber(source.inputTokens, asNumber(source.promptTokenCount)));
|
||||||
|
const output = asNumber(source.output_tokens, asNumber(source.outputTokens, asNumber(source.candidatesTokenCount)));
|
||||||
|
const cached = asNumber(
|
||||||
|
source.cached_input_tokens,
|
||||||
|
asNumber(source.cachedInputTokens, asNumber(source.cachedContentTokenCount)),
|
||||||
|
);
|
||||||
|
const cost = asNumber(parsed.total_cost_usd, asNumber(parsed.cost_usd, asNumber(parsed.cost)));
|
||||||
|
console.log(pc.blue(`tokens: in=${input} out=${output} cached=${cached} cost=$${cost.toFixed(6)}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function printGeminiStreamEvent(raw: string, _debug: boolean): void {
|
||||||
|
const line = raw.trim();
|
||||||
|
if (!line) return;
|
||||||
|
|
||||||
|
let parsed: Record<string, unknown> | null = null;
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(line) as Record<string, unknown>;
|
||||||
|
} catch {
|
||||||
|
console.log(line);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const type = asString(parsed.type);
|
||||||
|
|
||||||
|
if (type === "system") {
|
||||||
|
const subtype = asString(parsed.subtype);
|
||||||
|
if (subtype === "init") {
|
||||||
|
const sessionId =
|
||||||
|
asString(parsed.session_id) ||
|
||||||
|
asString(parsed.sessionId) ||
|
||||||
|
asString(parsed.sessionID) ||
|
||||||
|
asString(parsed.checkpoint_id);
|
||||||
|
const model = asString(parsed.model);
|
||||||
|
const details = [sessionId ? `session: ${sessionId}` : "", model ? `model: ${model}` : ""]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(", ");
|
||||||
|
console.log(pc.blue(`Gemini init${details ? ` (${details})` : ""}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (subtype === "error") {
|
||||||
|
const text = errorText(parsed.error ?? parsed.message ?? parsed.detail);
|
||||||
|
if (text) console.log(pc.red(`error: ${text}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(pc.blue(`system: ${subtype || "event"}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "assistant") {
|
||||||
|
printTextMessage("assistant", pc.green, parsed.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "user") {
|
||||||
|
printTextMessage("user", pc.gray, parsed.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "thinking") {
|
||||||
|
const text = asString(parsed.text).trim() || asString(asRecord(parsed.delta)?.text).trim();
|
||||||
|
if (text) console.log(pc.gray(`thinking: ${text}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "tool_call") {
|
||||||
|
const subtype = asString(parsed.subtype).trim().toLowerCase();
|
||||||
|
const toolCall = asRecord(parsed.tool_call ?? parsed.toolCall);
|
||||||
|
const [toolName] = toolCall ? Object.keys(toolCall) : [];
|
||||||
|
if (!toolCall || !toolName) {
|
||||||
|
console.log(pc.yellow(`tool_call${subtype ? `: ${subtype}` : ""}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const payload = asRecord(toolCall[toolName]) ?? {};
|
||||||
|
if (subtype === "started" || subtype === "start") {
|
||||||
|
console.log(pc.yellow(`tool_call: ${toolName}`));
|
||||||
|
console.log(pc.gray(stringifyUnknown(payload.args ?? payload.input ?? payload.arguments ?? payload)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (subtype === "completed" || subtype === "complete" || subtype === "finished") {
|
||||||
|
const isError =
|
||||||
|
parsed.is_error === true ||
|
||||||
|
payload.is_error === true ||
|
||||||
|
payload.error !== undefined ||
|
||||||
|
asString(payload.status).toLowerCase() === "error";
|
||||||
|
console.log((isError ? pc.red : pc.cyan)(`tool_result${isError ? " (error)" : ""}`));
|
||||||
|
console.log((isError ? pc.red : pc.gray)(stringifyUnknown(payload.result ?? payload.output ?? payload.error)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
console.log(pc.yellow(`tool_call: ${toolName}${subtype ? ` (${subtype})` : ""}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "result") {
|
||||||
|
printUsage(parsed);
|
||||||
|
const subtype = asString(parsed.subtype, "result");
|
||||||
|
const isError = parsed.is_error === true;
|
||||||
|
if (subtype || isError) {
|
||||||
|
console.log((isError ? pc.red : pc.blue)(`result: subtype=${subtype} is_error=${isError ? "true" : "false"}`));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "error") {
|
||||||
|
const text = errorText(parsed.error ?? parsed.message ?? parsed.detail);
|
||||||
|
if (text) console.log(pc.red(`error: ${text}`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(line);
|
||||||
|
}
|
||||||
1
packages/adapters/gemini-local/src/cli/index.ts
Normal file
1
packages/adapters/gemini-local/src/cli/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export { printGeminiStreamEvent } from "./format-event.js";
|
||||||
47
packages/adapters/gemini-local/src/index.ts
Normal file
47
packages/adapters/gemini-local/src/index.ts
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
export const type = "gemini_local";
|
||||||
|
export const label = "Gemini CLI (local)";
|
||||||
|
export const DEFAULT_GEMINI_LOCAL_MODEL = "auto";
|
||||||
|
|
||||||
|
export const models = [
|
||||||
|
{ id: DEFAULT_GEMINI_LOCAL_MODEL, label: "Auto" },
|
||||||
|
{ id: "gemini-2.5-pro", label: "Gemini 2.5 Pro" },
|
||||||
|
{ id: "gemini-2.5-flash", label: "Gemini 2.5 Flash" },
|
||||||
|
{ id: "gemini-2.5-flash-lite", label: "Gemini 2.5 Flash Lite" },
|
||||||
|
{ id: "gemini-2.0-flash", label: "Gemini 2.0 Flash" },
|
||||||
|
{ id: "gemini-2.0-flash-lite", label: "Gemini 2.0 Flash Lite" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const agentConfigurationDoc = `# gemini_local agent configuration
|
||||||
|
|
||||||
|
Adapter: gemini_local
|
||||||
|
|
||||||
|
Use when:
|
||||||
|
- You want Paperclip to run the Gemini CLI locally on the host machine
|
||||||
|
- You want Gemini chat sessions resumed across heartbeats with --resume
|
||||||
|
- You want Paperclip skills injected locally without polluting the global environment
|
||||||
|
|
||||||
|
Don't use when:
|
||||||
|
- You need webhook-style external invocation (use http or openclaw_gateway)
|
||||||
|
- You only need a one-shot script without an AI coding agent loop (use process)
|
||||||
|
- Gemini CLI is not installed on the machine that runs Paperclip
|
||||||
|
|
||||||
|
Core fields:
|
||||||
|
- cwd (string, optional): default absolute working directory fallback for the agent process (created if missing when possible)
|
||||||
|
- instructionsFilePath (string, optional): absolute path to a markdown instructions file prepended to the run prompt
|
||||||
|
- promptTemplate (string, optional): run prompt template
|
||||||
|
- model (string, optional): Gemini model id. Defaults to auto.
|
||||||
|
- sandbox (boolean, optional): run in sandbox mode (default: false, passes --sandbox=none)
|
||||||
|
- command (string, optional): defaults to "gemini"
|
||||||
|
- extraArgs (string[], optional): additional CLI args
|
||||||
|
- env (object, optional): KEY=VALUE environment variables
|
||||||
|
|
||||||
|
Operational fields:
|
||||||
|
- timeoutSec (number, optional): run timeout in seconds
|
||||||
|
- graceSec (number, optional): SIGTERM grace period in seconds
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
- Runs use positional prompt arguments, not stdin.
|
||||||
|
- Sessions resume with --resume when stored session cwd matches the current cwd.
|
||||||
|
- Paperclip auto-injects local skills into \`~/.gemini/skills/\` via symlinks, so the CLI can discover both credentials and skills in their natural location.
|
||||||
|
- Authentication can use GEMINI_API_KEY / GOOGLE_API_KEY or local Gemini CLI login.
|
||||||
|
`;
|
||||||
452
packages/adapters/gemini-local/src/server/execute.ts
Normal file
452
packages/adapters/gemini-local/src/server/execute.ts
Normal file
@@ -0,0 +1,452 @@
|
|||||||
|
import fs from "node:fs/promises";
|
||||||
|
import type { Dirent } from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import type { AdapterExecutionContext, AdapterExecutionResult } from "@paperclipai/adapter-utils";
|
||||||
|
import {
|
||||||
|
asBoolean,
|
||||||
|
asNumber,
|
||||||
|
asString,
|
||||||
|
asStringArray,
|
||||||
|
buildPaperclipEnv,
|
||||||
|
ensureAbsoluteDirectory,
|
||||||
|
ensureCommandResolvable,
|
||||||
|
ensurePaperclipSkillSymlink,
|
||||||
|
joinPromptSections,
|
||||||
|
ensurePathInEnv,
|
||||||
|
listPaperclipSkillEntries,
|
||||||
|
removeMaintainerOnlySkillSymlinks,
|
||||||
|
parseObject,
|
||||||
|
redactEnvForLogs,
|
||||||
|
renderTemplate,
|
||||||
|
runChildProcess,
|
||||||
|
} from "@paperclipai/adapter-utils/server-utils";
|
||||||
|
import { DEFAULT_GEMINI_LOCAL_MODEL } from "../index.js";
|
||||||
|
import {
|
||||||
|
describeGeminiFailure,
|
||||||
|
detectGeminiAuthRequired,
|
||||||
|
isGeminiTurnLimitResult,
|
||||||
|
isGeminiUnknownSessionError,
|
||||||
|
parseGeminiJsonl,
|
||||||
|
} from "./parse.js";
|
||||||
|
import { firstNonEmptyLine } from "./utils.js";
|
||||||
|
|
||||||
|
const __moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
function hasNonEmptyEnvValue(env: Record<string, string>, key: string): boolean {
|
||||||
|
const raw = env[key];
|
||||||
|
return typeof raw === "string" && raw.trim().length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveGeminiBillingType(env: Record<string, string>): "api" | "subscription" {
|
||||||
|
return hasNonEmptyEnvValue(env, "GEMINI_API_KEY") || hasNonEmptyEnvValue(env, "GOOGLE_API_KEY")
|
||||||
|
? "api"
|
||||||
|
: "subscription";
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderPaperclipEnvNote(env: Record<string, string>): string {
|
||||||
|
const paperclipKeys = Object.keys(env)
|
||||||
|
.filter((key) => key.startsWith("PAPERCLIP_"))
|
||||||
|
.sort();
|
||||||
|
if (paperclipKeys.length === 0) return "";
|
||||||
|
return [
|
||||||
|
"Paperclip runtime note:",
|
||||||
|
`The following PAPERCLIP_* environment variables are available in this run: ${paperclipKeys.join(", ")}`,
|
||||||
|
"Do not assume these variables are missing without checking your shell environment.",
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderApiAccessNote(env: Record<string, string>): string {
|
||||||
|
if (!hasNonEmptyEnvValue(env, "PAPERCLIP_API_URL") || !hasNonEmptyEnvValue(env, "PAPERCLIP_API_KEY")) return "";
|
||||||
|
return [
|
||||||
|
"Paperclip API access note:",
|
||||||
|
"Use run_shell_command with curl to make Paperclip API requests.",
|
||||||
|
"GET example:",
|
||||||
|
` run_shell_command({ command: "curl -s -H \\"Authorization: Bearer $PAPERCLIP_API_KEY\\" \\"$PAPERCLIP_API_URL/api/agents/me\\"" })`,
|
||||||
|
"POST/PATCH example:",
|
||||||
|
` run_shell_command({ command: "curl -s -X POST -H \\"Authorization: Bearer $PAPERCLIP_API_KEY\\" -H 'Content-Type: application/json' -H \\"X-Paperclip-Run-Id: $PAPERCLIP_RUN_ID\\" -d '{...}' \\"$PAPERCLIP_API_URL/api/issues/{id}/checkout\\"" })`,
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
].join("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function geminiSkillsHome(): string {
|
||||||
|
return path.join(os.homedir(), ".gemini", "skills");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inject Paperclip skills directly into `~/.gemini/skills/` via symlinks.
|
||||||
|
* This avoids needing GEMINI_CLI_HOME overrides, so the CLI naturally finds
|
||||||
|
* both its auth credentials and the injected skills in the real home directory.
|
||||||
|
*/
|
||||||
|
async function ensureGeminiSkillsInjected(
|
||||||
|
onLog: AdapterExecutionContext["onLog"],
|
||||||
|
): Promise<void> {
|
||||||
|
const skillsEntries = await listPaperclipSkillEntries(__moduleDir);
|
||||||
|
if (skillsEntries.length === 0) return;
|
||||||
|
|
||||||
|
const skillsHome = geminiSkillsHome();
|
||||||
|
try {
|
||||||
|
await fs.mkdir(skillsHome, { recursive: true });
|
||||||
|
} catch (err) {
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] Failed to prepare Gemini skills directory ${skillsHome}: ${err instanceof Error ? err.message : String(err)}\n`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const removedSkills = await removeMaintainerOnlySkillSymlinks(
|
||||||
|
skillsHome,
|
||||||
|
skillsEntries.map((entry) => entry.name),
|
||||||
|
);
|
||||||
|
for (const skillName of removedSkills) {
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] Removed maintainer-only Gemini skill "${skillName}" from ${skillsHome}\n`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const entry of skillsEntries) {
|
||||||
|
const target = path.join(skillsHome, entry.name);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await ensurePaperclipSkillSymlink(entry.source, target);
|
||||||
|
if (result === "skipped") continue;
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] ${result === "repaired" ? "Repaired" : "Linked"} Gemini skill: ${entry.name}\n`,
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] Failed to link Gemini skill "${entry.name}": ${err instanceof Error ? err.message : String(err)}\n`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExecutionResult> {
|
||||||
|
const { runId, agent, runtime, config, context, onLog, onMeta, authToken } = ctx;
|
||||||
|
|
||||||
|
const promptTemplate = asString(
|
||||||
|
config.promptTemplate,
|
||||||
|
"You are agent {{agent.id}} ({{agent.name}}). Continue your Paperclip work.",
|
||||||
|
);
|
||||||
|
const command = asString(config.command, "gemini");
|
||||||
|
const model = asString(config.model, DEFAULT_GEMINI_LOCAL_MODEL).trim();
|
||||||
|
const sandbox = asBoolean(config.sandbox, false);
|
||||||
|
|
||||||
|
const workspaceContext = parseObject(context.paperclipWorkspace);
|
||||||
|
const workspaceCwd = asString(workspaceContext.cwd, "");
|
||||||
|
const workspaceSource = asString(workspaceContext.source, "");
|
||||||
|
const workspaceId = asString(workspaceContext.workspaceId, "");
|
||||||
|
const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
|
||||||
|
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
|
||||||
|
const agentHome = asString(workspaceContext.agentHome, "");
|
||||||
|
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
||||||
|
? context.paperclipWorkspaces.filter(
|
||||||
|
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
||||||
|
)
|
||||||
|
: [];
|
||||||
|
const configuredCwd = asString(config.cwd, "");
|
||||||
|
const useConfiguredInsteadOfAgentHome = workspaceSource === "agent_home" && configuredCwd.length > 0;
|
||||||
|
const effectiveWorkspaceCwd = useConfiguredInsteadOfAgentHome ? "" : workspaceCwd;
|
||||||
|
const cwd = effectiveWorkspaceCwd || configuredCwd || process.cwd();
|
||||||
|
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
|
||||||
|
await ensureGeminiSkillsInjected(onLog);
|
||||||
|
|
||||||
|
const envConfig = parseObject(config.env);
|
||||||
|
const hasExplicitApiKey =
|
||||||
|
typeof envConfig.PAPERCLIP_API_KEY === "string" && envConfig.PAPERCLIP_API_KEY.trim().length > 0;
|
||||||
|
const env: Record<string, string> = { ...buildPaperclipEnv(agent) };
|
||||||
|
env.PAPERCLIP_RUN_ID = runId;
|
||||||
|
const wakeTaskId =
|
||||||
|
(typeof context.taskId === "string" && context.taskId.trim().length > 0 && context.taskId.trim()) ||
|
||||||
|
(typeof context.issueId === "string" && context.issueId.trim().length > 0 && context.issueId.trim()) ||
|
||||||
|
null;
|
||||||
|
const wakeReason =
|
||||||
|
typeof context.wakeReason === "string" && context.wakeReason.trim().length > 0
|
||||||
|
? context.wakeReason.trim()
|
||||||
|
: null;
|
||||||
|
const wakeCommentId =
|
||||||
|
(typeof context.wakeCommentId === "string" && context.wakeCommentId.trim().length > 0 && context.wakeCommentId.trim()) ||
|
||||||
|
(typeof context.commentId === "string" && context.commentId.trim().length > 0 && context.commentId.trim()) ||
|
||||||
|
null;
|
||||||
|
const approvalId =
|
||||||
|
typeof context.approvalId === "string" && context.approvalId.trim().length > 0
|
||||||
|
? context.approvalId.trim()
|
||||||
|
: null;
|
||||||
|
const approvalStatus =
|
||||||
|
typeof context.approvalStatus === "string" && context.approvalStatus.trim().length > 0
|
||||||
|
? context.approvalStatus.trim()
|
||||||
|
: null;
|
||||||
|
const linkedIssueIds = Array.isArray(context.issueIds)
|
||||||
|
? context.issueIds.filter((value): value is string => typeof value === "string" && value.trim().length > 0)
|
||||||
|
: [];
|
||||||
|
if (wakeTaskId) env.PAPERCLIP_TASK_ID = wakeTaskId;
|
||||||
|
if (wakeReason) env.PAPERCLIP_WAKE_REASON = wakeReason;
|
||||||
|
if (wakeCommentId) env.PAPERCLIP_WAKE_COMMENT_ID = wakeCommentId;
|
||||||
|
if (approvalId) env.PAPERCLIP_APPROVAL_ID = approvalId;
|
||||||
|
if (approvalStatus) env.PAPERCLIP_APPROVAL_STATUS = approvalStatus;
|
||||||
|
if (linkedIssueIds.length > 0) env.PAPERCLIP_LINKED_ISSUE_IDS = linkedIssueIds.join(",");
|
||||||
|
if (effectiveWorkspaceCwd) env.PAPERCLIP_WORKSPACE_CWD = effectiveWorkspaceCwd;
|
||||||
|
if (workspaceSource) env.PAPERCLIP_WORKSPACE_SOURCE = workspaceSource;
|
||||||
|
if (workspaceId) env.PAPERCLIP_WORKSPACE_ID = workspaceId;
|
||||||
|
if (workspaceRepoUrl) env.PAPERCLIP_WORKSPACE_REPO_URL = workspaceRepoUrl;
|
||||||
|
if (workspaceRepoRef) env.PAPERCLIP_WORKSPACE_REPO_REF = workspaceRepoRef;
|
||||||
|
if (agentHome) env.AGENT_HOME = agentHome;
|
||||||
|
if (workspaceHints.length > 0) env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(envConfig)) {
|
||||||
|
if (typeof value === "string") env[key] = value;
|
||||||
|
}
|
||||||
|
if (!hasExplicitApiKey && authToken) {
|
||||||
|
env.PAPERCLIP_API_KEY = authToken;
|
||||||
|
}
|
||||||
|
const billingType = resolveGeminiBillingType(env);
|
||||||
|
const runtimeEnv = ensurePathInEnv({ ...process.env, ...env });
|
||||||
|
await ensureCommandResolvable(command, cwd, runtimeEnv);
|
||||||
|
|
||||||
|
const timeoutSec = asNumber(config.timeoutSec, 0);
|
||||||
|
const graceSec = asNumber(config.graceSec, 20);
|
||||||
|
const extraArgs = (() => {
|
||||||
|
const fromExtraArgs = asStringArray(config.extraArgs);
|
||||||
|
if (fromExtraArgs.length > 0) return fromExtraArgs;
|
||||||
|
return asStringArray(config.args);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const runtimeSessionParams = parseObject(runtime.sessionParams);
|
||||||
|
const runtimeSessionId = asString(runtimeSessionParams.sessionId, runtime.sessionId ?? "");
|
||||||
|
const runtimeSessionCwd = asString(runtimeSessionParams.cwd, "");
|
||||||
|
const canResumeSession =
|
||||||
|
runtimeSessionId.length > 0 &&
|
||||||
|
(runtimeSessionCwd.length === 0 || path.resolve(runtimeSessionCwd) === path.resolve(cwd));
|
||||||
|
const sessionId = canResumeSession ? runtimeSessionId : null;
|
||||||
|
if (runtimeSessionId && !canResumeSession) {
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] Gemini session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${cwd}".\n`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
|
||||||
|
const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
|
||||||
|
let instructionsPrefix = "";
|
||||||
|
if (instructionsFilePath) {
|
||||||
|
try {
|
||||||
|
const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
|
||||||
|
instructionsPrefix =
|
||||||
|
`${instructionsContents}\n\n` +
|
||||||
|
`The above agent instructions were loaded from ${instructionsFilePath}. ` +
|
||||||
|
`Resolve any relative file references from ${instructionsDir}.\n\n`;
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] Loaded agent instructions file: ${instructionsFilePath}\n`,
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
const reason = err instanceof Error ? err.message : String(err);
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] Warning: could not read agent instructions file "${instructionsFilePath}": ${reason}\n`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const commandNotes = (() => {
|
||||||
|
const notes: string[] = ["Prompt is passed to Gemini as the final positional argument."];
|
||||||
|
notes.push("Added --approval-mode yolo for unattended execution.");
|
||||||
|
if (!instructionsFilePath) return notes;
|
||||||
|
if (instructionsPrefix.length > 0) {
|
||||||
|
notes.push(
|
||||||
|
`Loaded agent instructions from ${instructionsFilePath}`,
|
||||||
|
`Prepended instructions + path directive to prompt (relative references from ${instructionsDir}).`,
|
||||||
|
);
|
||||||
|
return notes;
|
||||||
|
}
|
||||||
|
notes.push(
|
||||||
|
`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`,
|
||||||
|
);
|
||||||
|
return notes;
|
||||||
|
})();
|
||||||
|
|
||||||
|
const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
|
||||||
|
const templateData = {
|
||||||
|
agentId: agent.id,
|
||||||
|
companyId: agent.companyId,
|
||||||
|
runId,
|
||||||
|
company: { id: agent.companyId },
|
||||||
|
agent,
|
||||||
|
run: { id: runId, source: "on_demand" },
|
||||||
|
context,
|
||||||
|
};
|
||||||
|
const renderedPrompt = renderTemplate(promptTemplate, templateData);
|
||||||
|
const renderedBootstrapPrompt =
|
||||||
|
!sessionId && bootstrapPromptTemplate.trim().length > 0
|
||||||
|
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
|
||||||
|
: "";
|
||||||
|
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
|
||||||
|
const paperclipEnvNote = renderPaperclipEnvNote(env);
|
||||||
|
const apiAccessNote = renderApiAccessNote(env);
|
||||||
|
const prompt = joinPromptSections([
|
||||||
|
instructionsPrefix,
|
||||||
|
renderedBootstrapPrompt,
|
||||||
|
sessionHandoffNote,
|
||||||
|
paperclipEnvNote,
|
||||||
|
apiAccessNote,
|
||||||
|
renderedPrompt,
|
||||||
|
]);
|
||||||
|
const promptMetrics = {
|
||||||
|
promptChars: prompt.length,
|
||||||
|
instructionsChars: instructionsPrefix.length,
|
||||||
|
bootstrapPromptChars: renderedBootstrapPrompt.length,
|
||||||
|
sessionHandoffChars: sessionHandoffNote.length,
|
||||||
|
runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length,
|
||||||
|
heartbeatPromptChars: renderedPrompt.length,
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildArgs = (resumeSessionId: string | null) => {
|
||||||
|
const args = ["--output-format", "stream-json"];
|
||||||
|
if (resumeSessionId) args.push("--resume", resumeSessionId);
|
||||||
|
if (model && model !== DEFAULT_GEMINI_LOCAL_MODEL) args.push("--model", model);
|
||||||
|
args.push("--approval-mode", "yolo");
|
||||||
|
if (sandbox) {
|
||||||
|
args.push("--sandbox");
|
||||||
|
} else {
|
||||||
|
args.push("--sandbox=none");
|
||||||
|
}
|
||||||
|
if (extraArgs.length > 0) args.push(...extraArgs);
|
||||||
|
args.push(prompt);
|
||||||
|
return args;
|
||||||
|
};
|
||||||
|
|
||||||
|
const runAttempt = async (resumeSessionId: string | null) => {
|
||||||
|
const args = buildArgs(resumeSessionId);
|
||||||
|
if (onMeta) {
|
||||||
|
await onMeta({
|
||||||
|
adapterType: "gemini_local",
|
||||||
|
command,
|
||||||
|
cwd,
|
||||||
|
commandNotes,
|
||||||
|
commandArgs: args.map((value, index) => (
|
||||||
|
index === args.length - 1 ? `<prompt ${prompt.length} chars>` : value
|
||||||
|
)),
|
||||||
|
env: redactEnvForLogs(env),
|
||||||
|
prompt,
|
||||||
|
promptMetrics,
|
||||||
|
context,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const proc = await runChildProcess(runId, command, args, {
|
||||||
|
cwd,
|
||||||
|
env,
|
||||||
|
timeoutSec,
|
||||||
|
graceSec,
|
||||||
|
onLog,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
proc,
|
||||||
|
parsed: parseGeminiJsonl(proc.stdout),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const toResult = (
|
||||||
|
attempt: {
|
||||||
|
proc: {
|
||||||
|
exitCode: number | null;
|
||||||
|
signal: string | null;
|
||||||
|
timedOut: boolean;
|
||||||
|
stdout: string;
|
||||||
|
stderr: string;
|
||||||
|
};
|
||||||
|
parsed: ReturnType<typeof parseGeminiJsonl>;
|
||||||
|
},
|
||||||
|
clearSessionOnMissingSession = false,
|
||||||
|
isRetry = false,
|
||||||
|
): AdapterExecutionResult => {
|
||||||
|
const authMeta = detectGeminiAuthRequired({
|
||||||
|
parsed: attempt.parsed.resultEvent,
|
||||||
|
stdout: attempt.proc.stdout,
|
||||||
|
stderr: attempt.proc.stderr,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (attempt.proc.timedOut) {
|
||||||
|
return {
|
||||||
|
exitCode: attempt.proc.exitCode,
|
||||||
|
signal: attempt.proc.signal,
|
||||||
|
timedOut: true,
|
||||||
|
errorMessage: `Timed out after ${timeoutSec}s`,
|
||||||
|
errorCode: authMeta.requiresAuth ? "gemini_auth_required" : null,
|
||||||
|
clearSession: clearSessionOnMissingSession,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const clearSessionForTurnLimit = isGeminiTurnLimitResult(attempt.parsed.resultEvent, attempt.proc.exitCode);
|
||||||
|
|
||||||
|
// On retry, don't fall back to old session ID — the old session was stale
|
||||||
|
const canFallbackToRuntimeSession = !isRetry;
|
||||||
|
const resolvedSessionId = attempt.parsed.sessionId
|
||||||
|
?? (canFallbackToRuntimeSession ? (runtimeSessionId ?? runtime.sessionId ?? null) : null);
|
||||||
|
const resolvedSessionParams = resolvedSessionId
|
||||||
|
? ({
|
||||||
|
sessionId: resolvedSessionId,
|
||||||
|
cwd,
|
||||||
|
...(workspaceId ? { workspaceId } : {}),
|
||||||
|
...(workspaceRepoUrl ? { repoUrl: workspaceRepoUrl } : {}),
|
||||||
|
...(workspaceRepoRef ? { repoRef: workspaceRepoRef } : {}),
|
||||||
|
} as Record<string, unknown>)
|
||||||
|
: null;
|
||||||
|
const parsedError = typeof attempt.parsed.errorMessage === "string" ? attempt.parsed.errorMessage.trim() : "";
|
||||||
|
const stderrLine = firstNonEmptyLine(attempt.proc.stderr);
|
||||||
|
const structuredFailure = attempt.parsed.resultEvent
|
||||||
|
? describeGeminiFailure(attempt.parsed.resultEvent)
|
||||||
|
: null;
|
||||||
|
const fallbackErrorMessage =
|
||||||
|
parsedError ||
|
||||||
|
structuredFailure ||
|
||||||
|
stderrLine ||
|
||||||
|
`Gemini exited with code ${attempt.proc.exitCode ?? -1}`;
|
||||||
|
|
||||||
|
return {
|
||||||
|
exitCode: attempt.proc.exitCode,
|
||||||
|
signal: attempt.proc.signal,
|
||||||
|
timedOut: false,
|
||||||
|
errorMessage: (attempt.proc.exitCode ?? 0) === 0 ? null : fallbackErrorMessage,
|
||||||
|
errorCode: (attempt.proc.exitCode ?? 0) !== 0 && authMeta.requiresAuth ? "gemini_auth_required" : null,
|
||||||
|
usage: attempt.parsed.usage,
|
||||||
|
sessionId: resolvedSessionId,
|
||||||
|
sessionParams: resolvedSessionParams,
|
||||||
|
sessionDisplayId: resolvedSessionId,
|
||||||
|
provider: "google",
|
||||||
|
model,
|
||||||
|
billingType,
|
||||||
|
costUsd: attempt.parsed.costUsd,
|
||||||
|
resultJson: attempt.parsed.resultEvent ?? {
|
||||||
|
stdout: attempt.proc.stdout,
|
||||||
|
stderr: attempt.proc.stderr,
|
||||||
|
},
|
||||||
|
summary: attempt.parsed.summary,
|
||||||
|
question: attempt.parsed.question,
|
||||||
|
clearSession: clearSessionForTurnLimit || Boolean(clearSessionOnMissingSession && !resolvedSessionId),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const initial = await runAttempt(sessionId);
|
||||||
|
if (
|
||||||
|
sessionId &&
|
||||||
|
!initial.proc.timedOut &&
|
||||||
|
(initial.proc.exitCode ?? 0) !== 0 &&
|
||||||
|
isGeminiUnknownSessionError(initial.proc.stdout, initial.proc.stderr)
|
||||||
|
) {
|
||||||
|
await onLog(
|
||||||
|
"stderr",
|
||||||
|
`[paperclip] Gemini resume session "${sessionId}" is unavailable; retrying with a fresh session.\n`,
|
||||||
|
);
|
||||||
|
const retry = await runAttempt(null);
|
||||||
|
return toResult(retry, true, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
return toResult(initial);
|
||||||
|
}
|
||||||
70
packages/adapters/gemini-local/src/server/index.ts
Normal file
70
packages/adapters/gemini-local/src/server/index.ts
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
export { execute } from "./execute.js";
|
||||||
|
export { testEnvironment } from "./test.js";
|
||||||
|
export {
|
||||||
|
parseGeminiJsonl,
|
||||||
|
isGeminiUnknownSessionError,
|
||||||
|
describeGeminiFailure,
|
||||||
|
detectGeminiAuthRequired,
|
||||||
|
isGeminiTurnLimitResult,
|
||||||
|
} from "./parse.js";
|
||||||
|
import type { AdapterSessionCodec } from "@paperclipai/adapter-utils";
|
||||||
|
|
||||||
|
function readNonEmptyString(value: unknown): string | null {
|
||||||
|
return typeof value === "string" && value.trim().length > 0 ? value.trim() : 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 sessionId =
|
||||||
|
readNonEmptyString(record.sessionId) ??
|
||||||
|
readNonEmptyString(record.session_id) ??
|
||||||
|
readNonEmptyString(record.sessionID);
|
||||||
|
if (!sessionId) return null;
|
||||||
|
const cwd =
|
||||||
|
readNonEmptyString(record.cwd) ??
|
||||||
|
readNonEmptyString(record.workdir) ??
|
||||||
|
readNonEmptyString(record.folder);
|
||||||
|
const workspaceId = readNonEmptyString(record.workspaceId) ?? readNonEmptyString(record.workspace_id);
|
||||||
|
const repoUrl = readNonEmptyString(record.repoUrl) ?? readNonEmptyString(record.repo_url);
|
||||||
|
const repoRef = readNonEmptyString(record.repoRef) ?? readNonEmptyString(record.repo_ref);
|
||||||
|
return {
|
||||||
|
sessionId,
|
||||||
|
...(cwd ? { cwd } : {}),
|
||||||
|
...(workspaceId ? { workspaceId } : {}),
|
||||||
|
...(repoUrl ? { repoUrl } : {}),
|
||||||
|
...(repoRef ? { repoRef } : {}),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
serialize(params: Record<string, unknown> | null) {
|
||||||
|
if (!params) return null;
|
||||||
|
const sessionId =
|
||||||
|
readNonEmptyString(params.sessionId) ??
|
||||||
|
readNonEmptyString(params.session_id) ??
|
||||||
|
readNonEmptyString(params.sessionID);
|
||||||
|
if (!sessionId) return null;
|
||||||
|
const cwd =
|
||||||
|
readNonEmptyString(params.cwd) ??
|
||||||
|
readNonEmptyString(params.workdir) ??
|
||||||
|
readNonEmptyString(params.folder);
|
||||||
|
const workspaceId = readNonEmptyString(params.workspaceId) ?? readNonEmptyString(params.workspace_id);
|
||||||
|
const repoUrl = readNonEmptyString(params.repoUrl) ?? readNonEmptyString(params.repo_url);
|
||||||
|
const repoRef = readNonEmptyString(params.repoRef) ?? readNonEmptyString(params.repo_ref);
|
||||||
|
return {
|
||||||
|
sessionId,
|
||||||
|
...(cwd ? { cwd } : {}),
|
||||||
|
...(workspaceId ? { workspaceId } : {}),
|
||||||
|
...(repoUrl ? { repoUrl } : {}),
|
||||||
|
...(repoRef ? { repoRef } : {}),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
getDisplayId(params: Record<string, unknown> | null) {
|
||||||
|
if (!params) return null;
|
||||||
|
return (
|
||||||
|
readNonEmptyString(params.sessionId) ??
|
||||||
|
readNonEmptyString(params.session_id) ??
|
||||||
|
readNonEmptyString(params.sessionID)
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
263
packages/adapters/gemini-local/src/server/parse.ts
Normal file
263
packages/adapters/gemini-local/src/server/parse.ts
Normal file
@@ -0,0 +1,263 @@
|
|||||||
|
import { asNumber, asString, parseJson, parseObject } from "@paperclipai/adapter-utils/server-utils";
|
||||||
|
|
||||||
|
function collectMessageText(message: unknown): string[] {
|
||||||
|
if (typeof message === "string") {
|
||||||
|
const trimmed = message.trim();
|
||||||
|
return trimmed ? [trimmed] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = parseObject(message);
|
||||||
|
const direct = asString(record.text, "").trim();
|
||||||
|
const lines: string[] = direct ? [direct] : [];
|
||||||
|
const content = Array.isArray(record.content) ? record.content : [];
|
||||||
|
|
||||||
|
for (const partRaw of content) {
|
||||||
|
const part = parseObject(partRaw);
|
||||||
|
const type = asString(part.type, "").trim();
|
||||||
|
if (type === "output_text" || type === "text" || type === "content") {
|
||||||
|
const text = asString(part.text, "").trim() || asString(part.content, "").trim();
|
||||||
|
if (text) lines.push(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readSessionId(event: Record<string, unknown>): string | null {
|
||||||
|
return (
|
||||||
|
asString(event.session_id, "").trim() ||
|
||||||
|
asString(event.sessionId, "").trim() ||
|
||||||
|
asString(event.sessionID, "").trim() ||
|
||||||
|
asString(event.checkpoint_id, "").trim() ||
|
||||||
|
asString(event.thread_id, "").trim() ||
|
||||||
|
null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function asErrorText(value: unknown): string {
|
||||||
|
if (typeof value === "string") return value;
|
||||||
|
const rec = parseObject(value);
|
||||||
|
const message =
|
||||||
|
asString(rec.message, "") ||
|
||||||
|
asString(rec.error, "") ||
|
||||||
|
asString(rec.code, "") ||
|
||||||
|
asString(rec.detail, "");
|
||||||
|
if (message) return message;
|
||||||
|
try {
|
||||||
|
return JSON.stringify(rec);
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function accumulateUsage(
|
||||||
|
target: { inputTokens: number; cachedInputTokens: number; outputTokens: number },
|
||||||
|
usageRaw: unknown,
|
||||||
|
) {
|
||||||
|
const usage = parseObject(usageRaw);
|
||||||
|
const usageMetadata = parseObject(usage.usageMetadata);
|
||||||
|
const source = Object.keys(usageMetadata).length > 0 ? usageMetadata : usage;
|
||||||
|
|
||||||
|
target.inputTokens += asNumber(
|
||||||
|
source.input_tokens,
|
||||||
|
asNumber(source.inputTokens, asNumber(source.promptTokenCount, 0)),
|
||||||
|
);
|
||||||
|
target.cachedInputTokens += asNumber(
|
||||||
|
source.cached_input_tokens,
|
||||||
|
asNumber(source.cachedInputTokens, asNumber(source.cachedContentTokenCount, 0)),
|
||||||
|
);
|
||||||
|
target.outputTokens += asNumber(
|
||||||
|
source.output_tokens,
|
||||||
|
asNumber(source.outputTokens, asNumber(source.candidatesTokenCount, 0)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseGeminiJsonl(stdout: string) {
|
||||||
|
let sessionId: string | null = null;
|
||||||
|
const messages: string[] = [];
|
||||||
|
let errorMessage: string | null = null;
|
||||||
|
let costUsd: number | null = null;
|
||||||
|
let resultEvent: Record<string, unknown> | null = null;
|
||||||
|
let question: { prompt: string; choices: Array<{ key: string; label: string; description?: string }> } | null = null;
|
||||||
|
const usage = {
|
||||||
|
inputTokens: 0,
|
||||||
|
cachedInputTokens: 0,
|
||||||
|
outputTokens: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const rawLine of stdout.split(/\r?\n/)) {
|
||||||
|
const line = rawLine.trim();
|
||||||
|
if (!line) continue;
|
||||||
|
|
||||||
|
const event = parseJson(line);
|
||||||
|
if (!event) continue;
|
||||||
|
|
||||||
|
const foundSessionId = readSessionId(event);
|
||||||
|
if (foundSessionId) sessionId = foundSessionId;
|
||||||
|
|
||||||
|
const type = asString(event.type, "").trim();
|
||||||
|
|
||||||
|
if (type === "assistant") {
|
||||||
|
messages.push(...collectMessageText(event.message));
|
||||||
|
const messageObj = parseObject(event.message);
|
||||||
|
const content = Array.isArray(messageObj.content) ? messageObj.content : [];
|
||||||
|
for (const partRaw of content) {
|
||||||
|
const part = parseObject(partRaw);
|
||||||
|
if (asString(part.type, "").trim() === "question") {
|
||||||
|
question = {
|
||||||
|
prompt: asString(part.prompt, "").trim(),
|
||||||
|
choices: (Array.isArray(part.choices) ? part.choices : []).map((choiceRaw) => {
|
||||||
|
const choice = parseObject(choiceRaw);
|
||||||
|
return {
|
||||||
|
key: asString(choice.key, "").trim(),
|
||||||
|
label: asString(choice.label, "").trim(),
|
||||||
|
description: asString(choice.description, "").trim() || undefined,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
break; // only one question per message
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "result") {
|
||||||
|
resultEvent = event;
|
||||||
|
accumulateUsage(usage, event.usage ?? event.usageMetadata);
|
||||||
|
const resultText =
|
||||||
|
asString(event.result, "").trim() ||
|
||||||
|
asString(event.text, "").trim() ||
|
||||||
|
asString(event.response, "").trim();
|
||||||
|
if (resultText && messages.length === 0) messages.push(resultText);
|
||||||
|
costUsd = asNumber(event.total_cost_usd, asNumber(event.cost_usd, asNumber(event.cost, costUsd ?? 0))) || costUsd;
|
||||||
|
const isError = event.is_error === true || asString(event.subtype, "").toLowerCase() === "error";
|
||||||
|
if (isError) {
|
||||||
|
const text = asErrorText(event.error ?? event.message ?? event.result).trim();
|
||||||
|
if (text) errorMessage = text;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "error") {
|
||||||
|
const text = asErrorText(event.error ?? event.message ?? event.detail).trim();
|
||||||
|
if (text) errorMessage = text;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "system") {
|
||||||
|
const subtype = asString(event.subtype, "").trim().toLowerCase();
|
||||||
|
if (subtype === "error") {
|
||||||
|
const text = asErrorText(event.error ?? event.message ?? event.detail).trim();
|
||||||
|
if (text) errorMessage = text;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "text") {
|
||||||
|
const part = parseObject(event.part);
|
||||||
|
const text = asString(part.text, "").trim();
|
||||||
|
if (text) messages.push(text);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "step_finish" || event.usage || event.usageMetadata) {
|
||||||
|
accumulateUsage(usage, event.usage ?? event.usageMetadata);
|
||||||
|
costUsd = asNumber(event.total_cost_usd, asNumber(event.cost_usd, asNumber(event.cost, costUsd ?? 0))) || costUsd;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
sessionId,
|
||||||
|
summary: messages.join("\n\n").trim(),
|
||||||
|
usage,
|
||||||
|
costUsd,
|
||||||
|
errorMessage,
|
||||||
|
resultEvent,
|
||||||
|
question,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isGeminiUnknownSessionError(stdout: string, stderr: string): boolean {
|
||||||
|
const haystack = `${stdout}\n${stderr}`
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
.join("\n");
|
||||||
|
|
||||||
|
return /unknown\s+session|session\s+.*\s+not\s+found|resume\s+.*\s+not\s+found|checkpoint\s+.*\s+not\s+found|cannot\s+resume|failed\s+to\s+resume/i.test(
|
||||||
|
haystack,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractGeminiErrorMessages(parsed: Record<string, unknown>): string[] {
|
||||||
|
const messages: string[] = [];
|
||||||
|
const errorMsg = asString(parsed.error, "").trim();
|
||||||
|
if (errorMsg) messages.push(errorMsg);
|
||||||
|
|
||||||
|
const raw = Array.isArray(parsed.errors) ? parsed.errors : [];
|
||||||
|
for (const entry of raw) {
|
||||||
|
if (typeof entry === "string") {
|
||||||
|
const msg = entry.trim();
|
||||||
|
if (msg) messages.push(msg);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
|
||||||
|
const obj = entry as Record<string, unknown>;
|
||||||
|
const msg = asString(obj.message, "") || asString(obj.error, "") || asString(obj.code, "");
|
||||||
|
if (msg) {
|
||||||
|
messages.push(msg);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
messages.push(JSON.stringify(obj));
|
||||||
|
} catch {
|
||||||
|
// skip non-serializable entry
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function describeGeminiFailure(parsed: Record<string, unknown>): string | null {
|
||||||
|
const status = asString(parsed.status, "");
|
||||||
|
const errors = extractGeminiErrorMessages(parsed);
|
||||||
|
|
||||||
|
const detail = errors[0] ?? "";
|
||||||
|
const parts = ["Gemini run failed"];
|
||||||
|
if (status) parts.push(`status=${status}`);
|
||||||
|
if (detail) parts.push(detail);
|
||||||
|
return parts.length > 1 ? parts.join(": ") : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const GEMINI_AUTH_REQUIRED_RE = /(?:not\s+authenticated|please\s+authenticate|api[_ ]?key\s+(?:required|missing|invalid)|authentication\s+required|unauthorized|invalid\s+credentials|not\s+logged\s+in|login\s+required|run\s+`?gemini\s+auth(?:\s+login)?`?\s+first)/i;
|
||||||
|
|
||||||
|
export function detectGeminiAuthRequired(input: {
|
||||||
|
parsed: Record<string, unknown> | null;
|
||||||
|
stdout: string;
|
||||||
|
stderr: string;
|
||||||
|
}): { requiresAuth: boolean } {
|
||||||
|
const errors = extractGeminiErrorMessages(input.parsed ?? {});
|
||||||
|
const messages = [...errors, input.stdout, input.stderr]
|
||||||
|
.join("\n")
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
const requiresAuth = messages.some((line) => GEMINI_AUTH_REQUIRED_RE.test(line));
|
||||||
|
return { requiresAuth };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isGeminiTurnLimitResult(
|
||||||
|
parsed: Record<string, unknown> | null | undefined,
|
||||||
|
exitCode?: number | null,
|
||||||
|
): boolean {
|
||||||
|
if (exitCode === 53) return true;
|
||||||
|
if (!parsed) return false;
|
||||||
|
|
||||||
|
const status = asString(parsed.status, "").trim().toLowerCase();
|
||||||
|
if (status === "turn_limit" || status === "max_turns") return true;
|
||||||
|
|
||||||
|
const error = asString(parsed.error, "").trim();
|
||||||
|
return /turn\s*limit|max(?:imum)?\s+turns?/i.test(error);
|
||||||
|
}
|
||||||
223
packages/adapters/gemini-local/src/server/test.ts
Normal file
223
packages/adapters/gemini-local/src/server/test.ts
Normal file
@@ -0,0 +1,223 @@
|
|||||||
|
import path from "node:path";
|
||||||
|
import type {
|
||||||
|
AdapterEnvironmentCheck,
|
||||||
|
AdapterEnvironmentTestContext,
|
||||||
|
AdapterEnvironmentTestResult,
|
||||||
|
} from "@paperclipai/adapter-utils";
|
||||||
|
import {
|
||||||
|
asBoolean,
|
||||||
|
asString,
|
||||||
|
asStringArray,
|
||||||
|
ensureAbsoluteDirectory,
|
||||||
|
ensureCommandResolvable,
|
||||||
|
ensurePathInEnv,
|
||||||
|
parseObject,
|
||||||
|
runChildProcess,
|
||||||
|
} from "@paperclipai/adapter-utils/server-utils";
|
||||||
|
import { DEFAULT_GEMINI_LOCAL_MODEL } from "../index.js";
|
||||||
|
import { detectGeminiAuthRequired, parseGeminiJsonl } from "./parse.js";
|
||||||
|
import { firstNonEmptyLine } from "./utils.js";
|
||||||
|
|
||||||
|
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 isNonEmpty(value: unknown): value is string {
|
||||||
|
return typeof value === "string" && value.trim().length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function commandLooksLike(command: string, expected: string): boolean {
|
||||||
|
const base = path.basename(command).toLowerCase();
|
||||||
|
return base === expected || base === `${expected}.cmd` || base === `${expected}.exe`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function summarizeProbeDetail(stdout: string, stderr: string, parsedError: string | null): string | null {
|
||||||
|
const raw = parsedError?.trim() || firstNonEmptyLine(stderr) || firstNonEmptyLine(stdout);
|
||||||
|
if (!raw) return null;
|
||||||
|
const clean = raw.replace(/\s+/g, " ").trim();
|
||||||
|
const max = 240;
|
||||||
|
return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function testEnvironment(
|
||||||
|
ctx: AdapterEnvironmentTestContext,
|
||||||
|
): Promise<AdapterEnvironmentTestResult> {
|
||||||
|
const checks: AdapterEnvironmentCheck[] = [];
|
||||||
|
const config = parseObject(ctx.config);
|
||||||
|
const command = asString(config.command, "gemini");
|
||||||
|
const cwd = asString(config.cwd, process.cwd());
|
||||||
|
|
||||||
|
try {
|
||||||
|
await ensureAbsoluteDirectory(cwd, { createIfMissing: true });
|
||||||
|
checks.push({
|
||||||
|
code: "gemini_cwd_valid",
|
||||||
|
level: "info",
|
||||||
|
message: `Working directory is valid: ${cwd}`,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
checks.push({
|
||||||
|
code: "gemini_cwd_invalid",
|
||||||
|
level: "error",
|
||||||
|
message: err instanceof Error ? err.message : "Invalid working directory",
|
||||||
|
detail: cwd,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const envConfig = parseObject(config.env);
|
||||||
|
const env: Record<string, string> = {};
|
||||||
|
for (const [key, value] of Object.entries(envConfig)) {
|
||||||
|
if (typeof value === "string") env[key] = value;
|
||||||
|
}
|
||||||
|
const runtimeEnv = ensurePathInEnv({ ...process.env, ...env });
|
||||||
|
try {
|
||||||
|
await ensureCommandResolvable(command, cwd, runtimeEnv);
|
||||||
|
checks.push({
|
||||||
|
code: "gemini_command_resolvable",
|
||||||
|
level: "info",
|
||||||
|
message: `Command is executable: ${command}`,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
checks.push({
|
||||||
|
code: "gemini_command_unresolvable",
|
||||||
|
level: "error",
|
||||||
|
message: err instanceof Error ? err.message : "Command is not executable",
|
||||||
|
detail: command,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const configGeminiApiKey = env.GEMINI_API_KEY;
|
||||||
|
const hostGeminiApiKey = process.env.GEMINI_API_KEY;
|
||||||
|
const configGoogleApiKey = env.GOOGLE_API_KEY;
|
||||||
|
const hostGoogleApiKey = process.env.GOOGLE_API_KEY;
|
||||||
|
const hasGca = env.GOOGLE_GENAI_USE_GCA === "true" || process.env.GOOGLE_GENAI_USE_GCA === "true";
|
||||||
|
if (
|
||||||
|
isNonEmpty(configGeminiApiKey) ||
|
||||||
|
isNonEmpty(hostGeminiApiKey) ||
|
||||||
|
isNonEmpty(configGoogleApiKey) ||
|
||||||
|
isNonEmpty(hostGoogleApiKey) ||
|
||||||
|
hasGca
|
||||||
|
) {
|
||||||
|
const source = hasGca
|
||||||
|
? "Google account login (GCA)"
|
||||||
|
: isNonEmpty(configGeminiApiKey) || isNonEmpty(configGoogleApiKey)
|
||||||
|
? "adapter config env"
|
||||||
|
: "server environment";
|
||||||
|
checks.push({
|
||||||
|
code: "gemini_api_key_present",
|
||||||
|
level: "info",
|
||||||
|
message: "Gemini API credentials are set for CLI authentication.",
|
||||||
|
detail: `Detected in ${source}.`,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
checks.push({
|
||||||
|
code: "gemini_api_key_missing",
|
||||||
|
level: "info",
|
||||||
|
message: "No explicit API key detected. Gemini CLI may still authenticate via `gemini auth login` (OAuth).",
|
||||||
|
hint: "If the hello probe fails with an auth error, set GEMINI_API_KEY or GOOGLE_API_KEY in adapter env, or run `gemini auth login`.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const canRunProbe =
|
||||||
|
checks.every((check) => check.code !== "gemini_cwd_invalid" && check.code !== "gemini_command_unresolvable");
|
||||||
|
if (canRunProbe) {
|
||||||
|
if (!commandLooksLike(command, "gemini")) {
|
||||||
|
checks.push({
|
||||||
|
code: "gemini_hello_probe_skipped_custom_command",
|
||||||
|
level: "info",
|
||||||
|
message: "Skipped hello probe because command is not `gemini`.",
|
||||||
|
detail: command,
|
||||||
|
hint: "Use the `gemini` CLI command to run the automatic installation and auth probe.",
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const model = asString(config.model, DEFAULT_GEMINI_LOCAL_MODEL).trim();
|
||||||
|
const approvalMode = asString(config.approvalMode, asBoolean(config.yolo, false) ? "yolo" : "default");
|
||||||
|
const sandbox = asBoolean(config.sandbox, false);
|
||||||
|
const extraArgs = (() => {
|
||||||
|
const fromExtraArgs = asStringArray(config.extraArgs);
|
||||||
|
if (fromExtraArgs.length > 0) return fromExtraArgs;
|
||||||
|
return asStringArray(config.args);
|
||||||
|
})();
|
||||||
|
|
||||||
|
const args = ["--output-format", "stream-json"];
|
||||||
|
if (model && model !== DEFAULT_GEMINI_LOCAL_MODEL) args.push("--model", model);
|
||||||
|
if (approvalMode !== "default") args.push("--approval-mode", approvalMode);
|
||||||
|
if (sandbox) {
|
||||||
|
args.push("--sandbox");
|
||||||
|
} else {
|
||||||
|
args.push("--sandbox=none");
|
||||||
|
}
|
||||||
|
if (extraArgs.length > 0) args.push(...extraArgs);
|
||||||
|
args.push("Respond with hello.");
|
||||||
|
|
||||||
|
const probe = await runChildProcess(
|
||||||
|
`gemini-envtest-${Date.now()}-${Math.random().toString(16).slice(2)}`,
|
||||||
|
command,
|
||||||
|
args,
|
||||||
|
{
|
||||||
|
cwd,
|
||||||
|
env,
|
||||||
|
timeoutSec: 45,
|
||||||
|
graceSec: 5,
|
||||||
|
onLog: async () => { },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const parsed = parseGeminiJsonl(probe.stdout);
|
||||||
|
const detail = summarizeProbeDetail(probe.stdout, probe.stderr, parsed.errorMessage);
|
||||||
|
const authMeta = detectGeminiAuthRequired({
|
||||||
|
parsed: parsed.resultEvent,
|
||||||
|
stdout: probe.stdout,
|
||||||
|
stderr: probe.stderr,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (probe.timedOut) {
|
||||||
|
checks.push({
|
||||||
|
code: "gemini_hello_probe_timed_out",
|
||||||
|
level: "warn",
|
||||||
|
message: "Gemini hello probe timed out.",
|
||||||
|
hint: "Retry the probe. If this persists, verify Gemini can run `Respond with hello.` from this directory manually.",
|
||||||
|
});
|
||||||
|
} else if ((probe.exitCode ?? 1) === 0) {
|
||||||
|
const summary = parsed.summary.trim();
|
||||||
|
const hasHello = /\bhello\b/i.test(summary);
|
||||||
|
checks.push({
|
||||||
|
code: hasHello ? "gemini_hello_probe_passed" : "gemini_hello_probe_unexpected_output",
|
||||||
|
level: hasHello ? "info" : "warn",
|
||||||
|
message: hasHello
|
||||||
|
? "Gemini hello probe succeeded."
|
||||||
|
: "Gemini probe ran but did not return `hello` as expected.",
|
||||||
|
...(summary ? { detail: summary.replace(/\s+/g, " ").trim().slice(0, 240) } : {}),
|
||||||
|
...(hasHello
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
hint: "Try `gemini --output-format json \"Respond with hello.\"` manually to inspect full output.",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
} else if (authMeta.requiresAuth) {
|
||||||
|
checks.push({
|
||||||
|
code: "gemini_hello_probe_auth_required",
|
||||||
|
level: "warn",
|
||||||
|
message: "Gemini CLI is installed, but authentication is not ready.",
|
||||||
|
...(detail ? { detail } : {}),
|
||||||
|
hint: "Run `gemini auth` or configure GEMINI_API_KEY / GOOGLE_API_KEY in adapter env/shell, then retry the probe.",
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
checks.push({
|
||||||
|
code: "gemini_hello_probe_failed",
|
||||||
|
level: "error",
|
||||||
|
message: "Gemini hello probe failed.",
|
||||||
|
...(detail ? { detail } : {}),
|
||||||
|
hint: "Run `gemini --output-format json \"Respond with hello.\"` manually in this working directory to debug.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
adapterType: ctx.adapterType,
|
||||||
|
status: summarizeStatus(checks),
|
||||||
|
checks,
|
||||||
|
testedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
8
packages/adapters/gemini-local/src/server/utils.ts
Normal file
8
packages/adapters/gemini-local/src/server/utils.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
export function firstNonEmptyLine(text: string): string {
|
||||||
|
return (
|
||||||
|
text
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.find(Boolean) ?? ""
|
||||||
|
);
|
||||||
|
}
|
||||||
76
packages/adapters/gemini-local/src/ui/build-config.ts
Normal file
76
packages/adapters/gemini-local/src/ui/build-config.ts
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import type { CreateConfigValues } from "@paperclipai/adapter-utils";
|
||||||
|
import { DEFAULT_GEMINI_LOCAL_MODEL } 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildGeminiLocalConfig(v: CreateConfigValues): Record<string, unknown> {
|
||||||
|
const ac: Record<string, unknown> = {};
|
||||||
|
if (v.cwd) ac.cwd = v.cwd;
|
||||||
|
if (v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;
|
||||||
|
if (v.promptTemplate) ac.promptTemplate = v.promptTemplate;
|
||||||
|
if (v.bootstrapPrompt) ac.bootstrapPromptTemplate = v.bootstrapPrompt;
|
||||||
|
ac.model = v.model || DEFAULT_GEMINI_LOCAL_MODEL;
|
||||||
|
ac.timeoutSec = 0;
|
||||||
|
ac.graceSec = 15;
|
||||||
|
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 (Object.keys(env).length > 0) ac.env = env;
|
||||||
|
ac.sandbox = !v.dangerouslyBypassSandbox;
|
||||||
|
|
||||||
|
if (v.command) ac.command = v.command;
|
||||||
|
if (v.extraArgs) ac.extraArgs = parseCommaArgs(v.extraArgs);
|
||||||
|
return ac;
|
||||||
|
}
|
||||||
2
packages/adapters/gemini-local/src/ui/index.ts
Normal file
2
packages/adapters/gemini-local/src/ui/index.ts
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export { parseGeminiStdoutLine } from "./parse-stdout.js";
|
||||||
|
export { buildGeminiLocalConfig } from "./build-config.js";
|
||||||
274
packages/adapters/gemini-local/src/ui/parse-stdout.ts
Normal file
274
packages/adapters/gemini-local/src/ui/parse-stdout.ts
Normal file
@@ -0,0 +1,274 @@
|
|||||||
|
import type { TranscriptEntry } from "@paperclipai/adapter-utils";
|
||||||
|
|
||||||
|
function safeJsonParse(text: string): unknown {
|
||||||
|
try {
|
||||||
|
return JSON.parse(text);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||||
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 stringifyUnknown(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 errorText(value: unknown): string {
|
||||||
|
if (typeof value === "string") return value;
|
||||||
|
const rec = asRecord(value);
|
||||||
|
if (!rec) return "";
|
||||||
|
const msg =
|
||||||
|
(typeof rec.message === "string" && rec.message) ||
|
||||||
|
(typeof rec.error === "string" && rec.error) ||
|
||||||
|
(typeof rec.code === "string" && rec.code) ||
|
||||||
|
"";
|
||||||
|
if (msg) return msg;
|
||||||
|
try {
|
||||||
|
return JSON.stringify(rec);
|
||||||
|
} catch {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectTextEntries(messageRaw: unknown, ts: string, kind: "assistant" | "user"): TranscriptEntry[] {
|
||||||
|
if (typeof messageRaw === "string") {
|
||||||
|
const text = messageRaw.trim();
|
||||||
|
return text ? [{ kind, ts, text }] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = asRecord(messageRaw);
|
||||||
|
if (!message) return [];
|
||||||
|
|
||||||
|
const entries: TranscriptEntry[] = [];
|
||||||
|
const directText = asString(message.text).trim();
|
||||||
|
if (directText) entries.push({ kind, ts, text: directText });
|
||||||
|
|
||||||
|
const content = Array.isArray(message.content) ? message.content : [];
|
||||||
|
for (const partRaw of content) {
|
||||||
|
const part = asRecord(partRaw);
|
||||||
|
if (!part) continue;
|
||||||
|
const type = asString(part.type).trim();
|
||||||
|
if (type !== "output_text" && type !== "text" && type !== "content") continue;
|
||||||
|
const text = asString(part.text).trim() || asString(part.content).trim();
|
||||||
|
if (text) entries.push({ kind, ts, text });
|
||||||
|
}
|
||||||
|
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseAssistantMessage(messageRaw: unknown, ts: string): TranscriptEntry[] {
|
||||||
|
if (typeof messageRaw === "string") {
|
||||||
|
const text = messageRaw.trim();
|
||||||
|
return text ? [{ kind: "assistant", ts, text }] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = asRecord(messageRaw);
|
||||||
|
if (!message) return [];
|
||||||
|
|
||||||
|
const entries: TranscriptEntry[] = [];
|
||||||
|
const directText = asString(message.text).trim();
|
||||||
|
if (directText) entries.push({ kind: "assistant", ts, text: directText });
|
||||||
|
|
||||||
|
const content = Array.isArray(message.content) ? message.content : [];
|
||||||
|
for (const partRaw of content) {
|
||||||
|
const part = asRecord(partRaw);
|
||||||
|
if (!part) continue;
|
||||||
|
const type = asString(part.type).trim();
|
||||||
|
|
||||||
|
if (type === "output_text" || type === "text" || type === "content") {
|
||||||
|
const text = asString(part.text).trim() || asString(part.content).trim();
|
||||||
|
if (text) entries.push({ kind: "assistant", ts, text });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "thinking") {
|
||||||
|
const text = asString(part.text).trim();
|
||||||
|
if (text) entries.push({ kind: "thinking", ts, text });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "tool_call") {
|
||||||
|
const name = asString(part.name, asString(part.tool, "tool"));
|
||||||
|
entries.push({
|
||||||
|
kind: "tool_call",
|
||||||
|
ts,
|
||||||
|
name,
|
||||||
|
input: part.input ?? part.arguments ?? part.args ?? {},
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "tool_result" || type === "tool_response") {
|
||||||
|
const toolUseId =
|
||||||
|
asString(part.tool_use_id) ||
|
||||||
|
asString(part.toolUseId) ||
|
||||||
|
asString(part.call_id) ||
|
||||||
|
asString(part.id) ||
|
||||||
|
"tool_result";
|
||||||
|
const contentText =
|
||||||
|
asString(part.output) ||
|
||||||
|
asString(part.text) ||
|
||||||
|
asString(part.result) ||
|
||||||
|
stringifyUnknown(part.output ?? part.result ?? part.text ?? part.response);
|
||||||
|
const isError = part.is_error === true || asString(part.status).toLowerCase() === "error";
|
||||||
|
entries.push({
|
||||||
|
kind: "tool_result",
|
||||||
|
ts,
|
||||||
|
toolUseId,
|
||||||
|
content: contentText,
|
||||||
|
isError,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseTopLevelToolEvent(parsed: Record<string, unknown>, ts: string): TranscriptEntry[] {
|
||||||
|
const subtype = asString(parsed.subtype).trim().toLowerCase();
|
||||||
|
const callId = asString(parsed.call_id, asString(parsed.callId, asString(parsed.id, "tool_call")));
|
||||||
|
const toolCall = asRecord(parsed.tool_call ?? parsed.toolCall);
|
||||||
|
if (!toolCall) {
|
||||||
|
return [{ kind: "system", ts, text: `tool_call${subtype ? ` (${subtype})` : ""}` }];
|
||||||
|
}
|
||||||
|
|
||||||
|
const [toolName] = Object.keys(toolCall);
|
||||||
|
if (!toolName) {
|
||||||
|
return [{ kind: "system", ts, text: `tool_call${subtype ? ` (${subtype})` : ""}` }];
|
||||||
|
}
|
||||||
|
const payload = asRecord(toolCall[toolName]) ?? {};
|
||||||
|
|
||||||
|
if (subtype === "started" || subtype === "start") {
|
||||||
|
return [{
|
||||||
|
kind: "tool_call",
|
||||||
|
ts,
|
||||||
|
name: toolName,
|
||||||
|
input: payload.args ?? payload.input ?? payload.arguments ?? payload,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (subtype === "completed" || subtype === "complete" || subtype === "finished") {
|
||||||
|
const result = payload.result ?? payload.output ?? payload.error;
|
||||||
|
const isError =
|
||||||
|
parsed.is_error === true ||
|
||||||
|
payload.is_error === true ||
|
||||||
|
payload.error !== undefined ||
|
||||||
|
asString(payload.status).toLowerCase() === "error";
|
||||||
|
return [{
|
||||||
|
kind: "tool_result",
|
||||||
|
ts,
|
||||||
|
toolUseId: callId,
|
||||||
|
content: result !== undefined ? stringifyUnknown(result) : `${toolName} completed`,
|
||||||
|
isError,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [{ kind: "system", ts, text: `tool_call${subtype ? ` (${subtype})` : ""}: ${toolName}` }];
|
||||||
|
}
|
||||||
|
|
||||||
|
function readSessionId(parsed: Record<string, unknown>): string {
|
||||||
|
return (
|
||||||
|
asString(parsed.session_id) ||
|
||||||
|
asString(parsed.sessionId) ||
|
||||||
|
asString(parsed.sessionID) ||
|
||||||
|
asString(parsed.checkpoint_id) ||
|
||||||
|
asString(parsed.thread_id)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readUsage(parsed: Record<string, unknown>) {
|
||||||
|
const usage = asRecord(parsed.usage) ?? asRecord(parsed.usageMetadata);
|
||||||
|
const usageMetadata = asRecord(usage?.usageMetadata);
|
||||||
|
const source = usageMetadata ?? usage ?? {};
|
||||||
|
return {
|
||||||
|
inputTokens: asNumber(source.input_tokens, asNumber(source.inputTokens, asNumber(source.promptTokenCount))),
|
||||||
|
outputTokens: asNumber(source.output_tokens, asNumber(source.outputTokens, asNumber(source.candidatesTokenCount))),
|
||||||
|
cachedTokens: asNumber(
|
||||||
|
source.cached_input_tokens,
|
||||||
|
asNumber(source.cachedInputTokens, asNumber(source.cachedContentTokenCount)),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseGeminiStdoutLine(line: string, ts: string): TranscriptEntry[] {
|
||||||
|
const parsed = asRecord(safeJsonParse(line));
|
||||||
|
if (!parsed) {
|
||||||
|
return [{ kind: "stdout", ts, text: line }];
|
||||||
|
}
|
||||||
|
|
||||||
|
const type = asString(parsed.type);
|
||||||
|
|
||||||
|
if (type === "system") {
|
||||||
|
const subtype = asString(parsed.subtype);
|
||||||
|
if (subtype === "init") {
|
||||||
|
const sessionId = readSessionId(parsed);
|
||||||
|
return [{ kind: "init", ts, model: asString(parsed.model, "gemini"), sessionId }];
|
||||||
|
}
|
||||||
|
if (subtype === "error") {
|
||||||
|
const text = errorText(parsed.error ?? parsed.message ?? parsed.detail);
|
||||||
|
return [{ kind: "stderr", ts, text: text || "error" }];
|
||||||
|
}
|
||||||
|
return [{ kind: "system", ts, text: `system: ${subtype || "event"}` }];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "assistant") {
|
||||||
|
return parseAssistantMessage(parsed.message, ts);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "user") {
|
||||||
|
return collectTextEntries(parsed.message, ts, "user");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "thinking") {
|
||||||
|
const text = asString(parsed.text).trim() || asString(asRecord(parsed.delta)?.text).trim();
|
||||||
|
return text ? [{ kind: "thinking", ts, text }] : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "tool_call") {
|
||||||
|
return parseTopLevelToolEvent(parsed, ts);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "result") {
|
||||||
|
const usage = readUsage(parsed);
|
||||||
|
const errors = parsed.is_error === true
|
||||||
|
? [errorText(parsed.error ?? parsed.message ?? parsed.result)].filter(Boolean)
|
||||||
|
: [];
|
||||||
|
return [{
|
||||||
|
kind: "result",
|
||||||
|
ts,
|
||||||
|
text: asString(parsed.result) || asString(parsed.text) || asString(parsed.response),
|
||||||
|
inputTokens: usage.inputTokens,
|
||||||
|
outputTokens: usage.outputTokens,
|
||||||
|
cachedTokens: usage.cachedTokens,
|
||||||
|
costUsd: asNumber(parsed.total_cost_usd, asNumber(parsed.cost_usd, asNumber(parsed.cost))),
|
||||||
|
subtype: asString(parsed.subtype, "result"),
|
||||||
|
isError: parsed.is_error === true,
|
||||||
|
errors,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type === "error") {
|
||||||
|
const text = errorText(parsed.error ?? parsed.message ?? parsed.detail);
|
||||||
|
return [{ kind: "stderr", ts, text: text || "error" }];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [{ kind: "stdout", ts, text: line }];
|
||||||
|
}
|
||||||
8
packages/adapters/gemini-local/tsconfig.json
Normal file
8
packages/adapters/gemini-local/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"extends": "../../../tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"outDir": "dist",
|
||||||
|
"rootDir": "src"
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -1,5 +1,13 @@
|
|||||||
# @paperclipai/adapter-openclaw-gateway
|
# @paperclipai/adapter-openclaw-gateway
|
||||||
|
|
||||||
|
## 0.3.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Stable release preparation for 0.3.1
|
||||||
|
- Updated dependencies
|
||||||
|
- @paperclipai/adapter-utils@0.3.1
|
||||||
|
|
||||||
## 0.3.0
|
## 0.3.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@paperclipai/adapter-openclaw-gateway",
|
"name": "@paperclipai/adapter-openclaw-gateway",
|
||||||
"version": "0.3.0",
|
"version": "0.3.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts",
|
".": "./src/index.ts",
|
||||||
|
|||||||
@@ -1069,7 +1069,6 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
|
|
||||||
const agentParams: Record<string, unknown> = {
|
const agentParams: Record<string, unknown> = {
|
||||||
...payloadTemplate,
|
...payloadTemplate,
|
||||||
paperclip: paperclipPayload,
|
|
||||||
message,
|
message,
|
||||||
sessionKey,
|
sessionKey,
|
||||||
idempotencyKey: ctx.runId,
|
idempotencyKey: ctx.runId,
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
# @paperclipai/adapter-opencode-local
|
# @paperclipai/adapter-opencode-local
|
||||||
|
|
||||||
|
## 0.3.1
|
||||||
|
|
||||||
|
### Patch Changes
|
||||||
|
|
||||||
|
- Stable release preparation for 0.3.1
|
||||||
|
- Updated dependencies
|
||||||
|
- @paperclipai/adapter-utils@0.3.1
|
||||||
|
|
||||||
## 0.3.0
|
## 0.3.0
|
||||||
|
|
||||||
### Minor Changes
|
### Minor Changes
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@paperclipai/adapter-opencode-local",
|
"name": "@paperclipai/adapter-opencode-local",
|
||||||
"version": "0.3.0",
|
"version": "0.3.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts",
|
".": "./src/index.ts",
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
asStringArray,
|
asStringArray,
|
||||||
parseObject,
|
parseObject,
|
||||||
buildPaperclipEnv,
|
buildPaperclipEnv,
|
||||||
|
joinPromptSections,
|
||||||
redactEnvForLogs,
|
redactEnvForLogs,
|
||||||
ensureAbsoluteDirectory,
|
ensureAbsoluteDirectory,
|
||||||
ensureCommandResolvable,
|
ensureCommandResolvable,
|
||||||
@@ -99,6 +100,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
const workspaceId = asString(workspaceContext.workspaceId, "");
|
const workspaceId = asString(workspaceContext.workspaceId, "");
|
||||||
const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
|
const workspaceRepoUrl = asString(workspaceContext.repoUrl, "");
|
||||||
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
|
const workspaceRepoRef = asString(workspaceContext.repoRef, "");
|
||||||
|
const agentHome = asString(workspaceContext.agentHome, "");
|
||||||
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
const workspaceHints = Array.isArray(context.paperclipWorkspaces)
|
||||||
? context.paperclipWorkspaces.filter(
|
? context.paperclipWorkspaces.filter(
|
||||||
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
(value): value is Record<string, unknown> => typeof value === "object" && value !== null,
|
||||||
@@ -150,6 +152,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
if (workspaceId) env.PAPERCLIP_WORKSPACE_ID = workspaceId;
|
if (workspaceId) env.PAPERCLIP_WORKSPACE_ID = workspaceId;
|
||||||
if (workspaceRepoUrl) env.PAPERCLIP_WORKSPACE_REPO_URL = workspaceRepoUrl;
|
if (workspaceRepoUrl) env.PAPERCLIP_WORKSPACE_REPO_URL = workspaceRepoUrl;
|
||||||
if (workspaceRepoRef) env.PAPERCLIP_WORKSPACE_REPO_REF = workspaceRepoRef;
|
if (workspaceRepoRef) env.PAPERCLIP_WORKSPACE_REPO_REF = workspaceRepoRef;
|
||||||
|
if (agentHome) env.AGENT_HOME = agentHome;
|
||||||
if (workspaceHints.length > 0) env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
|
if (workspaceHints.length > 0) env.PAPERCLIP_WORKSPACES_JSON = JSON.stringify(workspaceHints);
|
||||||
|
|
||||||
for (const [key, value] of Object.entries(envConfig)) {
|
for (const [key, value] of Object.entries(envConfig)) {
|
||||||
@@ -233,7 +236,8 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
];
|
];
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const renderedPrompt = renderTemplate(promptTemplate, {
|
const bootstrapPromptTemplate = asString(config.bootstrapPromptTemplate, "");
|
||||||
|
const templateData = {
|
||||||
agentId: agent.id,
|
agentId: agent.id,
|
||||||
companyId: agent.companyId,
|
companyId: agent.companyId,
|
||||||
runId,
|
runId,
|
||||||
@@ -241,8 +245,26 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
agent,
|
agent,
|
||||||
run: { id: runId, source: "on_demand" },
|
run: { id: runId, source: "on_demand" },
|
||||||
context,
|
context,
|
||||||
});
|
};
|
||||||
const prompt = `${instructionsPrefix}${renderedPrompt}`;
|
const renderedPrompt = renderTemplate(promptTemplate, templateData);
|
||||||
|
const renderedBootstrapPrompt =
|
||||||
|
!sessionId && bootstrapPromptTemplate.trim().length > 0
|
||||||
|
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
|
||||||
|
: "";
|
||||||
|
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
|
||||||
|
const prompt = joinPromptSections([
|
||||||
|
instructionsPrefix,
|
||||||
|
renderedBootstrapPrompt,
|
||||||
|
sessionHandoffNote,
|
||||||
|
renderedPrompt,
|
||||||
|
]);
|
||||||
|
const promptMetrics = {
|
||||||
|
promptChars: prompt.length,
|
||||||
|
instructionsChars: instructionsPrefix.length,
|
||||||
|
bootstrapPromptChars: renderedBootstrapPrompt.length,
|
||||||
|
sessionHandoffChars: sessionHandoffNote.length,
|
||||||
|
heartbeatPromptChars: renderedPrompt.length,
|
||||||
|
};
|
||||||
|
|
||||||
const buildArgs = (resumeSessionId: string | null) => {
|
const buildArgs = (resumeSessionId: string | null) => {
|
||||||
const args = ["run", "--format", "json"];
|
const args = ["run", "--format", "json"];
|
||||||
@@ -264,6 +286,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
|||||||
commandArgs: [...args, `<stdin prompt ${prompt.length} chars>`],
|
commandArgs: [...args, `<stdin prompt ${prompt.length} chars>`],
|
||||||
env: redactEnvForLogs(env),
|
env: redactEnvForLogs(env),
|
||||||
prompt,
|
prompt,
|
||||||
|
promptMetrics,
|
||||||
context,
|
context,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
} from "@paperclipai/adapter-utils/server-utils";
|
} from "@paperclipai/adapter-utils/server-utils";
|
||||||
|
|
||||||
const MODELS_CACHE_TTL_MS = 60_000;
|
const MODELS_CACHE_TTL_MS = 60_000;
|
||||||
|
const MODELS_DISCOVERY_TIMEOUT_MS = 20_000;
|
||||||
|
|
||||||
function resolveOpenCodeCommand(input: unknown): string {
|
function resolveOpenCodeCommand(input: unknown): string {
|
||||||
const envOverride =
|
const envOverride =
|
||||||
@@ -115,14 +116,14 @@ export async function discoverOpenCodeModels(input: {
|
|||||||
{
|
{
|
||||||
cwd,
|
cwd,
|
||||||
env: runtimeEnv,
|
env: runtimeEnv,
|
||||||
timeoutSec: 20,
|
timeoutSec: MODELS_DISCOVERY_TIMEOUT_MS / 1000,
|
||||||
graceSec: 3,
|
graceSec: 3,
|
||||||
onLog: async () => {},
|
onLog: async () => {},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
if (result.timedOut) {
|
if (result.timedOut) {
|
||||||
throw new Error("`opencode models` timed out.");
|
throw new Error(`\`opencode models\` timed out after ${MODELS_DISCOVERY_TIMEOUT_MS / 1000}s.`);
|
||||||
}
|
}
|
||||||
if ((result.exitCode ?? 1) !== 0) {
|
if ((result.exitCode ?? 1) !== 0) {
|
||||||
const detail = firstNonEmptyLine(result.stderr) || firstNonEmptyLine(result.stdout);
|
const detail = firstNonEmptyLine(result.stderr) || firstNonEmptyLine(result.stdout);
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ export function buildOpenCodeLocalConfig(v: CreateConfigValues): Record<string,
|
|||||||
if (v.cwd) ac.cwd = v.cwd;
|
if (v.cwd) ac.cwd = v.cwd;
|
||||||
if (v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;
|
if (v.instructionsFilePath) ac.instructionsFilePath = v.instructionsFilePath;
|
||||||
if (v.promptTemplate) ac.promptTemplate = v.promptTemplate;
|
if (v.promptTemplate) ac.promptTemplate = v.promptTemplate;
|
||||||
|
if (v.bootstrapPrompt) ac.bootstrapPromptTemplate = v.bootstrapPrompt;
|
||||||
if (v.model) ac.model = v.model;
|
if (v.model) ac.model = v.model;
|
||||||
if (v.thinkingEffort) ac.variant = v.thinkingEffort;
|
if (v.thinkingEffort) ac.variant = v.thinkingEffort;
|
||||||
// OpenCode sessions can run until the CLI exits naturally; keep timeout disabled (0)
|
// OpenCode sessions can run until the CLI exits naturally; keep timeout disabled (0)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user