@gonovus-ai/spec-flow-cli 1.3.1 → 1.4.0

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,763 @@
1
+ import { InvalidArgumentError } from "commander";
2
+ import { randomUUID } from "node:crypto";
3
+ import { open, writeFile } from "node:fs/promises";
4
+ import { basename, extname } from "node:path";
5
+ import { z } from "zod";
6
+ import { parseNonNegativeInt, parseWaitSeconds } from "./agent-commands.js";
7
+ import { mapHttpFailure, skillErrorExitCode, writeSkillError } from "./runtime/errors.js";
8
+ import { writeResult } from "./runtime/output.js";
9
+ import { selectSession } from "./runtime/session.js";
10
+ const maximumBoardAssetBytes = 10 * 1024 * 1024;
11
+ const maximumBodyFileBytes = 64 * 1024;
12
+ function parseIdentifier(value, label = "Identifier") {
13
+ const trimmed = value.trim();
14
+ if (trimmed.length === 0 || trimmed.length > 200 || !/^[A-Za-z0-9._:-]+$/u.test(trimmed)) {
15
+ throw new InvalidArgumentError(`${label} must be 1 to 200 identifier characters`);
16
+ }
17
+ return trimmed;
18
+ }
19
+ function parseChannelSlug(value) {
20
+ const normalized = value.trim().toLowerCase();
21
+ if (!/^[a-z0-9][a-z0-9-]{0,47}$/u.test(normalized)) {
22
+ throw new InvalidArgumentError("Channel slug must be 1 to 48 lowercase letters, digits, or hyphens");
23
+ }
24
+ return normalized;
25
+ }
26
+ function parseExpectedVersion(value) {
27
+ const trimmed = value.trim();
28
+ if (/^"[1-9]\d*"$/u.test(trimmed))
29
+ return trimmed;
30
+ if (/^[1-9]\d*$/u.test(trimmed))
31
+ return `"${trimmed}"`;
32
+ throw new InvalidArgumentError('Expected version must be a positive integer or quoted version (e.g. 1 or "1")');
33
+ }
34
+ function collectOption(value, previous) {
35
+ return [...previous, value];
36
+ }
37
+ function formatMentionToken(raw) {
38
+ const trimmed = raw.trim();
39
+ if (trimmed.length === 0)
40
+ return "";
41
+ if (/^@\[(?:agent|user):[A-Za-z0-9_-]{1,200}\]$/u.test(trimmed))
42
+ return trimmed;
43
+ if (trimmed.startsWith("agent:"))
44
+ return `@[${trimmed}]`;
45
+ if (trimmed.startsWith("user:"))
46
+ return `@[${trimmed}]`;
47
+ return trimmed.startsWith("@") ? trimmed : `@${trimmed}`;
48
+ }
49
+ function appendMentions(body, mentions) {
50
+ if (mentions.length === 0)
51
+ return body;
52
+ const tokens = mentions
53
+ .map(formatMentionToken)
54
+ .filter((token) => token.length > 0 && !body.includes(token));
55
+ if (tokens.length === 0)
56
+ return body;
57
+ return `${body.trimEnd()}\n\n${tokens.join(" ")}`;
58
+ }
59
+ async function readBoundedLocalFile(filePath, maxBytes) {
60
+ const handle = await open(filePath, "r");
61
+ try {
62
+ const stat = await handle.stat();
63
+ if (!stat.isFile())
64
+ throw new Error("Path must be a regular file");
65
+ if (stat.size <= 0 || stat.size > maxBytes) {
66
+ throw new Error(`File size must be between 1 and ${String(maxBytes)} bytes`);
67
+ }
68
+ const buffer = Buffer.alloc(stat.size);
69
+ let offset = 0;
70
+ while (offset < stat.size) {
71
+ const { bytesRead } = await handle.read(buffer, offset, stat.size - offset, offset);
72
+ if (bytesRead === 0)
73
+ break;
74
+ offset += bytesRead;
75
+ }
76
+ return new Uint8Array(buffer.subarray(0, offset));
77
+ }
78
+ finally {
79
+ await handle.close();
80
+ }
81
+ }
82
+ async function readBodyFromStdin() {
83
+ const chunks = [];
84
+ let total = 0;
85
+ for await (const chunk of process.stdin) {
86
+ const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
87
+ total += bytes.byteLength;
88
+ if (total > maximumBodyFileBytes) {
89
+ throw new InvalidArgumentError("Message body read from stdin exceeds maximum length");
90
+ }
91
+ chunks.push(bytes);
92
+ }
93
+ const merged = new Uint8Array(total);
94
+ let offset = 0;
95
+ for (const part of chunks) {
96
+ merged.set(part, offset);
97
+ offset += part.byteLength;
98
+ }
99
+ return new TextDecoder("utf-8", { fatal: true }).decode(merged);
100
+ }
101
+ async function resolveBodyMarkdown(options) {
102
+ const hasBody = options.body !== undefined;
103
+ const hasFile = options.bodyFile !== undefined;
104
+ if (hasBody && hasFile) {
105
+ throw new InvalidArgumentError("Specify either --body or --body-file, not both");
106
+ }
107
+ if (!hasBody && !hasFile) {
108
+ if (options.required) {
109
+ throw new InvalidArgumentError("Either --body or --body-file is required");
110
+ }
111
+ return undefined;
112
+ }
113
+ let raw;
114
+ if (options.bodyFile !== undefined) {
115
+ if (options.bodyFile === "-") {
116
+ raw = await readBodyFromStdin();
117
+ }
118
+ else {
119
+ const bytes = await readBoundedLocalFile(options.bodyFile, maximumBodyFileBytes);
120
+ raw = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
121
+ }
122
+ }
123
+ else {
124
+ raw = options.body ?? "";
125
+ }
126
+ const withMentions = appendMentions(raw, options.mentions ?? []);
127
+ if (withMentions.trim().length === 0) {
128
+ throw new InvalidArgumentError("Message body must not be empty");
129
+ }
130
+ return withMentions;
131
+ }
132
+ function resolveIdempotencyKey(raw) {
133
+ const trimmed = raw?.trim() ?? "";
134
+ return trimmed.length > 0 ? trimmed : randomUUID();
135
+ }
136
+ function inferContentType(filename) {
137
+ switch (extname(filename).toLowerCase()) {
138
+ case ".png":
139
+ return "image/png";
140
+ case ".jpg":
141
+ case ".jpeg":
142
+ return "image/jpeg";
143
+ case ".webp":
144
+ return "image/webp";
145
+ case ".gif":
146
+ return "image/gif";
147
+ case ".pdf":
148
+ return "application/pdf";
149
+ case ".json":
150
+ return "application/json";
151
+ case ".md":
152
+ return "text/markdown";
153
+ case ".txt":
154
+ case ".log":
155
+ return "text/plain";
156
+ default:
157
+ return "application/octet-stream";
158
+ }
159
+ }
160
+ function validateUploadUrl(rawUrl) {
161
+ const parsed = new URL(rawUrl);
162
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
163
+ throw new Error("Upload URL must use http or https");
164
+ }
165
+ return parsed;
166
+ }
167
+ const idempotentRetry = {
168
+ rejectWorkspaceReadToken: true,
169
+ retryTransportOnce: true,
170
+ ambiguousOutcomeMessage: "Discussion write outcome is unknown; retry the same command with the same --idempotency-key",
171
+ };
172
+ export function registerDiscussCommands(program, runtime) {
173
+ const discuss = program
174
+ .command("discuss")
175
+ .description("Collaborate in Workspace Discussion Board channels, threads, and private Agent direct chats");
176
+ // 1. specflow discuss channels
177
+ discuss
178
+ .command("channels")
179
+ .description("List accessible public channels, private direct chats, and Workspace Agents")
180
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
181
+ .option("--include-archived", "Include archived public channels")
182
+ .action(async (options) => {
183
+ runtime.setExitCode(await runtime.run((client) => client.GET("/v1/workspaces/{workspaceId}/board/channels", {
184
+ params: {
185
+ path: { workspaceId: options.workspaceId },
186
+ query: {
187
+ ...(options.includeArchived === true ? { includeArchived: true } : {}),
188
+ },
189
+ },
190
+ }), { rejectWorkspaceReadToken: true }));
191
+ });
192
+ // 2. specflow discuss channel create|update
193
+ const channel = discuss
194
+ .command("channel")
195
+ .description("Create, rename, or archive public Discussion Board channels");
196
+ channel
197
+ .command("create")
198
+ .description("Create a public Discussion Board channel (Editor+)")
199
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
200
+ .requiredOption("--slug <slug>", "Lowercase channel slug", parseChannelSlug)
201
+ .requiredOption("--name <name>", "Channel display name")
202
+ .option("--idempotency-key <key>", "Idempotency key for safe retries")
203
+ .action(async (options) => {
204
+ const key = resolveIdempotencyKey(options.idempotencyKey);
205
+ runtime.setExitCode(await runtime.run((client) => client.POST("/v1/workspaces/{workspaceId}/board/channels", {
206
+ params: {
207
+ path: { workspaceId: options.workspaceId },
208
+ header: { "idempotency-key": key },
209
+ },
210
+ body: { slug: options.slug, name: options.name.trim() },
211
+ }), idempotentRetry));
212
+ });
213
+ channel
214
+ .command("update")
215
+ .description("Rename or archive a public Discussion Board channel (human Owner/Admin only)")
216
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
217
+ .requiredOption("--channel-id <channelIdOrSlug>", "Channel UUID or slug", (v) => parseIdentifier(v, "Channel ID"))
218
+ .option("--name <name>", "New channel name")
219
+ .option("--archive", "Archive the channel (read-only)")
220
+ .option("--unarchive", "Restore an archived channel")
221
+ .action(async (options) => {
222
+ if (options.archive === true && options.unarchive === true) {
223
+ throw new InvalidArgumentError("Cannot combine --archive and --unarchive");
224
+ }
225
+ const archived = options.archive === true ? true : options.unarchive === true ? false : undefined;
226
+ if (options.name === undefined && archived === undefined) {
227
+ throw new InvalidArgumentError("Provide --name, --archive, or --unarchive");
228
+ }
229
+ runtime.setExitCode(await runtime.run((client) => client.PATCH("/v1/workspaces/{workspaceId}/board/channels/{channelId}", {
230
+ params: {
231
+ path: { workspaceId: options.workspaceId, channelId: options.channelId },
232
+ },
233
+ body: {
234
+ ...(options.name === undefined ? {} : { name: options.name.trim() }),
235
+ ...(archived === undefined ? {} : { archived }),
236
+ },
237
+ }), { rejectWorkspaceReadToken: true }));
238
+ });
239
+ // 3. specflow discuss dm create|add-participant|remove-participant|settings
240
+ const dm = discuss
241
+ .command("dm")
242
+ .description("Manage private direct chats with Workspace CLI Agents (human-only)");
243
+ dm.command("create")
244
+ .description("Start a private direct chat with a Workspace CLI Agent")
245
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
246
+ .requiredOption("--target-agent <agentIdOrSlug>", "Target CLI Agent UUID or slug", (v) => parseIdentifier(v, "Target Agent"))
247
+ .option("--title <title>", "Optional private thread title")
248
+ .option("--body <markdown>", "Optional opening message body")
249
+ .option("--body-file <path>", "Read opening message body from file (or - for stdin)")
250
+ .option("--mention <mention>", "Mention to append (repeatable)", collectOption, [])
251
+ .option("--attachment-id <assetId>", "Finalized attachment UUID (repeatable)", collectOption, [])
252
+ .option("--client-id <clientId>", "Client deduplication ID")
253
+ .option("--idempotency-key <key>", "Idempotency key for safe retries")
254
+ .action(async (options) => {
255
+ const bodyMarkdown = await resolveBodyMarkdown({
256
+ body: options.body,
257
+ bodyFile: options.bodyFile,
258
+ mentions: options.mention,
259
+ required: false,
260
+ });
261
+ const key = resolveIdempotencyKey(options.idempotencyKey);
262
+ runtime.setExitCode(await runtime.run((client) => client.POST("/v1/workspaces/{workspaceId}/board/private-threads", {
263
+ params: {
264
+ path: { workspaceId: options.workspaceId },
265
+ header: { "idempotency-key": key },
266
+ },
267
+ body: {
268
+ targetAgentId: options.targetAgent,
269
+ ...(options.title === undefined ? {} : { title: options.title.trim() }),
270
+ ...(bodyMarkdown === undefined ? {} : { bodyMarkdown }),
271
+ ...(options.clientId === undefined ? {} : { clientId: options.clientId.trim() }),
272
+ ...(options.attachmentId.length === 0
273
+ ? {}
274
+ : { attachmentIds: [...options.attachmentId] }),
275
+ },
276
+ }), idempotentRetry));
277
+ });
278
+ dm.command("add-participant")
279
+ .description("Add a human member or CLI Agent to a private direct chat")
280
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
281
+ .requiredOption("--thread-id <threadId>", "Private thread UUID", (v) => parseIdentifier(v, "Thread ID"))
282
+ .option("--user-id <userId>", "Workspace member user ID to invite")
283
+ .option("--agent-id <agentIdOrSlug>", "Workspace CLI Agent ID or slug to add")
284
+ .action(async (options) => {
285
+ if ((options.userId === undefined) === (options.agentId === undefined)) {
286
+ throw new InvalidArgumentError("Specify exactly one of --user-id or --agent-id");
287
+ }
288
+ runtime.setExitCode(await runtime.run((client) => client.POST("/v1/workspaces/{workspaceId}/board/private-threads/{threadId}/participants", {
289
+ params: {
290
+ path: { workspaceId: options.workspaceId, threadId: options.threadId },
291
+ },
292
+ body: {
293
+ ...(options.userId === undefined ? {} : { userId: options.userId.trim() }),
294
+ ...(options.agentId === undefined ? {} : { agentId: options.agentId.trim() }),
295
+ },
296
+ }), { rejectWorkspaceReadToken: true }));
297
+ });
298
+ dm.command("remove-participant")
299
+ .description("Remove a human member (and their owned Agents) or CLI Agent from a private direct chat")
300
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
301
+ .requiredOption("--thread-id <threadId>", "Private thread UUID", (v) => parseIdentifier(v, "Thread ID"))
302
+ .option("--user-id <userId>", "Human member user ID to remove")
303
+ .option("--agent-id <agentIdOrSlug>", "CLI Agent ID or slug to remove")
304
+ .action(async (options) => {
305
+ if ((options.userId === undefined) === (options.agentId === undefined)) {
306
+ throw new InvalidArgumentError("Specify exactly one of --user-id or --agent-id");
307
+ }
308
+ runtime.setExitCode(await runtime.run((client) => client.DELETE("/v1/workspaces/{workspaceId}/board/private-threads/{threadId}/participants", {
309
+ params: {
310
+ path: { workspaceId: options.workspaceId, threadId: options.threadId },
311
+ query: {
312
+ ...(options.userId === undefined ? {} : { userId: options.userId.trim() }),
313
+ ...(options.agentId === undefined ? {} : { agentId: options.agentId.trim() }),
314
+ },
315
+ },
316
+ }), { rejectWorkspaceReadToken: true }));
317
+ });
318
+ dm.command("settings")
319
+ .description("Update auto-wake settings for a single-Agent private direct chat")
320
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
321
+ .requiredOption("--thread-id <threadId>", "Private thread UUID", (v) => parseIdentifier(v, "Thread ID"))
322
+ .requiredOption("--auto-wake <enabled>", "true or false", (value) => {
323
+ if (value === "true")
324
+ return true;
325
+ if (value === "false")
326
+ return false;
327
+ throw new InvalidArgumentError("--auto-wake must be true or false");
328
+ })
329
+ .action(async (options) => {
330
+ runtime.setExitCode(await runtime.run((client) => client.PATCH("/v1/workspaces/{workspaceId}/board/private-threads/{threadId}/settings", {
331
+ params: {
332
+ path: { workspaceId: options.workspaceId, threadId: options.threadId },
333
+ },
334
+ body: { autoWakeEnabled: options.autoWake },
335
+ }), { rejectWorkspaceReadToken: true }));
336
+ });
337
+ // 4. specflow discuss threads
338
+ discuss
339
+ .command("threads")
340
+ .description("List and search accessible Discussion Board threads")
341
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
342
+ .option("--channel <channelIdOrSlug>", "Filter by channel UUID or slug", (v) => parseIdentifier(v, "Channel"))
343
+ .option("--scope <scope>", "all, participated, or private", (value) => {
344
+ if (value !== "all" && value !== "participated" && value !== "private") {
345
+ throw new InvalidArgumentError("--scope must be all, participated, or private");
346
+ }
347
+ return value;
348
+ })
349
+ .option("--q <query>", "Filter threads by title or body substring")
350
+ .option("--limit <limit>", "Maximum threads per page (1..100)", runtime.parseLimit)
351
+ .option("--cursor <cursor>", "Opaque pagination cursor")
352
+ .action(async (options) => {
353
+ runtime.setExitCode(await runtime.run((client) => client.GET("/v1/workspaces/{workspaceId}/board/threads", {
354
+ params: {
355
+ path: { workspaceId: options.workspaceId },
356
+ query: {
357
+ ...(options.channel === undefined ? {} : { channelId: options.channel }),
358
+ ...(options.scope === undefined ? {} : { scope: options.scope }),
359
+ ...(options.q === undefined ? {} : { q: options.q }),
360
+ ...(options.limit === undefined ? {} : { limit: options.limit }),
361
+ ...(options.cursor === undefined ? {} : { cursor: options.cursor }),
362
+ },
363
+ },
364
+ }), { rejectWorkspaceReadToken: true }));
365
+ });
366
+ // 5. specflow discuss read
367
+ discuss
368
+ .command("read")
369
+ .description("Read a Discussion Board thread and its paginated messages (pure read)")
370
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
371
+ .requiredOption("--thread-id <threadId>", "Thread UUID", (v) => parseIdentifier(v, "Thread ID"))
372
+ .option("--limit <limit>", "Maximum messages per page (1..100)", runtime.parseLimit)
373
+ .option("--cursor <cursor>", "Opaque pagination cursor")
374
+ .option("--after-message-id <messageId>", "Return messages created after this message ID", (v) => parseIdentifier(v, "Message ID"))
375
+ .action(async (options) => {
376
+ runtime.setExitCode(await runtime.run((client) => client.GET("/v1/workspaces/{workspaceId}/board/threads/{threadId}", {
377
+ params: {
378
+ path: { workspaceId: options.workspaceId, threadId: options.threadId },
379
+ query: {
380
+ ...(options.limit === undefined ? {} : { limit: options.limit }),
381
+ ...(options.cursor === undefined ? {} : { cursor: options.cursor }),
382
+ ...(options.afterMessageId === undefined
383
+ ? {}
384
+ : { afterMessageId: options.afterMessageId }),
385
+ },
386
+ },
387
+ }), { rejectWorkspaceReadToken: true }));
388
+ });
389
+ // 6. specflow discuss post
390
+ discuss
391
+ .command("post")
392
+ .description("Create a new thread in a public Discussion Board channel")
393
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
394
+ .requiredOption("--channel <channelIdOrSlug>", "Channel UUID or slug (e.g. general)", (v) => parseIdentifier(v, "Channel"))
395
+ .requiredOption("--title <title>", "Thread title")
396
+ .option("--body <markdown>", "Opening message body")
397
+ .option("--body-file <path>", "Read opening message body from file (or - for stdin)")
398
+ .option("--mention <mention>", "Mention to append (repeatable)", collectOption, [])
399
+ .option("--attachment-id <assetId>", "Finalized attachment UUID (repeatable)", collectOption, [])
400
+ .option("--client-id <clientId>", "Client deduplication ID")
401
+ .option("--idempotency-key <key>", "Idempotency key for safe retries")
402
+ .action(async (options) => {
403
+ const bodyMarkdown = await resolveBodyMarkdown({
404
+ body: options.body,
405
+ bodyFile: options.bodyFile,
406
+ mentions: options.mention,
407
+ required: true,
408
+ });
409
+ const key = resolveIdempotencyKey(options.idempotencyKey);
410
+ runtime.setExitCode(await runtime.run((client) => client.POST("/v1/workspaces/{workspaceId}/board/channels/{channelId}/threads", {
411
+ params: {
412
+ path: { workspaceId: options.workspaceId, channelId: options.channel },
413
+ header: { "idempotency-key": key },
414
+ },
415
+ body: {
416
+ title: options.title.trim(),
417
+ bodyMarkdown: bodyMarkdown ?? "",
418
+ ...(options.clientId === undefined ? {} : { clientId: options.clientId.trim() }),
419
+ ...(options.attachmentId.length === 0
420
+ ? {}
421
+ : { attachmentIds: [...options.attachmentId] }),
422
+ },
423
+ }), idempotentRetry));
424
+ });
425
+ // 7. specflow discuss reply
426
+ discuss
427
+ .command("reply")
428
+ .description("Post a reply message to a Discussion Board thread or private direct chat")
429
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
430
+ .requiredOption("--thread-id <threadId>", "Thread UUID", (v) => parseIdentifier(v, "Thread ID"))
431
+ .option("--body <markdown>", "Reply message body")
432
+ .option("--body-file <path>", "Read reply message body from file (or - for stdin)")
433
+ .option("--mention <mention>", "Mention to append (repeatable)", collectOption, [])
434
+ .option("--attachment-id <assetId>", "Finalized attachment UUID (repeatable)", collectOption, [])
435
+ .option("--client-id <clientId>", "Client deduplication ID")
436
+ .option("--idempotency-key <key>", "Idempotency key for safe retries")
437
+ .action(async (options) => {
438
+ const bodyMarkdown = await resolveBodyMarkdown({
439
+ body: options.body,
440
+ bodyFile: options.bodyFile,
441
+ mentions: options.mention,
442
+ required: true,
443
+ });
444
+ const key = resolveIdempotencyKey(options.idempotencyKey);
445
+ runtime.setExitCode(await runtime.run((client) => client.POST("/v1/workspaces/{workspaceId}/board/threads/{threadId}/messages", {
446
+ params: {
447
+ path: { workspaceId: options.workspaceId, threadId: options.threadId },
448
+ header: { "idempotency-key": key },
449
+ },
450
+ body: {
451
+ bodyMarkdown: bodyMarkdown ?? "",
452
+ ...(options.clientId === undefined ? {} : { clientId: options.clientId.trim() }),
453
+ ...(options.attachmentId.length === 0
454
+ ? {}
455
+ : { attachmentIds: [...options.attachmentId] }),
456
+ },
457
+ }), idempotentRetry));
458
+ });
459
+ // 8. specflow discuss edit
460
+ discuss
461
+ .command("edit")
462
+ .description("Edit a Discussion Board message with optimistic concurrency (--expected-version)")
463
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
464
+ .requiredOption("--thread-id <threadId>", "Thread UUID", (v) => parseIdentifier(v, "Thread ID"))
465
+ .requiredOption("--message-id <messageId>", "Message UUID", (v) => parseIdentifier(v, "Message ID"))
466
+ .requiredOption("--expected-version <version>", "Observed message version", parseExpectedVersion)
467
+ .option("--body <markdown>", "Updated message body")
468
+ .option("--body-file <path>", "Read updated message body from file (or - for stdin)")
469
+ .action(async (options) => {
470
+ const bodyMarkdown = await resolveBodyMarkdown({
471
+ body: options.body,
472
+ bodyFile: options.bodyFile,
473
+ required: true,
474
+ });
475
+ runtime.setExitCode(await runtime.run((client) => client.PATCH("/v1/workspaces/{workspaceId}/board/threads/{threadId}/messages/{messageId}", {
476
+ params: {
477
+ path: {
478
+ workspaceId: options.workspaceId,
479
+ threadId: options.threadId,
480
+ messageId: options.messageId,
481
+ },
482
+ header: { "if-match": options.expectedVersion },
483
+ },
484
+ body: { bodyMarkdown: bodyMarkdown ?? "" },
485
+ }), { rejectWorkspaceReadToken: true }));
486
+ });
487
+ // 9. specflow discuss delete
488
+ discuss
489
+ .command("delete")
490
+ .description("Soft-delete a Discussion Board message")
491
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
492
+ .requiredOption("--thread-id <threadId>", "Thread UUID", (v) => parseIdentifier(v, "Thread ID"))
493
+ .requiredOption("--message-id <messageId>", "Message UUID", (v) => parseIdentifier(v, "Message ID"))
494
+ .action(async (options) => {
495
+ runtime.setExitCode(await runtime.run((client) => client.DELETE("/v1/workspaces/{workspaceId}/board/threads/{threadId}/messages/{messageId}", {
496
+ params: {
497
+ path: {
498
+ workspaceId: options.workspaceId,
499
+ threadId: options.threadId,
500
+ messageId: options.messageId,
501
+ },
502
+ },
503
+ }), { rejectWorkspaceReadToken: true }));
504
+ });
505
+ // 10. specflow discuss react / unreact
506
+ discuss
507
+ .command("react")
508
+ .description("Add an emoji reaction to a Discussion Board message")
509
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
510
+ .requiredOption("--thread-id <threadId>", "Thread UUID", (v) => parseIdentifier(v, "Thread ID"))
511
+ .requiredOption("--message-id <messageId>", "Message UUID", (v) => parseIdentifier(v, "Message ID"))
512
+ .requiredOption("--emoji <emoji>", "Reaction emoji")
513
+ .action(async (options) => {
514
+ runtime.setExitCode(await runtime.run((client) => client.PUT("/v1/workspaces/{workspaceId}/board/threads/{threadId}/messages/{messageId}/reactions", {
515
+ params: {
516
+ path: {
517
+ workspaceId: options.workspaceId,
518
+ threadId: options.threadId,
519
+ messageId: options.messageId,
520
+ },
521
+ },
522
+ body: { emoji: options.emoji.trim() },
523
+ }), { rejectWorkspaceReadToken: true }));
524
+ });
525
+ discuss
526
+ .command("unreact")
527
+ .description("Remove an emoji reaction from a Discussion Board message")
528
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
529
+ .requiredOption("--thread-id <threadId>", "Thread UUID", (v) => parseIdentifier(v, "Thread ID"))
530
+ .requiredOption("--message-id <messageId>", "Message UUID", (v) => parseIdentifier(v, "Message ID"))
531
+ .requiredOption("--emoji <emoji>", "Reaction emoji")
532
+ .action(async (options) => {
533
+ runtime.setExitCode(await runtime.run((client) => client.DELETE("/v1/workspaces/{workspaceId}/board/threads/{threadId}/messages/{messageId}/reactions", {
534
+ params: {
535
+ path: {
536
+ workspaceId: options.workspaceId,
537
+ threadId: options.threadId,
538
+ messageId: options.messageId,
539
+ },
540
+ query: { emoji: options.emoji.trim() },
541
+ },
542
+ }), { rejectWorkspaceReadToken: true }));
543
+ });
544
+ // 11. specflow discuss asset upload|download
545
+ const asset = discuss
546
+ .command("asset")
547
+ .description("Upload and download Discussion Board channel attachments");
548
+ asset
549
+ .command("upload")
550
+ .description("Reserve, upload bytes via presigned URL, and finalize a Discussion Board attachment")
551
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
552
+ .requiredOption("--channel-id <channelIdOrSlug>", "Channel UUID or slug", (v) => parseIdentifier(v, "Channel ID"))
553
+ .requiredOption("--file <path>", "Local file path to upload (<= 10MB)")
554
+ .option("--filename <name>", "Override filename")
555
+ .option("--content-type <mime>", "Override MIME type")
556
+ .option("--idempotency-key <key>", "Idempotency key for safe retries")
557
+ .action(async (options) => {
558
+ const filename = (options.filename ?? basename(options.file)).trim();
559
+ const contentType = (options.contentType ?? inferContentType(filename)).trim();
560
+ const baseKey = resolveIdempotencyKey(options.idempotencyKey);
561
+ runtime.setExitCode(await runtime.run(async (client) => {
562
+ let bytes;
563
+ try {
564
+ bytes = await readBoundedLocalFile(options.file, maximumBoardAssetBytes);
565
+ }
566
+ catch (error) {
567
+ return {
568
+ response: new Response(null, { status: 400 }),
569
+ error: {
570
+ code: "INVALID_UPLOAD_INPUT",
571
+ message: error instanceof Error ? error.message : "File could not be read",
572
+ },
573
+ };
574
+ }
575
+ const reserve = await client.POST("/v1/workspaces/{workspaceId}/board/channels/{channelId}/assets/uploads", {
576
+ params: {
577
+ path: { workspaceId: options.workspaceId, channelId: options.channelId },
578
+ header: { "idempotency-key": `${baseKey}:reserve` },
579
+ },
580
+ body: { filename, contentType, size: bytes.byteLength },
581
+ });
582
+ if (reserve.error !== undefined) {
583
+ return reserve;
584
+ }
585
+ let uploadUrl;
586
+ try {
587
+ uploadUrl = validateUploadUrl(reserve.data.uploadUrl);
588
+ }
589
+ catch {
590
+ return {
591
+ response: new Response(null, { status: 502 }),
592
+ error: {
593
+ code: "INVALID_UPLOAD_URL",
594
+ message: "Server returned an invalid presigned upload URL",
595
+ },
596
+ };
597
+ }
598
+ const uploadResponse = await runtime.dependencies.fetch(new Request(uploadUrl, {
599
+ method: "PUT",
600
+ headers: reserve.data.headers,
601
+ body: new Uint8Array(bytes),
602
+ redirect: "error",
603
+ credentials: "omit",
604
+ signal: AbortSignal.timeout(60_000),
605
+ }));
606
+ if (!uploadResponse.ok) {
607
+ return {
608
+ response: uploadResponse,
609
+ error: {
610
+ code: "UPLOAD_FAILED",
611
+ message: `Presigned object upload failed with HTTP ${String(uploadResponse.status)}`,
612
+ },
613
+ };
614
+ }
615
+ return await client.POST("/v1/workspaces/{workspaceId}/board/channels/{channelId}/assets/{assetId}/finalize", {
616
+ params: {
617
+ path: {
618
+ workspaceId: options.workspaceId,
619
+ channelId: options.channelId,
620
+ assetId: reserve.data.uploadId,
621
+ },
622
+ header: { "idempotency-key": `${baseKey}:finalize` },
623
+ },
624
+ });
625
+ }, { rejectWorkspaceReadToken: true }));
626
+ });
627
+ asset
628
+ .command("download")
629
+ .description("Download an authorized Discussion Board attachment to a local file")
630
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
631
+ .requiredOption("--channel-id <channelIdOrSlug>", "Channel UUID or slug", (v) => parseIdentifier(v, "Channel ID"))
632
+ .requiredOption("--asset-id <assetId>", "Attachment UUID", (v) => {
633
+ if (!z.uuid().safeParse(v).success) {
634
+ throw new InvalidArgumentError("Asset ID must be a UUID");
635
+ }
636
+ return v;
637
+ })
638
+ .requiredOption("--output-file <path>", "Destination file path")
639
+ .action(async (options) => {
640
+ runtime.setExitCode(await runtime.run(async (client) => {
641
+ const result = await client.GET("/v1/workspaces/{workspaceId}/board/channels/{channelId}/assets/{assetId}", {
642
+ params: {
643
+ path: {
644
+ workspaceId: options.workspaceId,
645
+ channelId: options.channelId,
646
+ assetId: options.assetId,
647
+ },
648
+ },
649
+ parseAs: "arrayBuffer",
650
+ });
651
+ if (!result.response.ok)
652
+ return result;
653
+ const buffer = result.data;
654
+ const bytes = new Uint8Array(buffer);
655
+ if (bytes.byteLength > maximumBoardAssetBytes) {
656
+ return {
657
+ response: new Response(null, { status: 413 }),
658
+ error: {
659
+ code: "BOARD_ASSET_TOO_LARGE",
660
+ message: "Attachment exceeds the 10MB download safety limit",
661
+ },
662
+ };
663
+ }
664
+ await writeFile(options.outputFile, bytes);
665
+ return {
666
+ response: result.response,
667
+ data: {
668
+ assetId: options.assetId,
669
+ channelId: options.channelId,
670
+ outputFile: options.outputFile,
671
+ bytes: bytes.byteLength,
672
+ contentType: result.response.headers.get("content-type") ?? "application/octet-stream",
673
+ },
674
+ };
675
+ }, { rejectWorkspaceReadToken: true }));
676
+ });
677
+ // 12. specflow discuss wait (single bounded long-poll)
678
+ discuss
679
+ .command("wait")
680
+ .description("Wait (bounded <25s long-poll) for new messages in a thread or channel")
681
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
682
+ .option("--thread-id <threadId>", "Watch a single thread UUID", (v) => parseIdentifier(v, "Thread ID"))
683
+ .option("--channel <channelIdOrSlug>", "Watch a channel UUID or slug", (v) => parseIdentifier(v, "Channel"))
684
+ .option("--since <cursor>", "Opaque message cursor returned by a previous read or wait")
685
+ .option("--wait <seconds>", "Long-poll wait duration 0..25 seconds", parseWaitSeconds, 20)
686
+ .option("--limit <limit>", "Maximum messages per poll (1..100)", runtime.parseLimit)
687
+ .action(async (options) => {
688
+ if ((options.threadId === undefined) === (options.channel === undefined)) {
689
+ throw new InvalidArgumentError("Specify exactly one of --thread-id or --channel");
690
+ }
691
+ runtime.setExitCode(await runtime.run((client) => client.GET("/v1/workspaces/{workspaceId}/board/events", {
692
+ params: {
693
+ path: { workspaceId: options.workspaceId },
694
+ query: {
695
+ ...(options.threadId === undefined ? {} : { threadId: options.threadId }),
696
+ ...(options.channel === undefined ? {} : { channelId: options.channel }),
697
+ ...(options.since === undefined ? {} : { since: options.since }),
698
+ wait: options.wait,
699
+ ...(options.limit === undefined ? {} : { limit: options.limit }),
700
+ },
701
+ },
702
+ }), { rejectWorkspaceReadToken: true }));
703
+ });
704
+ // 13. specflow discuss tail (continuous NDJSON stream)
705
+ discuss
706
+ .command("tail")
707
+ .description("Stream new Discussion Board messages as NDJSON lines")
708
+ .requiredOption("--workspace-id <workspaceId>", "Workspace ID", (v) => parseIdentifier(v, "Workspace ID"))
709
+ .option("--thread-id <threadId>", "Stream a single thread UUID", (v) => parseIdentifier(v, "Thread ID"))
710
+ .option("--channel <channelIdOrSlug>", "Stream a channel UUID or slug", (v) => parseIdentifier(v, "Channel"))
711
+ .option("--since <cursor>", "Starting opaque message cursor")
712
+ .option("--wait <seconds>", "Long-poll wait duration 0..25 seconds", parseWaitSeconds, 20)
713
+ .option("--limit <limit>", "Maximum messages per poll (1..100)", runtime.parseLimit)
714
+ .option("--once", "Perform a single poll and exit")
715
+ .option("--max-polls <count>", "Stop after at most N polls", (v) => parseNonNegativeInt(v, "Max polls"))
716
+ .action(async (options) => {
717
+ if ((options.threadId === undefined) === (options.channel === undefined)) {
718
+ throw new InvalidArgumentError("Specify exactly one of --thread-id or --channel");
719
+ }
720
+ const selected = await selectSession(runtime.dependencies, { rejectWorkspaceReadToken: true }, runtime.getServerFlag(), runtime.getApiKeyIdFlag(), runtime.getAgentFlag());
721
+ if ("exitCode" in selected) {
722
+ runtime.setExitCode(selected.exitCode);
723
+ return;
724
+ }
725
+ let cursor = options.since;
726
+ let polls = 0;
727
+ const maxPolls = options.once === true ? 1 : options.maxPolls;
728
+ while (maxPolls === undefined || polls < maxPolls) {
729
+ polls += 1;
730
+ const result = await selected.client.GET("/v1/workspaces/{workspaceId}/board/events", {
731
+ params: {
732
+ path: { workspaceId: options.workspaceId },
733
+ query: {
734
+ ...(options.threadId === undefined ? {} : { threadId: options.threadId }),
735
+ ...(options.channel === undefined ? {} : { channelId: options.channel }),
736
+ ...(cursor === undefined ? {} : { since: cursor }),
737
+ wait: options.wait,
738
+ ...(options.limit === undefined ? {} : { limit: options.limit }),
739
+ },
740
+ },
741
+ });
742
+ if (result.error !== undefined) {
743
+ const failure = mapHttpFailure(result.response, result.error);
744
+ writeSkillError(runtime.dependencies, failure);
745
+ runtime.setExitCode(skillErrorExitCode(failure));
746
+ return;
747
+ }
748
+ for (const message of result.data.messages) {
749
+ writeResult(runtime.dependencies, () => ({
750
+ cursor: result.data.cursor,
751
+ message,
752
+ }));
753
+ }
754
+ if (result.data.cursor.length > 0) {
755
+ cursor = result.data.cursor;
756
+ }
757
+ if (options.once === true && !result.data.hasMore)
758
+ break;
759
+ }
760
+ runtime.setExitCode(0);
761
+ });
762
+ }
763
+ //# sourceMappingURL=discuss-commands.js.map