@gonovus-ai/spec-flow-cli 1.0.1 → 1.2.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.
Files changed (51) hide show
  1. package/README.md +24 -3
  2. package/dist/agent-commands.d.ts +11 -0
  3. package/dist/agent-commands.js +613 -0
  4. package/dist/agent-commands.js.map +1 -0
  5. package/dist/agent-session-commands.d.ts +3 -0
  6. package/dist/agent-session-commands.js +367 -0
  7. package/dist/agent-session-commands.js.map +1 -0
  8. package/dist/board-commands.d.ts +3 -0
  9. package/dist/board-commands.js +381 -0
  10. package/dist/board-commands.js.map +1 -0
  11. package/dist/cli.d.ts +4 -0
  12. package/dist/cli.js +117 -3
  13. package/dist/cli.js.map +1 -1
  14. package/dist/commands/work-item-output.d.ts +182 -0
  15. package/dist/commands/work-item-output.js +1 -0
  16. package/dist/commands/work-item-output.js.map +1 -1
  17. package/dist/context-agents-block.d.ts +57 -0
  18. package/dist/context-agents-block.js +331 -0
  19. package/dist/context-agents-block.js.map +1 -0
  20. package/dist/context-command-support.d.ts +186 -0
  21. package/dist/context-command-support.js +176 -0
  22. package/dist/context-command-support.js.map +1 -0
  23. package/dist/context-document-commands.d.ts +5 -0
  24. package/dist/context-document-commands.js +674 -0
  25. package/dist/context-document-commands.js.map +1 -0
  26. package/dist/index.js +42 -2
  27. package/dist/index.js.map +1 -1
  28. package/dist/program.js +1 -0
  29. package/dist/program.js.map +1 -1
  30. package/dist/resource-command-runtime.d.ts +1 -0
  31. package/dist/runtime/errors.d.ts +21 -0
  32. package/dist/runtime/errors.js +92 -1
  33. package/dist/runtime/errors.js.map +1 -1
  34. package/dist/runtime/execute.d.ts +9 -0
  35. package/dist/runtime/execute.js +18 -4
  36. package/dist/runtime/execute.js.map +1 -1
  37. package/dist/runtime/session.d.ts +1 -1
  38. package/dist/runtime/session.js +22 -11
  39. package/dist/runtime/session.js.map +1 -1
  40. package/dist/work-item-query-commands.js +48 -6
  41. package/dist/work-item-query-commands.js.map +1 -1
  42. package/dist/work-item-resource-link-commands.js +36 -0
  43. package/dist/work-item-resource-link-commands.js.map +1 -1
  44. package/dist/work-item-thread-commands.js +14 -1
  45. package/dist/work-item-thread-commands.js.map +1 -1
  46. package/guides/agent-sessions.md +110 -0
  47. package/guides/boards.md +123 -0
  48. package/guides/context-documents.md +181 -0
  49. package/guides/errors.md +15 -0
  50. package/guides/work-items.md +7 -0
  51. package/package.json +1 -1
package/README.md CHANGED
@@ -39,7 +39,7 @@ seven-day Better Auth CLI Session. It supports the Node.js 24 runtime line;
39
39
  Node.js 22 and unverified future major versions are intentionally unsupported.
40
40
 
41
41
  ```bash
42
- npm install --global @gonovus-ai/spec-flow-cli@1.0.1
42
+ npm install --global @gonovus-ai/spec-flow-cli@1.2.0
43
43
  specflow auth login
44
44
  specflow auth status
45
45
  specflow auth logout
@@ -61,13 +61,34 @@ default, provide `SPEC_FLOW_DEFAULT_API_URL` to the CLI build command. The packe
61
61
  installation smoke uses an isolated `.invalid` test origin when no build value is
62
62
  provided; it never substitutes a deployment URL into source.
63
63
 
64
+ ## Context Documents and boards
65
+
66
+ CLI 1.1.0 reads and drafts Context Documents (engineering specifications with
67
+ Guardrails and boards) and keeps a repository's AGENTS.md current:
68
+
69
+ ```bash
70
+ specflow context index --workspace-id <workspace-id> --repository owner/name
71
+ specflow context sync-agents --workspace-id <workspace-id>
72
+ specflow context sync-agents --check
73
+ specflow context-doc read --workspace-id <workspace-id> --document-id PAY-D3
74
+ specflow context-doc draft edit --workspace-id <workspace-id> --document-id PAY-D3 --body-file body.md --expected-version 7
75
+ specflow board read --workspace-id <workspace-id> --document-id PAY-D3 --board-id <board-id> --revision draft
76
+ specflow board image --workspace-id <workspace-id> --document-id PAY-D3 --board-id <board-id> --out board.png
77
+ specflow board import --workspace-id <workspace-id> --document-id PAY-D3 --file flow.mmd --mode new --dry-run
78
+ ```
79
+
80
+ `sync-agents` writes a `<!-- specflow:context:begin -->` block that reruns leave
81
+ byte-identical; `--check` exits 1 with a diff when it is stale. Changes written by
82
+ the CLI are Agent changes: Guardrails and proposed placement wait for a person's
83
+ review in the Web application, and publishing waits until then (`REVIEW_PENDING`).
84
+
64
85
  ## Compatibility and upgrades
65
86
 
66
87
  ```bash
