Files
PaperClipAI/cli/src/commands/client/token.ts
T
Aron PrinsandDevin Foley 70b1a9109d Improve CLI API parity coverage (#6626)
## Thinking Path

> - Paperclip is a control plane for AI-agent companies, with the CLI
acting as a scriptable operator and agent interface to that control
plane.
> - The REST API surface has grown across companies, agents, issues,
routines, plugins, auth, workspaces, secrets, and operational inspection
commands.
> - The CLI had drifted from that API surface: some commands were
missing, some command shapes differed from docs/reference material, and
several edge cases only failed during end-to-end local-source testing.
> - The local development runbook requires these tests to be disposable
and isolated from a real `~/.paperclip`, `~/.codex`, or `~/.claude`
installation.
> - This pull request adds broad CLI/API parity coverage, fixes the
actionable bugs found during that pass, and records the reproducible
test log under `doc/logs`.
> - The benefit is a more complete, scriptable CLI surface with
regression coverage for the command families exercised by the parity
run.

## What Changed

- Added or expanded CLI command coverage for access/auth, companies,
agents, projects, goals, issues and subresources, routines, plugins,
workspaces, activity/run/cost/dashboard inspection, assets, skills,
secrets, tokens, prompt/wake flows, and local setup helpers.
- Fixed CLI/API parity bugs found during the run, including context
profile patching, issue interaction optional payloads, malformed
tree-hold errors, environment duplicate handling, configure
invalid-section exit codes, worktree pnpm invocation, token agent ID
resolution, plugin tool worker lookup, and routine webhook secret
cleanup.
- Added missing CLI wrappers and route coverage for health/access,
invite resolution URL forwarding, join status normalization, secret
lifecycle commands, LLM docs routes, available-skill isolation, positive
board-claim coverage, and interactive `connect` prompt-flow tests.
- Added a schema-backed `/api/openapi.json` route sufficient for CLI
parity and `paperclipai openapi --json` smoke coverage.
- Added `doc/logs/2026-05-24-cli-api-parity-e2e-log.md` with the
detailed living test/bug log and renamed the log directory from
`doc/bugs` to `doc/logs`.
- Added `doc/plans/2026-05-23-cli-api-parity.md` and the OpenAPI parity
reference used during the pass.

OpenAPI note: this PR intentionally does not try to subsume
`feature/openapi-spec`. The OpenAPI implementation here is schema-backed
and better than the earlier route-inventory stub, but
`feature/openapi-spec` is the fuller/better OpenAPI branch because it
includes exact mounted-route coverage tests and additional current route
coverage. That branch should stay as its own PR and can supersede this
OpenAPI route implementation.

## Verification

Targeted automated checks run:

- `pnpm exec vitest run server/src/__tests__/openapi-routes.test.ts`
- `pnpm exec vitest run server/src/__tests__/board-claim.test.ts`
- `pnpm exec vitest run cli/src/__tests__/connect.test.ts`
- `pnpm exec vitest run cli/src/__tests__/agent-lifecycle.test.ts`
- `pnpm exec vitest run server/src/__tests__/plugin-database.test.ts`
- `pnpm exec vitest run server/src/__tests__/routines-service.test.ts`
- `pnpm --dir cli typecheck`
- `pnpm --dir server typecheck`

Manual/local E2E verification:

- Ran the full disposable local-source CLI/API parity pass with isolated
`PAPERCLIP_HOME`, `PAPERCLIP_CONFIG`, `PAPERCLIP_CONTEXT`,
`PAPERCLIP_AUTH_STORE`, `CODEX_HOME`, and `CLAUDE_HOME` under
`tmp/cli-api-parity`.
- Verified `DATABASE_URL` and `DATABASE_MIGRATION_URL` stayed unset for
the scratch server.
- Verified live health and schema-backed OpenAPI responses on
non-default port `3197`.
- Revoked created board/agent tokens and cleaned up temporary plugins,
secrets, non-default environments, and project workspaces.
- See `doc/logs/2026-05-24-cli-api-parity-e2e-log.md` for the full
command-by-command reproduction log.

Not run:

- Full `pnpm test`, `pnpm test:run`, or `pnpm build` were not run after
the entire branch because the branch is broad and the parity pass used
focused test/typecheck verification plus live isolated CLI reruns.

## Risks

- This is a broad PR and touches many CLI command modules, so review
surface is high. The changes are grouped around one theme, but a split
may be easier if maintainers prefer narrower PRs.
- The OpenAPI route in this PR is not the final/best OpenAPI
implementation. `feature/openapi-spec` has stronger exact-route coverage
and should remain the source for the dedicated OpenAPI PR.
- The living log is intentionally detailed and large. It is useful for
reproducibility but adds documentation weight.
- No UI changes are intended; screenshots are not applicable.

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

## Model Used

- OpenAI Codex, GPT-5-based coding agent in Codex desktop. Exact served
model/context-window identifier was not exposed in the local app. Work
used shell/Git/GitHub CLI tooling, local source inspection, targeted
test execution, and live isolated Paperclip CLI/API smoke testing.

## Checklist

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

---------

Co-authored-by: Devin Foley <devin@devinfoley.com>
2026-06-02 17:13:29 -07:00

245 lines
8.5 KiB
TypeScript

import { Command } from "commander";
import { createAgentKeySchema, createBoardApiKeySchema, type Agent } from "@paperclipai/shared";
import {
addCommonClientOptions,
apiPath,
formatInlineRecord,
handleCommandError,
printOutput,
resolveCommandContext,
type BaseClientOptions,
} from "./common.js";
interface AgentTokenOptions extends BaseClientOptions {
companyId?: string;
agent?: string;
name?: string;
}
interface BoardTokenOptions extends BaseClientOptions {
companyId?: string;
name?: string;
expiresAt?: string;
ttlDays?: string;
neverExpires?: boolean;
}
interface CreatedAgentKey {
id: string;
name: string;
token: string;
createdAt: string;
}
interface AgentKeyRow {
id: string;
name: string;
createdAt: string;
lastUsedAt?: string | null;
revokedAt?: string | null;
}
interface CreatedBoardKey {
id: string;
name: string;
token: string;
createdAt: string;
lastUsedAt: string | null;
revokedAt: string | null;
expiresAt: string | null;
}
interface BoardKeyRow {
id: string;
name: string;
createdAt: string;
lastUsedAt: string | null;
revokedAt: string | null;
expiresAt: string | null;
}
export function registerTokenCommands(program: Command): void {
const token = program.command("token").description("Manage Paperclip API tokens");
const agent = token.command("agent").description("Manage agent API keys");
addCommonClientOptions(
agent
.command("create")
.description("Create an agent API key")
.requiredOption("-C, --company-id <id>", "Company ID")
.requiredOption("--agent <agent>", "Agent ID, shortname, or unambiguous name")
.option("--name <name>", "API key label", "cli-agent")
.action(async (opts: AgentTokenOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
const agentRow = await resolveAgent(ctx.api, ctx.companyId ?? "", opts.agent ?? "");
const payload = createAgentKeySchema.parse({ name: opts.name });
const key = await ctx.api.post<CreatedAgentKey>(apiPath`/api/agents/${agentRow.id}/keys`, payload);
if (!key) throw new Error("Failed to create agent API key");
printOutput(
{
agentId: agentRow.id,
agentName: agentRow.name,
companyId: agentRow.companyId,
key,
},
{ json: ctx.json },
);
} catch (err) {
handleCommandError(err);
}
}),
{ includeCompany: false },
);
addCommonClientOptions(
agent
.command("list")
.description("List agent API keys")
.requiredOption("-C, --company-id <id>", "Company ID")
.requiredOption("--agent <agent>", "Agent ID, shortname, or unambiguous name")
.action(async (opts: AgentTokenOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
const agentRow = await resolveAgent(ctx.api, ctx.companyId ?? "", opts.agent ?? "");
const keys = (await ctx.api.get<AgentKeyRow[]>(apiPath`/api/agents/${agentRow.id}/keys`)) ?? [];
if (ctx.json) {
printOutput({ agentId: agentRow.id, companyId: agentRow.companyId, keys }, { json: true });
return;
}
for (const key of keys) {
console.log(formatInlineRecord({ id: key.id, name: key.name, createdAt: key.createdAt, revokedAt: key.revokedAt ?? null }));
}
if (keys.length === 0) printOutput([], { json: false });
} catch (err) {
handleCommandError(err);
}
}),
{ includeCompany: false },
);
addCommonClientOptions(
agent
.command("revoke")
.description("Revoke an agent API key")
.argument("<keyId>", "Agent API key ID")
.requiredOption("-C, --company-id <id>", "Company ID")
.requiredOption("--agent <agent>", "Agent ID, shortname, or unambiguous name")
.action(async (keyId: string, opts: AgentTokenOptions) => {
try {
const ctx = resolveCommandContext(opts, { requireCompany: true });
const agentRow = await resolveAgent(ctx.api, ctx.companyId ?? "", opts.agent ?? "");
const result = await ctx.api.delete<{ ok: true; keyId?: string }>(apiPath`/api/agents/${agentRow.id}/keys/${keyId}`);
printOutput({ ok: true, agentId: agentRow.id, companyId: agentRow.companyId, ...(result ?? {}) }, { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
{ includeCompany: false },
);
const board = token.command("board").description("Manage board API keys");
addCommonClientOptions(
board
.command("create")
.description("Create a named board API key")
.option("-C, --company-id <id>", "Company ID used for audit context")
.option("--name <name>", "API key label", "cli-board")
.option("--expires-at <iso8601>", "Expiration timestamp")
.option("--ttl-days <days>", "Expiration in days from now")
.option("--never-expires", "Create a non-expiring key")
.action(async (opts: BoardTokenOptions) => {
try {
const ctx = resolveCommandContext(opts);
const expiresAt = resolveBoardKeyExpiresAt(opts);
const payload = createBoardApiKeySchema.parse({
name: opts.name,
requestedCompanyId: opts.companyId ?? ctx.companyId ?? null,
expiresAt,
});
const key = await ctx.api.post<CreatedBoardKey>("/api/board-api-keys", payload);
if (!key) throw new Error("Failed to create board API key");
printOutput({ key }, { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
{ includeCompany: false },
);
addCommonClientOptions(
board
.command("list")
.description("List board API keys for the current board user")
.action(async (opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
const keys = (await ctx.api.get<BoardKeyRow[]>("/api/board-api-keys")) ?? [];
if (ctx.json) {
printOutput(keys, { json: true });
return;
}
for (const key of keys) {
console.log(formatInlineRecord({
id: key.id,
name: key.name,
createdAt: key.createdAt,
lastUsedAt: key.lastUsedAt,
expiresAt: key.expiresAt,
revokedAt: key.revokedAt,
}));
}
if (keys.length === 0) printOutput([], { json: false });
} catch (err) {
handleCommandError(err);
}
}),
);
addCommonClientOptions(
board
.command("revoke")
.description("Revoke a board API key")
.argument("<keyId>", "Board API key ID")
.action(async (keyId: string, opts: BaseClientOptions) => {
try {
const ctx = resolveCommandContext(opts);
const result = await ctx.api.delete<{ ok: true; keyId: string }>(apiPath`/api/board-api-keys/${keyId}`);
printOutput(result ?? { ok: true, keyId }, { json: ctx.json });
} catch (err) {
handleCommandError(err);
}
}),
);
}
async function resolveAgent(api: { get<T>(path: string): Promise<T | null> }, companyId: string, agentRef: string): Promise<Agent> {
const trimmed = agentRef.trim();
if (!trimmed) throw new Error("Agent reference is required");
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(trimmed)) {
const agent = await api.get<Agent>(apiPath`/api/agents/${trimmed}`);
if (!agent || agent.companyId !== companyId) throw new Error(`Agent not found: ${agentRef}`);
return agent;
}
const query = new URLSearchParams({ companyId });
const agent = await api.get<Agent>(`${apiPath`/api/agents/${trimmed}`}?${query.toString()}`);
if (!agent || agent.companyId !== companyId) throw new Error(`Agent not found: ${agentRef}`);
return agent;
}
function resolveBoardKeyExpiresAt(opts: BoardTokenOptions): Date | null | undefined {
if (opts.neverExpires) return null;
if (opts.expiresAt?.trim()) {
const date = new Date(opts.expiresAt.trim());
if (!Number.isFinite(date.getTime())) throw new Error(`Invalid --expires-at value: ${opts.expiresAt}`);
return date;
}
if (opts.ttlDays?.trim()) {
const days = Number(opts.ttlDays);
if (!Number.isFinite(days) || days <= 0) throw new Error(`Invalid --ttl-days value: ${opts.ttlDays}`);
return new Date(Date.now() + Math.floor(days * 24 * 60 * 60 * 1000));
}
return undefined;
}