mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 19:08:33 +01:00
feat(board): add headless channels, fenced task queues, paperclipai/sdk, and pc CLI (#23330)
<!-- Write all pull request text in Simplified Technical English (ASD-STE100): short sentences, one instruction per sentence, simple approved vocabulary, and the active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Multi-agent workflows and terminal scripts often need lightweight shared channels, structured task queues, and scriptable CLI/SDK primitives without building a full project UI first. > - Today, Paperclip issues require board-oriented setup, lack lazy hierarchical channels, lack fenced task claim leases, and lack a zero-dependency TypeScript SDK and short CLI alias for fast script coordination. > - Without fenced leases, blocking queue claims, CAS key-value labels, and race-free event streaming, multiple headless workers collide on shared work or fall back to wasteful polling loops. > - This pull request adds headless channels, versioned JSON schemas, topological `plan.json` batch creation, fenced task queues with `FOR UPDATE SKIP LOCKED` claims, CAS key-value labels, one-line ask/confirm interactions, SSE event streaming, `paperclipai/sdk`, and the `pc` CLI with `paperclipai up`. > - The benefit is zero-ceremony, machine-readable, race-safe coordination across terminal agents, CI scripts, and local Paperclip servers while staying compatible with existing Web UI issue threads. ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting (`packages/db`, `packages/shared`, `server/`, `cli/`, `doc/`, `skills/`) **Problem or motivation** Agents and terminal workflows need a fast way to post updates, queue DAG tasks, claim work without double-execution, ask humans for approval, and wait on board events without browser setup or polling loops. Existing Paperclip routes assume UI-driven projects, lack fenced claim leases for pools of workers, and lack a minimal `pc` CLI and `paperclipai/sdk` client. **Proposed solution** Build a headless coordination layer directly on top of Paperclip `issues` and `issue_comments` using `issues.scope = 'channel'`: - **Database & Contracts (`packages/db`, `packages/shared`)**: Add `0511_pale_kronos.sql` (`issues.scope`) and `0512_stormy_the_hood.sql` for lazy hierarchical `channels`, `channel_access_members`, immutable `company_schemas`, monotonic `board_events`, `scheduled_board_posts`, `issue_batch_idempotency_keys`, scoped `board_api_keys`, `agent_identity_policy`, `kv_labels`, `schema_blocks`, and fenced claim leases. Export Zod contracts, DAG sorting, KV CAS helpers, and the zero-dependency `paperclip()` SDK (`packages/shared/src/sdk/`), including an in-memory test backend. - **Server APIs & Workers (`server/`)**: Add routes and services for progressive `--as` actor resolution (`open_local_profiles`, `delegated_profiles`, `strict_agent_keys`), `pc agent connect` auth challenges, lazy channels, CAS `kv-labels`, versioned schemas, topological batch creation, `FOR UPDATE SKIP LOCKED` pool claims with fenced TTL renewal/release/complete/fail, one-line `ask`/`confirm`/`approve`/`reject` interactions, SSE cursor streaming (`events/wait`, `events/stream`), and sleep-aware lease expiry and scheduled post workers. - **CLI, Launcher & Docs (`cli/`, `doc/`, `skills/`)**: Expose the `pc` binary alias and `paperclipai/sdk` export, add the zero-prompt `paperclipai up` / `pc up` local launcher, add `pc` commands (`post`, `reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent connect/login`), add documentation (`doc/CHANNELS-AND-QUEUES.md`, `doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`), and add `skills/paperclip-lite/SKILL.md`. **Alternatives considered** - **Separate message and queue tables outside `issues`**: Rejected because channel posts and queued tasks would lose Paperclip identifiers (`PC-1`), comments, attachments, privacy ACLs, and direct Web UI issue URLs (`/<prefix>/issues/PC-1`). - **Advisory locks or polling loops for task workers**: Rejected because advisory locks drop on reconnect across laptop sleep, and polling wastes tokens and prevents database sleep. Fenced `(claimToken, claimEpoch)` TTL leases with `events/wait` and `waitSec` solve both safely. **Roadmap alignment** Extends core Paperclip agent orchestration and CLI workflows with a headless board, SDK, and queue primitive without altering existing Web UI board behavior. **Additional context** This PR builds on the `issues.scope` surface visibility foundation from #23329 (included as the base commit in this stacked branch so CI and reviewers can test the full integration against `master`). ## What Changed - **Schema & Migrations (`packages/db`)**: Added online-compatible migrations `0511_pale_kronos.sql` and `0512_stormy_the_hood.sql`, schema definitions (`channels.ts`, `company_schemas.ts`, `headless_board.ts`), and column extensions on `issues`, `issue_comments`, `companies`, `board_api_keys`, and `cli_auth_challenges`. - **Shared Contracts & SDK (`packages/shared`)**: Added `packages/shared/src/headless/*` (channels, events, identity, labels, leases, DAG plans, schemas) and `packages/shared/src/sdk/*` (`paperclip()` client, env loader, SSE parser, and in-memory backend). - **Server Routes & Services (`server/`)**: Added `headless-channels-schemas.ts`, `headless-queues-events.ts`, `headless-identity.ts` routes and supporting services (`headless-channels.ts`, `headless-common.ts`, `headless-events-schedules-interactions.ts`, `headless-identity.ts`, `headless-labels-batch.ts`, `headless-schemas.ts`, `headless-task-queue.ts`), plus `issues.scope` visibility isolation and `board-auth.ts` extensions. - **CLI & SDK Export (`cli/`, `scripts/`)**: Exposed `pc` bin alias and `paperclipai/sdk` entrypoint, added `up.ts` zero-prompt launcher and `cli/src/commands/board/*` commands (`post`, `reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent`). - **Docs, Skill & Runner Registry (`doc/`, `skills/`, `tests/runner-e2e/`)**: Added `doc/CHANNELS-AND-QUEUES.md`, `doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`, plan docs, `skills/paperclip-lite/SKILL.md`, and synchronized `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/shared build` — passed. - `pnpm --filter @paperclipai/db check:migrations` — passed (`0511_pale_kronos.sql` and `0512_stormy_the_hood.sql` verified online-compatible, 2 new migrations since `630cf0423024`, none blocked). - `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check` — passed (`598` inputs, `changed: false`). - `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/source-sdk-public-inputs.test.mjs` — 13/13 tests passed. - `node scripts/check-maps.mjs` — passed (`35` areas, `192` capability IDs aligned). - `pnpm exec vitest run packages/shared/src/headless/headless.test.ts packages/shared/src/sdk/sdk.test.ts cli/src/__tests__/headless-board-cli.test.ts` — 3 files, 22/22 tests passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-scope-visibility.test.ts src/__tests__/headless-channels-schemas-batch.test.ts src/__tests__/headless-identity-auth.test.ts src/__tests__/headless-queues-leases-events.test.ts src/__tests__/headless-e2e-sdk-cli.test.ts` — 5 files, 25/25 tests passed. - `pnpm --filter @paperclipai/shared typecheck && pnpm --filter @paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck && pnpm --filter paperclipai typecheck` — all passed. - `pnpm --filter paperclipai build` — passed. ## Risks - **Two new migrations (`0511`, `0512`)**: Both migrations are marked online-compatible (`NOT VALID` constraints validated afterwards, `CONCURRENTLY` index creation, idempotent statements for non-transactional execution) and checked by `check:migrations`. If #23329 lands separately with `0511` modified or renumbered, this branch will rebase on top cleanly. - **Large surface area (91 files)**: Changes are primarily additive new modules (`headless-*`, `cli/src/commands/board/*`, `packages/shared/src/headless/*`, `packages/shared/src/sdk/*`); existing Web UI board behavior remains isolated via `issues.scope`. - **Full repository Vitest suite**: Only the targeted headless, SDK, CLI, server, and runner-e2e pin suites ran locally after rebasing; full cross-package CI checks will validate the remaining suite. ## Model Used - Google DeepMind Antigravity (Gemini coding agent) with tool use and code execution ## 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 - [x] 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 - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
43fedd51c5
commit
ea56320e10
100 files changed
+32616
-79
No files matched your search
@@ -0,0 +1,491 @@
|
||||
import pc from "picocolors";
|
||||
import type { Command } from "commander";
|
||||
import { AGENT_ROLES, type Agent, type AgentRole } from "@paperclipai/shared";
|
||||
import { parseDurationMs, PaperclipError } from "@paperclipai/shared/sdk";
|
||||
import { loginBoardCli, openUrl } from "../../client/board-auth.js";
|
||||
import {
|
||||
addBoardClientOptions,
|
||||
handleBoardError,
|
||||
resolveBoardClient,
|
||||
type BoardCommonOptions,
|
||||
type ResolvedBoardClient,
|
||||
} from "./client.js";
|
||||
import { writeProfileRecord } from "./store.js";
|
||||
|
||||
interface AgentConnectOptions extends BoardCommonOptions {
|
||||
role?: string;
|
||||
ttl?: string;
|
||||
saveProfile?: string;
|
||||
revealKey?: boolean;
|
||||
}
|
||||
|
||||
interface AgentLoginOptions extends BoardCommonOptions {
|
||||
name: string;
|
||||
role?: string;
|
||||
ttl?: string;
|
||||
saveProfile?: string;
|
||||
browser?: boolean;
|
||||
}
|
||||
|
||||
interface AgentConnectApiResponse {
|
||||
agent?: Agent;
|
||||
agentId?: string;
|
||||
agentName?: string;
|
||||
companyId?: string;
|
||||
token?: string;
|
||||
apiKey?: string;
|
||||
key?: {
|
||||
id: string;
|
||||
name: string;
|
||||
token: string;
|
||||
createdAt?: string;
|
||||
expiresAt?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
function shellEscape(value: string): string {
|
||||
return value.replace(/'/g, "'\"'\"'");
|
||||
}
|
||||
|
||||
function redactApiKeyToken(token: string): string {
|
||||
const prefixMatch = /^([a-z]+_)/i.exec(token.trim());
|
||||
const prefix = prefixMatch ? prefixMatch[1]! : "";
|
||||
return `${prefix}••••••••`;
|
||||
}
|
||||
|
||||
function buildHeadlessAgentExports(
|
||||
input: {
|
||||
apiBase: string;
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
apiKey: string;
|
||||
profile: string;
|
||||
},
|
||||
opts: { revealKey?: boolean } = {},
|
||||
): string {
|
||||
const lines = [
|
||||
`export PAPERCLIP_API_URL='${shellEscape(input.apiBase)}'`,
|
||||
`export PAPERCLIP_COMPANY_ID='${shellEscape(input.companyId)}'`,
|
||||
`export PAPERCLIP_AGENT_ID='${shellEscape(input.agentId)}'`,
|
||||
];
|
||||
if (opts.revealKey) {
|
||||
lines.push(`export PAPERCLIP_API_KEY='${shellEscape(input.apiKey)}'`);
|
||||
} else {
|
||||
lines.push(`# PAPERCLIP_API_KEY='${redactApiKeyToken(input.apiKey)}' (redacted; stored in local profile)`);
|
||||
}
|
||||
lines.push(`export PAPERCLIP_PROFILE='${shellEscape(input.profile)}'`);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function normalizeAgentRole(rawRole?: string): AgentRole {
|
||||
const candidate = rawRole?.trim().toLowerCase() ?? "";
|
||||
if ((AGENT_ROLES as readonly string[]).includes(candidate)) {
|
||||
return candidate as AgentRole;
|
||||
}
|
||||
return "general";
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function connectHeadlessAgentWithClient(
|
||||
resolved: ResolvedBoardClient,
|
||||
input: {
|
||||
name: string;
|
||||
role?: string;
|
||||
ttl?: string;
|
||||
saveProfile?: string;
|
||||
},
|
||||
): Promise<{
|
||||
profile: string;
|
||||
profilePath: string;
|
||||
agentId: string;
|
||||
agentName: string;
|
||||
companyId: string;
|
||||
apiBase: string;
|
||||
apiKey: string;
|
||||
keyId?: string;
|
||||
expiresAt?: string | null;
|
||||
}> {
|
||||
const companyId = await resolved.resolveCompanyId();
|
||||
const profileName = (input.saveProfile?.trim() || input.name.trim());
|
||||
const ttlSec = input.ttl ? Math.max(1, Math.round(parseDurationMs(input.ttl) / 1000)) : undefined;
|
||||
|
||||
let agentId: string | undefined;
|
||||
let agentName = input.name.trim();
|
||||
let apiKey: string | undefined;
|
||||
let keyId: string | undefined;
|
||||
let expiresAt: string | null | undefined;
|
||||
|
||||
try {
|
||||
const connected = await resolved.requestJson<AgentConnectApiResponse>(
|
||||
`/api/companies/${encodeURIComponent(companyId)}/agents/connect`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: agentName,
|
||||
...(input.role ? { role: input.role } : {}),
|
||||
...(ttlSec !== undefined ? { ttlSec } : {}),
|
||||
}),
|
||||
},
|
||||
);
|
||||
agentId = connected.agent?.id ?? connected.agentId;
|
||||
agentName = connected.agent?.name ?? connected.agentName ?? agentName;
|
||||
apiKey = connected.key?.token ?? connected.apiKey ?? connected.token;
|
||||
keyId = connected.key?.id;
|
||||
expiresAt = connected.key?.expiresAt;
|
||||
} catch (err) {
|
||||
if (!(err instanceof PaperclipError) || err.status !== 404) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (!agentId || !apiKey) {
|
||||
const existingAgents = await resolved.requestJson<Agent[]>(
|
||||
`/api/companies/${encodeURIComponent(companyId)}/agents`,
|
||||
{ method: "GET" },
|
||||
);
|
||||
const lower = agentName.toLowerCase();
|
||||
let target = (existingAgents ?? []).find(
|
||||
(a) => a.name.toLowerCase() === lower || a.urlKey?.toLowerCase() === lower,
|
||||
);
|
||||
|
||||
if (!target) {
|
||||
target = await resolved.requestJson<Agent>(
|
||||
`/api/companies/${encodeURIComponent(companyId)}/agents`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: agentName,
|
||||
role: normalizeAgentRole(input.role),
|
||||
adapterType: "headless",
|
||||
}),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const keyName = `cli-${profileName}-${new Date().toISOString().replaceAll(":", "-")}`;
|
||||
const createdKey = await resolved.requestJson<{
|
||||
id: string;
|
||||
name: string;
|
||||
token: string;
|
||||
createdAt: string;
|
||||
expiresAt?: string | null;
|
||||
}>(`/api/agents/${encodeURIComponent(target.id)}/keys`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: keyName,
|
||||
...(ttlSec !== undefined ? { ttlSec } : {}),
|
||||
}),
|
||||
});
|
||||
|
||||
agentId = target.id;
|
||||
agentName = target.name;
|
||||
apiKey = createdKey.token;
|
||||
keyId = createdKey.id;
|
||||
expiresAt = createdKey.expiresAt ?? null;
|
||||
}
|
||||
|
||||
const profilePath = writeProfileRecord(profileName, {
|
||||
agentId,
|
||||
agentName,
|
||||
companyId,
|
||||
apiBase: resolved.apiBase,
|
||||
apiKey,
|
||||
...(input.role ? { role: input.role } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
profile: profileName,
|
||||
profilePath,
|
||||
agentId,
|
||||
agentName,
|
||||
companyId,
|
||||
apiBase: resolved.apiBase,
|
||||
apiKey,
|
||||
keyId,
|
||||
expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
export async function handleBoardWhoami(opts: BoardCommonOptions): Promise<void> {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const info = await resolved.client.whoami();
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(info, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`${pc.bold("API:")} ${info.apiBase}`);
|
||||
console.log(`${pc.bold("Company:")} ${info.companyName} [${info.companyPrefix}] (${info.companyId})`);
|
||||
const principalDetail = info.agentId
|
||||
? `agent @${info.agentName ?? info.agentId}`
|
||||
: info.actorProfile
|
||||
? `${info.principalType} (profile=${info.actorProfile}${info.userId ? `, user=${info.userId}` : ""})`
|
||||
: `${info.principalType}${info.userId ? ` (user=${info.userId})` : ""}`;
|
||||
console.log(`${pc.bold("Principal:")} ${principalDetail}`);
|
||||
console.log(`${pc.bold("Policy:")} ${info.agentIdentityPolicy}`);
|
||||
if (info.scopes) {
|
||||
console.log(`${pc.bold("Scopes:")} ${JSON.stringify(info.scopes)}`);
|
||||
}
|
||||
}
|
||||
|
||||
function buildSafeAgentLoginJson(connected: {
|
||||
profile: string;
|
||||
profilePath: string;
|
||||
agentId: string;
|
||||
agentName: string;
|
||||
companyId: string;
|
||||
apiBase: string;
|
||||
keyId?: string | null;
|
||||
expiresAt?: string | null;
|
||||
}) {
|
||||
return {
|
||||
ok: true,
|
||||
profile: connected.profile,
|
||||
profilePath: connected.profilePath,
|
||||
agentId: connected.agentId,
|
||||
agentName: connected.agentName,
|
||||
companyId: connected.companyId,
|
||||
apiBase: connected.apiBase,
|
||||
...(connected.keyId !== undefined ? { keyId: connected.keyId } : {}),
|
||||
...(connected.expiresAt !== undefined ? { expiresAt: connected.expiresAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function registerBoardAgentAuthCommands(agentCmd: Command): void {
|
||||
addBoardClientOptions(
|
||||
agentCmd
|
||||
.command("connect")
|
||||
.description("Create or reuse a headless agent, mint an API key, and store a local profile")
|
||||
.argument("<name>", "Agent name / profile name")
|
||||
.option("--role <role>", "Agent role (e.g. worker, security, engineer, general)", "general")
|
||||
.option("--ttl <duration>", "Key TTL duration (e.g. 7d, 24h)")
|
||||
.option("--save-profile <name>", "Local profile filename under ~/.paperclip/profiles/ (defaults to <name>)")
|
||||
.option("--reveal-key", "Print the unredacted PAPERCLIP_API_KEY to stdout")
|
||||
.action(async (name: string, opts: AgentConnectOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const result = await connectHeadlessAgentWithClient(resolved, {
|
||||
name,
|
||||
role: opts.role,
|
||||
ttl: opts.ttl,
|
||||
saveProfile: opts.saveProfile,
|
||||
});
|
||||
const exportsText = buildHeadlessAgentExports(result, { revealKey: opts.revealKey });
|
||||
const displayedToken = opts.revealKey
|
||||
? result.apiKey
|
||||
: redactApiKeyToken(result.apiKey);
|
||||
if (resolved.json) {
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
ok: true,
|
||||
profile: result.profile,
|
||||
profilePath: result.profilePath,
|
||||
agentId: result.agentId,
|
||||
agentName: result.agentName,
|
||||
companyId: result.companyId,
|
||||
apiBase: result.apiBase,
|
||||
key: {
|
||||
id: result.keyId ?? null,
|
||||
token: displayedToken,
|
||||
redacted: !opts.revealKey,
|
||||
expiresAt: result.expiresAt ?? null,
|
||||
},
|
||||
exports: exportsText,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`# Saved agent profile '${result.profile}' to ${result.profilePath}`);
|
||||
console.log(exportsText);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
{ includeCompany: true },
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
agentCmd
|
||||
.command("login")
|
||||
.description("Provision a headless agent API key via browser approval")
|
||||
.requiredOption("--name <name>", "Agent name to create or connect")
|
||||
.option("--role <role>", "Agent role", "general")
|
||||
.option("--ttl <duration>", "Key TTL duration (e.g. 7d)")
|
||||
.option("--save-profile <name>", "Local profile filename (defaults to --name)")
|
||||
.option("--no-browser", "Do not attempt to open a browser automatically")
|
||||
.action(async (opts: AgentLoginOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const profileName = opts.saveProfile?.trim() || opts.name.trim();
|
||||
let requestedCompanyId: string | null = null;
|
||||
if (opts.company || opts.companyId) {
|
||||
try {
|
||||
requestedCompanyId = await resolved.resolveCompanyId();
|
||||
} catch {
|
||||
requestedCompanyId = (opts.company ?? opts.companyId)?.trim() ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
let directAgentChallengeSupported = true;
|
||||
let challengeResponse: {
|
||||
id: string;
|
||||
token: string;
|
||||
boardApiToken?: string;
|
||||
approvalPath: string;
|
||||
approvalUrl: string | null;
|
||||
pollPath: string;
|
||||
expiresAt: string;
|
||||
suggestedPollIntervalMs: number;
|
||||
} | null = null;
|
||||
|
||||
try {
|
||||
challengeResponse = await resolved.requestJson("/api/cli-auth/challenges", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
command: `paperclipai agent login --name ${opts.name}`,
|
||||
clientName: "paperclipai cli",
|
||||
requestedAccess: "board",
|
||||
requestedCompanyId,
|
||||
challengeKind: "agent_key",
|
||||
agentName: opts.name,
|
||||
...(opts.role ? { agentRole: opts.role } : {}),
|
||||
}),
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof PaperclipError && err.status === 400) {
|
||||
directAgentChallengeSupported = false;
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (!directAgentChallengeSupported || !challengeResponse) {
|
||||
const login = await loginBoardCli({
|
||||
apiBase: resolved.apiBase,
|
||||
requestedAccess: "board",
|
||||
requestedCompanyId,
|
||||
command: `paperclipai agent login --name ${opts.name}`,
|
||||
openBrowser: opts.browser,
|
||||
});
|
||||
const authedResolved = resolveBoardClient({
|
||||
...opts,
|
||||
apiBase: resolved.apiBase,
|
||||
apiKey: login.token,
|
||||
});
|
||||
const connected = await connectHeadlessAgentWithClient(authedResolved, {
|
||||
name: opts.name,
|
||||
role: opts.role,
|
||||
ttl: opts.ttl,
|
||||
saveProfile: profileName,
|
||||
});
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(buildSafeAgentLoginJson(connected), null, 2));
|
||||
return;
|
||||
}
|
||||
console.log(
|
||||
pc.green(`Connected agent '${connected.agentName}' and saved profile '${connected.profile}' to ${connected.profilePath}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const approvalUrl =
|
||||
challengeResponse.approvalUrl ?? `${resolved.apiBase}${challengeResponse.approvalPath}`;
|
||||
console.error(pc.bold("Agent authorization required"));
|
||||
console.error(`Open this URL in your browser to approve agent '${opts.name}':\n${approvalUrl}`);
|
||||
if (opts.browser !== false) {
|
||||
await openUrl(approvalUrl);
|
||||
}
|
||||
|
||||
const expiresAtMs = Date.parse(challengeResponse.expiresAt);
|
||||
const pollMs = Math.max(500, challengeResponse.suggestedPollIntervalMs || 1000);
|
||||
while (Date.now() < expiresAtMs) {
|
||||
const status = await resolved.requestJson<{
|
||||
status: "pending" | "approved" | "cancelled" | "expired";
|
||||
agentApiToken?: string;
|
||||
agentId?: string;
|
||||
companyId?: string;
|
||||
}>(
|
||||
`/api${challengeResponse.pollPath}?token=${encodeURIComponent(challengeResponse.token)}`,
|
||||
{ method: "GET" },
|
||||
);
|
||||
|
||||
if (status.status === "approved") {
|
||||
const resolvedAgentToken = status.agentApiToken ?? challengeResponse.boardApiToken;
|
||||
if (resolvedAgentToken && status.agentId && status.companyId) {
|
||||
const profilePath = writeProfileRecord(profileName, {
|
||||
agentId: status.agentId,
|
||||
agentName: opts.name.trim(),
|
||||
companyId: status.companyId,
|
||||
apiBase: resolved.apiBase,
|
||||
apiKey: resolvedAgentToken,
|
||||
...(opts.role ? { role: opts.role } : {}),
|
||||
});
|
||||
const out = {
|
||||
ok: true,
|
||||
profile: profileName,
|
||||
profilePath,
|
||||
agentId: status.agentId,
|
||||
agentName: opts.name.trim(),
|
||||
companyId: status.companyId,
|
||||
apiBase: resolved.apiBase,
|
||||
};
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(out, null, 2));
|
||||
} else {
|
||||
console.log(
|
||||
pc.green(`Approved agent '${opts.name}' and saved profile '${profileName}' to ${profilePath}`),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!challengeResponse.boardApiToken) {
|
||||
throw new Error("Approved challenge did not yield an agent or board token.");
|
||||
}
|
||||
const authedResolved = resolveBoardClient({
|
||||
...opts,
|
||||
apiBase: resolved.apiBase,
|
||||
apiKey: challengeResponse.boardApiToken,
|
||||
});
|
||||
const connected = await connectHeadlessAgentWithClient(authedResolved, {
|
||||
name: opts.name,
|
||||
role: opts.role,
|
||||
ttl: opts.ttl,
|
||||
saveProfile: profileName,
|
||||
});
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(buildSafeAgentLoginJson(connected), null, 2));
|
||||
} else {
|
||||
console.log(
|
||||
pc.green(`Approved agent '${connected.agentName}' and saved profile '${connected.profile}' to ${connected.profilePath}`),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (status.status === "cancelled") {
|
||||
throw new Error("Agent login challenge was cancelled.");
|
||||
}
|
||||
if (status.status === "expired") {
|
||||
throw new Error("Agent login challenge expired before approval.");
|
||||
}
|
||||
|
||||
await sleep(pollMs);
|
||||
}
|
||||
|
||||
throw new Error("Agent login challenge expired before approval.");
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
{ includeCompany: true },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,582 @@
|
||||
import pc from "picocolors";
|
||||
import type { Command } from "commander";
|
||||
import type { ChannelPage, ChannelView, ThreadDetailView } from "@paperclipai/shared/sdk";
|
||||
import { channelsCommand } from "../channels.js";
|
||||
import {
|
||||
addBoardClientOptions,
|
||||
collectOption,
|
||||
handleBoardError,
|
||||
isPcBinary,
|
||||
isScriptOutput,
|
||||
parseJsonArg,
|
||||
parseKeyValuePairs,
|
||||
parseLabelsList,
|
||||
readTextInput,
|
||||
resolveBoardClient,
|
||||
splitCsvValues,
|
||||
type BoardCommonOptions,
|
||||
} from "./client.js";
|
||||
|
||||
interface ChannelsListOptions extends BoardCommonOptions {
|
||||
prefix?: string;
|
||||
boardChannels?: boolean;
|
||||
}
|
||||
|
||||
interface ChannelCreateOptions extends BoardCommonOptions {
|
||||
private?: boolean;
|
||||
project?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface PostOptions extends BoardCommonOptions {
|
||||
title?: string;
|
||||
file?: string;
|
||||
attach?: string[];
|
||||
label?: string[];
|
||||
schema?: string;
|
||||
data?: string;
|
||||
board?: boolean;
|
||||
idempotencyKey?: string;
|
||||
}
|
||||
|
||||
interface ReplyOptions extends BoardCommonOptions {
|
||||
file?: string;
|
||||
attach?: string[];
|
||||
label?: string[];
|
||||
schema?: string;
|
||||
data?: string;
|
||||
after?: string;
|
||||
internal?: boolean;
|
||||
idempotencyKey?: string;
|
||||
}
|
||||
|
||||
interface ReadOptions extends BoardCommonOptions {
|
||||
label?: string[];
|
||||
status?: string[];
|
||||
after?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
interface LabelOptions extends BoardCommonOptions {
|
||||
set?: string[];
|
||||
unset?: string[];
|
||||
if?: string[];
|
||||
ifUnset?: string[];
|
||||
}
|
||||
|
||||
export function shouldRouteToBoardChannels(opts: ChannelsListOptions, prefixArg?: string): boolean {
|
||||
if (isPcBinary()) return true;
|
||||
if (opts.boardChannels) return true;
|
||||
if (prefixArg !== undefined) return true;
|
||||
if (opts.prefix !== undefined) return true;
|
||||
if (opts.company !== undefined) return true;
|
||||
if (opts.companyId !== undefined) return true;
|
||||
if (opts.apiBase !== undefined) return true;
|
||||
if (opts.as !== undefined) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function tryParseJsonObject(raw: string): Record<string, unknown> | null {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed.startsWith("{")) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed) as unknown;
|
||||
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, unknown>;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveTextAndSchema(input: {
|
||||
textParts: string[];
|
||||
file?: string;
|
||||
schemaRef?: string;
|
||||
dataJson?: string;
|
||||
}): {
|
||||
text: string | undefined;
|
||||
schema: { ref: string; data: Record<string, unknown> } | undefined;
|
||||
} {
|
||||
const fileText = input.file !== undefined ? readTextInput(undefined, input.file) : undefined;
|
||||
|
||||
if (!input.schemaRef) {
|
||||
const inline = input.textParts.length > 0 ? input.textParts.join(" ") : undefined;
|
||||
return {
|
||||
text: fileText ?? inline,
|
||||
schema: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
let data: Record<string, unknown> | null = null;
|
||||
let prose: string | undefined = fileText;
|
||||
|
||||
if (input.dataJson !== undefined) {
|
||||
const parsed = parseJsonArg(input.dataJson, "--data");
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
||||
throw new Error("--data must be a JSON object");
|
||||
}
|
||||
data = parsed as Record<string, unknown>;
|
||||
if (prose === undefined && input.textParts.length > 0) {
|
||||
prose = input.textParts.join(" ");
|
||||
}
|
||||
} else if (input.textParts.length > 0) {
|
||||
const last = input.textParts[input.textParts.length - 1]!;
|
||||
const parsedLast = tryParseJsonObject(last);
|
||||
if (parsedLast) {
|
||||
data = parsedLast;
|
||||
const before = input.textParts.slice(0, -1).join(" ").trim();
|
||||
if (prose === undefined && before) {
|
||||
prose = before;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!data && fileText !== undefined) {
|
||||
const parsedFile = tryParseJsonObject(fileText);
|
||||
if (parsedFile) {
|
||||
data = parsedFile;
|
||||
prose = input.textParts.length > 0 ? input.textParts.join(" ") : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
throw new Error(
|
||||
`--schema ${input.schemaRef} requires a JSON object payload via --data '<json>', positional JSON argument, or --file <path|->`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
text: prose,
|
||||
schema: { ref: input.schemaRef, data },
|
||||
};
|
||||
}
|
||||
|
||||
function formatChannelList(channels: ChannelView[]): void {
|
||||
if (channels.length === 0) {
|
||||
console.log(pc.dim("(no channels)"));
|
||||
return;
|
||||
}
|
||||
|
||||
const groups = new Map<string, ChannelView[]>();
|
||||
for (const ch of channels) {
|
||||
const slashIdx = ch.path.indexOf("/");
|
||||
const group = slashIdx === -1 ? "" : `${ch.path.slice(0, slashIdx)}/`;
|
||||
const list = groups.get(group) ?? [];
|
||||
list.push(ch);
|
||||
groups.set(group, list);
|
||||
}
|
||||
|
||||
for (const [group, items] of groups.entries()) {
|
||||
if (group) {
|
||||
console.log(pc.bold(group));
|
||||
}
|
||||
for (const ch of items) {
|
||||
const vis = ch.visibility === "private" ? pc.yellow(" [private]") : "";
|
||||
const counts = pc.dim(`(${ch.threadCount} threads, ${ch.readyTaskCount} ready)`);
|
||||
const desc = ch.description ? pc.dim(` — ${ch.description}`) : "";
|
||||
console.log(` #${ch.path}${vis} ${counts}${desc}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function formatLabelsInline(
|
||||
kvLabels: Record<string, string> | undefined,
|
||||
tagLabels: string[] | undefined,
|
||||
): string {
|
||||
const parts: string[] = [];
|
||||
for (const tag of tagLabels ?? []) {
|
||||
parts.push(`#${tag}`);
|
||||
}
|
||||
for (const [k, v] of Object.entries(kvLabels ?? {})) {
|
||||
parts.push(`${k}=${v}`);
|
||||
}
|
||||
return parts.length > 0 ? pc.dim(` [${parts.join(" ")}]`) : "";
|
||||
}
|
||||
|
||||
function formatReadPage(page: ChannelPage, opts: { quiet?: boolean }): void {
|
||||
console.log(pc.bold(`#${page.channel}`) + pc.dim(` (${page.items.length} items)`));
|
||||
if (page.items.length === 0) {
|
||||
console.log(pc.dim(" (empty)"));
|
||||
} else {
|
||||
for (const item of page.items) {
|
||||
// Omit [backlog] on passive channel posts so discussions read naturally
|
||||
const statusBadge = item.isPassivePost ? "" : ` [${item.status}]`;
|
||||
const actor = item.actorProfile
|
||||
? `@${item.actorProfile}`
|
||||
: item.assigneeAgentId
|
||||
? `agent:${item.assigneeAgentId.slice(0, 8)}`
|
||||
: "board";
|
||||
const replies = item.replyCount > 0 ? `, ${item.replyCount} replies` : "";
|
||||
const labels = formatLabelsInline(item.kvLabels, item.tagLabels);
|
||||
console.log(
|
||||
` ${pc.cyan(item.identifier)}${statusBadge} ${item.title} ${pc.dim(`(#${item.channel ?? "board"}, ${actor}${replies})`)}${labels}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (process.stdout.isTTY && !opts.quiet) {
|
||||
console.log(pc.dim(`cursor: ${page.cursor} (use --after ${page.cursor} for newer updates)`));
|
||||
}
|
||||
}
|
||||
|
||||
function formatThreadDetail(detail: ThreadDetailView, opts: { quiet?: boolean }): void {
|
||||
const { issue } = detail;
|
||||
const statusBadge = issue.isPassivePost ? "" : ` [${issue.status}]`;
|
||||
const chBadge = issue.channel ? ` #${issue.channel}` : "";
|
||||
console.log(`${pc.cyan(pc.bold(issue.identifier))}${statusBadge}${pc.dim(chBadge)} ${pc.bold(issue.title)}`);
|
||||
const labels = formatLabelsInline(issue.kvLabels, issue.tagLabels);
|
||||
if (labels) {
|
||||
console.log(` labels:${labels}`);
|
||||
}
|
||||
if (issue.resultSchemaRef) {
|
||||
console.log(pc.dim(` resultSchema: ${issue.resultSchemaRef}`));
|
||||
}
|
||||
if (issue.description) {
|
||||
console.log("");
|
||||
console.log(issue.description);
|
||||
}
|
||||
const blocks = issue.blocks ?? [];
|
||||
if (blocks.length > 0) {
|
||||
for (const block of blocks) {
|
||||
console.log(pc.dim(` [${block.schema}@${block.version}] `) + JSON.stringify(block.data));
|
||||
}
|
||||
}
|
||||
const comments = detail.comments ?? [];
|
||||
if (comments.length > 0) {
|
||||
console.log("");
|
||||
console.log(pc.bold(`Replies (${comments.length}):`));
|
||||
for (const comment of comments) {
|
||||
const who = comment.actorProfile ?? comment.authorType;
|
||||
const internal = comment.internal ? pc.yellow(" [internal]") : "";
|
||||
console.log(` ${pc.dim(comment.id)} ${pc.cyan(who)}${internal}: ${comment.body}`);
|
||||
for (const block of comment.blocks ?? []) {
|
||||
console.log(pc.dim(` [${block.schema}@${block.version}] `) + JSON.stringify(block.data));
|
||||
}
|
||||
}
|
||||
}
|
||||
const interactions = detail.interactions ?? [];
|
||||
if (interactions.length > 0) {
|
||||
console.log("");
|
||||
console.log(pc.bold(`Interactions (${interactions.length}):`));
|
||||
for (const ix of interactions) {
|
||||
const outcome = ix.answer ?? ix.note;
|
||||
const suffix = outcome ? pc.green(` -> ${outcome}`) : "";
|
||||
console.log(` ${pc.dim(ix.id)} [${ix.status}] ${ix.kind}: ${ix.prompt}${suffix}`);
|
||||
}
|
||||
}
|
||||
if (process.stdout.isTTY && !opts.quiet) {
|
||||
console.log(pc.dim(`cursor: ${detail.cursor} (use --after ${detail.cursor} for newer updates)`));
|
||||
}
|
||||
}
|
||||
|
||||
async function executeChannelsList(
|
||||
prefixArg: string | undefined,
|
||||
cmdOpts: ChannelsListOptions,
|
||||
forceBoard: boolean,
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (!forceBoard && !shouldRouteToBoardChannels(cmdOpts, prefixArg)) {
|
||||
await channelsCommand({ json: cmdOpts.json });
|
||||
return;
|
||||
}
|
||||
const resolved = resolveBoardClient(cmdOpts);
|
||||
const effectivePrefix = cmdOpts.prefix ?? prefixArg;
|
||||
const list = await resolved.client.channels.list(effectivePrefix);
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(list, null, 2));
|
||||
return;
|
||||
}
|
||||
formatChannelList(list);
|
||||
} catch (err) {
|
||||
handleBoardError(err, cmdOpts);
|
||||
}
|
||||
}
|
||||
|
||||
function configureChannelsSubtree(cmd: Command, opts: { forceBoard: boolean }): void {
|
||||
addBoardClientOptions(
|
||||
cmd
|
||||
.description(
|
||||
opts.forceBoard
|
||||
? "List board channels"
|
||||
: "Show release channels (paperclipai) or board channels (pc / --board-channels / --prefix)",
|
||||
)
|
||||
.argument("[prefix]", "Optional channel path prefix (e.g. build/)")
|
||||
.option("--prefix <path>", "Filter board channels by path prefix (e.g. build/)")
|
||||
.option("--board-channels", "Force listing board channels instead of release channels")
|
||||
.action(async (prefixArg: string | undefined, cmdOpts: ChannelsListOptions) => {
|
||||
await executeChannelsList(prefixArg, cmdOpts, opts.forceBoard);
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
cmd
|
||||
.command("list")
|
||||
.description("List board channels")
|
||||
.argument("[prefix]", "Optional channel path prefix (e.g. build/)")
|
||||
.option("--prefix <path>", "Filter board channels by path prefix (e.g. build/)")
|
||||
.action(async (prefixArg: string | undefined, listOpts: ChannelsListOptions) => {
|
||||
await executeChannelsList(prefixArg, listOpts, true);
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
cmd
|
||||
.command("create")
|
||||
.description("Create a board channel")
|
||||
.argument("<path>", "Channel path (e.g. build/auth)")
|
||||
.option("--private", "Create a private channel")
|
||||
.option("--project <id-or-slug>", "Default project ID or slug for this channel")
|
||||
.option("--description <text>", "Channel description")
|
||||
.action(async (channelPath: string, createOpts: ChannelCreateOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(createOpts);
|
||||
const created = await resolved.client.channels.create(channelPath, {
|
||||
...(createOpts.private ? { visibility: "private" as const } : {}),
|
||||
...(createOpts.project ? { defaultProjectId: createOpts.project } : {}),
|
||||
...(createOpts.description !== undefined ? { description: createOpts.description } : {}),
|
||||
});
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(created, null, 2));
|
||||
return;
|
||||
}
|
||||
if (isScriptOutput(resolved)) {
|
||||
console.log(created.path);
|
||||
return;
|
||||
}
|
||||
console.log(pc.green(`Channel #${created.path} (${created.visibility}) ready.`));
|
||||
} catch (err) {
|
||||
handleBoardError(err, createOpts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function registerBoardChannelCommands(program: Command): void {
|
||||
const existingChannels = program.commands.find((c) => c.name() === "channels");
|
||||
if (existingChannels) {
|
||||
throw new Error("Unexpected duplicate 'channels' command before board channel registration");
|
||||
}
|
||||
const channelsCmd = program.command("channels");
|
||||
configureChannelsSubtree(channelsCmd, { forceBoard: false });
|
||||
|
||||
const board = program.commands.find((c) => c.name() === "board") ?? program.command("board").description("Board operator operations");
|
||||
const boardChannelsCmd = board.command("channels");
|
||||
configureChannelsSubtree(boardChannelsCmd, { forceBoard: true });
|
||||
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("post")
|
||||
.description("Post a passive note or structured message to a channel")
|
||||
.argument("<channel>", "Channel path (e.g. deploys/prod)")
|
||||
.argument("[text...]", "Post text (or JSON block when --schema is used)")
|
||||
.option("--title <text>", "Explicit title")
|
||||
.option("--file <path>", "Read message body (or schema JSON) from file or '-' for stdin")
|
||||
.option("--attach <file>", "Attach file(s) to the created post", collectOption, [])
|
||||
.option("--label <k=v>", "Set label(s) (repeatable)", collectOption, [])
|
||||
.option("--schema <ref>", "Attach a validated schema block (<name>@<version>)")
|
||||
.option("--data <json>", "JSON object data for --schema")
|
||||
.option("--board", "Also surface this post on the main Tasks board (scope=board)")
|
||||
.option("--idempotency-key <key>", "Idempotency key for safe retries")
|
||||
.action(async (channel: string, textParts: string[], opts: PostOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const { text, schema } = resolveTextAndSchema({
|
||||
textParts,
|
||||
file: opts.file,
|
||||
schemaRef: opts.schema,
|
||||
dataJson: opts.data,
|
||||
});
|
||||
if ((!text || !text.trim()) && !schema && !opts.title?.trim()) {
|
||||
throw new Error("Post requires message text, --title, --file, or --schema payload.");
|
||||
}
|
||||
const { kvLabels, tagLabels } = parseLabelsList(opts.label);
|
||||
const created = await resolved.client.post(channel, {
|
||||
...(opts.title !== undefined ? { title: opts.title } : {}),
|
||||
...(text !== undefined ? { text } : {}),
|
||||
...(Object.keys(kvLabels).length > 0 ? { labels: kvLabels } : {}),
|
||||
...(tagLabels.length > 0 ? { tagLabels } : {}),
|
||||
...(schema ? { schema } : {}),
|
||||
...(opts.board ? { board: true } : {}),
|
||||
...(opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : {}),
|
||||
});
|
||||
|
||||
if (opts.attach && opts.attach.length > 0) {
|
||||
await resolved.uploadIssueAttachments(created.companyId, created.id, opts.attach);
|
||||
}
|
||||
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(created, null, 2));
|
||||
return;
|
||||
}
|
||||
if (isScriptOutput(resolved)) {
|
||||
console.log(created.identifier);
|
||||
return;
|
||||
}
|
||||
console.log(
|
||||
`${pc.cyan(created.identifier)} #${created.channel ?? channel} ${created.title} ${pc.dim(`(${created.cursor})`)}`,
|
||||
);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("reply")
|
||||
.description("Reply to an existing thread or task")
|
||||
.argument("<id>", "Issue identifier (e.g. PAP-142) or UUID")
|
||||
.argument("[text...]", "Reply text (or JSON block when --schema is used)")
|
||||
.option("--file <path>", "Read reply body (or schema JSON) from file or '-' for stdin")
|
||||
.option("--attach <file>", "Attach file(s) to the thread", collectOption, [])
|
||||
.option("--label <k=v>", "Set comment kv-label(s) (repeatable)", collectOption, [])
|
||||
.option("--schema <ref>", "Attach a validated schema block (<name>@<version>)")
|
||||
.option("--data <json>", "JSON object data for --schema")
|
||||
.option("--after <commentId>", "Optimistic guard: fail with 409 newer_message if newer comments exist")
|
||||
.option("--internal", "Mark reply as internal")
|
||||
.option("--idempotency-key <key>", "Idempotency key for safe retries")
|
||||
.action(async (id: string, textParts: string[], opts: ReplyOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const { text, schema } = resolveTextAndSchema({
|
||||
textParts,
|
||||
file: opts.file,
|
||||
schemaRef: opts.schema,
|
||||
dataJson: opts.data,
|
||||
});
|
||||
if ((!text || !text.trim()) && !schema) {
|
||||
throw new Error("Reply requires message text, --file, or --schema payload.");
|
||||
}
|
||||
const kvLabels = parseKeyValuePairs(opts.label, "--label");
|
||||
const comment = await resolved.client.reply(id, {
|
||||
...(text !== undefined ? { body: text } : {}),
|
||||
...(Object.keys(kvLabels).length > 0 ? { labels: kvLabels } : {}),
|
||||
...(schema ? { schema } : {}),
|
||||
...(opts.after ? { after: opts.after } : {}),
|
||||
...(opts.internal ? { internal: true } : {}),
|
||||
...(opts.idempotencyKey ? { idempotencyKey: opts.idempotencyKey } : {}),
|
||||
});
|
||||
|
||||
if (opts.attach && opts.attach.length > 0) {
|
||||
const companyId = await resolved.resolveCompanyId();
|
||||
await resolved.uploadIssueAttachments(companyId, comment.issueId, opts.attach);
|
||||
}
|
||||
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(comment, null, 2));
|
||||
return;
|
||||
}
|
||||
if (isScriptOutput(resolved)) {
|
||||
console.log(comment.id);
|
||||
return;
|
||||
}
|
||||
console.log(
|
||||
`${pc.cyan(comment.id)} on ${comment.identifier} ${pc.dim(`(${comment.cursor})`)}`,
|
||||
);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("read")
|
||||
.description("Read a channel feed (e.g. build/) or full thread/task (e.g. PAP-142)")
|
||||
.argument("[target]", "Channel path or issue identifier/UUID", "general")
|
||||
.option("--label <expr>", "Filter by label expression (repeatable)", collectOption, [])
|
||||
.option("--status <status>", "Filter by issue status (repeatable or comma-separated)", collectOption, [])
|
||||
.option("--after <cursor>", "Return updates after cursor (evt_...)")
|
||||
.option("-n, --limit <n>", "Maximum number of items", (val) => Number.parseInt(val, 10))
|
||||
.action(async (target: string, opts: ReadOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const statuses = splitCsvValues(opts.status) as Array<
|
||||
"backlog" | "todo" | "in_progress" | "in_review" | "blocked" | "done" | "cancelled"
|
||||
>;
|
||||
const result = await resolved.client.read(target, {
|
||||
...(opts.label && opts.label.length > 0 ? { label: opts.label } : {}),
|
||||
...(statuses.length > 0 ? { status: statuses } : {}),
|
||||
...(opts.after ? { after: opts.after } : {}),
|
||||
...(opts.limit !== undefined && Number.isFinite(opts.limit) ? { limit: opts.limit } : {}),
|
||||
});
|
||||
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
if (result.kind === "channel") {
|
||||
formatReadPage(result, resolved);
|
||||
} else {
|
||||
formatThreadDetail(result, resolved);
|
||||
}
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("label")
|
||||
.description("Atomically set/unset key=value labels with optional compare-and-swap (--if)")
|
||||
.argument("<id>", "Issue identifier (e.g. PAP-50) or UUID")
|
||||
.argument("[kv...]", "Key=value pairs to set")
|
||||
.option("--set <k=v>", "Key=value pair to set (repeatable)", collectOption, [])
|
||||
.option("--unset <key>", "Label key(s) to remove (repeatable)", collectOption, [])
|
||||
.option("--if <k=v>", "CAS precondition: key=value, or key=null / key= when unset (repeatable)", collectOption, [])
|
||||
.option("--if-unset <key>", "CAS precondition: key must currently be unset (repeatable)", collectOption, [])
|
||||
.action(async (id: string, kvArgs: string[], opts: LabelOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const setMap = parseKeyValuePairs([...(opts.set ?? []), ...kvArgs], "label");
|
||||
const ifMap: Record<string, string | null> = {};
|
||||
for (const rawIf of opts.if ?? []) {
|
||||
const eqIdx = rawIf.indexOf("=");
|
||||
if (eqIdx === -1) {
|
||||
throw new Error(`Invalid --if "${rawIf}": expected <key>=<value> or <key>=null`);
|
||||
}
|
||||
const key = rawIf.slice(0, eqIdx).trim();
|
||||
const val = rawIf.slice(eqIdx + 1).trim();
|
||||
if (!key) {
|
||||
throw new Error(`Invalid --if "${rawIf}": key must be non-empty`);
|
||||
}
|
||||
ifMap[key] = val === "" || val === "null" ? null : val;
|
||||
}
|
||||
for (const key of opts.ifUnset ?? []) {
|
||||
const trimmed = key.trim();
|
||||
if (trimmed) {
|
||||
ifMap[trimmed] = null;
|
||||
}
|
||||
}
|
||||
const unsetList = (opts.unset ?? []).map((k) => k.trim()).filter(Boolean);
|
||||
|
||||
if (
|
||||
Object.keys(setMap).length === 0 &&
|
||||
unsetList.length === 0 &&
|
||||
Object.keys(ifMap).length === 0
|
||||
) {
|
||||
throw new Error("Specify at least one <k=v>, --set <k=v>, --unset <key>, --if <k=v>, or --if-unset <key>.");
|
||||
}
|
||||
|
||||
const result = await resolved.client.label(id, {
|
||||
...(Object.keys(setMap).length > 0 ? { set: setMap } : {}),
|
||||
...(unsetList.length > 0 ? { unset: unsetList } : {}),
|
||||
...(Object.keys(ifMap).length > 0 ? { if: ifMap } : {}),
|
||||
});
|
||||
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
const labelSummary = Object.entries(result.kvLabels)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join(" ");
|
||||
console.log(`${pc.cyan(id)} ${labelSummary || pc.dim("(no labels)")} ${pc.dim(`(${result.cursor})`)}`);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import pc from "picocolors";
|
||||
import type { Command } from "commander";
|
||||
import {
|
||||
paperclip,
|
||||
PaperclipError,
|
||||
type CompanyResolutionView,
|
||||
type PaperclipHandle,
|
||||
} from "@paperclipai/shared/sdk";
|
||||
import { getStoredBoardCredential } from "../../client/board-auth.js";
|
||||
import { readContext, resolveProfile } from "../../client/context.js";
|
||||
import { ApiRequestError } from "../../client/http.js";
|
||||
import { inferApiBaseFromConfig, inferContentTypeFromPath, normalizeApiBase } from "../client/common.js";
|
||||
import { detectGitWorkspaceInfo } from "../git-workspace.js";
|
||||
import { readProfileRecord } from "./store.js";
|
||||
|
||||
export interface BoardCommonOptions {
|
||||
apiBase?: string;
|
||||
apiKey?: string;
|
||||
company?: string;
|
||||
companyId?: string;
|
||||
as?: string;
|
||||
config?: string;
|
||||
dataDir?: string;
|
||||
context?: string;
|
||||
quiet?: boolean;
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export interface RepoLocalBoardConfig {
|
||||
source?: "local_context" | "paperclip_json";
|
||||
apiBase?: string;
|
||||
companyId?: string;
|
||||
company?: string;
|
||||
}
|
||||
|
||||
export interface ResolvedBoardClient {
|
||||
client: PaperclipHandle;
|
||||
apiBase: string;
|
||||
apiKey: string | undefined;
|
||||
company: string | undefined;
|
||||
profile: string | null;
|
||||
quiet: boolean;
|
||||
json: boolean;
|
||||
resolveCompanyId: () => Promise<string>;
|
||||
requestJson: <T>(reqPath: string, init?: RequestInit) => Promise<T>;
|
||||
uploadIssueAttachments: (companyId: string, issueId: string, files: string[]) => Promise<unknown[]>;
|
||||
}
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
export function isPcBinary(argv: string[] = process.argv): boolean {
|
||||
if (process.env.PAPERCLIP_CLI_PERSONA === "pc") {
|
||||
return true;
|
||||
}
|
||||
const binPath = argv[1] ?? "";
|
||||
if (!binPath) return false;
|
||||
const binName = path.basename(binPath).replace(/\.(?:js|mjs|cjs|ts)$/i, "");
|
||||
return binName === "pc";
|
||||
}
|
||||
|
||||
export function addBoardClientOptions(
|
||||
command: Command,
|
||||
opts: { includeCompany?: boolean; includeJson?: boolean } = {},
|
||||
): Command {
|
||||
command
|
||||
.option("--api-base <url>", "Base URL for the Paperclip API")
|
||||
.option("--api-key <token>", "Bearer token for board or agent calls")
|
||||
.option("--company <id-or-prefix>", "Company ID or issue prefix (e.g. PAP)")
|
||||
.option("--as <profile>", "Act as a named profile or registered headless agent")
|
||||
.option("-c, --config <path>", "Path to Paperclip config file")
|
||||
.option("-d, --data-dir <path>", "Paperclip data directory root")
|
||||
.option("--context <path>", "Path to CLI context file")
|
||||
.option("-q, --quiet", "Print only minimal identifiers for scripting");
|
||||
|
||||
if (opts.includeCompany !== false) {
|
||||
command.option("-C, --company-id <id>", "Company ID (overrides context default)");
|
||||
}
|
||||
if (opts.includeJson !== false) {
|
||||
command.option("--json", "Output raw JSON");
|
||||
}
|
||||
|
||||
return command;
|
||||
}
|
||||
|
||||
export function readRepoLocalBoardConfig(cwd = process.cwd()): RepoLocalBoardConfig | null {
|
||||
const git = detectGitWorkspaceInfo(cwd);
|
||||
const roots = [
|
||||
...(git ? [git.root] : []),
|
||||
path.resolve(cwd),
|
||||
];
|
||||
const uniqueRoots = [...new Set(roots.map((r) => path.resolve(r)))];
|
||||
|
||||
for (const root of uniqueRoots) {
|
||||
const envHome = process.env.PAPERCLIP_HOME?.trim();
|
||||
if (envHome && path.resolve(envHome) !== path.join(root, ".paperclip", "board")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const localContextPath = path.join(root, ".paperclip", "context.json");
|
||||
if (fs.existsSync(localContextPath)) {
|
||||
try {
|
||||
const profile = resolveProfile(readContext(localContextPath)).profile;
|
||||
if (profile.apiBase || profile.companyId) {
|
||||
return {
|
||||
source: "local_context",
|
||||
apiBase: profile.apiBase,
|
||||
companyId: profile.companyId,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed optional repo context file
|
||||
}
|
||||
}
|
||||
|
||||
const candidate = path.join(root, ".paperclip.json");
|
||||
if (!fs.existsSync(candidate)) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(candidate, "utf8")) as unknown;
|
||||
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
||||
const rec = parsed as Record<string, unknown>;
|
||||
return {
|
||||
source: "paperclip_json",
|
||||
apiBase: typeof rec.apiBase === "string" ? rec.apiBase : undefined,
|
||||
companyId: typeof rec.companyId === "string" ? rec.companyId : undefined,
|
||||
company: typeof rec.company === "string" ? rec.company : undefined,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed optional repo file
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function readTextInput(inlineText?: string, filePath?: string): string | undefined {
|
||||
if (filePath !== undefined) {
|
||||
if (filePath === "-") {
|
||||
return fs.readFileSync(0, "utf8");
|
||||
}
|
||||
return fs.readFileSync(path.resolve(filePath), "utf8");
|
||||
}
|
||||
return inlineText;
|
||||
}
|
||||
|
||||
export function parseJsonArg(raw: string, label = "JSON"): unknown {
|
||||
try {
|
||||
return JSON.parse(raw) as unknown;
|
||||
} catch (err) {
|
||||
throw new Error(`Invalid ${label}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function collectOption(value: string, previous: string[] = []): string[] {
|
||||
return [...previous, value];
|
||||
}
|
||||
|
||||
export function parseLabelsList(rawLabels: string[] | undefined): {
|
||||
kvLabels: Record<string, string>;
|
||||
tagLabels: string[];
|
||||
} {
|
||||
const kvLabels: Record<string, string> = {};
|
||||
const tagLabels: string[] = [];
|
||||
for (const item of rawLabels ?? []) {
|
||||
const trimmed = item.trim();
|
||||
if (!trimmed) continue;
|
||||
const eqIdx = trimmed.indexOf("=");
|
||||
if (eqIdx === -1) {
|
||||
tagLabels.push(trimmed);
|
||||
continue;
|
||||
}
|
||||
const key = trimmed.slice(0, eqIdx).trim();
|
||||
const val = trimmed.slice(eqIdx + 1).trim();
|
||||
if (!key || !val) {
|
||||
throw new Error(`Invalid label "${item}": expected <key>=<value>`);
|
||||
}
|
||||
kvLabels[key] = val;
|
||||
}
|
||||
return { kvLabels, tagLabels };
|
||||
}
|
||||
|
||||
export function parseKeyValuePairs(items: string[] | undefined, flagName = "label"): Record<string, string> {
|
||||
const result: Record<string, string> = {};
|
||||
for (const item of items ?? []) {
|
||||
const eqIdx = item.indexOf("=");
|
||||
if (eqIdx === -1) {
|
||||
throw new Error(`Invalid ${flagName} "${item}": expected <key>=<value>`);
|
||||
}
|
||||
const key = item.slice(0, eqIdx).trim();
|
||||
const val = item.slice(eqIdx + 1).trim();
|
||||
if (!key || !val) {
|
||||
throw new Error(`Invalid ${flagName} "${item}": expected non-empty <key>=<value>`);
|
||||
}
|
||||
result[key] = val;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function splitCsvValues(values: string[] | undefined): string[] {
|
||||
const out: string[] = [];
|
||||
for (const entry of values ?? []) {
|
||||
for (const part of entry.split(",")) {
|
||||
const trimmed = part.trim();
|
||||
if (trimmed) out.push(trimmed);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function parseFetchError(res: Response): Promise<PaperclipError> {
|
||||
const text = await res.text().catch(() => "");
|
||||
let parsed: Record<string, unknown> | null = null;
|
||||
if (text) {
|
||||
try {
|
||||
const raw = JSON.parse(text) as unknown;
|
||||
if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
|
||||
parsed = raw as Record<string, unknown>;
|
||||
}
|
||||
} catch {
|
||||
// plain text
|
||||
}
|
||||
}
|
||||
const nestedDetails =
|
||||
parsed?.details && typeof parsed.details === "object" && !Array.isArray(parsed.details)
|
||||
? (parsed.details as Record<string, unknown>)
|
||||
: null;
|
||||
const code =
|
||||
(typeof parsed?.code === "string" && parsed.code) ||
|
||||
(typeof nestedDetails?.code === "string" && nestedDetails.code) ||
|
||||
(typeof parsed?.error === "string" && parsed.error) ||
|
||||
`http_${res.status}`;
|
||||
const message =
|
||||
(typeof parsed?.message === "string" && parsed.message) ||
|
||||
(typeof parsed?.error === "string" && parsed.error) ||
|
||||
text ||
|
||||
`Request failed with status ${res.status}`;
|
||||
const rawNext = Array.isArray(parsed?.next)
|
||||
? parsed.next
|
||||
: Array.isArray(nestedDetails?.next)
|
||||
? nestedDetails.next
|
||||
: undefined;
|
||||
const next = rawNext?.filter((item): item is string => typeof item === "string");
|
||||
return new PaperclipError({
|
||||
status: res.status,
|
||||
code,
|
||||
message,
|
||||
next,
|
||||
details: parsed ?? undefined,
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveBoardClient(opts: BoardCommonOptions): ResolvedBoardClient {
|
||||
const profile =
|
||||
opts.as !== undefined
|
||||
? opts.as.trim() || null
|
||||
: process.env.PAPERCLIP_PROFILE?.trim() || null;
|
||||
|
||||
const rawStoredProfile = profile ? readProfileRecord(profile) : null;
|
||||
let contextProfile: { apiBase?: string; companyId?: string; apiKeyEnvVarName?: string } = {};
|
||||
try {
|
||||
const context = readContext(opts.context);
|
||||
contextProfile = resolveProfile(context).profile;
|
||||
} catch {
|
||||
// Allow operating even if context file is absent or unreadable
|
||||
}
|
||||
const repoLocal = opts.context || opts.dataDir ? null : readRepoLocalBoardConfig();
|
||||
|
||||
const explicitApiBase = opts.apiBase?.trim();
|
||||
const envApiBase = process.env.PAPERCLIP_API_URL?.trim();
|
||||
const explicitOrRepoApiBase =
|
||||
explicitApiBase ||
|
||||
envApiBase ||
|
||||
repoLocal?.apiBase?.trim() ||
|
||||
undefined;
|
||||
|
||||
const storedProfile =
|
||||
rawStoredProfile &&
|
||||
(!explicitOrRepoApiBase ||
|
||||
!rawStoredProfile.apiBase?.trim() ||
|
||||
normalizeApiBase(rawStoredProfile.apiBase.trim()) === normalizeApiBase(explicitOrRepoApiBase))
|
||||
? rawStoredProfile
|
||||
: null;
|
||||
|
||||
const profileApiBase = storedProfile?.apiBase?.trim();
|
||||
const repoEndpointApiBase =
|
||||
!explicitApiBase &&
|
||||
!envApiBase &&
|
||||
!profileApiBase &&
|
||||
(repoLocal?.source === "paperclip_json" || repoLocal?.source === "local_context")
|
||||
? repoLocal.apiBase?.trim()
|
||||
: undefined;
|
||||
|
||||
const rawApiBase =
|
||||
explicitOrRepoApiBase ||
|
||||
profileApiBase ||
|
||||
contextProfile.apiBase?.trim() ||
|
||||
inferApiBaseFromConfig(opts.config);
|
||||
const apiBase = normalizeApiBase(rawApiBase);
|
||||
|
||||
const sameOrigin = (a?: string, b?: string): boolean => {
|
||||
if (!a || !b) return false;
|
||||
try {
|
||||
return new URL(normalizeApiBase(a)).origin === new URL(normalizeApiBase(b)).origin;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const untrustedRepoEndpoint =
|
||||
Boolean(repoEndpointApiBase) &&
|
||||
!sameOrigin(apiBase, contextProfile.apiBase);
|
||||
|
||||
const explicitAsRequested = opts.as !== undefined && Boolean(opts.as.trim());
|
||||
const explicitFlagKey = opts.apiKey?.trim() || undefined;
|
||||
const envApiKey = process.env.PAPERCLIP_API_KEY?.trim() || undefined;
|
||||
const profileEnvKey = contextProfile.apiKeyEnvVarName
|
||||
? process.env[contextProfile.apiKeyEnvVarName]?.trim() || undefined
|
||||
: undefined;
|
||||
const hasOriginlessProfileKey = Boolean(
|
||||
storedProfile?.apiKey && !storedProfile.apiBase,
|
||||
);
|
||||
const trustedProfileKey =
|
||||
storedProfile?.apiKey &&
|
||||
((storedProfile.apiBase && sameOrigin(storedProfile.apiBase, apiBase)) ||
|
||||
(!storedProfile.apiBase && !untrustedRepoEndpoint))
|
||||
? storedProfile.apiKey
|
||||
: undefined;
|
||||
const storedBoardKey = getStoredBoardCredential(apiBase)?.token;
|
||||
|
||||
if (
|
||||
untrustedRepoEndpoint &&
|
||||
!explicitFlagKey &&
|
||||
(envApiKey || profileEnvKey || hasOriginlessProfileKey)
|
||||
) {
|
||||
throw new Error(
|
||||
`Refusing to send ambient credentials to untrusted ${repoLocal?.source === "local_context" ? ".paperclip/context.json" : ".paperclip.json"} apiBase '${apiBase}'. Pass --api-base or --api-key explicitly if you trust this endpoint.`,
|
||||
);
|
||||
}
|
||||
|
||||
const ambientKey = untrustedRepoEndpoint ? undefined : (envApiKey ?? profileEnvKey);
|
||||
const apiKey =
|
||||
explicitFlagKey ??
|
||||
(explicitAsRequested
|
||||
? (trustedProfileKey ?? storedBoardKey ?? ambientKey)
|
||||
: (ambientKey ?? trustedProfileKey ?? storedBoardKey));
|
||||
|
||||
const repoLocalMatchesApiBase =
|
||||
!repoLocal?.apiBase?.trim() || normalizeApiBase(repoLocal.apiBase.trim()) === apiBase;
|
||||
const contextMatchesApiBase =
|
||||
!contextProfile.apiBase?.trim() || normalizeApiBase(contextProfile.apiBase.trim()) === apiBase;
|
||||
|
||||
const company =
|
||||
opts.company?.trim() ||
|
||||
opts.companyId?.trim() ||
|
||||
process.env.PAPERCLIP_COMPANY_ID?.trim() ||
|
||||
storedProfile?.companyId?.trim() ||
|
||||
(repoLocalMatchesApiBase ? repoLocal?.companyId?.trim() || repoLocal?.company?.trim() : undefined) ||
|
||||
(contextMatchesApiBase ? contextProfile.companyId?.trim() : undefined) ||
|
||||
undefined;
|
||||
|
||||
const buildHeaders = (initHeaders?: HeadersInit): Headers => {
|
||||
const headers = new Headers(initHeaders);
|
||||
if (apiKey && !headers.has("authorization")) {
|
||||
headers.set("authorization", `Bearer ${apiKey}`);
|
||||
}
|
||||
if (profile && !storedProfile?.apiKey && !headers.has("x-paperclip-actor-profile")) {
|
||||
headers.set("x-paperclip-actor-profile", profile);
|
||||
}
|
||||
return headers;
|
||||
};
|
||||
|
||||
const requestJson = async <T>(reqPath: string, init: RequestInit = {}): Promise<T> => {
|
||||
const url = `${apiBase}${reqPath.startsWith("/") ? reqPath : `/${reqPath}`}`;
|
||||
const headers = buildHeaders(init.headers);
|
||||
if (init.body !== undefined && typeof init.body === "string" && !headers.has("content-type")) {
|
||||
headers.set("content-type", "application/json");
|
||||
}
|
||||
if (!headers.has("accept")) {
|
||||
headers.set("accept", "application/json");
|
||||
}
|
||||
const res = await fetch(url, { ...init, headers });
|
||||
if (!res.ok) {
|
||||
throw await parseFetchError(res);
|
||||
}
|
||||
if (res.status === 204) {
|
||||
return null as T;
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
};
|
||||
|
||||
let cachedCompanyId: string | null = null;
|
||||
const resolveCompanyId = async (): Promise<string> => {
|
||||
if (cachedCompanyId) return cachedCompanyId;
|
||||
if (company && UUID_RE.test(company)) {
|
||||
cachedCompanyId = company.toLowerCase();
|
||||
return cachedCompanyId;
|
||||
}
|
||||
const qs = company ? `?company=${encodeURIComponent(company)}` : "";
|
||||
const resolved = await requestJson<CompanyResolutionView>(`/api/companies/resolve-default${qs}`, {
|
||||
method: "GET",
|
||||
});
|
||||
cachedCompanyId = resolved.id;
|
||||
return resolved.id;
|
||||
};
|
||||
|
||||
const uploadIssueAttachments = async (
|
||||
resolvedCompanyId: string,
|
||||
issueId: string,
|
||||
files: string[],
|
||||
): Promise<unknown[]> => {
|
||||
const uploaded: unknown[] = [];
|
||||
for (const filePath of files) {
|
||||
const resolvedPath = path.resolve(filePath);
|
||||
const bytes = fs.readFileSync(resolvedPath);
|
||||
const form = new FormData();
|
||||
const mimeType = inferContentTypeFromPath(resolvedPath) ?? "application/octet-stream";
|
||||
form.set("file", new Blob([bytes], { type: mimeType }), path.basename(resolvedPath));
|
||||
const url = `${apiBase}/api/companies/${encodeURIComponent(resolvedCompanyId)}/issues/${encodeURIComponent(issueId)}/attachments`;
|
||||
const headers = buildHeaders();
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: form,
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw await parseFetchError(res);
|
||||
}
|
||||
uploaded.push(await res.json());
|
||||
}
|
||||
return uploaded;
|
||||
};
|
||||
|
||||
// Pass a non-existent homeDir only when storedProfile wasn't used, or pass explicit apiKey/profile:
|
||||
// Note: when storedProfile?.apiKey was found in store.ts, we already placed it in apiKey above!
|
||||
const client = paperclip({
|
||||
apiBase,
|
||||
apiKey,
|
||||
company,
|
||||
profile: storedProfile?.apiKey ? null : profile,
|
||||
});
|
||||
|
||||
return {
|
||||
client,
|
||||
apiBase,
|
||||
apiKey,
|
||||
company,
|
||||
profile,
|
||||
quiet: Boolean(opts.quiet),
|
||||
json: Boolean(opts.json),
|
||||
resolveCompanyId,
|
||||
requestJson,
|
||||
uploadIssueAttachments,
|
||||
};
|
||||
}
|
||||
|
||||
export function isScriptOutput(opts: { quiet?: boolean; json?: boolean }): boolean {
|
||||
return !opts.json && (Boolean(opts.quiet) || !process.stdout.isTTY);
|
||||
}
|
||||
|
||||
export function handleBoardError(error: unknown, opts: { json?: boolean } = {}): never {
|
||||
let code = "cli_error";
|
||||
let message = error instanceof Error ? error.message : String(error);
|
||||
let next: string[] | undefined;
|
||||
|
||||
if (error instanceof PaperclipError) {
|
||||
code = error.code;
|
||||
message = error.message;
|
||||
next = error.next;
|
||||
} else if (error instanceof ApiRequestError) {
|
||||
code = `http_${error.status}`;
|
||||
message = error.message;
|
||||
}
|
||||
|
||||
if (opts.json) {
|
||||
console.error(
|
||||
JSON.stringify({
|
||||
error: code,
|
||||
message,
|
||||
...(next && next.length > 0 ? { next } : {}),
|
||||
}),
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.error(pc.red(`Error (${code}): ${message}`));
|
||||
if (next && next.length > 0) {
|
||||
for (const suggestion of next) {
|
||||
console.error(pc.dim(` next: ${suggestion}`));
|
||||
}
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
import pc from "picocolors";
|
||||
import type { Command } from "commander";
|
||||
import type { BoardEventType, BoardEventView } from "@paperclipai/shared/sdk";
|
||||
import {
|
||||
addBoardClientOptions,
|
||||
collectOption,
|
||||
handleBoardError,
|
||||
isScriptOutput,
|
||||
resolveBoardClient,
|
||||
splitCsvValues,
|
||||
type BoardCommonOptions,
|
||||
} from "./client.js";
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const ISSUE_ID_RE = /^[A-Z][A-Z0-9]*-\d+$/i;
|
||||
|
||||
interface ScheduleOptions extends BoardCommonOptions {
|
||||
in?: string;
|
||||
at?: string;
|
||||
every?: string;
|
||||
until?: string;
|
||||
post?: boolean;
|
||||
target?: string;
|
||||
}
|
||||
|
||||
interface SchedulesListOptions extends BoardCommonOptions {
|
||||
target?: string;
|
||||
}
|
||||
|
||||
interface TailOptions extends BoardCommonOptions {
|
||||
event?: string[];
|
||||
label?: string[];
|
||||
mentions?: string | boolean;
|
||||
after?: string;
|
||||
}
|
||||
|
||||
interface WaitOptions extends TailOptions {
|
||||
timeout?: string;
|
||||
}
|
||||
|
||||
function isIssueRef(target: string): boolean {
|
||||
const trimmed = target.trim();
|
||||
return UUID_RE.test(trimmed) || ISSUE_ID_RE.test(trimmed);
|
||||
}
|
||||
|
||||
function formatEventLine(evt: BoardEventView): string {
|
||||
const where = evt.identifier ?? (evt.channel ? `#${evt.channel}` : evt.companyId.slice(0, 8));
|
||||
const actor = evt.actor.profile ?? evt.actor.name ?? evt.actor.type;
|
||||
return `${pc.dim(`[${evt.cursor}]`)} ${pc.cyan(evt.type)} ${where} ${pc.dim(`by ${actor}`)}`;
|
||||
}
|
||||
|
||||
async function runSchedulesList(opts: SchedulesListOptions): Promise<void> {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const list = await resolved.client.schedules.list(
|
||||
opts.target ? { target: opts.target } : undefined,
|
||||
);
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(list, null, 2));
|
||||
return;
|
||||
}
|
||||
if (list.length === 0) {
|
||||
console.log(pc.dim("(no schedules)"));
|
||||
return;
|
||||
}
|
||||
for (const item of list) {
|
||||
console.log(
|
||||
` ${pc.cyan(item.id)} [${item.status}] ${item.target} next=${item.nextRunAt} ${item.message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function runScheduleCancel(id: string, opts: BoardCommonOptions): Promise<void> {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const res = await resolved.client.schedules.cancel(id);
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(res, null, 2));
|
||||
return;
|
||||
}
|
||||
console.log(`${pc.yellow("Cancelled")} schedule ${id}`);
|
||||
}
|
||||
|
||||
export function registerBoardEventCommands(program: Command): void {
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("schedule")
|
||||
.description("Schedule a delayed/recurring board post or task monitor wakeup (or 'list' / 'cancel <id>')")
|
||||
.argument("[args...]", "<target> <message...>, or 'list' / 'cancel <id>'")
|
||||
.option("--in <dur>", "Relative delay (e.g. 5m, 2h)")
|
||||
.option("--at <iso>", "Absolute ISO-8601 timestamp")
|
||||
.option("--every <dur>", "Recurring interval (e.g. 1d, 30m)")
|
||||
.option("--until <iso>", "End ISO-8601 timestamp for recurring schedules")
|
||||
.option("--post", "Post as a message rather than only a monitor wakeup")
|
||||
.option("--target <target>", "Filter target when listing schedules")
|
||||
.action(async (args: string[], opts: ScheduleOptions) => {
|
||||
try {
|
||||
const hasScheduleTiming = Boolean(opts.in || opts.at || opts.every);
|
||||
if (args.length === 0 || (args[0] === "list" && !hasScheduleTiming)) {
|
||||
await runSchedulesList({
|
||||
...opts,
|
||||
target: opts.target ?? args[1],
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (args[0] === "cancel" && !hasScheduleTiming) {
|
||||
const scheduleId = args[1]?.trim();
|
||||
if (!scheduleId) {
|
||||
throw new Error("Usage: pc schedule cancel <schedule-id>");
|
||||
}
|
||||
await runScheduleCancel(scheduleId, opts);
|
||||
return;
|
||||
}
|
||||
|
||||
const target = args[0]?.trim();
|
||||
const message = args.slice(1).join(" ").trim();
|
||||
if (!target || !message) {
|
||||
throw new Error(
|
||||
"Usage: pc schedule <target> <message> --in <dur>|--at <iso>|--every <dur> (or 'pc schedule list' / 'pc schedule cancel <id>')",
|
||||
);
|
||||
}
|
||||
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const created = await resolved.client.schedule(target, {
|
||||
message,
|
||||
...(opts.in !== undefined ? { in: opts.in } : {}),
|
||||
...(opts.at !== undefined ? { at: opts.at } : {}),
|
||||
...(opts.every !== undefined ? { every: opts.every } : {}),
|
||||
...(opts.until !== undefined ? { until: opts.until } : {}),
|
||||
...(opts.post ? { post: true } : {}),
|
||||
});
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(created, null, 2));
|
||||
return;
|
||||
}
|
||||
if (isScriptOutput(resolved)) {
|
||||
console.log(created.id);
|
||||
return;
|
||||
}
|
||||
const cursorSuffix = created.cursor ? `, cursor=${created.cursor}` : "";
|
||||
console.log(
|
||||
`${pc.green("Scheduled")} ${pc.cyan(created.id)} on ${created.target} (nextRunAt=${created.nextRunAt}${cursorSuffix})`,
|
||||
);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const schedules = addBoardClientOptions(
|
||||
program
|
||||
.command("schedules")
|
||||
.description("List and cancel board schedules")
|
||||
.option("--target <target>", "Filter by target channel or issue")
|
||||
.action(async (opts: SchedulesListOptions) => {
|
||||
try {
|
||||
await runSchedulesList(opts);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
schedules
|
||||
.command("list")
|
||||
.description("List scheduled posts and monitors")
|
||||
.option("--target <target>", "Filter by target channel or issue")
|
||||
.action(async (opts: SchedulesListOptions) => {
|
||||
try {
|
||||
await runSchedulesList(opts);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
schedules
|
||||
.command("cancel")
|
||||
.description("Cancel a scheduled post or monitor")
|
||||
.argument("<id>", "Schedule ID")
|
||||
.action(async (id: string, opts: BoardCommonOptions) => {
|
||||
try {
|
||||
await runScheduleCancel(id, opts);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("tail")
|
||||
.description("Stream live board events over SSE until interrupted")
|
||||
.argument("[target]", "Optional channel path or issue identifier/UUID")
|
||||
.option("--event <csv>", "Filter by event type(s)", collectOption, [])
|
||||
.option("--label <expr>", "Filter by label expression (repeatable)", collectOption, [])
|
||||
.option("--mentions [handle]", "Filter for mentions of handle (or active profile)")
|
||||
.option("--after <cursor>", "Replay events after cursor (evt_0 for all history; defaults to live from now)")
|
||||
.action(async (target: string | undefined, opts: TailOptions) => {
|
||||
const ac = new AbortController();
|
||||
const onSig = () => ac.abort();
|
||||
process.once("SIGINT", onSig);
|
||||
process.once("SIGTERM", onSig);
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const eventTypes = splitCsvValues(opts.event) as BoardEventType[];
|
||||
const mentionsHandle =
|
||||
typeof opts.mentions === "string"
|
||||
? opts.mentions
|
||||
: opts.mentions === true
|
||||
? resolved.profile ?? "@me"
|
||||
: undefined;
|
||||
|
||||
const filters = {
|
||||
...(target
|
||||
? isIssueRef(target)
|
||||
? { issueId: target }
|
||||
: { channel: target }
|
||||
: {}),
|
||||
...(eventTypes.length > 0 ? { event: eventTypes } : {}),
|
||||
...(opts.label && opts.label.length > 0 ? { label: opts.label } : {}),
|
||||
...(mentionsHandle ? { mentions: mentionsHandle } : {}),
|
||||
...(opts.after ? { after: opts.after } : {}),
|
||||
};
|
||||
|
||||
for await (const evt of resolved.client.events(filters, { signal: ac.signal })) {
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(evt));
|
||||
} else {
|
||||
console.log(formatEventLine(evt));
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (!ac.signal.aborted) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
} finally {
|
||||
process.removeListener("SIGINT", onSig);
|
||||
process.removeListener("SIGTERM", onSig);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("wait")
|
||||
.description("Block until a matching board event arrives (with cursor replay)")
|
||||
.argument("[target]", "Optional channel path or issue identifier/UUID")
|
||||
.option("--event <csv>", "Filter by event type(s)", collectOption, [])
|
||||
.option("--label <expr>", "Filter by label expression (repeatable)", collectOption, [])
|
||||
.option("--mentions [handle]", "Filter for mentions of handle (or active profile)")
|
||||
.option("--after <cursor>", "Replay events after cursor (evt_0 for all history; defaults to live from now)")
|
||||
.option("--timeout <dur>", "Maximum wait duration (e.g. 30m, 10s)", "30m")
|
||||
.action(async (target: string | undefined, opts: WaitOptions) => {
|
||||
let timedOut = false;
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const eventTypes = splitCsvValues(opts.event) as BoardEventType[];
|
||||
const mentionsHandle =
|
||||
typeof opts.mentions === "string"
|
||||
? opts.mentions
|
||||
: opts.mentions === true
|
||||
? resolved.profile ?? "@me"
|
||||
: undefined;
|
||||
|
||||
const evt = await resolved.client.wait(
|
||||
target,
|
||||
{
|
||||
...(eventTypes.length > 0 ? { event: eventTypes } : {}),
|
||||
...(opts.label && opts.label.length > 0 ? { label: opts.label } : {}),
|
||||
...(mentionsHandle ? { mentions: mentionsHandle } : {}),
|
||||
...(opts.after ? { after: opts.after } : {}),
|
||||
...(opts.timeout ? { timeout: opts.timeout } : {}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!evt) {
|
||||
if (resolved.json) {
|
||||
console.error(
|
||||
JSON.stringify({
|
||||
error: "timeout",
|
||||
reason: "timeout",
|
||||
message: "Timed out waiting for matching board event",
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
console.error(pc.yellow("Timed out waiting for matching board event."));
|
||||
}
|
||||
timedOut = true;
|
||||
} else if (resolved.json) {
|
||||
console.log(JSON.stringify(evt, null, 2));
|
||||
} else if (isScriptOutput(resolved)) {
|
||||
console.log(evt.cursor);
|
||||
} else {
|
||||
console.log(formatEventLine(evt));
|
||||
}
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
if (timedOut) {
|
||||
process.exit(1);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Command } from "commander";
|
||||
import { registerBoardChannelCommands } from "./channels.js";
|
||||
import { registerBoardEventCommands } from "./events.js";
|
||||
import { registerBoardInteractionCommands } from "./interactions.js";
|
||||
import { registerBoardSchemaCommands } from "./schemas.js";
|
||||
import { registerBoardTaskCommands } from "./tasks.js";
|
||||
|
||||
export function registerBoardCommands(program: Command): void {
|
||||
registerBoardChannelCommands(program);
|
||||
registerBoardTaskCommands(program);
|
||||
registerBoardInteractionCommands(program);
|
||||
registerBoardSchemaCommands(program);
|
||||
registerBoardEventCommands(program);
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import pc from "picocolors";
|
||||
import type { Command } from "commander";
|
||||
import {
|
||||
addBoardClientOptions,
|
||||
collectOption,
|
||||
handleBoardError,
|
||||
isScriptOutput,
|
||||
resolveBoardClient,
|
||||
splitCsvValues,
|
||||
type BoardCommonOptions,
|
||||
} from "./client.js";
|
||||
import { deleteClaimRecord, resolveClaimCredentials } from "./store.js";
|
||||
|
||||
interface AskOptions extends BoardCommonOptions {
|
||||
choice?: string[];
|
||||
choices?: string[];
|
||||
human?: boolean;
|
||||
humanOnly?: boolean;
|
||||
agent?: string;
|
||||
}
|
||||
|
||||
interface ConfirmOptions extends BoardCommonOptions {
|
||||
human?: boolean;
|
||||
humanOnly?: boolean;
|
||||
wakeOnAccept?: boolean;
|
||||
}
|
||||
|
||||
interface ApproveOptions extends BoardCommonOptions {
|
||||
answer?: string;
|
||||
note?: string;
|
||||
interactionId?: string;
|
||||
}
|
||||
|
||||
interface RejectOptions extends BoardCommonOptions {
|
||||
reason?: string;
|
||||
note?: string;
|
||||
interactionId?: string;
|
||||
}
|
||||
|
||||
export function registerBoardInteractionCommands(program: Command): void {
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("ask")
|
||||
.description("Ask a question on a thread/task (moves to blocked and releases pool lease)")
|
||||
.argument("<id>", "Issue identifier (e.g. PAP-14) or UUID")
|
||||
.argument("<question>", "Question prompt")
|
||||
.option("--choices <csv>", "Comma-separated answer choices (repeatable)", collectOption, [])
|
||||
.option("--choice <csv>", "Alias for --choices", collectOption, [])
|
||||
.option("--human-only", "Require human resolution (resolverPolicy=human_only)")
|
||||
.option("--human", "Alias for --human-only")
|
||||
.option("--agent <id>", "Target agent ID or handle")
|
||||
.action(async (id: string, question: string, opts: AskOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const companyId = await resolved.resolveCompanyId();
|
||||
const claim = resolveClaimCredentials({
|
||||
companyId,
|
||||
issueRef: id,
|
||||
activeProfile: resolved.profile,
|
||||
requireClaim: false,
|
||||
});
|
||||
const mergedChoices = splitCsvValues([...(opts.choices ?? []), ...(opts.choice ?? [])]);
|
||||
const humanOnly = Boolean(opts.humanOnly || opts.human);
|
||||
const interaction = await resolved.client.ask(id, question, {
|
||||
...(mergedChoices.length > 0 ? { choices: mergedChoices } : {}),
|
||||
...(humanOnly ? { humanOnly: true } : {}),
|
||||
...(opts.agent ? { agent: opts.agent } : {}),
|
||||
...(claim ? { claimToken: claim.claimToken } : {}),
|
||||
});
|
||||
if (claim?.source === "store") {
|
||||
deleteClaimRecord(companyId, id);
|
||||
}
|
||||
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(interaction, null, 2));
|
||||
return;
|
||||
}
|
||||
if (isScriptOutput(resolved)) {
|
||||
console.log(interaction.id);
|
||||
return;
|
||||
}
|
||||
console.log(
|
||||
`${pc.cyan(interaction.identifier)} asked (${interaction.id}) ${pc.dim(`status=${interaction.status}`)}`,
|
||||
);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("confirm")
|
||||
.description("Request confirmation on a thread/task (moves to blocked and releases pool lease)")
|
||||
.argument("<id>", "Issue identifier (e.g. PAP-14) or UUID")
|
||||
.argument("<prompt>", "Confirmation prompt")
|
||||
.option("--human-only", "Require human resolution (resolverPolicy=human_only)")
|
||||
.option("--human", "Alias for --human-only")
|
||||
.option("--wake-on-accept", "Wake assignee when accepted")
|
||||
.action(async (id: string, prompt: string, opts: ConfirmOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const companyId = await resolved.resolveCompanyId();
|
||||
const claim = resolveClaimCredentials({
|
||||
companyId,
|
||||
issueRef: id,
|
||||
activeProfile: resolved.profile,
|
||||
requireClaim: false,
|
||||
});
|
||||
const humanOnly = Boolean(opts.humanOnly || opts.human);
|
||||
const interaction = await resolved.client.confirm(id, prompt, {
|
||||
...(humanOnly ? { humanOnly: true } : {}),
|
||||
...(opts.wakeOnAccept ? { wakeOnAccept: true } : {}),
|
||||
...(claim ? { claimToken: claim.claimToken } : {}),
|
||||
});
|
||||
if (claim?.source === "store") {
|
||||
deleteClaimRecord(companyId, id);
|
||||
}
|
||||
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(interaction, null, 2));
|
||||
return;
|
||||
}
|
||||
if (isScriptOutput(resolved)) {
|
||||
console.log(interaction.id);
|
||||
return;
|
||||
}
|
||||
console.log(
|
||||
`${pc.cyan(interaction.identifier)} confirmation (${interaction.id}) ${pc.dim(`status=${interaction.status}`)}`,
|
||||
);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("approve")
|
||||
.description("Approve or answer a pending confirmation or question on an issue")
|
||||
.argument("<id>", "Issue identifier (e.g. PAP-14) or UUID")
|
||||
.argument("[answer...]", "Optional answer or approval note")
|
||||
.option("--answer <text>", "Answer text for a pending question")
|
||||
.option("--note <text>", "Optional approval note")
|
||||
.option("--interaction-id <id>", "Specific interaction ID to resolve")
|
||||
.action(async (id: string, answerParts: string[], opts: ApproveOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const positional = answerParts.length > 0 ? answerParts.join(" ") : undefined;
|
||||
const answer = opts.answer ?? positional;
|
||||
const interaction = await resolved.client.approve(id, {
|
||||
...(answer !== undefined ? { answer } : {}),
|
||||
...(opts.note !== undefined ? { note: opts.note } : {}),
|
||||
...(opts.interactionId ? { interactionId: opts.interactionId } : {}),
|
||||
});
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(interaction, null, 2));
|
||||
return;
|
||||
}
|
||||
console.log(
|
||||
`${pc.green("Approved")} ${pc.cyan(interaction.identifier)} (${interaction.id})`,
|
||||
);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
program
|
||||
.command("reject")
|
||||
.description("Reject a pending confirmation or question on an issue")
|
||||
.argument("<id>", "Issue identifier (e.g. PAP-14) or UUID")
|
||||
.argument("[reason...]", "Optional rejection reason")
|
||||
.option("--reason <text>", "Rejection reason")
|
||||
.option("--note <text>", "Alias for --reason")
|
||||
.option("--interaction-id <id>", "Specific interaction ID to resolve")
|
||||
.action(async (id: string, reasonParts: string[], opts: RejectOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const positional = reasonParts.length > 0 ? reasonParts.join(" ") : undefined;
|
||||
const reason = opts.reason ?? opts.note ?? positional;
|
||||
const interaction = await resolved.client.reject(id, {
|
||||
...(reason !== undefined ? { reason } : {}),
|
||||
...(opts.interactionId ? { interactionId: opts.interactionId } : {}),
|
||||
});
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(interaction, null, 2));
|
||||
return;
|
||||
}
|
||||
console.log(
|
||||
`${pc.yellow("Rejected")} ${pc.cyan(interaction.identifier)} (${interaction.id})`,
|
||||
);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import pc from "picocolors";
|
||||
import type { Command } from "commander";
|
||||
import {
|
||||
addBoardClientOptions,
|
||||
handleBoardError,
|
||||
isScriptOutput,
|
||||
parseJsonArg,
|
||||
readTextInput,
|
||||
resolveBoardClient,
|
||||
type BoardCommonOptions,
|
||||
} from "./client.js";
|
||||
|
||||
interface SchemaCreateOptions extends BoardCommonOptions {
|
||||
file?: string;
|
||||
data?: string;
|
||||
schema?: string;
|
||||
version?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
async function runSchemasList(opts: BoardCommonOptions): Promise<void> {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const items = await resolved.client.schemas.list();
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(items, null, 2));
|
||||
return;
|
||||
}
|
||||
if (items.length === 0) {
|
||||
console.log(pc.dim("(no schemas)"));
|
||||
return;
|
||||
}
|
||||
for (const item of items) {
|
||||
const origin = item.builtIn ? pc.dim(" [built-in]") : "";
|
||||
const desc = item.description ? pc.dim(` — ${item.description}`) : "";
|
||||
console.log(` ${pc.cyan(item.ref)}${origin}${desc}`);
|
||||
}
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}
|
||||
|
||||
export function registerBoardSchemaCommands(program: Command): void {
|
||||
const schemas = addBoardClientOptions(
|
||||
program
|
||||
.command("schemas")
|
||||
.description("List, inspect, and register versioned JSON schemas")
|
||||
.action(async (opts: BoardCommonOptions) => {
|
||||
await runSchemasList(opts);
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
schemas
|
||||
.command("list")
|
||||
.description("List available schemas for the company")
|
||||
.action(async (opts: BoardCommonOptions) => {
|
||||
await runSchemasList(opts);
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
schemas
|
||||
.command("inspect")
|
||||
.alias("get")
|
||||
.description("Inspect a schema definition by <name>@<version>")
|
||||
.argument("<ref>", "Schema reference (e.g. finding@1)")
|
||||
.action(async (ref: string, opts: BoardCommonOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const schema = await resolved.client.schemas.get(ref);
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(schema, null, 2));
|
||||
return;
|
||||
}
|
||||
console.log(pc.cyan(pc.bold(schema.ref)) + (schema.builtIn ? pc.dim(" [built-in]") : ""));
|
||||
if (schema.description) console.log(pc.dim(schema.description));
|
||||
console.log(JSON.stringify(schema.jsonSchema, null, 2));
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
addBoardClientOptions(
|
||||
schemas
|
||||
.command("create")
|
||||
.description("Register an immutable schema version (<name>@<version>)")
|
||||
.argument("<ref>", "Schema reference (<name>@<version> or <name> with --version)")
|
||||
.option("--version <n>", "Schema version number when omitted from <ref>")
|
||||
.option("--file <path>", "Path to JSON schema file or '-' for stdin")
|
||||
.option("--data <json>", "Inline JSON schema object")
|
||||
.option("--schema <json>", "Alias for --data '<json>'")
|
||||
.option("--description <text>", "Schema description")
|
||||
.action(async (rawRef: string, opts: SchemaCreateOptions) => {
|
||||
try {
|
||||
const resolved = resolveBoardClient(opts);
|
||||
const trimmedRef = rawRef.trim();
|
||||
const effectiveRef = trimmedRef.includes("@")
|
||||
? trimmedRef
|
||||
: opts.version
|
||||
? `${trimmedRef}@${opts.version.trim()}`
|
||||
: trimmedRef;
|
||||
const rawJson = opts.data ?? opts.schema ?? readTextInput(undefined, opts.file);
|
||||
if (!rawJson) {
|
||||
throw new Error("Provide a JSON schema via --schema '<json>', --data '<json>', or --file <path|->.");
|
||||
}
|
||||
const parsed = parseJsonArg(rawJson, "JSON schema");
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
||||
throw new Error("Schema definition must be a JSON object.");
|
||||
}
|
||||
const result = await resolved.client.schemas.create({
|
||||
ref: effectiveRef,
|
||||
jsonSchema: parsed as Record<string, unknown>,
|
||||
...(opts.description !== undefined ? { description: opts.description } : {}),
|
||||
});
|
||||
if (resolved.json) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
if (isScriptOutput(resolved)) {
|
||||
console.log(result.schema.ref);
|
||||
return;
|
||||
}
|
||||
const verb = result.created ? "Registered" : "Already registered (identical)";
|
||||
console.log(`${pc.green(verb)} ${pc.cyan(result.schema.ref)}`);
|
||||
} catch (err) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { PaperclipError } from "@paperclipai/shared/sdk";
|
||||
import { resolvePaperclipHomeDir } from "../../config/home.js";
|
||||
import { detectGitWorkspaceInfo } from "../git-workspace.js";
|
||||
|
||||
function resolveEffectiveStoreHome(homeDir?: string): string {
|
||||
if (homeDir) return homeDir;
|
||||
if (process.env.PAPERCLIP_HOME?.trim()) {
|
||||
return resolvePaperclipHomeDir();
|
||||
}
|
||||
const git = detectGitWorkspaceInfo(process.cwd());
|
||||
const roots = Array.from(new Set([...(git ? [git.root] : []), path.resolve(process.cwd())]));
|
||||
for (const root of roots) {
|
||||
const localPaperclipDir = path.join(root, ".paperclip");
|
||||
if (fs.existsSync(path.join(localPaperclipDir, "context.json"))) {
|
||||
return localPaperclipDir;
|
||||
}
|
||||
}
|
||||
return resolvePaperclipHomeDir();
|
||||
}
|
||||
|
||||
export interface StoredAgentProfileRecord {
|
||||
agentId: string;
|
||||
agentName: string;
|
||||
companyId: string;
|
||||
apiBase: string;
|
||||
apiKey: string;
|
||||
role?: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface StoredClaimRecord {
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
identifier: string;
|
||||
claimToken: string;
|
||||
claimEpoch: number;
|
||||
leaseExpiresAt: string;
|
||||
profile: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ResolvedClaimCredentials {
|
||||
claimToken: string;
|
||||
claimEpoch?: number;
|
||||
issueId?: string;
|
||||
identifier?: string;
|
||||
source: "env" | "store";
|
||||
}
|
||||
|
||||
function sanitizeSegment(raw: string, label: string): string {
|
||||
const trimmed = raw.trim();
|
||||
const safe = trimmed.replace(/[^a-zA-Z0-9._-]/g, "");
|
||||
if (!safe || safe === "." || safe === ".." || safe !== trimmed) {
|
||||
throw new Error(`Invalid ${label} "${raw}" for local credential storage.`);
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
|
||||
function sanitizeFilename(raw: string): string {
|
||||
const safe = raw.trim().replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
if (!safe || safe === "." || safe === "..") {
|
||||
throw new Error(`Invalid identifier "${raw}" for local storage.`);
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
|
||||
function writeSecureJson(filePath: string, data: unknown): void {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
|
||||
try {
|
||||
fs.chmodSync(filePath, 0o600);
|
||||
} catch {
|
||||
// Best-effort on non-POSIX filesystems
|
||||
}
|
||||
}
|
||||
|
||||
function readJsonOrNull<T>(filePath: string): T | null {
|
||||
if (!fs.existsSync(filePath)) return null;
|
||||
try {
|
||||
const raw = fs.readFileSync(filePath, "utf8");
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
return typeof parsed === "object" && parsed !== null ? (parsed as T) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveProfileStorePath(profileName: string, homeDir?: string): string {
|
||||
const baseHome = resolveEffectiveStoreHome(homeDir);
|
||||
const safeName = sanitizeSegment(profileName, "profile name");
|
||||
return path.join(baseHome, "profiles", `${safeName}.json`);
|
||||
}
|
||||
|
||||
export function readProfileRecord(
|
||||
profileName: string,
|
||||
homeDir?: string,
|
||||
): StoredAgentProfileRecord | null {
|
||||
try {
|
||||
const filePath = resolveProfileStorePath(profileName, homeDir);
|
||||
const parsed = readJsonOrNull<Partial<StoredAgentProfileRecord>>(filePath);
|
||||
if (!parsed) return null;
|
||||
const apiKey =
|
||||
(typeof parsed.apiKey === "string" && parsed.apiKey) ||
|
||||
((parsed as Record<string, unknown>).agent_api_key as string | undefined) ||
|
||||
((parsed as Record<string, unknown>).agentApiKey as string | undefined);
|
||||
if (!apiKey) return null;
|
||||
return {
|
||||
agentId: typeof parsed.agentId === "string" ? parsed.agentId : "",
|
||||
agentName: typeof parsed.agentName === "string" ? parsed.agentName : profileName,
|
||||
companyId: typeof parsed.companyId === "string" ? parsed.companyId : "",
|
||||
apiBase: typeof parsed.apiBase === "string" ? parsed.apiBase : "",
|
||||
apiKey,
|
||||
...(typeof parsed.role === "string" ? { role: parsed.role } : {}),
|
||||
...(typeof parsed.createdAt === "string" ? { createdAt: parsed.createdAt } : {}),
|
||||
...(typeof parsed.updatedAt === "string" ? { updatedAt: parsed.updatedAt } : {}),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function writeProfileRecord(
|
||||
profileName: string,
|
||||
record: StoredAgentProfileRecord,
|
||||
homeDir?: string,
|
||||
): string {
|
||||
const filePath = resolveProfileStorePath(profileName, homeDir);
|
||||
const now = new Date().toISOString();
|
||||
writeSecureJson(filePath, {
|
||||
...record,
|
||||
createdAt: record.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
});
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export function resolveClaimsCompanyDir(companyId: string, homeDir?: string): string {
|
||||
const baseHome = resolveEffectiveStoreHome(homeDir);
|
||||
return path.join(baseHome, "claims", sanitizeFilename(companyId));
|
||||
}
|
||||
|
||||
export function resolveClaimFilePath(
|
||||
companyId: string,
|
||||
issueId: string,
|
||||
homeDir?: string,
|
||||
): string {
|
||||
return path.join(resolveClaimsCompanyDir(companyId, homeDir), `${sanitizeFilename(issueId)}.json`);
|
||||
}
|
||||
|
||||
export function saveClaimRecord(record: StoredClaimRecord, homeDir?: string): string {
|
||||
const filePath = resolveClaimFilePath(record.companyId, record.issueId, homeDir);
|
||||
writeSecureJson(filePath, record);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export function findClaimRecord(
|
||||
companyId: string,
|
||||
issueRef: string,
|
||||
homeDir?: string,
|
||||
): StoredClaimRecord | null {
|
||||
const trimmed = issueRef.trim();
|
||||
if (!trimmed) return null;
|
||||
|
||||
const directPath = resolveClaimFilePath(companyId, trimmed, homeDir);
|
||||
const direct = readJsonOrNull<StoredClaimRecord>(directPath);
|
||||
if (direct && typeof direct.claimToken === "string") {
|
||||
return direct;
|
||||
}
|
||||
|
||||
const dir = resolveClaimsCompanyDir(companyId, homeDir);
|
||||
if (!fs.existsSync(dir)) return null;
|
||||
|
||||
const upper = trimmed.toUpperCase();
|
||||
for (const entry of fs.readdirSync(dir)) {
|
||||
if (!entry.endsWith(".json")) continue;
|
||||
const candidate = readJsonOrNull<StoredClaimRecord>(path.join(dir, entry));
|
||||
if (!candidate || typeof candidate.claimToken !== "string") continue;
|
||||
if (
|
||||
candidate.issueId === trimmed ||
|
||||
candidate.identifier?.toUpperCase() === upper
|
||||
) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function deleteClaimRecord(
|
||||
companyId: string,
|
||||
issueRef: string,
|
||||
homeDir?: string,
|
||||
): boolean {
|
||||
const existing = findClaimRecord(companyId, issueRef, homeDir);
|
||||
if (!existing) return false;
|
||||
const filePath = resolveClaimFilePath(companyId, existing.issueId, homeDir);
|
||||
try {
|
||||
fs.unlinkSync(filePath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveClaimCredentials(input: {
|
||||
companyId: string;
|
||||
issueRef: string;
|
||||
activeProfile: string | null;
|
||||
requireClaim: boolean;
|
||||
homeDir?: string;
|
||||
}): ResolvedClaimCredentials | null {
|
||||
const envToken = process.env.PAPERCLIP_CLAIM_TOKEN?.trim();
|
||||
const envTaskId = process.env.PAPERCLIP_TASK_ID?.trim();
|
||||
const envIssueUuid = process.env.PAPERCLIP_ISSUE_UUID?.trim();
|
||||
const envProfile = process.env.PAPERCLIP_PROFILE?.trim() || null;
|
||||
|
||||
if (envToken) {
|
||||
const refUpper = input.issueRef.trim().toUpperCase();
|
||||
const matchesEnvTarget =
|
||||
(!envTaskId && !envIssueUuid) ||
|
||||
envTaskId?.toUpperCase() === refUpper ||
|
||||
envIssueUuid?.toLowerCase() === input.issueRef.trim().toLowerCase();
|
||||
|
||||
if (matchesEnvTarget) {
|
||||
if (envProfile !== null && (input.activeProfile ?? null) !== envProfile) {
|
||||
throw new PaperclipError({
|
||||
status: 409,
|
||||
code: "claim_not_held",
|
||||
message: `Task "${input.issueRef}" claim in environment belongs to profile "${envProfile}", not "${input.activeProfile ?? "default"}"`,
|
||||
next: [`Retry with --as ${envProfile}`],
|
||||
});
|
||||
}
|
||||
const rawEpoch = process.env.PAPERCLIP_CLAIM_EPOCH?.trim();
|
||||
const parsedEpoch =
|
||||
rawEpoch !== undefined && /^\d+$/.test(rawEpoch)
|
||||
? Number.parseInt(rawEpoch, 10)
|
||||
: undefined;
|
||||
return {
|
||||
claimToken: envToken,
|
||||
...(parsedEpoch !== undefined ? { claimEpoch: parsedEpoch } : {}),
|
||||
...(envIssueUuid ? { issueId: envIssueUuid } : {}),
|
||||
...(envTaskId ? { identifier: envTaskId } : {}),
|
||||
source: "env",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const stored = findClaimRecord(input.companyId, input.issueRef, input.homeDir);
|
||||
if (stored) {
|
||||
const heldProfile = stored.profile ?? null;
|
||||
const callerProfile = input.activeProfile ?? null;
|
||||
if (heldProfile !== callerProfile) {
|
||||
throw new PaperclipError({
|
||||
status: 409,
|
||||
code: "claim_not_held",
|
||||
message: `Task "${input.issueRef}" is claimed locally by profile "${heldProfile ?? "(none)"}", not "${callerProfile ?? "(none)"}"`,
|
||||
next: heldProfile
|
||||
? [`pc tasks complete ${input.issueRef} --as ${heldProfile}`]
|
||||
: [`pc tasks claim ${input.issueRef}${callerProfile ? ` --as ${callerProfile}` : ""}`],
|
||||
});
|
||||
}
|
||||
return {
|
||||
claimToken: stored.claimToken,
|
||||
claimEpoch: stored.claimEpoch,
|
||||
issueId: stored.issueId,
|
||||
identifier: stored.identifier,
|
||||
source: "store",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.requireClaim) {
|
||||
throw new PaperclipError({
|
||||
status: 409,
|
||||
code: "claim_not_held",
|
||||
message: `No active local claim held for task "${input.issueRef}"`,
|
||||
next: [`pc tasks claim ${input.issueRef}${input.activeProfile ? ` --as ${input.activeProfile}` : ""}`],
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,6 @@
|
||||
import { Command } from "commander";
|
||||
import { handleBoardError, isPcBinary } from "../board/client.js";
|
||||
import { handleBoardWhoami } from "../board/agent-auth.js";
|
||||
import {
|
||||
addCommonClientOptions,
|
||||
apiPath,
|
||||
@@ -364,16 +366,41 @@ export function registerAccessCommands(program: Command): void {
|
||||
);
|
||||
}
|
||||
|
||||
interface WhoamiOptions extends BaseClientOptions {
|
||||
as?: string;
|
||||
company?: string;
|
||||
companyId?: string;
|
||||
}
|
||||
|
||||
function shouldUseBoardWhoami(opts: WhoamiOptions): boolean {
|
||||
if (opts.as !== undefined) return true;
|
||||
if (opts.company !== undefined) return true;
|
||||
if (opts.companyId !== undefined) return true;
|
||||
if (Boolean(process.env.PAPERCLIP_PROFILE?.trim())) return true;
|
||||
if (isPcBinary()) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function addWhoamiCommand(parent: Command): void {
|
||||
addCommonClientOptions(
|
||||
parent
|
||||
.command("whoami")
|
||||
.description("Show current CLI auth identity")
|
||||
.action(async (opts: BaseClientOptions) => {
|
||||
.option("--as <profile>", "Resolve identity for a profile or registered agent")
|
||||
.option("--company <id-or-prefix>", "Company ID or issue prefix (e.g. PAP)")
|
||||
.option("-C, --company-id <id>", "Company ID")
|
||||
.action(async (opts: WhoamiOptions) => {
|
||||
try {
|
||||
if (shouldUseBoardWhoami(opts)) {
|
||||
await handleBoardWhoami(opts);
|
||||
return;
|
||||
}
|
||||
const ctx = resolveCommandContext(opts);
|
||||
printOutput(await ctx.api.get("/api/cli-auth/me"), { json: ctx.json });
|
||||
} catch (err) {
|
||||
if (shouldUseBoardWhoami(opts)) {
|
||||
handleBoardError(err, opts);
|
||||
}
|
||||
handleCommandError(err);
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -25,6 +25,7 @@ import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { registerBoardAgentAuthCommands } from "../board/agent-auth.js";
|
||||
import {
|
||||
addCommonClientOptions,
|
||||
apiPath,
|
||||
@@ -228,6 +229,7 @@ function buildAgentEnvExports(input: {
|
||||
|
||||
export function registerAgentCommands(program: Command): void {
|
||||
const agent = program.command("agent").description("Agent operations");
|
||||
registerBoardAgentAuthCommands(agent);
|
||||
|
||||
addCommonClientOptions(
|
||||
agent
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { createServer } from "node:net";
|
||||
import * as p from "@clack/prompts";
|
||||
import pc from "picocolors";
|
||||
import { Option, type Command } from "commander";
|
||||
import { type Company } from "@paperclipai/shared";
|
||||
import { paperclip, type ChannelView } from "@paperclipai/shared/sdk";
|
||||
import { PaperclipApiClient } from "../client/http.js";
|
||||
import { readContext, setCurrentProfile, upsertProfile } from "../client/context.js";
|
||||
import {
|
||||
expandHomePrefix,
|
||||
resolveDefaultConfigPath,
|
||||
resolveDefaultContextPath,
|
||||
resolvePaperclipHomeDir,
|
||||
resolvePaperclipInstanceId,
|
||||
} from "../config/home.js";
|
||||
import { readConfig } from "../config/store.js";
|
||||
import { detectGitWorkspaceInfo } from "./git-workspace.js";
|
||||
import { runCommand, type StartedServer } from "./run.js";
|
||||
import { resolveTestDriveServerPort } from "./test-drive.js";
|
||||
|
||||
export const UP_BIND_MODES = ["loopback", "tailnet", "lan"] as const;
|
||||
export type UpBindMode = (typeof UP_BIND_MODES)[number];
|
||||
|
||||
export interface UpOptions {
|
||||
local?: boolean;
|
||||
dataDir?: string;
|
||||
port?: number | string;
|
||||
bind?: UpBindMode;
|
||||
companyName?: string;
|
||||
context?: boolean;
|
||||
}
|
||||
|
||||
export type UpApi = Pick<PaperclipApiClient, "get" | "post">;
|
||||
|
||||
export interface UpBootstrapResult {
|
||||
reused: boolean;
|
||||
company: Company;
|
||||
issuePrefix: string;
|
||||
channel: ChannelView | null;
|
||||
}
|
||||
|
||||
export interface UpDependencies {
|
||||
run: typeof runCommand;
|
||||
createApi: (apiBase: string) => UpApi;
|
||||
ensureGeneralChannel: (apiBase: string, companyId: string) => Promise<ChannelView | null>;
|
||||
updateContext: (input: {
|
||||
apiBase: string;
|
||||
companyId: string;
|
||||
contextPath?: string;
|
||||
}) => string;
|
||||
}
|
||||
|
||||
export function deriveCompanyIssuePrefix(companyName: string): string {
|
||||
const cleaned = companyName
|
||||
.toUpperCase()
|
||||
.replace(/[^A-Z0-9]+/g, "");
|
||||
if (cleaned.length >= 3) {
|
||||
return cleaned.slice(0, 3);
|
||||
}
|
||||
if (cleaned.length > 0) {
|
||||
return cleaned.padEnd(3, "P");
|
||||
}
|
||||
return "PAP";
|
||||
}
|
||||
|
||||
export function resolveUpCompanyName(options: Pick<UpOptions, "companyName" | "local">, cwd = process.cwd()): string {
|
||||
const explicit = options.companyName?.trim();
|
||||
if (explicit) return explicit;
|
||||
if (options.local) {
|
||||
const git = detectGitWorkspaceInfo(cwd);
|
||||
const root = git?.root ?? path.resolve(cwd);
|
||||
const base = path.basename(root).trim();
|
||||
if (base) return base;
|
||||
}
|
||||
return "Workspace";
|
||||
}
|
||||
|
||||
export function checkLocalGitignore(workspaceRoot: string): {
|
||||
isGitRepo: boolean;
|
||||
ignored: boolean;
|
||||
gitignorePath: string;
|
||||
} {
|
||||
const git = detectGitWorkspaceInfo(workspaceRoot);
|
||||
const gitignorePath = path.join(workspaceRoot, ".gitignore");
|
||||
if (!git) {
|
||||
return { isGitRepo: false, ignored: true, gitignorePath };
|
||||
}
|
||||
if (!fs.existsSync(gitignorePath)) {
|
||||
return { isGitRepo: true, ignored: false, gitignorePath };
|
||||
}
|
||||
const content = fs.readFileSync(gitignorePath, "utf8");
|
||||
const lines = content.split(/\r?\n/).map((line) => line.trim());
|
||||
const ignored = lines.some(
|
||||
(line) =>
|
||||
!line.startsWith("#") &&
|
||||
(line === ".paperclip" ||
|
||||
line === ".paperclip/" ||
|
||||
line === "/.paperclip" ||
|
||||
line === "/.paperclip/" ||
|
||||
line === ".paperclip/board" ||
|
||||
line === ".paperclip/board/"),
|
||||
);
|
||||
return { isGitRepo: true, ignored, gitignorePath };
|
||||
}
|
||||
|
||||
async function checkPortAvailable(port: number, host = "127.0.0.1"): Promise<boolean> {
|
||||
return await new Promise<boolean>((resolve) => {
|
||||
const server = createServer();
|
||||
server.unref();
|
||||
server.once("error", () => resolve(false));
|
||||
server.listen(port, host, () => {
|
||||
server.close(() => resolve(true));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function parseExplicitPort(raw: number | string | undefined): number | undefined {
|
||||
if (raw === undefined) return undefined;
|
||||
const num = typeof raw === "number" ? raw : Number.parseInt(String(raw).trim(), 10);
|
||||
if (!Number.isInteger(num) || num < 1 || num > 65535) {
|
||||
throw new Error(`Invalid --port "${String(raw)}": expected an integer between 1 and 65535.`);
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
export async function prepareUpEnvironment(
|
||||
options: UpOptions,
|
||||
cwd = process.cwd(),
|
||||
): Promise<{
|
||||
dataDir: string;
|
||||
workspaceRoot: string | null;
|
||||
contextPath: string;
|
||||
port: number;
|
||||
bind: UpBindMode;
|
||||
gitignoreMissing: boolean;
|
||||
}> {
|
||||
if (options.local && options.dataDir?.trim()) {
|
||||
throw new Error("--local and --data-dir cannot be combined.");
|
||||
}
|
||||
|
||||
const bind: UpBindMode = options.bind ?? "loopback";
|
||||
if (!UP_BIND_MODES.includes(bind)) {
|
||||
throw new Error(`Invalid --bind "${String(bind)}": expected one of ${UP_BIND_MODES.join(", ")}.`);
|
||||
}
|
||||
|
||||
let workspaceRoot: string | null = null;
|
||||
let dataDir: string;
|
||||
let contextPath: string;
|
||||
|
||||
if (options.local) {
|
||||
const git = detectGitWorkspaceInfo(cwd);
|
||||
workspaceRoot = git?.root ?? path.resolve(cwd);
|
||||
dataDir = path.join(workspaceRoot, ".paperclip", "board");
|
||||
contextPath = path.join(workspaceRoot, ".paperclip", "context.json");
|
||||
process.env.PAPERCLIP_HOME = dataDir;
|
||||
process.env.PAPERCLIP_INSTANCE_ID = "default";
|
||||
process.env.PAPERCLIP_CONFIG = resolveDefaultConfigPath("default");
|
||||
process.env.PAPERCLIP_CONTEXT = contextPath;
|
||||
} else if (options.dataDir?.trim()) {
|
||||
dataDir = path.resolve(expandHomePrefix(options.dataDir.trim()));
|
||||
process.env.PAPERCLIP_HOME = dataDir;
|
||||
const instanceId = resolvePaperclipInstanceId();
|
||||
process.env.PAPERCLIP_INSTANCE_ID = instanceId;
|
||||
process.env.PAPERCLIP_CONFIG = resolveDefaultConfigPath(instanceId);
|
||||
contextPath = process.env.PAPERCLIP_CONTEXT?.trim()
|
||||
? path.resolve(process.env.PAPERCLIP_CONTEXT.trim())
|
||||
: resolveDefaultContextPath();
|
||||
process.env.PAPERCLIP_CONTEXT = contextPath;
|
||||
} else {
|
||||
dataDir = resolvePaperclipHomeDir();
|
||||
const instanceId = resolvePaperclipInstanceId();
|
||||
process.env.PAPERCLIP_INSTANCE_ID = instanceId;
|
||||
process.env.PAPERCLIP_CONFIG = process.env.PAPERCLIP_CONFIG?.trim() || resolveDefaultConfigPath(instanceId);
|
||||
contextPath = process.env.PAPERCLIP_CONTEXT?.trim()
|
||||
? path.resolve(process.env.PAPERCLIP_CONTEXT.trim())
|
||||
: resolveDefaultContextPath();
|
||||
process.env.PAPERCLIP_CONTEXT = contextPath;
|
||||
}
|
||||
|
||||
process.env.PAPERCLIP_OPEN_ON_LISTEN = "false";
|
||||
if (bind !== "loopback") {
|
||||
process.env.PAPERCLIP_BIND = bind;
|
||||
}
|
||||
|
||||
const explicitPort = parseExplicitPort(options.port);
|
||||
let port: number;
|
||||
if (explicitPort !== undefined) {
|
||||
if (!(await checkPortAvailable(explicitPort))) {
|
||||
throw new Error(`Port ${explicitPort} is already in use.`);
|
||||
}
|
||||
port = explicitPort;
|
||||
} else {
|
||||
let preferredPort = 3100;
|
||||
try {
|
||||
preferredPort = readConfig(process.env.PAPERCLIP_CONFIG)?.server.port ?? preferredPort;
|
||||
} catch {
|
||||
// Doctor handles invalid config diagnostics on startup.
|
||||
}
|
||||
port = await resolveTestDriveServerPort(preferredPort);
|
||||
}
|
||||
process.env.PORT = String(port);
|
||||
|
||||
const gitignoreCheck = workspaceRoot ? checkLocalGitignore(workspaceRoot) : null;
|
||||
const gitignoreMissing = Boolean(gitignoreCheck?.isGitRepo && !gitignoreCheck.ignored);
|
||||
|
||||
return {
|
||||
dataDir,
|
||||
workspaceRoot,
|
||||
contextPath,
|
||||
port,
|
||||
bind,
|
||||
gitignoreMissing,
|
||||
};
|
||||
}
|
||||
|
||||
export async function bootstrapUpBoard(input: {
|
||||
api: UpApi;
|
||||
apiBase: string;
|
||||
companyName: string;
|
||||
ensureGeneralChannel: (apiBase: string, companyId: string) => Promise<ChannelView | null>;
|
||||
}): Promise<UpBootstrapResult> {
|
||||
const companies = (await input.api.get<Company[]>("/api/companies")) ?? [];
|
||||
const activeCompanies = companies.filter((c) => c.status !== "archived");
|
||||
let company = activeCompanies[0];
|
||||
let reused = true;
|
||||
|
||||
if (!company) {
|
||||
reused = false;
|
||||
const created = await input.api.post<Company>("/api/companies", {
|
||||
name: input.companyName,
|
||||
});
|
||||
if (!created) {
|
||||
throw new Error("Paperclip returned no result while creating the default company.");
|
||||
}
|
||||
company = created;
|
||||
}
|
||||
|
||||
const issuePrefix =
|
||||
typeof company.issuePrefix === "string" && company.issuePrefix.trim().length > 0
|
||||
? company.issuePrefix.trim()
|
||||
: deriveCompanyIssuePrefix(company.name);
|
||||
|
||||
const channel = await input.ensureGeneralChannel(input.apiBase, company.id);
|
||||
return { reused, company, issuePrefix, channel };
|
||||
}
|
||||
|
||||
function formatReadyUrl(server: StartedServer): string {
|
||||
const rawHost =
|
||||
server.host === "0.0.0.0" || server.host === "::" || server.host === "[::]"
|
||||
? "127.0.0.1"
|
||||
: server.host;
|
||||
const host = rawHost.includes(":") && !rawHost.startsWith("[") ? `[${rawHost}]` : rawHost;
|
||||
return `http://${host}:${server.listenPort}`;
|
||||
}
|
||||
|
||||
export function formatUpReadyBanner(input: {
|
||||
url: string;
|
||||
companyName: string;
|
||||
issuePrefix: string;
|
||||
deploymentMode: string;
|
||||
dataDir: string;
|
||||
contextUpdated: boolean;
|
||||
contextPath: string;
|
||||
companyId: string;
|
||||
}): string[] {
|
||||
const lines = [
|
||||
`Paperclip ready at ${input.url} (Company: ${input.companyName} [${input.issuePrefix}], mode: ${input.deploymentMode})`,
|
||||
`Channel: #general | Data: ${input.dataDir}`,
|
||||
input.contextUpdated
|
||||
? `Context: ${input.contextPath} (company=${input.companyId})`
|
||||
: `Context: skipped (--no-context)`,
|
||||
`Next: pc post general "Hello board" | pc tasks create general "First task"`,
|
||||
];
|
||||
return lines;
|
||||
}
|
||||
|
||||
const defaultUpDependencies: UpDependencies = {
|
||||
run: runCommand,
|
||||
createApi: (apiBase) => new PaperclipApiClient({ apiBase }),
|
||||
ensureGeneralChannel: async (apiBase, companyId) => {
|
||||
const client = paperclip({ apiBase, company: companyId });
|
||||
return await client.channels.ensure("general");
|
||||
},
|
||||
updateContext: ({ apiBase, companyId, contextPath }) => {
|
||||
const existing = readContext(contextPath);
|
||||
const targetProfile = existing.currentProfile || "default";
|
||||
upsertProfile(
|
||||
targetProfile,
|
||||
{
|
||||
apiBase,
|
||||
companyId,
|
||||
},
|
||||
contextPath,
|
||||
);
|
||||
setCurrentProfile(targetProfile, contextPath);
|
||||
return contextPath ?? resolveDefaultContextPath();
|
||||
},
|
||||
};
|
||||
|
||||
export async function upCommand(
|
||||
options: UpOptions,
|
||||
dependencies: UpDependencies = defaultUpDependencies,
|
||||
cwd = process.cwd(),
|
||||
): Promise<void> {
|
||||
const dataDir = resolvePaperclipHomeDir();
|
||||
const companyName = resolveUpCompanyName(options, cwd);
|
||||
const contextPath = process.env.PAPERCLIP_CONTEXT ?? resolveDefaultContextPath();
|
||||
const bind: UpBindMode = options.bind ?? "loopback";
|
||||
const skipContext = options.context === false;
|
||||
|
||||
if (options.local) {
|
||||
const git = detectGitWorkspaceInfo(cwd);
|
||||
const root = git?.root ?? path.resolve(cwd);
|
||||
const check = checkLocalGitignore(root);
|
||||
if (check.isGitRepo && !check.ignored) {
|
||||
p.log.warn(
|
||||
`Local board state lives at ${path.join(root, ".paperclip", "board")} — add ".paperclip/" to ${check.gitignorePath} to keep it out of git.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await dependencies.run({
|
||||
repair: true,
|
||||
yes: true,
|
||||
bind,
|
||||
installService: false,
|
||||
skipServiceManagerCheck: Boolean(options.local || options.dataDir?.trim()),
|
||||
introLabel: "paperclipai up",
|
||||
afterStart: async (server) => {
|
||||
const url = formatReadyUrl(server);
|
||||
const api = dependencies.createApi(url);
|
||||
const result = await bootstrapUpBoard({
|
||||
api,
|
||||
apiBase: url,
|
||||
companyName,
|
||||
ensureGeneralChannel: dependencies.ensureGeneralChannel,
|
||||
});
|
||||
|
||||
let savedContextPath = contextPath;
|
||||
if (!skipContext) {
|
||||
savedContextPath = dependencies.updateContext({
|
||||
apiBase: url,
|
||||
companyId: result.company.id,
|
||||
contextPath,
|
||||
});
|
||||
}
|
||||
|
||||
const config = readConfig(process.env.PAPERCLIP_CONFIG);
|
||||
const mode = config?.server.deploymentMode ?? (bind === "loopback" ? "local_trusted" : "authenticated");
|
||||
const bannerLines = formatUpReadyBanner({
|
||||
url,
|
||||
companyName: result.company.name,
|
||||
issuePrefix: result.issuePrefix,
|
||||
deploymentMode: mode,
|
||||
dataDir,
|
||||
contextUpdated: !skipContext,
|
||||
contextPath: savedContextPath,
|
||||
companyId: result.company.id,
|
||||
});
|
||||
|
||||
console.log("");
|
||||
for (const line of bannerLines) {
|
||||
console.log(pc.green(line));
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function registerUpCommand(
|
||||
program: Command,
|
||||
dependencies: UpDependencies = defaultUpDependencies,
|
||||
): void {
|
||||
program
|
||||
.command("up")
|
||||
.description("Start a ready-to-use local Paperclip board with zero prompts or LLM keys")
|
||||
.option("--local", "Store board state in <git-root-or-cwd>/.paperclip/board")
|
||||
.option("-d, --data-dir <path>", "Paperclip data directory root")
|
||||
.option("-p, --port <port>", "Server listen port (defaults to 3100 or next free port)")
|
||||
.addOption(
|
||||
new Option("--bind <mode>", "Reachability preset (loopback, tailnet, lan)")
|
||||
.choices(UP_BIND_MODES)
|
||||
.default("loopback"),
|
||||
)
|
||||
.option("--company-name <name>", "Initial company name when bootstrapping a fresh board")
|
||||
.option("--no-context", "Do not update local CLI context with the started board URL and company")
|
||||
.action(async (options: UpOptions) => {
|
||||
await upCommand(options, dependencies);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user