67
- specflow version --json --skill-version 0.6.2 --compatible-cli "^1.0.0"
88
+ specflow version --json --skill-version 0.8.0 --compatible-cli "^1.2.0"
68
89
  specflow upgrade
69
90
  specflow upgrade --yes
70
- specflow upgrade --to 1.0.1
91
+ specflow upgrade --to 1.2.0
71
92
  ```
72
93
 
73
94
  `version` shows the installed CLI and public advice from the selected origin.
@@ -0,0 +1,11 @@
1
+ import { type Command } from "commander";
2
+ import type { CliDependencies } from "./cli.js";
3
+ import type { ResourceCommandRuntime } from "./resource-command-runtime.js";
4
+ export interface AgentCommandRuntime extends ResourceCommandRuntime {
5
+ readonly dependencies: CliDependencies;
6
+ readonly getServerFlag: () => unknown;
7
+ readonly getApiKeyIdFlag: () => unknown;
8
+ readonly getAgentFlag: () => unknown;
9
+ readonly parseProjectId: (value: string) => string;
10
+ }
11
+ export declare function registerAgentCommands(program: Command, runtime: AgentCommandRuntime): void;
@@ -0,0 +1,613 @@
1
+ import { InvalidArgumentError } from "commander";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, open, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { z } from "zod";
6
+ import { registerAgentSessionCommands } from "./agent-session-commands.js";
7
+ import { formatResourceDiagnostic } from "./cli.js";
8
+ import { mapHttpFailure, skillErrorExitCode, writeSkillError, } from "./runtime/errors.js";
9
+ import { writeResult } from "./runtime/output.js";
10
+ import { selectSession } from "./runtime/session.js";
11
+ const controlPlaneOptions = {
12
+ omitAgentHeader: true,
13
+ rejectWorkspaceReadToken: true,
14
+ };
15
+ const cursorStateSchema = z
16
+ .object({
17
+ agentId: z.string().min(1).max(128).optional(),
18
+ slug: z.string().min(1).max(64).optional(),
19
+ workspaceId: z.string().min(1).max(200),
20
+ cursorSeq: z.number().int().nonnegative(),
21
+ })
22
+ .strict();
23
+ function parseNonNegativeInt(value, label) {
24
+ if (!/^(0|[1-9]\d*)$/u.test(value)) {
25
+ throw new InvalidArgumentError(`${label} must be a non-negative integer`);
26
+ }
27
+ const parsed = Number(value);
28
+ if (!Number.isSafeInteger(parsed)) {
29
+ throw new InvalidArgumentError(`${label} must be a safe integer`);
30
+ }
31
+ return parsed;
32
+ }
33
+ function parseWaitSeconds(value) {
34
+ const seconds = parseNonNegativeInt(value, "Wait seconds");
35
+ if (seconds > 25) {
36
+ throw new InvalidArgumentError("Wait seconds must be between 0 and 25");
37
+ }
38
+ return seconds;
39
+ }
40
+ function parseSlug(value) {
41
+ const normalized = value.trim().toLowerCase();
42
+ if (!/^[a-z][a-z0-9-]{0,31}$/u.test(normalized)) {
43
+ throw new InvalidArgumentError("Agent slug must start with a lowercase letter and use 1 to 32 lowercase letters, digits, or hyphens");
44
+ }
45
+ return normalized;
46
+ }
47
+ function parseAgentExpectedVersion(value) {
48
+ const trimmed = value.trim();
49
+ if (/^"[1-9]\d*"$/u.test(trimmed)) {
50
+ return trimmed;
51
+ }
52
+ if (/^[1-9]\d*$/u.test(trimmed)) {
53
+ return `"${trimmed}"`;
54
+ }
55
+ throw new InvalidArgumentError('Expected version must be a positive integer or quoted version (e.g. 1 or "1")');
56
+ }
57
+ function parseAgentIdOrSlug(value) {
58
+ const trimmed = value.trim();
59
+ if (trimmed.length === 0 || trimmed.length > 128) {
60
+ throw new InvalidArgumentError("Agent ID or slug must be 1 to 128 characters");
61
+ }
62
+ return trimmed;
63
+ }
64
+ function collectProjectIds(parseProjectId) {
65
+ return (value, previous) => {
66
+ const projectId = parseProjectId(value);
67
+ return previous.includes(projectId) ? previous : [...previous, projectId];
68
+ };
69
+ }
70
+ function resolveDefaultCursorFile(environment, workspaceId, agentKey) {
71
+ const configBase = environment.XDG_CONFIG_HOME !== undefined && environment.XDG_CONFIG_HOME.trim().length > 0
72
+ ? environment.XDG_CONFIG_HOME.trim()
73
+ : environment.HOME !== undefined && environment.HOME.trim().length > 0
74
+ ? join(environment.HOME.trim(), ".config")
75
+ : null;
76
+ if (configBase === null)
77
+ return null;
78
+ const safeWorkspace = workspaceId
79
+ .trim()
80
+ .toLowerCase()
81
+ .replace(/[^a-z0-9._-]/gu, "_");
82
+ const safeName = agentKey
83
+ .trim()
84
+ .toLowerCase()
85
+ .replace(/[^a-z0-9._-]/gu, "_");
86
+ return join(configBase, "specflow", "cursors", safeWorkspace, `${safeName}.json`);
87
+ }
88
+ async function readCursorState(filePath) {
89
+ try {
90
+ const raw = await readFile(filePath, "utf8");
91
+ const parsed = cursorStateSchema.safeParse(JSON.parse(raw));
92
+ return parsed.success ? parsed.data : null;
93
+ }
94
+ catch (error) {
95
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
96
+ return null;
97
+ }
98
+ throw error;
99
+ }
100
+ }
101
+ async function writeCursorStateAtomic(filePath, state) {
102
+ const directory = dirname(filePath);
103
+ await mkdir(directory, { recursive: true });
104
+ const tempPath = join(directory, `.cursor.${String(process.pid)}.${randomUUID()}.tmp`);
105
+ const serialized = `${JSON.stringify(state, null, 2)}\n`;
106
+ try {
107
+ await writeFile(tempPath, serialized, { encoding: "utf8", mode: 0o600 });
108
+ await rename(tempPath, filePath);
109
+ }
110
+ catch (error) {
111
+ await unlink(tempPath).catch(() => undefined);
112
+ throw error;
113
+ }
114
+ }
115
+ const cursorLockMetadataSchema = z.object({
116
+ pid: z.number().int().positive(),
117
+ });
118
+ function isProcessMissing(pid) {
119
+ try {
120
+ process.kill(pid, 0);
121
+ return false;
122
+ }
123
+ catch (error) {
124
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ESRCH";
125
+ }
126
+ }
127
+ async function tryReclaimStaleLock(lockPath) {
128
+ let raw;
129
+ try {
130
+ raw = await readFile(lockPath, "utf8");
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ let parsedJson;
136
+ try {
137
+ parsedJson = JSON.parse(raw);
138
+ }
139
+ catch {
140
+ return false;
141
+ }
142
+ const metadata = cursorLockMetadataSchema.safeParse(parsedJson);
143
+ if (!metadata.success || !isProcessMissing(metadata.data.pid)) {
144
+ return false;
145
+ }
146
+ await unlink(lockPath).catch(() => undefined);
147
+ return true;
148
+ }
149
+ async function acquireCursorLock(cursorFilePath) {
150
+ const lockPath = `${cursorFilePath}.lock`;
151
+ await mkdir(dirname(lockPath), { recursive: true });
152
+ let handle = null;
153
+ for (let attempt = 0; attempt < 2; attempt += 1) {
154
+ try {
155
+ handle = await open(lockPath, "wx", 0o600);
156
+ break;
157
+ }
158
+ catch (error) {
159
+ if (typeof error === "object" &&
160
+ error !== null &&
161
+ "code" in error &&
162
+ error.code === "EEXIST") {
163
+ if (attempt === 0 && (await tryReclaimStaleLock(lockPath))) {
164
+ continue;
165
+ }
166
+ return null;
167
+ }
168
+ throw error;
169
+ }
170
+ }
171
+ if (handle === null)
172
+ return null;
173
+ try {
174
+ await handle.writeFile(`${JSON.stringify({ pid: process.pid, acquiredAt: new Date().toISOString() })}\n`, "utf8");
175
+ }
176
+ finally {
177
+ await handle.close();
178
+ }
179
+ let released = false;
180
+ return {
181
+ release: async () => {
182
+ if (released)
183
+ return;
184
+ released = true;
185
+ await unlink(lockPath).catch(() => undefined);
186
+ },
187
+ };
188
+ }
189
+ function defaultSleep(milliseconds) {
190
+ return new Promise((resolve) => {
191
+ setTimeout(resolve, milliseconds);
192
+ });
193
+ }
194
+ function writeAgentEventsPollResult(dependencies, data) {
195
+ return writeResult(dependencies, () => data);
196
+ }
197
+ export function registerAgentCommands(program, runtime) {
198
+ const agent = program
199
+ .command("agent")
200
+ .description("Register, manage, and listen for events as a Workspace Agent");
201
+ agent
202
+ .command("register")
203
+ .description("Register a CLI Agent owned by the authenticated member and write cursorSeq 0")
204
+ .requiredOption("--workspace-id <workspaceId>")
205
+ .requiredOption("--name <name>", "Agent display name")
206
+ .requiredOption("--slug <slug>", "Workspace-unique lowercase Agent slug", parseSlug)
207
+ .option("--project-id <projectId>", "Active Project to grant; repeat for several Projects", collectProjectIds(runtime.parseProjectId), [])
208
+ .option("--cursor-file <path>", "Path for the persisted cursor file (defaults to ~/.config/specflow/cursors/<workspaceId>/<slug>.json)")
209
+ .action(async (options) => {
210
+ const cursorFile = options.cursorFile ??
211
+ resolveDefaultCursorFile(runtime.dependencies.environment, options.workspaceId, options.slug);
212
+ const registeredBox = { value: null };
213
+ const exitCode = await runtime.run(async (client) => {
214
+ const result = await client.POST("/v1/workspaces/{workspaceId}/agents/cli", {
215
+ params: { path: { workspaceId: options.workspaceId } },
216
+ body: {
217
+ name: options.name,
218
+ slug: options.slug,
219
+ projectIds: options.projectId,
220
+ },
221
+ });
222
+ if (result.response.ok && result.data !== undefined) {
223
+ registeredBox.value = {
224
+ agentId: result.data.agent.id,
225
+ slug: result.data.agent.slug,
226
+ cursorSeq: result.data.cursorSeq,
227
+ };
228
+ }
229
+ return result;
230
+ }, controlPlaneOptions);
231
+ if (exitCode !== 0) {
232
+ runtime.setExitCode(exitCode);
233
+ return;
234
+ }
235
+ const saved = registeredBox.value;
236
+ if (saved !== null && cursorFile !== null) {
237
+ try {
238
+ await writeCursorStateAtomic(cursorFile, {
239
+ agentId: saved.agentId,
240
+ slug: saved.slug,
241
+ workspaceId: options.workspaceId,
242
+ cursorSeq: saved.cursorSeq,
243
+ });
244
+ }
245
+ catch {
246
+ writeSkillError(runtime.dependencies, {
247
+ message: `Agent was registered, but failed to persist cursor file at ${cursorFile}`,
248
+ reason: "Temporary Failure",
249
+ retryable: true,
250
+ });
251
+ runtime.setExitCode(4);
252
+ return;
253
+ }
254
+ }
255
+ runtime.setExitCode(0);
256
+ });
257
+ agent
258
+ .command("list")
259
+ .description("List Workspace Agents visible to the caller")
260
+ .requiredOption("--workspace-id <workspaceId>")
261
+ .action(async (options) => {
262
+ runtime.setExitCode(await runtime.run((client) => client.GET("/v1/workspaces/{workspaceId}/agents", {
263
+ params: { path: { workspaceId: options.workspaceId } },
264
+ }), controlPlaneOptions));
265
+ });
266
+ agent
267
+ .command("read")
268
+ .description("Read one Workspace Agent by ID or slug")
269
+ .requiredOption("--workspace-id <workspaceId>")
270
+ .requiredOption("--agent-id <agentIdOrSlug>", "Agent UUID or slug", parseAgentIdOrSlug)
271
+ .action(async (options) => {
272
+ runtime.setExitCode(await runtime.run((client) => client.GET("/v1/workspaces/{workspaceId}/agents/{agentId}", {
273
+ params: {
274
+ path: { workspaceId: options.workspaceId, agentId: options.agentId },
275
+ },
276
+ }), controlPlaneOptions));
277
+ });
278
+ agent
279
+ .command("update")
280
+ .description("Rename or enable/disable an owned CLI Agent")
281
+ .requiredOption("--workspace-id <workspaceId>")
282
+ .requiredOption("--agent-id <agentIdOrSlug>", "Agent UUID or slug", parseAgentIdOrSlug)
283
+ .requiredOption("--expected-version <version>", 'Agent version returned by SpecFlow (e.g. 1 or "1")', parseAgentExpectedVersion)
284
+ .option("--name <name>", "Updated display name")
285
+ .option("--enable", "Set Agent status to active")
286
+ .option("--disable", "Set Agent status to disabled")
287
+ .action(async (options) => {
288
+ if (options.enable === true && options.disable === true) {
289
+ throw new InvalidArgumentError("Cannot combine --enable and --disable");
290
+ }
291
+ if (options.name === undefined && options.enable !== true && options.disable !== true) {
292
+ throw new InvalidArgumentError("Agent update requires at least one of --name, --enable, or --disable");
293
+ }
294
+ const enabled = options.enable === true ? true : options.disable === true ? false : undefined;
295
+ runtime.setExitCode(await runtime.run((client) => client.PATCH("/v1/workspaces/{workspaceId}/agents/{agentId}", {
296
+ params: {
297
+ path: { workspaceId: options.workspaceId, agentId: options.agentId },
298
+ header: { "if-match": options.expectedVersion },
299
+ },
300
+ body: {
301
+ ...(options.name === undefined ? {} : { name: options.name }),
302
+ ...(enabled === undefined ? {} : { enabled }),
303
+ },
304
+ }), controlPlaneOptions));
305
+ });
306
+ agent
307
+ .command("delete")
308
+ .description("Hard-delete an Agent with no historical references")
309
+ .requiredOption("--workspace-id <workspaceId>")
310
+ .requiredOption("--agent-id <agentIdOrSlug>", "Agent UUID or slug", parseAgentIdOrSlug)
311
+ .requiredOption("--expected-version <version>", 'Agent version returned by SpecFlow (e.g. 1 or "1")', parseAgentExpectedVersion)
312
+ .action(async (options) => {
313
+ runtime.setExitCode(await runtime.run(async (client) => {
314
+ const result = await client.DELETE("/v1/workspaces/{workspaceId}/agents/{agentId}", {
315
+ params: {
316
+ path: { workspaceId: options.workspaceId, agentId: options.agentId },
317
+ header: { "if-match": options.expectedVersion },
318
+ },
319
+ });
320
+ return result.response.status === 204
321
+ ? { ...result, data: { deleted: true, agentId: options.agentId } }
322
+ : result;
323
+ }, controlPlaneOptions));
324
+ });
325
+ const agentProject = agent
326
+ .command("project")
327
+ .description("Grant or revoke Active Project access for an Agent");
328
+ agentProject
329
+ .command("add")
330
+ .requiredOption("--workspace-id <workspaceId>")
331
+ .requiredOption("--agent-id <agentIdOrSlug>", "Agent UUID or slug", parseAgentIdOrSlug)
332
+ .requiredOption("--project-id <projectId>", "Project ID", runtime.parseProjectId)
333
+ .requiredOption("--expected-version <version>", 'Agent version returned by SpecFlow (e.g. 1 or "1")', parseAgentExpectedVersion)
334
+ .action(async (options) => {
335
+ runtime.setExitCode(await runtime.run((client) => client.PUT("/v1/workspaces/{workspaceId}/agents/{agentId}/projects/{projectId}", {
336
+ params: {
337
+ path: {
338
+ workspaceId: options.workspaceId,
339
+ agentId: options.agentId,
340
+ projectId: options.projectId,
341
+ },
342
+ header: { "if-match": options.expectedVersion },
343
+ },
344
+ }), controlPlaneOptions));
345
+ });
346
+ agentProject
347
+ .command("remove")
348
+ .requiredOption("--workspace-id <workspaceId>")
349
+ .requiredOption("--agent-id <agentIdOrSlug>", "Agent UUID or slug", parseAgentIdOrSlug)
350
+ .requiredOption("--project-id <projectId>", "Project ID", runtime.parseProjectId)
351
+ .requiredOption("--expected-version <version>", 'Agent version returned by SpecFlow (e.g. 1 or "1")', parseAgentExpectedVersion)
352
+ .action(async (options) => {
353
+ runtime.setExitCode(await runtime.run((client) => client.DELETE("/v1/workspaces/{workspaceId}/agents/{agentId}/projects/{projectId}", {
354
+ params: {
355
+ path: {
356
+ workspaceId: options.workspaceId,
357
+ agentId: options.agentId,
358
+ projectId: options.projectId,
359
+ },
360
+ header: { "if-match": options.expectedVersion },
361
+ },
362
+ }), controlPlaneOptions));
363
+ });
364
+ agent
365
+ .command("listen")
366
+ .description("Poll durable Agent events with local cursor locking and atomic persistence (JSON output)")
367
+ .requiredOption("--workspace-id <workspaceId>")
368
+ .option("--agent <agentIdOrSlug>", "Agent UUID or slug", parseAgentIdOrSlug)
369
+ .option("--cursor-file <path>", "Local cursor file path (defaults to ~/.config/specflow/cursors/<workspaceId>/<agent>.json)")
370
+ .option("--after <seq>", "Override starting cursor sequence", (value) => parseNonNegativeInt(value, "after"))
371
+ .option("--limit <limit>", "Events per poll batch, 1 through 100", runtime.parseLimit, 50)
372
+ .option("--wait <seconds>", "Server long-poll wait in seconds, 0 through 25 (default 15, or 0 with --once)", parseWaitSeconds)
373
+ .option("--once", "Perform a single poll cycle, persist cursor, print JSON response, and exit")
374
+ .option("--auto-register", "Automatically register the CLI Agent if it does not exist yet (requires --name)")
375
+ .option("--name <name>", "Agent display name used with --auto-register")
376
+ .option("--project-id <projectId>", "Active Project to grant when using --auto-register; repeat for several Projects", collectProjectIds(runtime.parseProjectId), [])
377
+ .action(async (options) => {
378
+ const rootAgent = runtime.getAgentFlag();
379
+ const envAgent = runtime.dependencies.environment.SPEC_FLOW_AGENT;
380
+ const resolvedAgent = options.agent ??
381
+ (typeof rootAgent === "string"
382
+ ? parseAgentIdOrSlug(rootAgent)
383
+ : typeof envAgent === "string" && envAgent.trim().length > 0
384
+ ? parseAgentIdOrSlug(envAgent)
385
+ : undefined);
386
+ if (resolvedAgent === undefined) {
387
+ throw new InvalidArgumentError("required option '--agent <agentIdOrSlug>' not specified");
388
+ }
389
+ if (options.autoRegister === true) {
390
+ parseSlug(resolvedAgent);
391
+ if (options.name === undefined || options.name.trim().length === 0) {
392
+ throw new InvalidArgumentError("--auto-register requires --name <name>");
393
+ }
394
+ }
395
+ const exitCode = await runAgentListen(runtime, { ...options, agent: resolvedAgent });
396
+ runtime.setExitCode(exitCode);
397
+ });
398
+ registerAgentSessionCommands(agent, runtime);
399
+ }
400
+ async function runAgentListen(runtime, options) {
401
+ const { dependencies } = runtime;
402
+ const selected = await selectSession(dependencies, controlPlaneOptions, runtime.getServerFlag(), runtime.getApiKeyIdFlag());
403
+ if ("exitCode" in selected)
404
+ return selected.exitCode;
405
+ const cursorFile = options.cursorFile ??
406
+ resolveDefaultCursorFile(dependencies.environment, options.workspaceId, options.agent);
407
+ let lock = null;
408
+ if (cursorFile !== null) {
409
+ try {
410
+ lock = await acquireCursorLock(cursorFile);
411
+ }
412
+ catch {
413
+ writeSkillError(dependencies, {
414
+ message: `Failed to acquire cursor lock for ${cursorFile}`,
415
+ reason: "Temporary Failure",
416
+ retryable: true,
417
+ });
418
+ return 4;
419
+ }
420
+ if (lock === null) {
421
+ writeSkillError(dependencies, {
422
+ message: `Another specflow agent listen process holds the cursor lock for ${cursorFile}`,
423
+ reason: "Invalid Operation",
424
+ retryable: false,
425
+ });
426
+ return 2;
427
+ }
428
+ }
429
+ const listenerState = { stopped: false };
430
+ const isStopped = () => listenerState.stopped;
431
+ const activeAbort = { controller: null };
432
+ const handleSignal = () => {
433
+ listenerState.stopped = true;
434
+ activeAbort.controller?.abort();
435
+ };
436
+ process.on("SIGINT", handleSignal);
437
+ process.on("SIGTERM", handleSignal);
438
+ try {
439
+ let persisted = null;
440
+ if (cursorFile !== null) {
441
+ try {
442
+ persisted = await readCursorState(cursorFile);
443
+ }
444
+ catch {
445
+ writeSkillError(dependencies, {
446
+ message: `Failed to read cursor file at ${cursorFile}`,
447
+ reason: "Invalid Operation",
448
+ retryable: false,
449
+ });
450
+ return 2;
451
+ }
452
+ }
453
+ const normalizedRequestedAgent = options.agent.trim().toLowerCase();
454
+ const matchedPersisted = persisted !== null &&
455
+ persisted.workspaceId === options.workspaceId &&
456
+ (persisted.agentId === options.agent ||
457
+ persisted.slug?.toLowerCase() === normalizedRequestedAgent ||
458
+ (persisted.agentId === undefined && persisted.slug === undefined))
459
+ ? persisted
460
+ : null;
461
+ let resolvedAgentId = matchedPersisted?.agentId;
462
+ let resolvedAgent = resolvedAgentId ?? options.agent;
463
+ let resolvedSlug = matchedPersisted?.slug;
464
+ let currentCursor = options.after ?? matchedPersisted?.cursorSeq;
465
+ if (options.autoRegister === true && matchedPersisted === null) {
466
+ const registered = await ensureAutoRegistered(selected.client, dependencies, options.workspaceId, options.agent, options.name ?? options.agent, options.projectId);
467
+ if ("exitCode" in registered)
468
+ return registered.exitCode;
469
+ resolvedAgentId = registered.agentId;
470
+ resolvedAgent = registered.agentId;
471
+ resolvedSlug = registered.slug;
472
+ if (currentCursor === undefined && registered.cursorSeq !== undefined) {
473
+ currentCursor = registered.cursorSeq;
474
+ }
475
+ if (cursorFile !== null && currentCursor !== undefined) {
476
+ await writeCursorStateAtomic(cursorFile, {
477
+ agentId: resolvedAgentId,
478
+ slug: resolvedSlug,
479
+ workspaceId: options.workspaceId,
480
+ cursorSeq: currentCursor,
481
+ });
482
+ }
483
+ }
484
+ const defaultWait = options.once === true ? 0 : 15;
485
+ const configuredWait = options.wait ?? defaultWait;
486
+ const sleep = dependencies.sleep ?? defaultSleep;
487
+ let consecutiveTransientErrors = 0;
488
+ let forceImmediateNext = false;
489
+ while (!isStopped()) {
490
+ const controller = new AbortController();
491
+ activeAbort.controller = controller;
492
+ const waitSeconds = forceImmediateNext ? 0 : configuredWait;
493
+ forceImmediateNext = false;
494
+ let result;
495
+ try {
496
+ result = await selected.client.GET("/v1/workspaces/{workspaceId}/agents/{agentId}/events", {
497
+ params: {
498
+ path: { workspaceId: options.workspaceId, agentId: resolvedAgent },
499
+ query: {
500
+ ...(currentCursor === undefined ? {} : { after: currentCursor }),
501
+ limit: options.limit,
502
+ wait: waitSeconds,
503
+ },
504
+ },
505
+ signal: controller.signal,
506
+ });
507
+ }
508
+ catch (error) {
509
+ activeAbort.controller = null;
510
+ if (isStopped() || (error instanceof Error && error.name === "AbortError")) {
511
+ return 0;
512
+ }
513
+ const transportError = {
514
+ message: "SpecFlow could not be reached while polling Agent events",
515
+ reason: "Temporary Failure",
516
+ retryable: true,
517
+ };
518
+ if (options.once === true) {
519
+ writeSkillError(dependencies, transportError);
520
+ return skillErrorExitCode(transportError);
521
+ }
522
+ consecutiveTransientErrors += 1;
523
+ dependencies.stderr(formatResourceDiagnostic(transportError.message));
524
+ await sleep(Math.min(1_000 * 2 ** (consecutiveTransientErrors - 1), 5_000));
525
+ continue;
526
+ }
527
+ activeAbort.controller = null;
528
+ if (!result.response.ok || result.data === undefined) {
529
+ const failure = mapHttpFailure(result.response, result.error);
530
+ if (options.once === true || !failure.retryable) {
531
+ writeSkillError(dependencies, failure);
532
+ return skillErrorExitCode(failure);
533
+ }
534
+ consecutiveTransientErrors += 1;
535
+ dependencies.stderr(formatResourceDiagnostic(failure.message));
536
+ await sleep(Math.min(1_000 * 2 ** (consecutiveTransientErrors - 1), 5_000));
537
+ continue;
538
+ }
539
+ consecutiveTransientErrors = 0;
540
+ const page = result.data;
541
+ if (options.once === true) {
542
+ const outputExit = writeAgentEventsPollResult(dependencies, page);
543
+ if (outputExit !== 0)
544
+ return outputExit;
545
+ if (cursorFile !== null) {
546
+ await writeCursorStateAtomic(cursorFile, {
547
+ ...(resolvedAgentId === undefined ? {} : { agentId: resolvedAgentId }),
548
+ ...(resolvedSlug === undefined ? {} : { slug: resolvedSlug }),
549
+ workspaceId: options.workspaceId,
550
+ cursorSeq: page.nextCursor,
551
+ });
552
+ }
553
+ return 0;
554
+ }
555
+ for (const event of page.events) {
556
+ dependencies.stdout(`${JSON.stringify(event)}\n`);
557
+ }
558
+ currentCursor = page.nextCursor;
559
+ if (cursorFile !== null) {
560
+ await writeCursorStateAtomic(cursorFile, {
561
+ ...(resolvedAgentId === undefined ? {} : { agentId: resolvedAgentId }),
562
+ ...(resolvedSlug === undefined ? {} : { slug: resolvedSlug }),
563
+ workspaceId: options.workspaceId,
564
+ cursorSeq: page.nextCursor,
565
+ });
566
+ }
567
+ if (page.hasMore) {
568
+ forceImmediateNext = true;
569
+ }
570
+ }
571
+ return 0;
572
+ }
573
+ finally {
574
+ process.off("SIGINT", handleSignal);
575
+ process.off("SIGTERM", handleSignal);
576
+ await lock?.release();
577
+ }
578
+ }
579
+ async function ensureAutoRegistered(client, dependencies, workspaceId, slug, name, projectIds) {
580
+ const existing = await client.GET("/v1/workspaces/{workspaceId}/agents/{agentId}", {
581
+ params: { path: { workspaceId, agentId: slug } },
582
+ });
583
+ if (existing.response.ok && existing.data !== undefined) {
584
+ return {
585
+ agentId: existing.data.agent.id,
586
+ slug: existing.data.agent.slug,
587
+ };
588
+ }
589
+ if (existing.response.status !== 404) {
590
+ const failure = mapHttpFailure(existing.response, existing.error);
591
+ writeSkillError(dependencies, failure);
592
+ return { exitCode: skillErrorExitCode(failure) };
593
+ }
594
+ const created = await client.POST("/v1/workspaces/{workspaceId}/agents/cli", {
595
+ params: { path: { workspaceId } },
596
+ body: {
597
+ name: name.trim(),
598
+ slug: parseSlug(slug),
599
+ projectIds: [...projectIds],
600
+ },
601
+ });
602
+ if (!created.response.ok || created.data === undefined) {
603
+ const failure = mapHttpFailure(created.response, created.error);
604
+ writeSkillError(dependencies, failure);
605
+ return { exitCode: skillErrorExitCode(failure) };
606
+ }
607
+ return {
608
+ agentId: created.data.agent.id,
609
+ slug: created.data.agent.slug,
610
+ cursorSeq: created.data.cursorSeq,
611
+ };
612
+ }
613
+ //# sourceMappingURL=agent-commands.js.map