mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work, where agents and humans coordinate tasks through the REST API,
`paperclipai` CLI, Native Runner API catalog, and Public MCP tools.
> - Structured coordination primitives (`channel`, `kvLabels`,
`resultSchemaRef`, and `schemaBlocks`) previously worked on `/headless`
endpoints, while canonical `/api/issues` routes, `GET
/api/issues/:id/heartbeat-context`, `paperclipai issue` CLI commands,
and Public MCP task tools did not accept or surface those fields
consistently, and OpenAPI exposed headless routes with summary-only
stubs.
> - Because agents wake up from `heartbeat-context`, inspect endpoint
schemas through OpenAPI and `runnerApiReference`, or mutate tasks
through canonical `POST`/`PATCH /api/issues` routes, CLI flags, and
Public MCP tools, missing fields on those surfaces forced callers onto
parallel endpoints or caused agents to miss required deliverable schemas
until after closing a task.
> - We chose to wire structured coordination directly onto the canonical
issue validators, routes, `heartbeat-context`, CLI flags, OpenAPI
schemas, `runnerApiReference` examples, and Public MCP task tools while
reusing existing channel-privacy and JSON Schema registries.
> - For Markdown ```` ```json schema=<name>@<version> ```` extraction in
issue descriptions and comments, we avoided multi-line backtracking
regular expressions and implemented a single-pass $O(N)$ CommonMark
character-index line scanner with strict input, fence-body, and block
caps so adversarial unclosed fences remain linear.
> - When an agent transitions an issue with `resultSchemaRef` to final
status `done`, `PATCH /api/issues/:id` now verifies that a valid
matching schema block exists across incoming or stored issue/comment
blocks and returns a self-documenting HTTP `422`
(`result_schema_validation_failed` with `requiredResultSchema` and
`jsonSchema`) while still allowing human board actors to close tasks
manually.
## Linked Issues or Issue Description
**What existing behavior does this improve?**
Canonical issue creation, updates, comments, list filters,
`heartbeat-context`, OpenAPI schemas, `runnerApiReference` examples,
`paperclipai issue` CLI commands, and Public MCP task tools now support
structured coordination fields (`channel`, `kvLabels`,
`resultSchemaRef`, and `schemaBlocks`) with full parity alongside
existing headless routes.
**Subsystem affected**
Server API (`packages/shared/src/validators/issue.ts`,
`server/src/routes/issues.ts`, `server/src/services/issues.ts`,
`server/src/routes/openapi.ts`,
`server/src/services/native-runtime/runner-api-reference.ts`,
`server/src/services/public-mcp/*`) and CLI
(`cli/src/commands/client/issue.ts`).
**Current behavior**
- `createIssueSchema`, `updateIssueSchema`, and `addIssueCommentSchema`
do not accept `channel`, `kvLabels`, `resultSchemaRef`, or
`schemaBlocks`.
- Canonical `GET /api/companies/:companyId/issues` does not filter by
`?channel=` or `?kvLabel=`, `GET /api/issues/:id/heartbeat-context`
omits `channelId`, `channelPath`, `kvLabels`, `resultSchemaRef`, and
`schemaBlocks`, and `PATCH /api/issues/:id` does not enforce
`resultSchemaRef` when an agent marks an issue `done`.
- `server/src/routes/openapi.ts` registers headless
channel/schema/kv-label/batch/queue/schedule/event endpoints with
summary-only stubs without `parameters` or `requestBody` schemas, and
`runnerApiReference` lacks examples for key headless coordination
routes.
- `paperclipai issue` (`create`, `update`, `comment`, `list`) and Public
MCP (`paperclip_search_tasks`, `paperclip_create_task`,
`paperclip_update_task`, `paperclip_add_comment`) do not expose channel,
key-value label, result schema, or schema block inputs/outputs.
**Proposed behavior**
- Extend `@paperclipai/shared` issue validators
(`createIssueBaseSchema`, `updateIssueSchema`, `addIssueCommentSchema`)
with validated `kvLabels`, `resultSchemaRef`, `channel`, `schemaBlocks`,
`commentKvLabels`, and `commentSchemaBlocks`.
- Add a linear $O(N)$ single-pass CommonMark schema fence scanner
(`server/src/services/schema-fence-scanner.ts`) with zero regexes and
strict input/fence caps (`512 KiB` text, `64 KiB` fence body, `64`
candidate fences, `32` blocks).
- Support `channel`, `kvLabels`, `resultSchemaRef`, and explicit/fenced
`schemaBlocks` on `POST /api/companies/:companyId/issues`, `POST
/api/issues/:id/children`, `PATCH /api/issues/:id`, `POST
/api/issues/:id/comments`, `GET /api/companies/:companyId/issues`
(`?channel=` and `?kvLabel=`), and `GET
/api/issues/:id/heartbeat-context`, enforcing private-channel access
rules and HTTP `422` `result_schema_validation_failed` (with
`requiredResultSchema` and `jsonSchema`) when an agent transitions an
issue with `resultSchemaRef` to final status `done`.
- Replace summary-only headless OpenAPI stubs with full `query` and
`requestBody` schemas, document `channel` and `kvLabel` query parameters
on `GET /api/companies/{companyId}/issues`, and add `runnerApiReference`
examples for `PATCH /api/issues/{}/kv-labels`, `POST
/api/companies/{}/channels/posts`, `POST /api/companies/{}/schemas`, and
`POST /api/companies/{}/issues/batch`.
- Add `--kv`, `--unset-kv`, `--result-schema`, `--channel`, and
`--schema-block` flags to `paperclipai issue` (`create`, `update`,
`comment`, `list`), and expose structured fields and inputs on Public
MCP task tools and projections.
**Reason and benefit**
Agents and humans can use one canonical set of issue endpoints, CLI
flags, Native Runner API discovery schemas, and Public MCP tools to
route work into channels, filter and patch structured `kvLabels`, attach
validated `schemaBlocks`, and enforce `resultSchemaRef` deliverables at
completion time with immediate JSON Schema feedback.
**Breaking changes**
No — purely additive on canonical issue schemas, CLI flags, OpenAPI
definitions, and Public MCP tools. Existing callers without
`resultSchemaRef` or structured fields behave identically, and human
board actors (`req.actor.type === "board"`) can still close tasks with
`resultSchemaRef` without attaching a schema block.
## What Changed
- **Shared Issue Validators
(`packages/shared/src/validators/issue.ts`)**: Added
`issueKvLabelsSchema`, `issueKvLabelsPatchSchema` (`null` unsets keys),
`issueResultSchemaRefSchema`, `issueChannelInputSchema`, and
`issueSchemaBlocksSchema`; extended `createIssueBaseSchema`,
`updateIssueSchema`, and `addIssueCommentSchema`; refreshed
`tests/runner-e2e/source-sdk-public-inputs.json`.
- **Linear Schema Fence Scanner & Structured Helpers
(`server/src/services/schema-fence-scanner.ts`,
`server/src/services/issue-structured-fields.ts`,
`server/src/services/issue-visibility.ts`)**: Implemented a
character-index single-pass CommonMark fence scanner with no
backtracking regexes, plus channel resolution/privacy helpers,
`kvLabels` merge/filter helpers, schema block validation, and agent
`done` deliverable enforcement.
- **Canonical Issue Routes & Service (`server/src/routes/issues.ts`,
`server/src/services/issues.ts`,
`server/src/routes/headless-channels-schemas.ts`)**: Wired `channel`,
`kvLabels`, `resultSchemaRef`, and `schemaBlocks` across create, child
create, update, comment, list (`?channel=`, `?kvLabel=`), and
`heartbeat-context` (`channelId`, privacy-checked `channelPath`,
`kvLabels`, `resultSchemaRef`, `schemaBlocks`), plus HTTP `422`
`result_schema_validation_failed` enforcement when an agent marks an
issue `done` without a valid deliverable block.
- **OpenAPI, Docs & Runner API Reference
(`server/src/routes/openapi.ts`,
`server/src/services/native-runtime/runner-api-reference.ts`,
`docs/api/issues.md`)**: Replaced summary-only headless OpenAPI entries
with full `query` and `requestBody` schemas reusing shared channel/batch
schemas across all 27 headless endpoints, documented `channel` and
`kvLabel` on `GET /api/companies/{companyId}/issues`, documented all new
canonical issue fields and `422 result_schema_validation_failed`
behavior in `docs/api/issues.md`, and added `runnerApiReference`
examples for `PATCH /api/issues/{}/kv-labels`, `POST
/api/companies/{}/channels/posts`, `POST /api/companies/{}/schemas`, and
`POST /api/companies/{}/issues/batch`.
- **CLI & Public MCP (`cli/src/commands/client/issue.ts`,
`server/src/services/public-mcp/{contracts,capabilities,expanded-capabilities}.ts`)**:
Added `--kv`, `--unset-kv`, `--result-schema`, `--channel`, and
`--schema-block` flags to `paperclipai issue` (`create`, `update`,
`comment`, `list`) and added structured fields and parameters to Public
MCP task contracts and tools (`paperclip_search_tasks`,
`paperclip_create_task`, `paperclip_update_task`,
`paperclip_add_comment`).
## Verification
- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck` — passed.
- `pnpm exec vitest run packages/shared/src/validators/issue.test.ts` —
65/65 passed (including Zod `z.toJSONSchema` compatibility).
- `pnpm exec vitest run
server/src/__tests__/schema-fence-scanner.test.ts` — 4/4 passed (`5,000`
repeated unterminated ```` ```json ```` lines scanned in `< 50ms`).
- `pnpm exec vitest run
server/src/__tests__/canonical-issue-structured-parity.test.ts
server/src/__tests__/headless-channels-schemas-batch.test.ts
server/src/__tests__/headless-e2e-sdk-cli.test.ts` — 14/14 passed.
(During initial test execution, an invalid `resultSchemaRef` fence on
`PATCH /api/issues/:id { status: "done", comment }` hit generic
`schema_validation_failed` before
`assertAgentResultSchemaSatisfiedOnDone`; reordered
`assertAgentResultSchemaSatisfiedOnDone` ahead of `validateSchemaBlocks`
so agents consistently receive `result_schema_validation_failed` with
`requiredResultSchema` and `jsonSchema`, then re-ran green.)
- `pnpm exec vitest run server/src/__tests__/openapi-routes.test.ts
server/src/services/native-runtime/runner-api.test.ts
server/src/services/native-runtime/runner-api-reference.test.ts` —
2,444/2,444 passed.
- `pnpm exec vitest run cli/src/__tests__/issue-subresources.test.ts` —
7/7 passed.
- `pnpm exec vitest run server/src/__tests__/public-mcp.test.ts` — 84/84
passed.
- `(cd server && node scripts/typecheck-layers.mjs)` and `pnpm --filter
paperclipai typecheck` — passed all typecheck layers.
- `node scripts/check-module-boundaries.mjs`, `node
scripts/check-agent-lifecycle-boundaries.mjs`, `node
scripts/check-test-budget.mjs`, and `node
tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD)
--check` — passed.
- `pnpm verify` — exited `2` (`Broad input:
tests/runner-e2e/source-sdk-public-inputs.json`) after refreshing
`source-sdk-public-inputs.json`; focused Vitest suites and layered
typechecks passed locally and broad coverage runs in required PR CI.
- **Round 1 PR CI & review follow-up**: Initial PR CI caught a circular
module initialization (`openapi.ts` importing
`ResolveInteractionInputSchema` from
`services/headless-events-schedules-interactions.ts`, leaving
`runnerApiCallSchema` undefined in `native-workflow-tools.ts`), and code
review flagged private-channel issue/child `visibility` inheritance,
locked-row `resultSchemaRef` enforcement + agent immutability, follow-up
edits on already-`done` tasks, SDK non-UUID retry-key routing on `POST
/issues/:id/comments`, strict `> 512 KiB` fence rejection,
`schemaBlocks` on `paperclip_create_task`/`paperclip_update_task`,
`timeout` query param on `/events/wait`, and `docs/api/issues.md`
updates. Removed the `services/*` import from `openapi.ts`, fixed each
review finding, and verified `tool-input-variant-admission.test.ts`,
`teams-catalog-service.test.ts`,
`canonical-issue-structured-parity.test.ts`, `public-mcp.test.ts`,
`headless-channels-schemas-batch.test.ts`,
`headless-e2e-sdk-cli.test.ts`, `headless-identity-auth.test.ts`, and
`schema-fence-scanner.test.ts` (2,663/2,663 tests passing across 13
suites).
## Risks
- **Private channel existence or path leakage**: Mitigated by checking
`canAccessChannel` on canonical channel writes, list filters
(`?channel=`), and `GET /api/issues/:id/heartbeat-context` (failing
closed with `404` on inaccessible private channel targets and returning
`channelPath: null` when a private channel is not accessible to the
caller).
- **Adversarial Markdown payloads on issue/comment writes**: Mitigated
by scanning fences with a pure character-index single-pass CommonMark
line scanner with zero regular expressions, bounded at `512 KiB` input
text, `64 KiB` per fence body, `64` candidate fences, and `32` schema
blocks.
- **`resultSchemaRef` completion blocking**: Mitigated by enforcing
`422` `result_schema_validation_failed` only when `req.actor.type ===
"agent"` and the effective target status after execution-policy routing
is `"done"`, preserving manual task closure for board humans and
intermediate `in_review` transitions.
## Model Used
Google DeepMind `gemini-3.1-pro` via Antigravity agentic coding harness
(1M context window, high reasoning effort, native workspace/file/test
tool execution).
## Checklist
- [x] I searched the [GitHub PR
list](https://github.com/paperclipai/paperclip/pulls?q=is%3Apr) (open +
recently closed) for similar PRs and confirmed this is not a duplicate
- [x] My code follows the project's [code
comments](CONTRIBUTING.md#code-comments) guidelines (self-documenting,
minimal comments)
- [x] `pnpm -r typecheck` passes (verified locally across
`@paperclipai/shared`, `server` layered typecheck, and `paperclipai`
CLI; full workspace `typecheck_release_registry` verified in PR CI)
- [x] `pnpm test:run` passes (focused owner Vitest suites passed
locally; full CI matrix verified in PR CI)
- [ ] `pnpm build` passes
- [ ] If I changed `packages/db`, I ran `pnpm db:generate` and committed
the migration
- [x] If I added a user-facing capability, I updated `README.md` or
relevant docs (`docs/api/issues.md`)
- [x] This PR focuses on a single concern (no unrelated changes bundled)
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
1651 lines
58 KiB
TypeScript
1651 lines
58 KiB
TypeScript
import { Command } from "commander";
|
|
import { readFile, writeFile } from "node:fs/promises";
|
|
import {
|
|
addIssueCommentSchema,
|
|
acceptIssueThreadInteractionSchema,
|
|
cancelIssueThreadInteractionSchema,
|
|
checkoutIssueSchema,
|
|
createChildIssueSchema,
|
|
createIssueLabelSchema,
|
|
createIssueSchema,
|
|
createIssueThreadInteractionSchema,
|
|
createIssueTreeHoldSchema,
|
|
createIssueWorkProductSchema,
|
|
type FeedbackTrace,
|
|
type HeartbeatRun,
|
|
linkIssueApprovalSchema,
|
|
previewIssueTreeControlSchema,
|
|
rejectIssueThreadInteractionSchema,
|
|
releaseIssueTreeHoldSchema,
|
|
respondIssueThreadInteractionSchema,
|
|
resolveIssueRecoveryActionSchema,
|
|
restoreIssueDocumentRevisionSchema,
|
|
parseSchemaRef,
|
|
schemaBlockSchema,
|
|
type SchemaBlock,
|
|
updateIssueSchema,
|
|
updateIssueWorkProductSchema,
|
|
type Issue,
|
|
type IssueComment,
|
|
upsertIssueDocumentSchema,
|
|
upsertIssueFeedbackVoteSchema,
|
|
} from "@paperclipai/shared";
|
|
import {
|
|
addCommonClientOptions,
|
|
apiPath,
|
|
formatInlineRecord,
|
|
handleCommandError,
|
|
inferContentTypeFromPath,
|
|
printOutput,
|
|
resolveCommandContext,
|
|
type BaseClientOptions,
|
|
} from "./common.js";
|
|
import {
|
|
buildFeedbackTraceQuery,
|
|
normalizeFeedbackTraceExportFormat,
|
|
serializeFeedbackTraces,
|
|
} from "./feedback.js";
|
|
|
|
interface IssueBaseOptions extends BaseClientOptions {
|
|
status?: string;
|
|
assigneeAgentId?: string;
|
|
projectId?: string;
|
|
channel?: string;
|
|
kv?: string[];
|
|
match?: string;
|
|
}
|
|
|
|
interface IssueCreateOptions extends BaseClientOptions {
|
|
title: string;
|
|
description?: string;
|
|
status?: string;
|
|
priority?: string;
|
|
assigneeAgentId?: string;
|
|
projectId?: string;
|
|
goalId?: string;
|
|
parentId?: string;
|
|
standalone?: boolean;
|
|
requestDepth?: string;
|
|
billingCode?: string;
|
|
kv?: string[];
|
|
resultSchema?: string;
|
|
channel?: string;
|
|
schemaBlock?: string[];
|
|
}
|
|
|
|
interface IssueUpdateOptions extends BaseClientOptions {
|
|
title?: string;
|
|
description?: string;
|
|
status?: string;
|
|
priority?: string;
|
|
assigneeAgentId?: string;
|
|
projectId?: string;
|
|
goalId?: string;
|
|
parentId?: string;
|
|
requestDepth?: string;
|
|
billingCode?: string;
|
|
comment?: string;
|
|
hiddenAt?: string;
|
|
kv?: string[];
|
|
unsetKv?: string[];
|
|
resultSchema?: string;
|
|
channel?: string;
|
|
schemaBlock?: string[];
|
|
}
|
|
|
|
interface IssueCommentOptions extends BaseClientOptions {
|
|
body: string;
|
|
attachmentId?: string[];
|
|
kv?: string[];
|
|
schemaBlock?: string[];
|
|
reopen?: boolean;
|
|
resume?: boolean;
|
|
}
|
|
|
|
interface IssueCommentListOptions extends BaseClientOptions {
|
|
afterCommentId?: string;
|
|
order?: string;
|
|
limit?: string;
|
|
}
|
|
|
|
interface IssueCheckoutOptions extends BaseClientOptions {
|
|
agentId: string;
|
|
expectedStatuses?: string;
|
|
}
|
|
|
|
interface IssueFeedbackOptions extends BaseClientOptions {
|
|
targetType?: string;
|
|
vote?: string;
|
|
status?: string;
|
|
from?: string;
|
|
to?: string;
|
|
sharedOnly?: boolean;
|
|
includePayload?: boolean;
|
|
out?: string;
|
|
format?: string;
|
|
}
|
|
|
|
interface IssueDeleteOptions extends BaseClientOptions {
|
|
yes?: boolean;
|
|
}
|
|
|
|
interface JsonPayloadOptions extends BaseClientOptions {
|
|
payloadJson: string;
|
|
}
|
|
|
|
interface IssueDocumentPutOptions extends BaseClientOptions {
|
|
title?: string;
|
|
format?: string;
|
|
body?: string;
|
|
bodyFile?: string;
|
|
changeSummary?: string;
|
|
baseRevisionId?: string;
|
|
}
|
|
|
|
interface IssueAttachmentUploadOptions extends BaseClientOptions {
|
|
companyId?: string;
|
|
file: string;
|
|
commentId?: string;
|
|
}
|
|
|
|
interface IssueAttachmentDownloadOptions extends BaseClientOptions {
|
|
out?: string;
|
|
}
|
|
|
|
interface IssueLabelCreateOptions extends BaseClientOptions {
|
|
companyId?: string;
|
|
name: string;
|
|
color: string;
|
|
}
|
|
|
|
interface IssueRecoveryResolveOptions extends BaseClientOptions {
|
|
actionId?: string;
|
|
outcome: string;
|
|
sourceIssueStatus: string;
|
|
resolutionNote?: string;
|
|
}
|
|
|
|
interface InteractionAcceptOptions extends BaseClientOptions {
|
|
selectedClientKeys?: string;
|
|
selectedOptionIds?: string;
|
|
}
|
|
|
|
interface InteractionReasonOptions extends BaseClientOptions {
|
|
reason?: string;
|
|
}
|
|
|
|
interface InteractionRespondOptions extends BaseClientOptions {
|
|
answersJson: string;
|
|
summaryMarkdown?: string;
|
|
}
|
|
|
|
interface TreeHoldListOptions extends BaseClientOptions {
|
|
status?: string;
|
|
mode?: string;
|
|
includeMembers?: boolean;
|
|
}
|
|
|
|
export function registerIssueCommands(program: Command): void {
|
|
const issue = program.command("issue").description("Issue operations");
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("list")
|
|
.description("List issues for a company")
|
|
.option("-C, --company-id <id>", "Company ID")
|
|
.option("--status <csv>", "Comma-separated statuses")
|
|
.option("--assignee-agent-id <id>", "Filter by assignee agent ID")
|
|
.option("--project-id <id>", "Filter by project ID")
|
|
.option("--channel <pathOrId>", "Filter by channel path, subtree ('prefix/*'), or UUID")
|
|
.option("--kv <filter>", "Filter by key-value label ('key', 'key=value', or 'key=v1|v2')", collectStringOption)
|
|
.option("--match <text>", "Local text match on identifier/title/description")
|
|
.action(async (opts: IssueBaseOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts, { requireCompany: true });
|
|
const params = new URLSearchParams();
|
|
if (opts.status) params.set("status", opts.status);
|
|
if (opts.assigneeAgentId) params.set("assigneeAgentId", opts.assigneeAgentId);
|
|
if (opts.projectId) params.set("projectId", opts.projectId);
|
|
if (opts.channel) params.set("channel", opts.channel);
|
|
for (const filterExpr of opts.kv ?? []) {
|
|
params.append("kvLabel", filterExpr);
|
|
}
|
|
|
|
const query = params.toString();
|
|
const path = `${apiPath`/api/companies/${ctx.companyId}/issues`}${query ? `?${query}` : ""}`;
|
|
const rows = (await ctx.api.get<Issue[]>(path)) ?? [];
|
|
|
|
const filtered = filterIssueRows(rows, opts.match);
|
|
if (ctx.json) {
|
|
printOutput(filtered, { json: true });
|
|
return;
|
|
}
|
|
|
|
if (filtered.length === 0) {
|
|
printOutput([], { json: false });
|
|
return;
|
|
}
|
|
|
|
for (const item of filtered) {
|
|
console.log(
|
|
formatInlineRecord({
|
|
identifier: item.identifier,
|
|
id: item.id,
|
|
status: item.status,
|
|
priority: item.priority,
|
|
assigneeAgentId: item.assigneeAgentId,
|
|
title: item.title,
|
|
projectId: item.projectId,
|
|
}),
|
|
);
|
|
}
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
{ includeCompany: false },
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("get")
|
|
.description("Get an issue by UUID or identifier (e.g. PC-12)")
|
|
.argument("<idOrIdentifier>", "Issue ID or identifier")
|
|
.action(async (idOrIdentifier: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const row = await ctx.api.get<Issue>(apiPath`/api/issues/${idOrIdentifier}`);
|
|
printOutput(row, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("delete")
|
|
.description("Delete an issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.option("--yes", "Confirm deletion")
|
|
.action(async (issueId: string, opts: IssueDeleteOptions) => {
|
|
try {
|
|
if (!opts.yes) throw new Error("Refusing to delete without --yes");
|
|
const ctx = resolveCommandContext(opts);
|
|
const deleted = await ctx.api.delete<Issue>(apiPath`/api/issues/${issueId}`);
|
|
printOutput(deleted, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("heartbeat-context")
|
|
.description("Get heartbeat context for an issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const context = await ctx.api.get(apiPath`/api/issues/${issueId}/heartbeat-context`);
|
|
printOutput(context, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("create")
|
|
.description("Create an issue")
|
|
.requiredOption("-C, --company-id <id>", "Company ID")
|
|
.requiredOption("--title <title>", "Issue title")
|
|
.option("--description <text>", "Issue description")
|
|
.option("--status <status>", "Issue status")
|
|
.option("--priority <priority>", "Issue priority")
|
|
.option("--assignee-agent-id <id>", "Assignee agent ID")
|
|
.option("--project-id <id>", "Project ID")
|
|
.option("--goal-id <id>", "Goal ID")
|
|
.option("--parent-id <id>", "Parent issue ID")
|
|
.option(
|
|
"--standalone",
|
|
"Create a top-level issue. Without --parent-id, an agent run's issue otherwise becomes the parent.",
|
|
)
|
|
.option("--request-depth <n>", "Request depth integer")
|
|
.option("--billing-code <code>", "Billing code")
|
|
.option("--kv <key=value>", "Set key-value label (repeatable)", collectStringOption)
|
|
.option("--result-schema <ref>", "Required result schema reference (e.g. finding@1)")
|
|
.option("--channel <pathOrId>", "Channel path (e.g. build/auth) or UUID")
|
|
.option(
|
|
"--schema-block <ref=json>",
|
|
"Attach structured schema block (<name>@<ver>=<json> or JSON envelope, repeatable)",
|
|
collectStringOption,
|
|
)
|
|
.action(async (opts: IssueCreateOptions) => {
|
|
try {
|
|
if (opts.standalone && opts.parentId) {
|
|
throw new Error("--standalone cannot be combined with --parent-id");
|
|
}
|
|
const ctx = resolveCommandContext(opts, { requireCompany: true });
|
|
const payload = createIssueSchema.parse({
|
|
title: opts.title,
|
|
description: opts.description,
|
|
status: opts.status,
|
|
priority: opts.priority,
|
|
assigneeAgentId: opts.assigneeAgentId,
|
|
projectId: opts.projectId,
|
|
goalId: opts.goalId,
|
|
parentId: opts.standalone ? null : opts.parentId,
|
|
requestDepth: parseOptionalInt(opts.requestDepth),
|
|
billingCode: opts.billingCode,
|
|
kvLabels: parseKvPairs(opts.kv),
|
|
resultSchemaRef: opts.resultSchema,
|
|
channel: opts.channel,
|
|
schemaBlocks: parseSchemaBlockOptions(opts.schemaBlock),
|
|
});
|
|
|
|
const created = await ctx.api.post<Issue>(apiPath`/api/companies/${ctx.companyId}/issues`, payload);
|
|
printOutput(created, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
{ includeCompany: false },
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("update")
|
|
.description("Update an issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.option("--title <title>", "Issue title")
|
|
.option("--description <text>", "Issue description")
|
|
.option("--status <status>", "Issue status")
|
|
.option("--priority <priority>", "Issue priority")
|
|
.option("--assignee-agent-id <id>", "Assignee agent ID")
|
|
.option("--project-id <id>", "Project ID")
|
|
.option("--goal-id <id>", "Goal ID")
|
|
.option("--parent-id <id>", "Parent issue ID")
|
|
.option("--request-depth <n>", "Request depth integer")
|
|
.option("--billing-code <code>", "Billing code")
|
|
.option("--comment <text>", "Optional comment to add with update")
|
|
.option("--hidden-at <iso8601|null>", "Set hiddenAt timestamp or literal 'null'")
|
|
.option("--kv <key=value>", "Set key-value label (repeatable)", collectStringOption)
|
|
.option("--unset-kv <key>", "Unset key-value label key (repeatable)", collectStringOption)
|
|
.option("--result-schema <ref>", "Set required result schema ref, or pass 'none'/'' to clear")
|
|
.option("--channel <pathOrId>", "Move issue to channel path/UUID, or pass 'none'/'' to clear")
|
|
.option(
|
|
"--schema-block <ref=json>",
|
|
"Replace issue schema blocks (<name>@<ver>=<json> or JSON envelope, repeatable)",
|
|
collectStringOption,
|
|
)
|
|
.action(async (issueId: string, opts: IssueUpdateOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = updateIssueSchema.parse({
|
|
title: opts.title,
|
|
description: opts.description,
|
|
status: opts.status,
|
|
priority: opts.priority,
|
|
assigneeAgentId: opts.assigneeAgentId,
|
|
projectId: opts.projectId,
|
|
goalId: opts.goalId,
|
|
parentId: opts.parentId,
|
|
requestDepth: parseOptionalInt(opts.requestDepth),
|
|
billingCode: opts.billingCode,
|
|
comment: opts.comment,
|
|
hiddenAt: parseHiddenAt(opts.hiddenAt),
|
|
kvLabels: parseKvPatch(opts.kv, opts.unsetKv),
|
|
resultSchemaRef: parseNullableClearableOption(opts.resultSchema),
|
|
channel: parseNullableClearableOption(opts.channel),
|
|
schemaBlocks: parseSchemaBlockOptions(opts.schemaBlock),
|
|
});
|
|
|
|
const updated = await ctx.api.patch<Issue & { comment?: IssueComment | null }>(apiPath`/api/issues/${issueId}`, payload);
|
|
printOutput(updated, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("comment")
|
|
.description("Add comment to issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.requiredOption("--body <text>", "Comment body")
|
|
.option(
|
|
"--attachment-id <id...>",
|
|
"Bind uploaded issue attachments to this comment",
|
|
)
|
|
.option("--kv <key=value>", "Set comment key-value label (repeatable)", collectStringOption)
|
|
.option(
|
|
"--schema-block <ref=json>",
|
|
"Attach structured schema block (<name>@<ver>=<json> or JSON envelope, repeatable)",
|
|
collectStringOption,
|
|
)
|
|
.option("--reopen", "Reopen if issue is done/cancelled")
|
|
.option("--resume", "Request explicit follow-up and wake the assignee when resumable")
|
|
.action(async (issueId: string, opts: IssueCommentOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = addIssueCommentSchema.parse({
|
|
body: opts.body,
|
|
attachmentIds: opts.attachmentId,
|
|
kvLabels: parseKvPairs(opts.kv),
|
|
schemaBlocks: parseSchemaBlockOptions(opts.schemaBlock),
|
|
reopen: opts.reopen,
|
|
resume: opts.resume,
|
|
});
|
|
const comment = await ctx.api.post<IssueComment>(apiPath`/api/issues/${issueId}/comments`, payload);
|
|
printOutput(comment, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("comments")
|
|
.description("List issue comments")
|
|
.argument("<issueId>", "Issue ID")
|
|
.option("--after-comment-id <id>", "Only return comments after this comment ID")
|
|
.option("--order <order>", "asc or desc")
|
|
.option("--limit <n>", "Maximum comments to return")
|
|
.action(async (issueId: string, opts: IssueCommentListOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const params = new URLSearchParams();
|
|
if (opts.afterCommentId) params.set("afterCommentId", opts.afterCommentId);
|
|
if (opts.order) params.set("order", opts.order);
|
|
if (opts.limit) params.set("limit", opts.limit);
|
|
const query = params.toString();
|
|
const comments = (await ctx.api.get<IssueComment[]>(
|
|
`${apiPath`/api/issues/${issueId}/comments`}${query ? `?${query}` : ""}`,
|
|
)) ?? [];
|
|
printOutput(comments, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("comment:get")
|
|
.description("Get one issue comment")
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<commentId>", "Comment ID")
|
|
.action(async (issueId: string, commentId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const comment = await ctx.api.get<IssueComment>(apiPath`/api/issues/${issueId}/comments/${commentId}`);
|
|
printOutput(comment, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("comment:delete")
|
|
.description("Delete or cancel one issue comment")
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<commentId>", "Comment ID")
|
|
.action(async (issueId: string, commentId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const deleted = await ctx.api.delete<IssueComment>(apiPath`/api/issues/${issueId}/comments/${commentId}`);
|
|
printOutput(deleted, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("approvals")
|
|
.description("List approvals linked to an issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const approvals = await ctx.api.get(apiPath`/api/issues/${issueId}/approvals`);
|
|
printOutput(approvals, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("approval:link")
|
|
.description("Link an approval to an issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<approvalId>", "Approval ID")
|
|
.action(async (issueId: string, approvalId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = linkIssueApprovalSchema.parse({ approvalId });
|
|
const approvals = await ctx.api.post(apiPath`/api/issues/${issueId}/approvals`, payload);
|
|
printOutput(approvals, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("approval:unlink")
|
|
.description("Unlink an approval from an issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<approvalId>", "Approval ID")
|
|
.action(async (issueId: string, approvalId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const result = await ctx.api.delete(apiPath`/api/issues/${issueId}/approvals/${approvalId}`);
|
|
printOutput(result, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addIssuePostDeleteMarkerCommand(issue, "read", "Mark an issue as read", "post", "/read");
|
|
addIssuePostDeleteMarkerCommand(issue, "unread", "Mark an issue as unread", "delete", "/read");
|
|
addIssuePostDeleteMarkerCommand(issue, "archive", "Archive an issue from the inbox", "post", "/inbox-archive");
|
|
addIssuePostDeleteMarkerCommand(issue, "unarchive", "Unarchive an issue from the inbox", "delete", "/inbox-archive");
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("recovery-actions")
|
|
.description("List active recovery actions for an issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const result = await ctx.api.get(apiPath`/api/issues/${issueId}/recovery-actions`);
|
|
printOutput(result, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("recovery:resolve")
|
|
.description("Resolve an issue recovery action")
|
|
.argument("<issueId>", "Issue ID")
|
|
.requiredOption("--outcome <outcome>", "restored, false_positive, blocked, or cancelled")
|
|
.requiredOption("--source-issue-status <status>", "todo, done, or in_review for restored outcomes; blocked is only valid for blocked outcomes")
|
|
.option("--action-id <id>", "Specific recovery action ID")
|
|
.option("--resolution-note <text>", "Resolution note")
|
|
.action(async (issueId: string, opts: IssueRecoveryResolveOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = resolveIssueRecoveryActionSchema.parse({
|
|
actionId: opts.actionId,
|
|
outcome: opts.outcome,
|
|
sourceIssueStatus: opts.sourceIssueStatus,
|
|
resolutionNote: opts.resolutionNote,
|
|
});
|
|
const result = await ctx.api.post(apiPath`/api/issues/${issueId}/recovery-actions/resolve`, payload);
|
|
printOutput(result, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("child:create")
|
|
.description("Create a child issue from a JSON payload")
|
|
.argument("<issueId>", "Parent issue ID")
|
|
.requiredOption("--payload-json <json>", "CreateChildIssue JSON payload")
|
|
.action(async (issueId: string, opts: JsonPayloadOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = createChildIssueSchema.parse(parseJson(opts.payloadJson));
|
|
const child = await ctx.api.post<Issue>(apiPath`/api/issues/${issueId}/children`, payload);
|
|
printOutput(child, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("force-release")
|
|
.description("Force-release an issue from an agent checkout")
|
|
.argument("<issueId>", "Issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const result = await ctx.api.post(apiPath`/api/issues/${issueId}/admin/force-release`, {});
|
|
printOutput(result, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("work-products")
|
|
.description("List issue work products")
|
|
.argument("<issueId>", "Issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const rows = await ctx.api.get(apiPath`/api/issues/${issueId}/work-products`);
|
|
printOutput(rows, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("work-product:create")
|
|
.description("Create an issue work product from JSON")
|
|
.argument("<issueId>", "Issue ID")
|
|
.requiredOption("--payload-json <json>", "CreateIssueWorkProduct JSON payload")
|
|
.action(async (issueId: string, opts: JsonPayloadOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = createIssueWorkProductSchema.parse(parseJson(opts.payloadJson));
|
|
const product = await ctx.api.post(apiPath`/api/issues/${issueId}/work-products`, payload);
|
|
printOutput(product, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("work-product:update")
|
|
.description("Update a work product from JSON")
|
|
.argument("<workProductId>", "Work product ID")
|
|
.requiredOption("--payload-json <json>", "UpdateIssueWorkProduct JSON payload")
|
|
.action(async (workProductId: string, opts: JsonPayloadOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = updateIssueWorkProductSchema.parse(parseJson(opts.payloadJson));
|
|
const product = await ctx.api.patch(apiPath`/api/work-products/${workProductId}`, payload);
|
|
printOutput(product, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("work-product:delete")
|
|
.description("Delete a work product")
|
|
.argument("<workProductId>", "Work product ID")
|
|
.action(async (workProductId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const product = await ctx.api.delete(apiPath`/api/work-products/${workProductId}`);
|
|
printOutput(product, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("documents")
|
|
.description("List issue documents")
|
|
.argument("<issueId>", "Issue ID")
|
|
.option("--include-system", "Include system documents")
|
|
.action(async (issueId: string, opts: BaseClientOptions & { includeSystem?: boolean }) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const query = opts.includeSystem ? "?includeSystem=true" : "";
|
|
const docs = await ctx.api.get(`${apiPath`/api/issues/${issueId}/documents`}${query}`);
|
|
printOutput(docs, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("document:get")
|
|
.description("Get an issue document")
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<key>", "Document key")
|
|
.action(async (issueId: string, key: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const doc = await ctx.api.get(apiPath`/api/issues/${issueId}/documents/${key}`);
|
|
printOutput(doc, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("document:put")
|
|
.description("Create or update an issue document")
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<key>", "Document key")
|
|
.option("--title <title>", "Document title")
|
|
.option("--format <format>", "Document format", "markdown")
|
|
.option("--body <markdown>", "Document body")
|
|
.option("--body-file <path>", "Read document body from a file")
|
|
.option("--change-summary <text>", "Change summary")
|
|
.option("--base-revision-id <id>", "Expected base revision ID")
|
|
.action(async (issueId: string, key: string, opts: IssueDocumentPutOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const body = opts.bodyFile ? await readFile(opts.bodyFile, "utf8") : opts.body;
|
|
const payload = upsertIssueDocumentSchema.parse({
|
|
title: opts.title,
|
|
format: opts.format,
|
|
body,
|
|
changeSummary: opts.changeSummary,
|
|
baseRevisionId: opts.baseRevisionId,
|
|
});
|
|
const doc = await ctx.api.put(apiPath`/api/issues/${issueId}/documents/${key}`, payload);
|
|
printOutput(doc, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("interactions")
|
|
.description("List issue thread interactions")
|
|
.argument("<issueId>", "Issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const interactions = await ctx.api.get(apiPath`/api/issues/${issueId}/interactions`);
|
|
printOutput(interactions, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("interaction:create")
|
|
.description("Create an issue thread interaction from JSON")
|
|
.argument("<issueId>", "Issue ID")
|
|
.requiredOption("--payload-json <json>", "CreateIssueThreadInteraction JSON payload")
|
|
.action(async (issueId: string, opts: JsonPayloadOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = createIssueThreadInteractionSchema.parse(parseJson(opts.payloadJson));
|
|
const interaction = await ctx.api.post(apiPath`/api/issues/${issueId}/interactions`, payload);
|
|
printOutput(interaction, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("interaction:accept")
|
|
.description("Accept an issue thread interaction")
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<interactionId>", "Interaction ID")
|
|
.option("--selected-client-keys <csv>", "Client keys to accept")
|
|
.option("--selected-option-ids <csv>", "Checkbox option IDs to accept")
|
|
.action(async (issueId: string, interactionId: string, opts: InteractionAcceptOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = acceptIssueThreadInteractionSchema.parse({
|
|
selectedClientKeys: opts.selectedClientKeys === undefined ? undefined : parseCsv(opts.selectedClientKeys),
|
|
selectedOptionIds: opts.selectedOptionIds === undefined ? undefined : parseCsv(opts.selectedOptionIds),
|
|
});
|
|
const interaction = await ctx.api.post(apiPath`/api/issues/${issueId}/interactions/${interactionId}/accept`, payload);
|
|
printOutput(interaction, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
for (const [name, action, schema, description] of [
|
|
["interaction:reject", "reject", rejectIssueThreadInteractionSchema, "Reject an issue thread interaction"],
|
|
["interaction:cancel", "cancel", cancelIssueThreadInteractionSchema, "Cancel an issue thread interaction"],
|
|
] as const) {
|
|
addCommonClientOptions(
|
|
issue
|
|
.command(name)
|
|
.description(description)
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<interactionId>", "Interaction ID")
|
|
.option("--reason <text>", "Reason")
|
|
.action(async (issueId: string, interactionId: string, opts: InteractionReasonOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = schema.parse({ reason: opts.reason });
|
|
const interaction = await ctx.api.post(`${apiPath`/api/issues/${issueId}/interactions/${interactionId}`}/${action}`, payload);
|
|
printOutput(interaction, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
}
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("interaction:respond")
|
|
.description("Respond to an issue question interaction")
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<interactionId>", "Interaction ID")
|
|
.requiredOption("--answers-json <json>", "Answers array JSON")
|
|
.option("--summary-markdown <markdown>", "Optional response summary")
|
|
.action(async (issueId: string, interactionId: string, opts: InteractionRespondOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = respondIssueThreadInteractionSchema.parse({
|
|
answers: parseJson(opts.answersJson),
|
|
summaryMarkdown: opts.summaryMarkdown,
|
|
});
|
|
const interaction = await ctx.api.post(apiPath`/api/issues/${issueId}/interactions/${interactionId}/respond`, payload);
|
|
printOutput(interaction, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("tree-state")
|
|
.description("Get issue tree control state")
|
|
.argument("<issueId>", "Root issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const state = await ctx.api.get(apiPath`/api/issues/${issueId}/tree-control/state`);
|
|
printOutput(state, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("tree-preview")
|
|
.description("Preview issue tree control changes")
|
|
.argument("<issueId>", "Root issue ID")
|
|
.requiredOption("--payload-json <json>", "PreviewIssueTreeControl JSON payload")
|
|
.action(async (issueId: string, opts: JsonPayloadOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = previewIssueTreeControlSchema.parse(parseJson(opts.payloadJson));
|
|
const preview = await ctx.api.post(apiPath`/api/issues/${issueId}/tree-control/preview`, payload);
|
|
printOutput(preview, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("tree-holds")
|
|
.description("List issue tree holds")
|
|
.argument("<issueId>", "Root issue ID")
|
|
.option("--status <status>", "active or released")
|
|
.option("--mode <mode>", "pause, resume, cancel, or restore")
|
|
.option("--include-members", "Include hold members")
|
|
.action(async (issueId: string, opts: TreeHoldListOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const params = new URLSearchParams();
|
|
if (opts.status) params.set("status", opts.status);
|
|
if (opts.mode) params.set("mode", opts.mode);
|
|
if (opts.includeMembers) params.set("includeMembers", "true");
|
|
const query = params.toString();
|
|
const holds = await ctx.api.get(`${apiPath`/api/issues/${issueId}/tree-holds`}${query ? `?${query}` : ""}`);
|
|
printOutput(holds, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("tree-hold:create")
|
|
.description("Create an issue tree hold from JSON")
|
|
.argument("<issueId>", "Root issue ID")
|
|
.requiredOption("--payload-json <json>", "CreateIssueTreeHold JSON payload")
|
|
.action(async (issueId: string, opts: JsonPayloadOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = createIssueTreeHoldSchema.parse(parseJson(opts.payloadJson));
|
|
const hold = await ctx.api.post(apiPath`/api/issues/${issueId}/tree-holds`, payload);
|
|
printOutput(hold, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("tree-hold:get")
|
|
.description("Get an issue tree hold")
|
|
.argument("<issueId>", "Root issue ID")
|
|
.argument("<holdId>", "Hold ID")
|
|
.action(async (issueId: string, holdId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const hold = await ctx.api.get(apiPath`/api/issues/${issueId}/tree-holds/${holdId}`);
|
|
printOutput(hold, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("tree-hold:release")
|
|
.description("Release an issue tree hold")
|
|
.argument("<issueId>", "Root issue ID")
|
|
.argument("<holdId>", "Hold ID")
|
|
.option("--payload-json <json>", "ReleaseIssueTreeHold JSON payload", "{}")
|
|
.action(async (issueId: string, holdId: string, opts: JsonPayloadOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = releaseIssueTreeHoldSchema.parse(parseJson(opts.payloadJson));
|
|
const hold = await ctx.api.post(apiPath`/api/issues/${issueId}/tree-holds/${holdId}/release`, payload);
|
|
printOutput(hold, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("attachments")
|
|
.description("List issue attachments")
|
|
.argument("<issueId>", "Issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const attachments = await ctx.api.get(apiPath`/api/issues/${issueId}/attachments`);
|
|
printOutput(attachments, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("attachment:upload")
|
|
.description("Upload an issue attachment")
|
|
.argument("<issueId>", "Issue ID")
|
|
.option("-C, --company-id <id>", "Company ID")
|
|
.requiredOption("--file <path>", "File to upload")
|
|
.option("--comment-id <id>", "Attach to an issue comment")
|
|
.action(async (issueId: string, opts: IssueAttachmentUploadOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts, { requireCompany: true });
|
|
const attachment = await uploadAttachment(ctx.api.apiBase, ctx.api.apiKey, {
|
|
companyId: ctx.companyId ?? "",
|
|
issueId,
|
|
filePath: opts.file,
|
|
commentId: opts.commentId,
|
|
runId: ctx.api.runId,
|
|
});
|
|
printOutput(attachment, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
{ includeCompany: false },
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("attachment:download")
|
|
.description("Download an attachment")
|
|
.argument("<attachmentId>", "Attachment ID")
|
|
.option("--out <path>", "Output file path; prints to stdout when omitted")
|
|
.action(async (attachmentId: string, opts: IssueAttachmentDownloadOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const bytes = await downloadAttachment(ctx.api.apiBase, ctx.api.apiKey, attachmentId);
|
|
if (opts.out) {
|
|
await writeFile(opts.out, bytes);
|
|
if (ctx.json) printOutput({ out: opts.out, bytes: bytes.byteLength }, { json: true });
|
|
else console.log(`Wrote ${bytes.byteLength} byte(s) to ${opts.out}`);
|
|
return;
|
|
}
|
|
process.stdout.write(bytes);
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("attachment:delete")
|
|
.description("Delete an attachment")
|
|
.argument("<attachmentId>", "Attachment ID")
|
|
.action(async (attachmentId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const result = await ctx.api.delete(apiPath`/api/attachments/${attachmentId}`);
|
|
printOutput(result, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("label:list")
|
|
.description("List issue labels in a company")
|
|
.option("-C, --company-id <id>", "Company ID")
|
|
.action(async (opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts, { requireCompany: true });
|
|
const labels = await ctx.api.get(apiPath`/api/companies/${ctx.companyId}/labels`);
|
|
printOutput(labels, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
{ includeCompany: false },
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("label:create")
|
|
.description("Create an issue label")
|
|
.option("-C, --company-id <id>", "Company ID")
|
|
.requiredOption("--name <name>", "Label name")
|
|
.requiredOption("--color <hex>", "Label color, e.g. #4f46e5")
|
|
.action(async (opts: IssueLabelCreateOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts, { requireCompany: true });
|
|
const payload = createIssueLabelSchema.parse({ name: opts.name, color: opts.color });
|
|
const label = await ctx.api.post(apiPath`/api/companies/${ctx.companyId}/labels`, payload);
|
|
printOutput(label, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
{ includeCompany: false },
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("label:delete")
|
|
.description("Delete an issue label")
|
|
.argument("<labelId>", "Label ID")
|
|
.action(async (labelId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const result = await ctx.api.delete(apiPath`/api/labels/${labelId}`);
|
|
printOutput(result, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("feedback:votes")
|
|
.description("List feedback votes for an issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const votes = await ctx.api.get(apiPath`/api/issues/${issueId}/feedback-votes`);
|
|
printOutput(votes, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("feedback:vote")
|
|
.description("Create or update a feedback vote")
|
|
.argument("<issueId>", "Issue ID")
|
|
.requiredOption("--payload-json <json>", "UpsertIssueFeedbackVote JSON payload")
|
|
.action(async (issueId: string, opts: JsonPayloadOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = upsertIssueFeedbackVoteSchema.parse(parseJson(opts.payloadJson));
|
|
const vote = await ctx.api.post(apiPath`/api/issues/${issueId}/feedback-votes`, payload);
|
|
printOutput(vote, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
for (const [name, pathSuffix, description] of [
|
|
["document:delete", "", "Delete an issue document"],
|
|
["document:lock", "/lock", "Lock an issue document"],
|
|
["document:unlock", "/unlock", "Unlock an issue document"],
|
|
] as const) {
|
|
addCommonClientOptions(
|
|
issue
|
|
.command(name)
|
|
.description(description)
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<key>", "Document key")
|
|
.action(async (issueId: string, key: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const path = `${apiPath`/api/issues/${issueId}/documents/${key}`}${pathSuffix}`;
|
|
const result = name === "document:delete" ? await ctx.api.delete(path) : await ctx.api.post(path, {});
|
|
printOutput(result, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
}
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("document:revisions")
|
|
.description("List issue document revisions")
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<key>", "Document key")
|
|
.action(async (issueId: string, key: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const revisions = await ctx.api.get(apiPath`/api/issues/${issueId}/documents/${key}/revisions`);
|
|
printOutput(revisions, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("document:restore")
|
|
.description("Restore an issue document revision")
|
|
.argument("<issueId>", "Issue ID")
|
|
.argument("<key>", "Document key")
|
|
.argument("<revisionId>", "Revision ID")
|
|
.action(async (issueId: string, key: string, revisionId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = restoreIssueDocumentRevisionSchema.parse({});
|
|
const doc = await ctx.api.post(
|
|
apiPath`/api/issues/${issueId}/documents/${key}/revisions/${revisionId}/restore`,
|
|
payload,
|
|
);
|
|
printOutput(doc, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("feedback:list")
|
|
.description("List feedback traces for an issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.option("--target-type <type>", "Filter by target type")
|
|
.option("--vote <vote>", "Filter by vote value")
|
|
.option("--status <status>", "Filter by trace status")
|
|
.option("--from <iso8601>", "Only include traces created at or after this timestamp")
|
|
.option("--to <iso8601>", "Only include traces created at or before this timestamp")
|
|
.option("--shared-only", "Only include traces eligible for sharing/export")
|
|
.option("--include-payload", "Include stored payload snapshots in the response")
|
|
.action(async (issueId: string, opts: IssueFeedbackOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const traces = (await ctx.api.get<FeedbackTrace[]>(
|
|
`${apiPath`/api/issues/${issueId}/feedback-traces`}${buildFeedbackTraceQuery(opts)}`,
|
|
)) ?? [];
|
|
if (ctx.json) {
|
|
printOutput(traces, { json: true });
|
|
return;
|
|
}
|
|
printOutput(
|
|
traces.map((trace) => ({
|
|
id: trace.id,
|
|
issue: trace.issueIdentifier ?? trace.issueId,
|
|
vote: trace.vote,
|
|
status: trace.status,
|
|
targetType: trace.targetType,
|
|
target: trace.targetSummary.label,
|
|
})),
|
|
{ json: false },
|
|
);
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("runs")
|
|
.description("List heartbeat runs associated with an issue")
|
|
.argument("<issueId>", "Issue ID or identifier")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const rows = (await ctx.api.get<unknown[]>(apiPath`/api/issues/${issueId}/runs`)) ?? [];
|
|
printOutput(rows, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("live-runs")
|
|
.description("List queued and running heartbeat runs associated with an issue")
|
|
.argument("<issueId>", "Issue ID or identifier")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const rows = (await ctx.api.get<HeartbeatRun[]>(apiPath`/api/issues/${issueId}/live-runs`)) ?? [];
|
|
printOutput(rows, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("active-run")
|
|
.description("Show the active heartbeat run associated with an issue")
|
|
.argument("<issueId>", "Issue ID or identifier")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const run = await ctx.api.get<HeartbeatRun | null>(apiPath`/api/issues/${issueId}/active-run`);
|
|
printOutput(run, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("feedback:export")
|
|
.description("Export feedback traces for an issue")
|
|
.argument("<issueId>", "Issue ID")
|
|
.option("--target-type <type>", "Filter by target type")
|
|
.option("--vote <vote>", "Filter by vote value")
|
|
.option("--status <status>", "Filter by trace status")
|
|
.option("--from <iso8601>", "Only include traces created at or after this timestamp")
|
|
.option("--to <iso8601>", "Only include traces created at or before this timestamp")
|
|
.option("--shared-only", "Only include traces eligible for sharing/export")
|
|
.option("--include-payload", "Include stored payload snapshots in the export")
|
|
.option("--out <path>", "Write export to a file path instead of stdout")
|
|
.option("--format <format>", "Export format: json or ndjson", "ndjson")
|
|
.action(async (issueId: string, opts: IssueFeedbackOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const traces = (await ctx.api.get<FeedbackTrace[]>(
|
|
`${apiPath`/api/issues/${issueId}/feedback-traces`}${buildFeedbackTraceQuery(opts, opts.includePayload ?? true)}`,
|
|
)) ?? [];
|
|
const serialized = serializeFeedbackTraces(traces, opts.format);
|
|
if (opts.out?.trim()) {
|
|
await writeFile(opts.out, serialized, "utf8");
|
|
if (ctx.json) {
|
|
printOutput(
|
|
{ out: opts.out, count: traces.length, format: normalizeFeedbackTraceExportFormat(opts.format) },
|
|
{ json: true },
|
|
);
|
|
return;
|
|
}
|
|
console.log(`Wrote ${traces.length} feedback trace(s) to ${opts.out}`);
|
|
return;
|
|
}
|
|
process.stdout.write(`${serialized}${serialized.endsWith("\n") ? "" : "\n"}`);
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("checkout")
|
|
.description("Checkout issue for an agent")
|
|
.argument("<issueId>", "Issue ID")
|
|
.requiredOption("--agent-id <id>", "Agent ID")
|
|
.option(
|
|
"--expected-statuses <csv>",
|
|
"Expected current statuses",
|
|
"todo,backlog,blocked",
|
|
)
|
|
.action(async (issueId: string, opts: IssueCheckoutOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const payload = checkoutIssueSchema.parse({
|
|
agentId: opts.agentId,
|
|
expectedStatuses: parseCsv(opts.expectedStatuses),
|
|
});
|
|
const updated = await ctx.api.post<Issue>(apiPath`/api/issues/${issueId}/checkout`, payload);
|
|
printOutput(updated, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
|
|
addCommonClientOptions(
|
|
issue
|
|
.command("release")
|
|
.description("Release issue execution locks; clear the assignee only for unfinished issues")
|
|
.argument("<issueId>", "Issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const updated = await ctx.api.post<Issue>(apiPath`/api/issues/${issueId}/release`, {});
|
|
printOutput(updated, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
}
|
|
|
|
function parseCsv(value: string | undefined): string[] {
|
|
if (!value) return [];
|
|
return value.split(",").map((v) => v.trim()).filter(Boolean);
|
|
}
|
|
|
|
function addIssuePostDeleteMarkerCommand(
|
|
issue: Command,
|
|
name: string,
|
|
description: string,
|
|
method: "post" | "delete",
|
|
pathSuffix: string,
|
|
): void {
|
|
addCommonClientOptions(
|
|
issue
|
|
.command(name)
|
|
.description(description)
|
|
.argument("<issueId>", "Issue ID")
|
|
.action(async (issueId: string, opts: BaseClientOptions) => {
|
|
try {
|
|
const ctx = resolveCommandContext(opts);
|
|
const result = method === "post"
|
|
? await ctx.api.post(`${apiPath`/api/issues/${issueId}`}${pathSuffix}`, {})
|
|
: await ctx.api.delete(`${apiPath`/api/issues/${issueId}`}${pathSuffix}`);
|
|
printOutput(result, { json: ctx.json });
|
|
} catch (err) {
|
|
handleCommandError(err);
|
|
}
|
|
}),
|
|
);
|
|
}
|
|
|
|
function parseJson(value: string): unknown {
|
|
return JSON.parse(value) as unknown;
|
|
}
|
|
|
|
function parseOptionalInt(value: string | undefined): number | undefined {
|
|
if (value === undefined) return undefined;
|
|
const parsed = Number.parseInt(value, 10);
|
|
if (!Number.isFinite(parsed)) {
|
|
throw new Error(`Invalid integer value: ${value}`);
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
function collectStringOption(value: string, previous: string[] = []): string[] {
|
|
return [...previous, value];
|
|
}
|
|
|
|
function parseKvPairs(entries: string[] | undefined): Record<string, string> | undefined {
|
|
if (!entries || entries.length === 0) return undefined;
|
|
const out: Record<string, string> = {};
|
|
for (const raw of entries) {
|
|
const eqIdx = raw.indexOf("=");
|
|
if (eqIdx <= 0) {
|
|
throw new Error(`Invalid --kv '${raw}': expected key=value`);
|
|
}
|
|
const key = raw.slice(0, eqIdx).trim();
|
|
const value = raw.slice(eqIdx + 1);
|
|
if (!key || value.length === 0) {
|
|
throw new Error(`Invalid --kv '${raw}': key and value must be non-empty`);
|
|
}
|
|
out[key] = value;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function parseKvPatch(
|
|
setEntries: string[] | undefined,
|
|
unsetKeys: string[] | undefined,
|
|
): Record<string, string | null> | undefined {
|
|
if (
|
|
(!setEntries || setEntries.length === 0) &&
|
|
(!unsetKeys || unsetKeys.length === 0)
|
|
) {
|
|
return undefined;
|
|
}
|
|
const patch: Record<string, string | null> = {};
|
|
for (const rawKey of unsetKeys ?? []) {
|
|
const key = rawKey.trim();
|
|
if (!key) {
|
|
throw new Error("Invalid --unset-kv: key must be non-empty");
|
|
}
|
|
patch[key] = null;
|
|
}
|
|
const pairs = parseKvPairs(setEntries);
|
|
if (pairs) {
|
|
for (const [key, value] of Object.entries(pairs)) {
|
|
if (Object.prototype.hasOwnProperty.call(patch, key) && patch[key] === null) {
|
|
throw new Error(`Conflicting --kv and --unset-kv for key '${key}'`);
|
|
}
|
|
patch[key] = value;
|
|
}
|
|
}
|
|
return patch;
|
|
}
|
|
|
|
function parseNullableClearableOption(
|
|
value: string | undefined,
|
|
): string | null | undefined {
|
|
if (value === undefined) return undefined;
|
|
const trimmed = value.trim();
|
|
if (
|
|
trimmed === "" ||
|
|
trimmed.toLowerCase() === "none" ||
|
|
trimmed.toLowerCase() === "null"
|
|
) {
|
|
return null;
|
|
}
|
|
return trimmed;
|
|
}
|
|
|
|
function parseSchemaBlockOptions(
|
|
entries: string[] | undefined,
|
|
): SchemaBlock[] | undefined {
|
|
if (!entries || entries.length === 0) return undefined;
|
|
return entries.map(parseSingleSchemaBlockOption);
|
|
}
|
|
|
|
function parseSingleSchemaBlockOption(raw: string): SchemaBlock {
|
|
const trimmed = raw.trim();
|
|
if (trimmed.startsWith("{")) {
|
|
let parsed: unknown;
|
|
try {
|
|
parsed = JSON.parse(trimmed);
|
|
} catch {
|
|
throw new Error(`Invalid --schema-block JSON envelope: ${raw}`);
|
|
}
|
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
throw new Error(`Invalid --schema-block '${raw}': expected JSON object`);
|
|
}
|
|
const obj = parsed as Record<string, unknown>;
|
|
if (
|
|
typeof obj.ref === "string" ||
|
|
(typeof obj.schema === "string" && obj.schema.includes("@"))
|
|
) {
|
|
const refStr = typeof obj.ref === "string" ? obj.ref : String(obj.schema);
|
|
const parsedRef = parseSchemaRef(refStr.trim().toLowerCase());
|
|
return schemaBlockSchema.parse({
|
|
schema: parsedRef.name,
|
|
version: parsedRef.version,
|
|
data: obj.data,
|
|
});
|
|
}
|
|
return schemaBlockSchema.parse(obj);
|
|
}
|
|
|
|
const eqIdx = trimmed.indexOf("=");
|
|
if (eqIdx <= 0) {
|
|
throw new Error(
|
|
`Invalid --schema-block '${raw}': expected <name>@<version>=<json-object> or JSON envelope`,
|
|
);
|
|
}
|
|
const refStr = trimmed.slice(0, eqIdx).trim().toLowerCase();
|
|
const jsonPart = trimmed.slice(eqIdx + 1).trim();
|
|
const parsedRef = parseSchemaRef(refStr);
|
|
let parsedData: unknown;
|
|
try {
|
|
parsedData = JSON.parse(jsonPart);
|
|
} catch {
|
|
throw new Error(
|
|
`Invalid --schema-block '${raw}': payload after '=' must be valid JSON`,
|
|
);
|
|
}
|
|
if (!parsedData || typeof parsedData !== "object" || Array.isArray(parsedData)) {
|
|
throw new Error(
|
|
`Invalid --schema-block '${raw}': payload after '=' must be a JSON object`,
|
|
);
|
|
}
|
|
return schemaBlockSchema.parse({
|
|
schema: parsedRef.name,
|
|
version: parsedRef.version,
|
|
data: parsedData,
|
|
});
|
|
}
|
|
|
|
function parseHiddenAt(value: string | undefined): string | null | undefined {
|
|
if (value === undefined) return undefined;
|
|
if (value.trim().toLowerCase() === "null") return null;
|
|
return value;
|
|
}
|
|
|
|
function filterIssueRows(rows: Issue[], match: string | undefined): Issue[] {
|
|
if (!match?.trim()) return rows;
|
|
const needle = match.trim().toLowerCase();
|
|
return rows.filter((row) => {
|
|
const text = [row.identifier, row.title, row.description]
|
|
.filter((part): part is string => Boolean(part))
|
|
.join("\n")
|
|
.toLowerCase();
|
|
return text.includes(needle);
|
|
});
|
|
}
|
|
|
|
function buildApiUrl(apiBase: string, path: string): string {
|
|
const url = new URL(apiBase);
|
|
url.pathname = `${url.pathname.replace(/\/+$/, "")}${path.startsWith("/") ? path : `/${path}`}`;
|
|
return url.toString();
|
|
}
|
|
|
|
async function uploadAttachment(
|
|
apiBase: string,
|
|
apiKey: string | undefined,
|
|
input: { companyId: string; issueId: string; filePath: string; commentId?: string; runId?: string },
|
|
): Promise<unknown> {
|
|
const bytes = await readFile(input.filePath);
|
|
const form = new FormData();
|
|
form.set("file", new Blob([bytes], { type: inferContentTypeFromPath(input.filePath) }), input.filePath.split(/[\\/]/).pop() ?? "attachment");
|
|
if (input.commentId) form.set("issueCommentId", input.commentId);
|
|
// This multipart upload uses a hand-rolled fetch rather than PaperclipApiClient,
|
|
// so it must forward the agent run-id header itself — otherwise an
|
|
// agent-authenticated upload is rejected with "401 Agent run id required"
|
|
// (the client injects x-paperclip-run-id automatically for JSON requests).
|
|
const headers: Record<string, string> = {};
|
|
if (apiKey) headers.authorization = `Bearer ${apiKey}`;
|
|
if (input.runId) headers["x-paperclip-run-id"] = input.runId;
|
|
const response = await fetch(buildApiUrl(apiBase, apiPath`/api/companies/${input.companyId}/issues/${input.issueId}/attachments`), {
|
|
method: "POST",
|
|
headers,
|
|
body: form,
|
|
});
|
|
return parseFetchResponse(response);
|
|
}
|
|
|
|
async function downloadAttachment(
|
|
apiBase: string,
|
|
apiKey: string | undefined,
|
|
attachmentId: string,
|
|
): Promise<Buffer> {
|
|
const response = await fetch(buildApiUrl(apiBase, apiPath`/api/attachments/${attachmentId}/content`), {
|
|
headers: apiKey ? { authorization: `Bearer ${apiKey}` } : undefined,
|
|
});
|
|
if (!response.ok) {
|
|
await parseFetchResponse(response);
|
|
}
|
|
return Buffer.from(await response.arrayBuffer());
|
|
}
|
|
|
|
async function parseFetchResponse(response: Response): Promise<unknown> {
|
|
const text = await response.text();
|
|
const parsed = text.trim() ? safeJson(text) : null;
|
|
if (!response.ok) {
|
|
const message =
|
|
typeof parsed === "object" && parsed !== null && "error" in parsed && typeof parsed.error === "string"
|
|
? parsed.error
|
|
: `Request failed with status ${response.status}`;
|
|
throw new Error(`API error ${response.status}: ${message}`);
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
function safeJson(text: string): unknown {
|
|
try {
|
|
return JSON.parse(text) as unknown;
|
|
} catch {
|
|
return text;
|
|
}
|
|
}
|