@moondeck/station 1.0.12 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,416 @@
1
+ /** Embedded into the standalone CLI. No runtime dependency is shipped. */
2
+ export const ISSUE_CLI_SOURCE = String.raw`
3
+ function issueUsage(message) { throw new Error("issue: " + message); }
4
+ function issueFlags(args, allowed, booleans = ["json"]) {
5
+ const flags = {}; const positional = [];
6
+ for (let i = 0; i < args.length; i++) {
7
+ let arg = args[i];
8
+ if (arg === "-q") arg = "--q";
9
+ if (!arg.startsWith("--")) {
10
+ if (arg.startsWith("-")) issueUsage("unknown option " + arg);
11
+ positional.push(arg); continue;
12
+ }
13
+ const name = arg.slice(2);
14
+ if (!allowed.includes(name)) issueUsage("unknown option --" + name);
15
+ const repeated = ["assignee", "label", "labels", "remove-label", "mention"].includes(name);
16
+ if (!repeated && flags[name] !== undefined) issueUsage("duplicate option --" + name);
17
+ if (booleans.includes(name)) { flags[name] = true; continue; }
18
+ const value = args[++i];
19
+ if (value === undefined || value.startsWith("--") || value === "-q") issueUsage("--" + name + " needs a value");
20
+ if (repeated) (flags[name] ||= []).push(value);
21
+ else flags[name] = value;
22
+ }
23
+ if (flags.limit !== undefined && (!/^[0-9]+$/.test(flags.limit) || Number(flags.limit) < 1 || Number(flags.limit) > 100))
24
+ issueUsage("--limit must be an integer from 1 to 100");
25
+ if (flags.priority !== undefined && !["none", "low", "normal", "high", "urgent"].includes(flags.priority))
26
+ issueUsage("--priority must be none, low, normal, high or urgent");
27
+ return { flags, positional };
28
+ }
29
+ function issueKey(positional) {
30
+ if (positional.length !== 1 || !/^[a-z][a-z0-9]{1,5}-[1-9][0-9]*$/i.test(positional[0]))
31
+ issueUsage("supply one Issue identifier, such as ISS-12");
32
+ return positional[0];
33
+ }
34
+ function issueExpectedRevision(flags) {
35
+ const expected = flags["expected-revision"];
36
+ if (expected !== undefined && (!/^[0-9]+$/.test(expected) || !Number.isSafeInteger(Number(expected))))
37
+ issueUsage("--expected-revision must be a nonnegative safe integer");
38
+ return expected === undefined ? undefined : Number(expected);
39
+ }
40
+ function issueLabelOptions(flags) {
41
+ const add = flags.label || [], remove = flags["remove-label"] || [];
42
+ const replace = flags.labels !== undefined, clear = !!flags["clear-labels"];
43
+ if ((replace && clear) || ((replace || clear) && (add.length || remove.length)))
44
+ issueUsage("--labels and --clear-labels cannot be combined with each other or --label/--remove-label");
45
+ const names = replace ? flags.labels : [...add, ...remove];
46
+ if (names.some(name => !name.trim())) issueUsage("label names cannot be empty; use --clear-labels to remove all labels");
47
+ return { add, remove, replace: replace ? names : undefined, clear, changed: replace || clear || !!names.length };
48
+ }
49
+ async function issueLabelCatalog() {
50
+ return api("GET", "/api/agent/issues/labels");
51
+ }
52
+ function issueLabelIds(catalog, names) {
53
+ return [...new Set(names.map(name => {
54
+ const key = name.trim().replace(/\s+/g, " ").toLowerCase();
55
+ const label = catalog.labels.find(label => (label.nameKey ?? label.name.toLowerCase()) === key);
56
+ if (!label) issueUsage("unknown label " + JSON.stringify(name) + ". Run issue labels to see the workspace catalog; ask a human to create missing labels. Nothing was changed");
57
+ return label.id;
58
+ }))];
59
+ }
60
+ async function issueLabelSet(options, current = []) {
61
+ if (options.clear) return [];
62
+ const catalog = await issueLabelCatalog();
63
+ if (options.replace) return issueLabelLimit(issueLabelIds(catalog, options.replace));
64
+ const add = issueLabelIds(catalog, options.add), remove = issueLabelIds(catalog, options.remove);
65
+ if (add.some(id => remove.includes(id))) issueUsage("cannot add and remove the same label in one update");
66
+ return issueLabelLimit([...new Set([...current.filter(id => !remove.includes(id)), ...add])]);
67
+ }
68
+ function issueLabelLimit(ids) {
69
+ if (ids.length > 50) issueUsage("an Issue accepts at most 50 labels; nothing was changed");
70
+ return ids;
71
+ }
72
+ function issueDescription(flags) {
73
+ if (flags["description-file"] !== undefined && flags.description !== undefined)
74
+ issueUsage("--description-file cannot be combined with --description (text or stdin)");
75
+ const file = flags["description-file"];
76
+ if (file === undefined && flags.description === undefined) return flags["clear-description"] ? "" : undefined;
77
+ if ((file === "-" || flags.description === "-") && process.stdin.isTTY)
78
+ issueUsage("description stdin is a terminal; pipe Markdown or use --description-file PATH");
79
+ const description = file !== undefined ? readFlagFile(file) : flags.description === "-" ? readFlagFile("-") : flags.description;
80
+ if (description.length > 100000) issueUsage("description exceeds the 100,000 UTF-16 code unit limit (received " + description.length + "); nothing was sent");
81
+ if (description.includes(String.fromCharCode(0))) issueUsage("description cannot contain NUL; nothing was sent");
82
+ if (!description.trim()) {
83
+ if (!flags["clear-description"]) issueUsage("description is empty or whitespace-only; nothing was sent. Use --clear-description to erase it intentionally");
84
+ return "";
85
+ }
86
+ if (flags["clear-description"]) issueUsage("--clear-description cannot be combined with a nonempty description");
87
+ return description;
88
+ }
89
+ function issueChecklistLine(item) {
90
+ return item.index + " [" + (item.checked ? "x" : " ") + "] " + item.text;
91
+ }
92
+ function issueParentKey(flags) {
93
+ if (flags.parent !== undefined) {
94
+ if (!/^[a-z][a-z0-9]{1,5}-[1-9][0-9]*$/i.test(flags.parent))
95
+ issueUsage("--parent needs an Issue identifier, such as ISS-12");
96
+ if (flags["no-parent"]) issueUsage("--parent and --no-parent cannot be combined");
97
+ }
98
+ }
99
+ async function issueParentId(base, key) {
100
+ const detail = await api("GET", base + "/" + encodeURIComponent(key), undefined, { parentLookup: key });
101
+ return detail.issue.id;
102
+ }
103
+ function issueHierarchyLine(issue) {
104
+ return issue.key + " " + issue.title + " [" + issue.status.name + "]";
105
+ }
106
+ function issueErrorHint(code, status, context, retryAfter, details) {
107
+ if (context?.commentAction && status === 403)
108
+ console.error("Comments require issues.read + issues.write within the owner's rights; a human must grant missing issues.write. Edit/delete requires the same owner, Task and agent that posted the comment.");
109
+ if (context?.commentAction && code === "ISSUE_COMMENT_CONFLICT")
110
+ console.error("No changes saved: the comment changed since revision " + context.commentRevision + ". Rerun issue comments --json and use the comment revision, not the Issue revision. No automatic retry.");
111
+ if (context?.commentAction && code === "ISSUE_CHAT_IDEMPOTENCY_CONFLICT")
112
+ console.error("No new comment saved: this clientRequestId belongs to different content or another agent. Inspect issue comments --json; do not blindly post again.");
113
+ if (context?.commentAction && code === "ISSUE_MENTION_INVALID")
114
+ console.error("A mentioned member is no longer eligible to read this Issue. Refresh member names and permissions before posting; no automatic retry.");
115
+ if (status === 403 && context?.archiveAction)
116
+ console.error("No changes saved. Issue " + context.archiveAction + " requires issues.read + issues.write within the owner's rights; a human must grant issues.write if it is missing in Task permissions.");
117
+ if (status === 409 && context?.checklistIndex !== undefined) {
118
+ console.error("Nothing changed. Inspect the current checklist before retrying intentionally with --expected-revision.");
119
+ if (typeof details?.description === "string") {
120
+ const item = parseIssueChecklist(details.description).items[context.checklistIndex];
121
+ console.error("Current item at index " + context.checklistIndex + " (revision " + details.currentRevision + "): " +
122
+ (item ? issueChecklistLine(item) : "no item at this index"));
123
+ } else console.error("Current checklist unavailable in the conflict response; rerun issue checklist.");
124
+ }
125
+ if (status === 503 && code === "ISSUE_ACCESS_BUSY") {
126
+ const delay = /^\d+$/.test(retryAfter || "") ? Number(retryAfter) : Math.ceil((Date.parse(retryAfter) - Date.now()) / 1000);
127
+ const seconds = Number.isFinite(delay) ? Math.max(0, delay) : 1;
128
+ console.error("No changes saved; wait " + seconds + " s" + (retryAfter ? " (from Retry-After)" : " (Retry-After unavailable)") + ", rerun issue show, retry with --expected-revision. No automatic retry.");
129
+ }
130
+ if (code === "ISSUE_PARENT_CYCLE")
131
+ console.error("No changes saved. An Issue cannot be its own parent or have one of its descendants as parent (cycle).");
132
+ if (code === "ISSUE_DEPTH_LIMIT")
133
+ console.error("No changes saved. The parent would exceed 10 parent edges from the root, including the moved subtree. Choose a shallower parent.");
134
+ if (context?.parentLookup && status === 404)
135
+ console.error("Parent " + context.parentLookup + " was not found in this workspace. Cross-workspace parents are not supported; check the key and workspace.");
136
+ else if (context?.parentKey && code === "ISSUE_NOT_FOUND")
137
+ console.error("The Issue or parent was not found in this workspace. Cross-workspace parents are not supported; inspect both Issues before retrying.");
138
+ if (context?.parentLookup && status === 403)
139
+ console.error("Reading parent " + context.parentLookup + " requires issues.read within the human owner's Issue permissions. A human must grant the missing access before setting this parent.");
140
+ else if (context?.parentKey && status === 403)
141
+ console.error("Setting a parent requires issues.read on the parent and issues.write on the child, within the human owner's permissions. A human must grant any missing access.");
142
+ }
143
+ function issueLine(issue) {
144
+ const assignees = (issue.assignees || []).map((a) => a.handle ? "@" + a.handle : a.name || a.userId).join(", ") || "unassigned";
145
+ return issue.identifier + (issue.archivedAt != null ? " [archived]" : "") + " " + issue.title + " [" + (issue.status?.name || issue.statusId) + "] " + issue.priority +
146
+ " " + (issue.project?.key || issue.projectId) + " " + assignees +
147
+ " labels: " + ((issue.labels || []).map(label => label.name).join(", ") || "none");
148
+ }
149
+ function issuePage(page, current, json) {
150
+ if (json) return out(page);
151
+ const issues = current ? page.issues.map((entry) => entry.issue) : page.issues;
152
+ out(issues.length ? issues.map(issueLine).join(NL) : "No issues.");
153
+ if (page.nextCursor) out("More issues: repeat this command with --cursor " + page.nextCursor);
154
+ }
155
+ async function issueReadDetail(key, initial) {
156
+ const base = "/api/agent/issues";
157
+ const detail = initial || await api("GET", base + "/" + encodeURIComponent(key));
158
+ // Detail's first page is scoped on the server. Continue only when the
159
+ // agent is allowed linked Task details; never reconstruct scope locally.
160
+ let cursor = detail.tasksPage?.nextCursor;
161
+ while (detail.linkedTasksAvailable && cursor) {
162
+ const page = await api("GET", base + "/" + encodeURIComponent(key) + "/tasks?limit=100&cursor=" + encodeURIComponent(cursor));
163
+ detail.tasks.push(...page.tasks); cursor = page.nextCursor;
164
+ }
165
+ if (detail.tasksPage) detail.tasksPage.nextCursor = cursor || null;
166
+ // Children use the detail endpoint's own cursor, independently of Task
167
+ // visibility. Keep the first snapshot's fields and server progress counts.
168
+ let childrenCursor = detail.childrenPage?.nextCursor;
169
+ const seenCursors = new Set();
170
+ const children = new Map();
171
+ let duplicateChildren = false;
172
+ function addChildren(rows) {
173
+ for (const child of rows || []) {
174
+ if (children.has(child.id)) duplicateChildren = true;
175
+ else children.set(child.id, child);
176
+ }
177
+ }
178
+ addChildren(detail.children);
179
+ let pages = 1;
180
+ let stopReason;
181
+ let changedTotal = false;
182
+ while (childrenCursor) {
183
+ if (seenCursors.has(childrenCursor)) { stopReason = "repeated cursor"; break; }
184
+ if (pages >= 50) { stopReason = "50-page limit"; break; }
185
+ seenCursors.add(childrenCursor);
186
+ const page = await api("GET", base + "/" + encodeURIComponent(key) + "?childrenLimit=100&childrenCursor=" + encodeURIComponent(childrenCursor));
187
+ pages++;
188
+ addChildren(page.children);
189
+ if (page.childrenPage?.totalCount !== detail.childrenPage.totalCount) changedTotal = true;
190
+ childrenCursor = page.childrenPage?.nextCursor;
191
+ }
192
+ if (detail.children) detail.children = [...children.values()];
193
+ if (detail.childrenPage) {
194
+ detail.childrenPage.nextCursor = childrenCursor || null;
195
+ const reasons = [];
196
+ if (stopReason) reasons.push("stopped at " + stopReason);
197
+ if (duplicateChildren) reasons.push("duplicate children across pages");
198
+ if (changedTotal) reasons.push("total count changed between pages");
199
+ if (children.size !== detail.childrenPage.totalCount)
200
+ reasons.push("merged " + children.size + " children; expected " + detail.childrenPage.totalCount);
201
+ detail.childrenPage.consistent = reasons.length === 0;
202
+ if (stopReason) detail.childrenPage.stopReason = stopReason;
203
+ if (reasons.length) console.error("Warning: child listing may be incomplete or changed during paging (" + reasons.join("; ") + "). Rerun issue show before relying on this list.");
204
+ }
205
+ return issueDetailContext(detail);
206
+ }
207
+ function issueDetailContext(detail) {
208
+ // Absolute appOrigin links take precedence. Only a relative server fallback
209
+ // uses the CLI app base, retaining any explicitly configured proxy prefix.
210
+ if (detail.url) detail.url = new URL(detail.url.replace(/^\/+/, ""), APP_URL.replace(/\/+$/, "") + "/").href;
211
+ detail.checklist ||= parseIssueChecklist(detail.issue.description || "");
212
+ return detail;
213
+ }
214
+ async function issueCommand(action, args) {
215
+ if (action === "comment") return issueCommentCommand(args);
216
+ if (action === "attachment") return issueAttachmentGet(args);
217
+ if (["attachments", "attach", "detach"].includes(action)) return issueAttachmentsCommand(action, args);
218
+ const base = "/api/agent/issues";
219
+ if (action === "labels") {
220
+ const { flags, positional } = issueFlags(args, ["json"]);
221
+ if (positional.length) issueUsage("labels does not take positional arguments");
222
+ const catalog = await issueLabelCatalog();
223
+ return out(flags.json ? catalog : catalog.labels.length
224
+ ? catalog.labels.map(label => label.name + " " + label.color + " " + label.id).join(NL) : "No workspace labels.");
225
+ }
226
+ if (action === "list" || action === "current") {
227
+ const allowed = action === "list" ? ["status", "assignee", "project", "priority", "label", "archived", "q", "limit", "cursor", "no-sub-issues", "exclude-tree-of", "json"] : ["limit", "cursor", "json"];
228
+ const { flags, positional } = issueFlags(args, allowed, ["json", "no-sub-issues"]);
229
+ if (positional.length) issueUsage(action + " does not take positional arguments");
230
+ if (action === "current" && flags.limit !== undefined && Number(flags.limit) > 5) issueUsage("current --limit must be from 1 to 5");
231
+ if (flags.assignee?.length > 1) issueUsage("list accepts one --assignee");
232
+ if (flags.archived !== undefined && !["only", "include"].includes(flags.archived))
233
+ issueUsage("--archived must be only or include; omit it to exclude archived Issues");
234
+ const labels = issueLabelOptions(flags);
235
+ const query = new URLSearchParams();
236
+ for (const [name, value] of Object.entries(flags)) if (name !== "json" && name !== "label" && name !== "no-sub-issues" && name !== "exclude-tree-of") query.set(name, name === "assignee" ? value[0] : value);
237
+ if (labels.changed) for (const id of await issueLabelSet(labels)) query.append("labelIds", id);
238
+ if (flags["exclude-tree-of"] !== undefined) {
239
+ const selector = flags["exclude-tree-of"];
240
+ if (!selector.trim() || selector.length > 128 || selector.includes(String.fromCharCode(0))) issueUsage("--exclude-tree-of needs an Issue key or internal ID");
241
+ const root = await api("GET", base + "/" + encodeURIComponent(selector));
242
+ query.set("excludeTreeOf", root.issue.id);
243
+ }
244
+ if (flags["no-sub-issues"]) query.set("showSubIssues", "false");
245
+ const page = await api("GET", base + (action === "current" ? "/current" : "") + "?" + query);
246
+ if (action === "current" && flags.json) {
247
+ page.issues = page.issues.map(issueDetailContext);
248
+ }
249
+ if (page.skippedIssues) console.error("Warning: " + page.skippedIssues + " Issue(s) disappeared while reading current; refresh or continue with the returned cursor.");
250
+ return issuePage(page, action === "current", flags.json);
251
+ }
252
+ if (action === "comments") {
253
+ const { flags, positional } = issueFlags(args, ["limit", "before-seq", "json"]);
254
+ const key = issueKey(positional);
255
+ if (flags["before-seq"] !== undefined && (!/^[0-9]+$/.test(flags["before-seq"]) || !Number.isSafeInteger(Number(flags["before-seq"])) || Number(flags["before-seq"]) < 1))
256
+ issueUsage("--before-seq must be a positive safe integer");
257
+ const limit = Number(flags.limit || 50), comments = [], seen = new Set(), cursors = new Set();
258
+ let cursor = flags["before-seq"] === undefined ? null : Number(flags["before-seq"]);
259
+ let warning;
260
+ for (let pages = 0; pages < 50; pages++) {
261
+ if (cursor !== null && cursors.has(cursor)) { warning = "repeated history cursor"; break; }
262
+ if (cursor !== null) cursors.add(cursor);
263
+ const query = new URLSearchParams({ limit: "100" });
264
+ if (cursor !== null) query.set("beforeSeq", String(cursor));
265
+ const page = await api("GET", base + "/" + encodeURIComponent(key) + "/chat?" + query);
266
+ const rows = page.messages.filter(message => message.kind === "comment" && !seen.has(message.id)).sort((a, b) => b.seq - a.seq);
267
+ const selected = rows.slice(0, limit - comments.length);
268
+ for (const row of selected) { seen.add(row.id); comments.push(row); }
269
+ cursor = rows.length > selected.length ? selected.at(-1).seq : page.nextBeforeSeq;
270
+ if (cursor == null || comments.length >= limit) break;
271
+ if (pages === 49) warning = "50-page limit";
272
+ }
273
+ if (warning) console.error("Warning: stopped at " + warning + "; comment listing may be incomplete.");
274
+ const result = { comments, nextBeforeSeq: cursor ?? null, ...(warning ? { warning } : {}) };
275
+ if (flags.json) return out(result);
276
+ out(comments.length ? comments.map(comment => new Date(comment.createdAt).toISOString() + " " + comment.actor.name +
277
+ " " + comment.id + " (revision " + comment.revision + ")" + (comment.deletedAt != null ? " [removed]" : "") + NL +
278
+ (comment.deletedAt != null ? "Message removed" : comment.body)).join(NL + NL) : "No comments.");
279
+ if (cursor != null) out("More comments: issue comments " + key + " --before-seq " + cursor);
280
+ return;
281
+ }
282
+ if (action === "archive" || action === "restore") {
283
+ const { flags, positional } = issueFlags(args, ["expected-revision", "json", ...(action === "archive" ? ["include-sub-issues"] : [])], ["json", "include-sub-issues"]);
284
+ const key = issueKey(positional);
285
+ const expected = issueExpectedRevision(flags);
286
+ const path = base + "/" + encodeURIComponent(key);
287
+ const body = { expectedRevision: expected ?? (await api("GET", path)).issue.revision };
288
+ if (action === "archive") body.includeSubIssues = !!flags["include-sub-issues"];
289
+ const result = await api("POST", path + "/" + action, body, { archiveAction: action });
290
+ return out(flags.json ? result : (action === "archive" ? "Archived " : "Restored ") + result.issue.identifier +
291
+ " (" + result.affectedIssueIds.length + " Issue(s) affected; revision " + result.issue.revision + "). " +
292
+ (action === "archive" ? "No Issues deleted; linked Tasks keep running." : "Only this Issue restored; status retained."));
293
+ }
294
+ if (action === "activity") {
295
+ const { flags, positional } = issueFlags(args, ["limit", "cursor", "json"]);
296
+ const key = issueKey(positional);
297
+ const query = new URLSearchParams();
298
+ for (const name of ["limit", "cursor"]) if (flags[name] !== undefined) query.set(name, flags[name]);
299
+ const page = await api("GET", base + "/" + encodeURIComponent(key) + "/activity" + (query.size ? "?" + query : ""));
300
+ if (flags.json) return out(page);
301
+ out(page.events.length ? page.events.map((event) => {
302
+ const actor = event.actor.kind === "system" ? "system" : event.actor.kind === "agent"
303
+ ? "agent " + (event.actor.agentId || "(unavailable)") + " (owner " + event.actor.userId + ")" : event.actor.userId;
304
+ return new Date(event.occurredAt).toISOString() + " " + actor + " " + event.summary;
305
+ }).join(NL) : "No activity.");
306
+ if (page.nextCursor) out("More activity: repeat this command with --cursor " + page.nextCursor);
307
+ return;
308
+ }
309
+ if (action === "checklist" || action === "check" || action === "uncheck") {
310
+ const reading = action === "checklist";
311
+ const { flags, positional } = issueFlags(args, reading ? ["json"] : ["expected-revision", "json"]);
312
+ const key = issueKey(reading ? positional : positional.slice(0, 1));
313
+ const expected = issueExpectedRevision(flags);
314
+ const index = positional[1];
315
+ if (!reading && (positional.length !== 2 || !/^[0-9]+$/.test(index) || !Number.isSafeInteger(Number(index)) || Number(index) > 99999))
316
+ issueUsage("check/uncheck needs a zero-based checklist index from 0 to 99999");
317
+ const path = base + "/" + encodeURIComponent(key);
318
+ const detail = await api("GET", path);
319
+ const checklist = parseIssueChecklist(detail.issue.description || "");
320
+ if (reading) {
321
+ if (flags.json) return out({ identifier: detail.issue.identifier, revision: detail.issue.revision, ...checklist });
322
+ out("Checklist: " + checklist.checked + "/" + checklist.total + " checked (revision " + detail.issue.revision + ")");
323
+ return out(checklist.items.length ? checklist.items.map(issueChecklistLine).join(NL) : "No checklist items.");
324
+ }
325
+ const itemIndex = Number(index);
326
+ const item = checklist.items[itemIndex];
327
+ if (!item) issueUsage("no checklist item at index " + itemIndex + " in revision " + detail.issue.revision + "; nothing changed");
328
+ const checked = action === "check";
329
+ // Preview/validate through the shared source helper: GFM markers can span
330
+ // tabs or multiple lines. Only the atomic tick identity is sent below.
331
+ const preview = issueMarkdownParser().applyIssueChecklistTick(detail.issue.description || "", item, checked);
332
+ if (preview === null) issueUsage("checklist source marker no longer matches; nothing changed. Rerun issue checklist");
333
+ const result = await api("POST", path + "/checklist", {
334
+ itemIndex, textHash: await hashIssueChecklistText(item.text), checked,
335
+ expectedRevision: expected ?? detail.issue.revision,
336
+ }, { checklistIndex: itemIndex });
337
+ return out(flags.json ? result : (result.changed ? "Updated " : "Already set: ") + key + " item " + itemIndex + " " + (checked ? "[x] " : "[ ] ") + item.text + " (revision " + result.issue.revision + ")");
338
+ }
339
+ if (action === "show") {
340
+ const { flags, positional } = issueFlags(args, ["json"]);
341
+ const key = issueKey(positional);
342
+ const detail = await issueReadDetail(key);
343
+ if (flags.json) return out(detail);
344
+ out(issueLine(detail.issue));
345
+ out("Revision: " + detail.issue.revision);
346
+ if (detail.url) out("URL: " + detail.url);
347
+ const progress = detail.issue.checklistProgress || issueChecklistProgress(detail.issue.description || "");
348
+ out("Checklist: " + progress.checked + "/" + progress.total + " checked");
349
+ out("Description:" + NL + (detail.issue.description || "(empty)"));
350
+ const parent = detail.parent ?? detail.issue.parent;
351
+ out("Parent: " + (parent ? issueHierarchyLine(parent) : "None."));
352
+ if (detail.children) {
353
+ out("Direct children: " + detail.issue.childDoneCount + "/" + detail.issue.childCount + " done (canceled excluded from progress)");
354
+ out(detail.children.length ? detail.children.map((child) => " " + issueHierarchyLine(child) + (child.hasRunningTask ? " [running Task]" : "")).join(NL) : " None.");
355
+ }
356
+ if (!detail.linkedTasksAvailable) out("Linked Task details require tasks.read; a human can grant it in Task permissions.");
357
+ else out("Linked Tasks:" + NL + (detail.tasks.length ? detail.tasks.map((t) => " " + t.taskId + " " + t.name + " " + t.runtimeStatus).join(NL) : " None visible."));
358
+ if (detail.attachments) out("Attachments:" + NL + (detail.attachments.length ? detail.attachments.map(item => issueAttachmentLine(item, detail.issue.identifier)).join(NL) : " None."));
359
+ if (detail.activity) out("Recent activity:" + NL + (detail.activity.events.length ? detail.activity.events.map(event => " " + new Date(event.occurredAt).toISOString() + " " + event.summary).join(NL) : " None."));
360
+ return;
361
+ }
362
+ if (action === "create") {
363
+ const { flags, positional } = issueFlags(args, ["title", "description", "project", "status", "assignee", "priority", "parent", "label", "json"]);
364
+ if (positional.length || !flags.title?.trim()) issueUsage("create needs --title and no positional arguments");
365
+ issueParentKey(flags);
366
+ const labels = issueLabelOptions(flags);
367
+ const body = {};
368
+ for (const name of ["title", "description", "project", "status", "priority"]) if (flags[name] !== undefined) body[name] = flags[name];
369
+ if (flags.assignee) body.assignees = flags.assignee;
370
+ if (labels.changed) body.labelIds = await issueLabelSet(labels);
371
+ if (flags.parent !== undefined) body.parentId = await issueParentId(base, flags.parent);
372
+ const result = await api("POST", base, body, { parentKey: flags.parent });
373
+ return out(flags.json ? result : "Created " + issueLine(result.issue));
374
+ }
375
+ if (action === "update") {
376
+ const { flags, positional } = issueFlags(args, ["status", "assignee", "priority", "title", "description", "description-file", "clear-description", "expected-revision", "parent", "no-parent", "label", "remove-label", "labels", "clear-labels", "override-active-tasks", "json"], ["json", "override-active-tasks", "no-parent", "clear-description", "clear-labels"]);
377
+ const key = issueKey(positional);
378
+ issueParentKey(flags);
379
+ const expected = issueExpectedRevision(flags);
380
+ const labels = issueLabelOptions(flags);
381
+ const body = {};
382
+ const description = issueDescription(flags);
383
+ if (description !== undefined) body.description = description;
384
+ if (flags["no-parent"]) body.parentId = null;
385
+ for (const name of ["status", "priority", "title"]) if (flags[name] !== undefined) body[name] = flags[name];
386
+ if (flags.assignee) {
387
+ if (flags.assignee.some((s) => !/^[+-].+/.test(s))) issueUsage("update --assignee needs +HANDLE or -HANDLE (repeat for multiple changes)");
388
+ body.assignees = flags.assignee;
389
+ }
390
+ if (!Object.keys(body).length && flags.parent === undefined && !labels.changed) issueUsage("update needs a field change (status, assignee, priority, title, description, parent or labels)");
391
+ if (flags["override-active-tasks"] && !flags.status) issueUsage("--override-active-tasks requires --status");
392
+ if (flags["override-active-tasks"]) body.overrideActiveTasks = true;
393
+ const path = base + "/" + encodeURIComponent(key);
394
+ const current = expected === undefined || labels.add.length || labels.remove.length ? (await api("GET", path)).issue : undefined;
395
+ body.expectedRevision = expected ?? current.revision;
396
+ if (labels.changed) body.labelIds = await issueLabelSet(labels, current?.labelIds ?? current?.labels?.map(label => label.id) ?? []);
397
+ if (flags.parent !== undefined) body.parentId = await issueParentId(base, flags.parent);
398
+ if ((labels.add.length || labels.remove.length) && body.expectedRevision === current.revision &&
399
+ Object.keys(body).every(name => name === "labelIds" || name === "expectedRevision")) {
400
+ const existing = new Set(current.labelIds ?? current.labels?.map(label => label.id) ?? []);
401
+ if (existing.size === body.labelIds.length && body.labelIds.every(id => existing.has(id)))
402
+ return out(flags.json ? { issue: current, changed: false } : "Unchanged " + issueLine(current) + " (revision " + current.revision + ")");
403
+ }
404
+ const result = await api("PATCH", path, body, { parentKey: flags.parent });
405
+ return out(flags.json ? result : "Updated " + issueLine(result.issue));
406
+ }
407
+ if (action === "link" || action === "unlink") {
408
+ const { flags, positional } = issueFlags(args, ["task", "json"]);
409
+ const key = issueKey(positional);
410
+ // Omission is meaningful: the server resolves the authenticated Task.
411
+ const result = await api(action === "link" ? "POST" : "DELETE", base + "/" + encodeURIComponent(key) + "/tasks", flags.task === undefined ? {} : { taskId: flags.task });
412
+ return out(flags.json ? result : (action === "link" ? "Linked " : "Unlinked ") + key + " " + (action === "link" ? "to " : "from ") + result.taskId + (result.changed ? "" : " (already so)"));
413
+ }
414
+ issueUsage("commands: list, labels, comment KEY-N, comment edit/delete KEY-N ID, comments KEY-N, archive KEY-N, restore KEY-N, show KEY-N, current, create --title T, update KEY-N, link KEY-N, unlink KEY-N, checklist KEY-N, check/uncheck KEY-N INDEX, activity KEY-N, attachments KEY-N, attach KEY-N FILES_PATH..., detach KEY-N ID; all accept --json");
415
+ }
416
+ `;
package/lib/agent-cli.ts CHANGED
@@ -1,3 +1,7 @@
1
+ import { ISSUE_MARKDOWN_SOURCE } from "./issue-markdown.generated";
2
+ import { ISSUE_ATTACHMENTS_CLI_SOURCE } from "./agent-cli-issue-attachments";
3
+ import { ISSUE_COMMENTS_CLI_SOURCE } from "./agent-cli-issue-comments";
4
+ import { ISSUE_CLI_SOURCE } from "./agent-cli-issues";
1
5
  import { effectiveAppUrl } from "./cloud-endpoint";
