Files
PaperClipAI/cli/src/commands/client/token.ts
T
655d6c9d8e fix(cli): make -C/--company-id optional on client commands enforced via resolveCommandContext (#11601)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The `paperclipai` CLI is how humans and other agents drive Paperclip
from a terminal or script
> - Many `client/*` command files declare `-C, --company-id` with
`.requiredOption(...)`, so commander aborts argument parsing before the
command's action ever runs
> - Every one of those same actions calls `resolveCommandContext(opts, {
requireCompany: true })`, which already resolves the company id from
`--company-id` -> `PAPERCLIP_COMPANY_ID` -> the context profile, and
throws a clear error only when all three are empty
> - So a command like `agent list` fails immediately on a bare parse
error even when the caller has `PAPERCLIP_COMPANY_ID` exported or a
context profile set, while a sibling command like `issue list` (no
`requiredOption`) works fine from the same environment — same resolver,
inconsistent enforcement point
> - This pull request replaces `.requiredOption("-C, --company-id <id>",
...)` with `.option(...)` at every site backed by
`resolveCommandContext(..., { requireCompany: true })`, leaving
`requireCompany: true` untouched so the resolver still enforces the
requirement, just with its existing, more informative error message
> - The benefit is that `--company-id` behaves consistently across every
client command: env var and context-profile fallback always work, and
the error message when nothing is set comes from one place instead of
commander's generic "required option not specified"

## Linked Issues or Issue Description

No public GitHub issue exists for this yet, so following the Enhancement
proposal template inline:

**What existing behavior does this improve?**
The `-C, --company-id` option on CLI client commands under
`cli/src/commands/client/`.

**Subsystem affected**
Unsure / cross-cutting within the CLI — this is not one of the listed
subsystems (server/, ui/, packages/db, packages/shared,
packages/adapters, packages/plugins); it is
`cli/src/commands/client/**`.

**Current behavior**
28 commands across
`cli/src/commands/client/{activity,agent,approval,company,goal,plugin,project,secrets,token}.ts`
declare `-C, --company-id` via commander's `.requiredOption(...)`.
Commander enforces that flag at argument-parse time and exits with a
generic `error: required option '-C, --company-id <id>' not specified`
before the command's action function runs — even though every one of
those actions calls `resolveCommandContext(opts, { requireCompany: true
})`, which is fully capable of resolving the company id from
`PAPERCLIP_COMPANY_ID` or the context profile. Other commands in the
same CLI (e.g. `issue list`) use `.option(...)` for the same flag and
already work from env/profile. The result is an inconsistent, confusing
failure mode depending on which command you call.

**Proposed behavior**
All 28 sites use `.option("-C, --company-id <id>", ...)` instead of
`.requiredOption(...)`. `requireCompany: true` stays in
`resolveCommandContext`, so a company id is still required end-to-end —
it can now come from `--company-id`, `PAPERCLIP_COMPANY_ID`, or the
context profile, uniformly, with one shared, descriptive error message
when none of the three are set.

**Breaking changes**
None for correctly-configured callers. A caller that relied on
commander's parse-time rejection (rather than the resolver's `Company ID
is required...` message) would see a different error message, but the
exit-code behavior (non-zero, no company id resolved) is unchanged. No
response shape, output format, or successful-path behavior changes.

## What Changed

- Replaced `.requiredOption("-C, --company-id <id>", ...)` with
`.option("-C, --company-id <id>", ...)` at all 28 call sites across
`cli/src/commands/client/activity.ts`, `agent.ts`, `approval.ts`,
`company.ts`, `goal.ts`, `plugin.ts`, `project.ts`, `secrets.ts`, and
`token.ts`.
- Left `resolveCommandContext(opts, { requireCompany: true })` unchanged
everywhere — enforcement still happens there, with its existing error
message.
- Added `cli/src/__tests__/company-id-option.test.ts`, a regression test
modelled on `auth-command-registration.test.ts` that registers every
affected command family (`company`, `issue`, `agent`, `approval`,
`activity`, `dashboard`, `feedback`, `goal`, `plugin`, `project`,
`secrets`, `token`), walks the full command tree, and asserts
`--company-id` is never `mandatory` (commander's `.requiredOption`
discriminator) and never declared more than once on the same command.

## Verification

```
$ grep -rn 'requiredOption("-C' cli/src/commands/client/
# exit code 1, no matches
```

```
$ cd cli && pnpm exec vitest run src/__tests__/company-id-option.test.ts
 Test Files  1 passed (1)
      Tests  2 passed (2)
```

Red on the unpatched tree (reverting only the fix files reproduces 9+
offending commands):

```
$ git stash push -- cli/src/commands/client/*.ts
$ pnpm exec vitest run src/__tests__/company-id-option.test.ts
 ❯ … 1 failed
AssertionError: --company-id must never be mandatory; offending commands: …
$ git stash pop
```

```
$ pnpm -C cli build
# green (tsc --noEmit at the repo root reports ~139 pre-existing errors in
# server/src/** from a missing built @paperclipai/plugin-sdk dist, present
# identically on the unpatched tree and unrelated to this diff;
# cli/src/commands/client/** itself has zero new type errors)
```

Behavioral check via `cli/src/index.ts`:

```
$ PAPERCLIP_COMPANY_ID=test-co-123 PAPERCLIP_API_KEY=fake pnpm exec tsx src/index.ts agent list --json
API error 401: Unauthorized
# past argument parsing, into an HTTP/auth error — this is the intended fix

$ pnpm exec tsx src/index.ts agent list --json --context /tmp/pc-empty-context.json
Company ID is required. Pass --company-id, set PAPERCLIP_COMPANY_ID, or set context profile companyId via `paperclipai context set`.
```

## Risks

Low risk. This only relaxes a commander-level parse constraint; the
underlying requirement (`requireCompany: true`) is untouched, so every
affected command still refuses to proceed without a resolvable company
id. The main behavioral shift is the error message and the point at
which the error surfaces (resolver instead of commander), which is
strictly more informative. No API, schema, or persisted-data changes.

## Model Used

Claude (Anthropic), Claude Opus, extended thinking / chain-of-thought
reasoning enabled, with tool use (repo grep/read/edit, test execution)
throughout implementation and verification.

## 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 searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

## Related PRs found during duplicate search

- #4276 (`feat(cli): unify issue flag matrix (A+B) — -C optional +
per-subcommand guards`) — open, overlapping intent (also makes `-C`
optional) but scoped to `issue create` only plus a separate flag-hint
feature; does not touch the other 27 sites this PR fixes. Not a
duplicate.
- #2538 (`Refine CLI company commands behavior, tests`) — open, touches
`company.ts` but for import-adapter validation, unrelated to
`--company-id` enforcement. Not a duplicate.

No exact duplicate of this PR's scope (making `--company-id` a
non-mandatory option across all 28 client-command call sites while
keeping resolver-level enforcement) was found in the open or closed PR
list.

---------

Co-authored-by: dzianisv <dzianisv@gmail.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: commitperclip[bot] <284812584+commitperclip[bot]@users.noreply.github.com>
2026-12-04 11:25:29 -08:00

245 lines
8.6 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")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--agent <agent>", "Agent ID, shortname, or unambiguous name")
.option("--name <name>", "API key label", "cli-agent")
.action(async (opts: AgentTokenOptions) => {
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")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.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")
.option("-C, --company-id <id>", "Company ID (overrides context default)")
.requiredOption("--agent <agent>", "Agent ID, shortname, or unambiguous name")
.action(async (keyId: string, opts: AgentTokenOptions) => {
try {
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;
}