2
6
  import { TASK_PROJECT_ADD_WAIT_MS } from "../src/protocol";
3
7
  import { validateShareablePath, ENGINE_ACCOUNT_PATH_RULES } from "../src/workspace-path-policy";
@@ -338,21 +342,72 @@ function todoRef(args) {
338
342
  }
339
343
  function todoText(args) { return args.join(" ").trim(); }
340
344
 
341
- async function api(method, path, body) {
342
- const res = await fetch(API_URL + path, {
343
- method,
344
- headers: { authorization: "Bearer " + TOKEN, "content-type": "application/json" },
345
- body: body ? JSON.stringify(body) : undefined,
346
- });
347
- const text = await res.text();
345
+ async function api(method, path, body, context) {
346
+ let res, text;
347
+ try {
348
+ res = await fetch(API_URL + path, {
349
+ method,
350
+ ...(context?.commentRequestId ? { signal: AbortSignal.timeout(15000) } : {}),
351
+ headers: { authorization: "Bearer " + TOKEN, "content-type": context?.raw ? "application/octet-stream" : "application/json" },
352
+ body: context?.raw ? body : body ? JSON.stringify(body) : undefined,
353
+ });
354
+ text = await res.text();
355
+ } catch (error) {
356
+ if (context?.commentRequestId) {
357
+ if ((context.transportRetries || 0) < 2) {
358
+ context.transportRetries = (context.transportRetries || 0) + 1;
359
+ console.error("Comment response lost; retrying the identical request with clientRequestId " + context.commentRequestId + " (" + context.transportRetries + "/2).");
360
+ await new Promise(resolve => setTimeout(resolve, 250 * context.transportRetries));
361
+ return api(method, path, body, context);
362
+ }
363
+ console.error("Comment outcome is unknown. clientRequestId " + context.commentRequestId + ". Inspect issue comments --json before posting again; a new invocation uses a new key.");
364
+ }
365
+ if (context?.commentAction && !context.commentRequestId)
366
+ console.error("Comment update outcome is unknown; inspect issue comments --json before retrying with its current comment revision. No automatic retry.");
367
+ if (context?.uploadedPath) console.error("Uploaded file remains at " + context.uploadedPath + "; inspect Issue attachments before retrying. No file was deleted.");
368
+ if (context?.uploadPath) console.error("Upload outcome is uncertain at " + context.uploadPath + "; inspect Files before retrying. No attachment request was sent.");
369
+ throw error;
370
+ }
348
371
  let json; try { json = JSON.parse(text); } catch { json = text; }
349
372
  if (!res.ok) {
350
373
  const msg = (json && json.error && json.error.message) || text || res.statusText;
351
374
  console.error("moondeck: " + res.status + " " + msg);
375
+ if (path.startsWith("/api/agent/issues") && json?.error?.code === "ISSUE_ACTIVE_TASKS") {
376
+ console.error("No changes saved. To mark Done despite active linked Tasks, repeat issue update with --override-active-tasks after confirming that intent.");
377
+ }
378
+ if (path.startsWith("/api/agent/issues") && json?.error?.code === "ISSUE_REVISION_CONFLICT") {
379
+ console.error("The Issue changed since revision " + body.expectedRevision + ". No changes saved. Run issue show to inspect the latest revision before repeating your update.");
380
+ }
381
+ if (path.startsWith("/api/agent/issues")) issueErrorHint(json?.error?.code, res.status, context, res.headers.get("retry-after"), json?.error?.details);
382
+ if (context?.uploadPath) console.error("Files upload refused: " + (json?.error?.code || res.status) + ". No attachment request was sent.");
383
+ if (context?.uploadPath && json?.error?.code === "FILE_EXISTS") console.error("Existing file preserved. Agent uploads only create new files; choose a new Files path. No attachment was added.");
384
+ if (context?.uploadPath && res.status === 403) console.error("Upload requires files.write within the human owner's Files permissions; a human must grant missing access.");
385
+ if (context?.attachmentAction && res.status === 403)
386
+ console.error("Attachments need issues.read" + (["attachments", "get"].includes(context.attachmentAction) ? "" : " + issues.write") + " and readable Files: files.read for org/, files.me.read or files.read for me/. A human must grant missing access; owner, runtime and plan limits still apply.");
387
+ if ((context?.attachmentAction || context?.uploadPath) && res.status === 429) {
388
+ const delay = res.headers.get("retry-after") || json?.error?.details?.retryAfterSeconds;
389
+ console.error("Attachment request rate or capacity limit reached; " + (delay ? "wait " + delay + " s" : "wait before retrying") + ". No automatic retry. Rerun issue attachments or issue show before retrying a mutation with --expected-revision.");
390
+ }
391
+ if (context?.attachmentAction && json?.error?.code === "ISSUE_ATTACHMENT_LIMIT")
392
+ console.error("An Issue supports at most 100 attachment references. No references added; unlink unused references with issue detach (files are retained), then rerun issue show before retrying with --expected-revision.");
393
+ if (context?.attachmentAction && json?.error?.code === "ISSUE_FILES_UNAVAILABLE")
394
+ console.error("Selected Files could not be checked; no references added. Wait, rerun issue show, then retry with --expected-revision. No automatic retry.");
395
+ if (context?.uploadedPath) console.error("Uploaded file remains at " + context.uploadedPath + "; inspect Issue attachments before retrying. No file was deleted.");
352
396
  process.exit(1);
353
397
  }
354
398
  return json;
355
399
  }
400
+ let issueMarkdown;
401
+ function issueMarkdownParser() {
402
+ // Only evaluate trusted, generated bundle bytes when a command needs them.
403
+ return issueMarkdown ||= new Function(${JSON.stringify(ISSUE_MARKDOWN_SOURCE + "\nreturn IssueMarkdown;")})();
404
+ }
405
+ function parseIssueChecklist(markdown) { return issueMarkdownParser().parseIssueChecklist(markdown); }
406
+ function issueChecklistProgress(markdown) { return issueMarkdownParser().issueChecklistProgress(markdown); }
407
+ function hashIssueChecklistText(text) { return issueMarkdownParser().hashIssueChecklistText(text); }
408
+ ${ISSUE_CLI_SOURCE}
409
+ ${ISSUE_COMMENTS_CLI_SOURCE}
410
+ ${ISSUE_ATTACHMENTS_CLI_SOURCE}
356
411
  function out(v) { console.log(typeof v === "string" ? v : JSON.stringify(v, null, 2)); }
357
412
  const NL = String.fromCharCode(10);
358
413
  function flagValue(v) { return typeof v === "string" && v !== "true" && v.length > 0; }
@@ -809,6 +864,7 @@ const { flags, rest: pos } = parseFlags(rest);
809
864
  const validateShareablePath = ${validateShareablePath.toString()};
810
865
  const assertShareablePath = (path) => validateShareablePath(path, ${JSON.stringify(ENGINE_ACCOUNT_PATH_RULES)});
811
866
  async function main() {
867
+ if (group === "issue") return issueCommand(action, rest);
812
868
  if (group === "support") {
813
869
  if (action !== "submit" || !flags.category || !flags.message || Object.keys(flags).some(k => !["category", "message", "subject", "file"].includes(k))) {
814
870
  console.error('moondeck: support submit --category bug|question|feature|account|other --message "details" [--subject "subject"] [--file path]…'); process.exit(1);
@@ -1496,6 +1552,37 @@ async function main() {
1496
1552
  " Never paste secrets into chat. A person supplies them through the private dialog.",
1497
1553
  ' moondeck support submit --category bug --message "details" [--subject "subject"] [--file path]…',
1498
1554
  " moondeck artifacts",
1555
+ " moondeck issue list [--status NAME] [--assignee me|HANDLE|unassigned] [--project KEY] [--priority P] [--label NAME]... [--archived only|include] [-q TEXT] [--exclude-tree-of KEY|ID] [--no-sub-issues] [--limit 1..100] [--cursor C] [--json]",
1556
+ " moondeck issue show KEY-N [--json]",
1557
+ " moondeck issue comment KEY-N (--body TEXT | --body-file PATH|-) [--mention NAME]... [--json]",
1558
+ " moondeck issue comment edit KEY-N COMMENT_ID (--body TEXT | --body-file PATH|-) [--mention NAME]... [--clear-mentions] [--expected-revision N] [--json]",
1559
+ " moondeck issue comment delete KEY-N COMMENT_ID [--expected-revision N] [--json]",
1560
+ " Comment writes need issues.read + issues.write. Only the same owner, Task and agent may edit/delete.",
1561
+ " moondeck issue comments KEY-N [--limit 1..100] [--before-seq N] [--json] Read recent comments.",
1562
+ " moondeck issue archive KEY-N [--include-sub-issues] [--expected-revision N] [--json]",
1563
+ " moondeck issue restore KEY-N [--expected-revision N] [--json] Restore this Issue; keep its status.",
1564
+ " moondeck issue labels [--json] List the existing workspace label catalog (issues.read).",
1565
+ " Repeat --label NAME on list (any-of filtering) or create (add existing labels).",
1566
+ " show includes checklist progress, parent and direct children with visible running Tasks (up to 50 pages); warns on incomplete paging; child progress excludes canceled children.",
1567
+ " moondeck issue current [--limit 1..5] [--cursor C] [--json]",
1568
+ " moondeck issue create --title T [--description D] [--project KEY] [--status S] [--assignee A] [--priority P] [--parent KEY-N] [--label NAME]... [--json]",
1569
+ " moondeck issue update KEY-N [--status S] [--assignee +HANDLE|-HANDLE] [--priority P] [--title T] [--label NAME]... [--remove-label NAME]... [--labels NAME]... [--clear-labels] [--description TEXT|- | --description-file PATH | --clear-description] [--parent KEY-N|--no-parent] [--expected-revision N] [--override-active-tasks] [--json]",
1570
+ " Description: Markdown, at most 100,000 UTF-16 code units; file/stdin preserve whitespace. Empty input requires --clear-description; nonempty input cannot be combined with it.",
1571
+ " Labels: repeat --label NAME to add and --remove-label NAME to remove; repeat --labels NAME to replace the set; --clear-labels clears it. Commas are literal name characters. Replacement/clear cannot mix with add/remove. At most 50 labels.",
1572
+ " Label-only add/remove prints Unchanged (JSON changed:false) and skips PATCH when the fetched set and expected revision already match; other field changes and stale revision fences still reach the server.",
1573
+ " Label names match the workspace catalog case-insensitively; unknown names fail and are never created. Labels share the field update's revision fence; conflicts never retry automatically.",
1574
+ " moondeck issue checklist KEY-N [--json]",
1575
+ " moondeck issue check|uncheck KEY-N INDEX [--expected-revision N] [--json]",
1576
+ " INDEX is zero-based; checks use a fresh read and text hash. Conflicts show the current item and never retry.",
1577
+ " moondeck issue activity KEY-N [--limit 1..100] [--cursor C] [--json]",
1578
+ " moondeck issue attachments KEY-N [--json]",
1579
+ " moondeck issue attachment get KEY-N ATTACHMENT_ID [-o PATH] [--json]",
1580
+ " moondeck issue attach KEY-N org/PATH|me/PATH... [--expected-revision N] [--json]",
1581
+ " moondeck issue attach KEY-N --upload LOCAL_PATH [--expected-revision N] [--json]",
1582
+ " Upload: up to 200 MiB, unique filename under org/Issues/<canonical KEY>/. Requires files.write and files.read.",
1583
+ " moondeck issue detach KEY-N ATTACHMENT_ID [--expected-revision N] [--json]",
1584
+ " Attachments are Files references. Detach never deletes the file; failed attachment admission retains an upload.",
1585
+ " moondeck issue link|unlink KEY-N [--task ID] [--json]",
1499
1586
  " moondeck projects list",
1500
1587
  " moondeck files ls [org|me[/prefix]] (one folder: names, sizes, mtimes, etags; defaults to org)",
1501
1588
  " moondeck files get <org|me>/<path> [<dest>] (download; default /workspace/files/<org|me>/<path>; -r is a folder, capped at 500 files / 1 GB)",