@agentuity/cli 1.0.35 → 1.0.37

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 (103) hide show
  1. package/bin/cli.ts +43 -11
  2. package/dist/cmd/cloud/keyvalue/create-namespace.js +3 -3
  3. package/dist/cmd/cloud/keyvalue/create-namespace.js.map +1 -1
  4. package/dist/cmd/cloud/keyvalue/delete-namespace.d.ts.map +1 -1
  5. package/dist/cmd/cloud/keyvalue/delete-namespace.js +7 -5
  6. package/dist/cmd/cloud/keyvalue/delete-namespace.js.map +1 -1
  7. package/dist/cmd/cloud/keyvalue/delete.d.ts.map +1 -1
  8. package/dist/cmd/cloud/keyvalue/delete.js +9 -3
  9. package/dist/cmd/cloud/keyvalue/delete.js.map +1 -1
  10. package/dist/cmd/cloud/keyvalue/get.d.ts.map +1 -1
  11. package/dist/cmd/cloud/keyvalue/get.js +6 -3
  12. package/dist/cmd/cloud/keyvalue/get.js.map +1 -1
  13. package/dist/cmd/cloud/keyvalue/keys.d.ts.map +1 -1
  14. package/dist/cmd/cloud/keyvalue/keys.js +9 -3
  15. package/dist/cmd/cloud/keyvalue/keys.js.map +1 -1
  16. package/dist/cmd/cloud/keyvalue/list-namespaces.js +3 -3
  17. package/dist/cmd/cloud/keyvalue/list-namespaces.js.map +1 -1
  18. package/dist/cmd/cloud/keyvalue/repl.d.ts.map +1 -1
  19. package/dist/cmd/cloud/keyvalue/repl.js +3 -1
  20. package/dist/cmd/cloud/keyvalue/repl.js.map +1 -1
  21. package/dist/cmd/cloud/keyvalue/search.d.ts.map +1 -1
  22. package/dist/cmd/cloud/keyvalue/search.js +6 -3
  23. package/dist/cmd/cloud/keyvalue/search.js.map +1 -1
  24. package/dist/cmd/cloud/keyvalue/set.d.ts.map +1 -1
  25. package/dist/cmd/cloud/keyvalue/set.js +7 -5
  26. package/dist/cmd/cloud/keyvalue/set.js.map +1 -1
  27. package/dist/cmd/cloud/keyvalue/stats.d.ts.map +1 -1
  28. package/dist/cmd/cloud/keyvalue/stats.js +6 -3
  29. package/dist/cmd/cloud/keyvalue/stats.js.map +1 -1
  30. package/dist/cmd/cloud/region/index.d.ts.map +1 -1
  31. package/dist/cmd/cloud/region/index.js +3 -1
  32. package/dist/cmd/cloud/region/index.js.map +1 -1
  33. package/dist/cmd/cloud/region/list.d.ts +2 -0
  34. package/dist/cmd/cloud/region/list.d.ts.map +1 -0
  35. package/dist/cmd/cloud/region/list.js +55 -0
  36. package/dist/cmd/cloud/region/list.js.map +1 -0
  37. package/dist/cmd/cloud/sandbox/cp.d.ts.map +1 -1
  38. package/dist/cmd/cloud/sandbox/cp.js +31 -0
  39. package/dist/cmd/cloud/sandbox/cp.js.map +1 -1
  40. package/dist/cmd/cloud/sandbox/exec.d.ts.map +1 -1
  41. package/dist/cmd/cloud/sandbox/exec.js +44 -11
  42. package/dist/cmd/cloud/sandbox/exec.js.map +1 -1
  43. package/dist/cmd/cloud/task/create.d.ts.map +1 -1
  44. package/dist/cmd/cloud/task/create.js +19 -0
  45. package/dist/cmd/cloud/task/create.js.map +1 -1
  46. package/dist/cmd/cloud/task/get.d.ts.map +1 -1
  47. package/dist/cmd/cloud/task/get.js +58 -4
  48. package/dist/cmd/cloud/task/get.js.map +1 -1
  49. package/dist/cmd/cloud/task/util.d.ts +1 -0
  50. package/dist/cmd/cloud/task/util.d.ts.map +1 -1
  51. package/dist/cmd/cloud/task/util.js +13 -0
  52. package/dist/cmd/cloud/task/util.js.map +1 -1
  53. package/dist/cmd/coder/hub-url.d.ts +35 -0
  54. package/dist/cmd/coder/hub-url.d.ts.map +1 -0
  55. package/dist/cmd/coder/hub-url.js +101 -0
  56. package/dist/cmd/coder/hub-url.js.map +1 -0
  57. package/dist/cmd/coder/index.d.ts +2 -0
  58. package/dist/cmd/coder/index.d.ts.map +1 -0
  59. package/dist/cmd/coder/index.js +27 -0
  60. package/dist/cmd/coder/index.js.map +1 -0
  61. package/dist/cmd/coder/inspect.d.ts +2 -0
  62. package/dist/cmd/coder/inspect.d.ts.map +1 -0
  63. package/dist/cmd/coder/inspect.js +145 -0
  64. package/dist/cmd/coder/inspect.js.map +1 -0
  65. package/dist/cmd/coder/list.d.ts +2 -0
  66. package/dist/cmd/coder/list.d.ts.map +1 -0
  67. package/dist/cmd/coder/list.js +109 -0
  68. package/dist/cmd/coder/list.js.map +1 -0
  69. package/dist/cmd/coder/start.d.ts +2 -0
  70. package/dist/cmd/coder/start.d.ts.map +1 -0
  71. package/dist/cmd/coder/start.js +384 -0
  72. package/dist/cmd/coder/start.js.map +1 -0
  73. package/dist/cmd/dev/index.d.ts.map +1 -1
  74. package/dist/cmd/dev/index.js +4 -0
  75. package/dist/cmd/dev/index.js.map +1 -1
  76. package/dist/cmd/index.d.ts.map +1 -1
  77. package/dist/cmd/index.js +1 -0
  78. package/dist/cmd/index.js.map +1 -1
  79. package/package.json +6 -6
  80. package/src/cmd/cloud/keyvalue/create-namespace.ts +3 -3
  81. package/src/cmd/cloud/keyvalue/delete-namespace.ts +7 -5
  82. package/src/cmd/cloud/keyvalue/delete.ts +9 -3
  83. package/src/cmd/cloud/keyvalue/get.ts +6 -3
  84. package/src/cmd/cloud/keyvalue/keys.ts +9 -3
  85. package/src/cmd/cloud/keyvalue/list-namespaces.ts +3 -3
  86. package/src/cmd/cloud/keyvalue/repl.ts +3 -1
  87. package/src/cmd/cloud/keyvalue/search.ts +6 -3
  88. package/src/cmd/cloud/keyvalue/set.ts +7 -5
  89. package/src/cmd/cloud/keyvalue/stats.ts +6 -3
  90. package/src/cmd/cloud/region/index.ts +3 -1
  91. package/src/cmd/cloud/region/list.ts +62 -0
  92. package/src/cmd/cloud/sandbox/cp.ts +32 -0
  93. package/src/cmd/cloud/sandbox/exec.ts +62 -13
  94. package/src/cmd/cloud/task/create.ts +22 -0
  95. package/src/cmd/cloud/task/get.ts +68 -4
  96. package/src/cmd/cloud/task/util.ts +18 -0
  97. package/src/cmd/coder/hub-url.ts +105 -0
  98. package/src/cmd/coder/index.ts +27 -0
  99. package/src/cmd/coder/inspect.ts +200 -0
  100. package/src/cmd/coder/list.ts +143 -0
  101. package/src/cmd/coder/start.ts +419 -0
  102. package/src/cmd/dev/index.ts +5 -0
  103. package/src/cmd/index.ts +1 -0
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { createCommand } from '../../../types';
3
3
  import * as tui from '../../../tui';
4
- import { createStorageAdapter, cacheTaskId } from './util';
4
+ import { createStorageAdapterOptionalOrg, cacheTaskId } from './util';
5
5
  import { getCommand } from '../../../command-prefix';
6
6
 
7
7
  const EntityRefSchema = z
@@ -19,6 +19,15 @@ const UserEntityRefSchema = z
19
19
  })
20
20
  .optional();
21
21
 
22
+ const SubtaskSchema = z.object({
23
+ id: z.string().describe('Subtask ID'),
24
+ title: z.string().describe('Subtask title'),
25
+ type: z.string().describe('Subtask type'),
26
+ status: z.string().describe('Subtask status'),
27
+ priority: z.string().describe('Subtask priority'),
28
+ assignee: UserEntityRefSchema.describe('Subtask assignee'),
29
+ });
30
+
22
31
  const TaskGetResponseSchema = z.object({
23
32
  success: z.boolean().describe('Whether the operation succeeded'),
24
33
  task: z.object({
@@ -41,6 +50,7 @@ const TaskGetResponseSchema = z.object({
41
50
  closed_date: z.string().optional().describe('Date task was closed'),
42
51
  cancelled_date: z.string().optional().describe('Date task was cancelled'),
43
52
  }),
53
+ subtasks: z.array(SubtaskSchema).optional().describe('Subtasks of this task'),
44
54
  durationMs: z.number().describe('Operation duration in milliseconds'),
45
55
  });
46
56
 
@@ -60,21 +70,27 @@ export const getSubcommand = createCommand({
60
70
  command: getCommand('cloud task get task_abc123 --json'),
61
71
  description: 'Get task details as JSON',
62
72
  },
73
+ {
74
+ command: getCommand('cloud task get task_abc123 --no-subtasks'),
75
+ description: 'Get task details without subtasks',
76
+ },
63
77
  ],
64
78
  schema: {
65
79
  args: z.object({
66
80
  id: z.string().min(1).describe('the task ID to get'),
67
81
  }),
82
+ options: z.object({
83
+ 'no-subtasks': z.boolean().optional().describe('Do not show subtasks'),
84
+ }),
68
85
  response: TaskGetResponseSchema,
69
86
  },
70
87
 
71
88
  async handler(ctx) {
72
- const { args, options } = ctx;
89
+ const { args, opts, options } = ctx;
73
90
  const started = Date.now();
74
- const storage = await createStorageAdapter(ctx);
91
+ const storage = await createStorageAdapterOptionalOrg(ctx);
75
92
 
76
93
  const task = await storage.get(args.id);
77
- const durationMs = Date.now() - started;
78
94
 
79
95
  if (!task) {
80
96
  tui.fatal(`Task not found: ${args.id}`);
@@ -82,6 +98,37 @@ export const getSubcommand = createCommand({
82
98
 
83
99
  await cacheTaskId(ctx, task.id);
84
100
 
101
+ // Fetch subtasks unless disabled
102
+ let subtasksList: {
103
+ id: string;
104
+ title: string;
105
+ type: string;
106
+ status: string;
107
+ priority: string;
108
+ assignee?: { id: string; name: string; type?: 'human' | 'agent' };
109
+ }[] = [];
110
+ let subtasksError: string | undefined;
111
+ if (!opts['no-subtasks']) {
112
+ try {
113
+ const subtasksResult = await storage.list({ parent_id: task.id });
114
+ subtasksList = subtasksResult.tasks.map((st) => ({
115
+ id: st.id,
116
+ title: st.title,
117
+ type: st.type,
118
+ status: st.status,
119
+ priority: st.priority,
120
+ assignee: st.assignee,
121
+ }));
122
+ } catch (err) {
123
+ subtasksError = err instanceof Error ? err.message : 'Failed to fetch subtasks';
124
+ if (!options.json) {
125
+ tui.warn(`Could not load subtasks: ${subtasksError}`);
126
+ }
127
+ }
128
+ }
129
+
130
+ const durationMs = Date.now() - started;
131
+
85
132
  if (!options.json) {
86
133
  const tableData: Record<string, string> = {
87
134
  ID: task.id,
@@ -133,6 +180,21 @@ export const getSubcommand = createCommand({
133
180
  tui.header('Metadata');
134
181
  tui.json(task.metadata);
135
182
  }
183
+
184
+ // Show subtasks
185
+ if (subtasksList.length > 0) {
186
+ tui.newline();
187
+ tui.header('Subtasks');
188
+ const subtaskRows = subtasksList.map((st) => ({
189
+ ID: st.id,
190
+ Title: st.title,
191
+ Type: st.type,
192
+ Status: st.status,
193
+ Priority: st.priority,
194
+ Assignee: st.assignee?.name ?? 'Unassigned',
195
+ }));
196
+ tui.table(subtaskRows, ['ID', 'Title', 'Type', 'Status', 'Priority', 'Assignee']);
197
+ }
136
198
  }
137
199
 
138
200
  return {
@@ -157,6 +219,8 @@ export const getSubcommand = createCommand({
157
219
  closed_date: task.closed_date,
158
220
  cancelled_date: task.cancelled_date,
159
221
  },
222
+ subtasks: subtasksList.length > 0 ? subtasksList : undefined,
223
+ subtasksError,
160
224
  durationMs,
161
225
  };
162
226
  },
@@ -36,6 +36,24 @@ export async function createStorageAdapter(ctx: TaskContext) {
36
36
  return new TaskStorageService(baseUrl, adapter);
37
37
  }
38
38
 
39
+ export async function createStorageAdapterOptionalOrg(ctx: TaskContext) {
40
+ const orgId =
41
+ ctx.options.orgId ?? (process.env.AGENTUITY_CLOUD_ORG_ID || ctx.config?.preferences?.orgId);
42
+
43
+ const headers: Record<string, string> = {
44
+ Authorization: `Bearer ${ctx.auth.apiKey}`,
45
+ };
46
+ if (orgId) {
47
+ headers['x-agentuity-orgid'] = orgId;
48
+ }
49
+
50
+ const adapter = createServerFetchAdapter({ headers }, ctx.logger);
51
+
52
+ const region = await getDefaultRegion(ctx.config?.name ?? defaultProfileName, ctx.config);
53
+ const baseUrl = getCatalystUrl(region, ctx.config?.overrides);
54
+ return new TaskStorageService(baseUrl, adapter);
55
+ }
56
+
39
57
  export async function cacheTaskId(
40
58
  ctx: {
41
59
  config: Config | null;
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Hub URL resolution for Coder CLI commands.
3
+ *
4
+ * Resolution priority:
5
+ * 1. --hub-url flag (explicit per-command override)
6
+ * 2. AGENTUITY_CODER_HUB_URL env var
7
+ * 3. AGENTUITY_DEVMODE_URL env var (dev tunnel URL)
8
+ */
9
+
10
+ import { getVersion } from '../../version';
11
+
12
+ /**
13
+ * Resolve the Hub HTTP base URL for REST API calls.
14
+ * Converts ws:// URLs to http:// automatically.
15
+ *
16
+ * @param flagUrl Optional --hub-url flag value
17
+ * @returns HTTP base URL (e.g. "http://localhost:3500") or null if Hub is unreachable
18
+ */
19
+ export async function resolveHubUrl(flagUrl?: string): Promise<string | null> {
20
+ // 1. Explicit flag
21
+ if (flagUrl) return normalizeToHttp(flagUrl);
22
+
23
+ // 2. Env var (explicit)
24
+ const envUrl = process.env.AGENTUITY_CODER_HUB_URL;
25
+ if (envUrl) return normalizeToHttp(envUrl);
26
+
27
+ // 3. Dev mode URL (tunnel)
28
+ const devUrl = process.env.AGENTUITY_DEVMODE_URL;
29
+ if (devUrl) return normalizeToHttp(devUrl);
30
+
31
+ return null;
32
+ }
33
+
34
+ /**
35
+ * Resolve the Hub WebSocket URL for Pi extension connections.
36
+ * Converts http:// URLs to ws:// automatically and ensures /api/ws path.
37
+ *
38
+ * @param flagUrl Optional --hub-url flag value
39
+ * @returns WebSocket URL (e.g. "ws://127.0.0.1:3500/api/ws") or null
40
+ */
41
+ export async function resolveHubWsUrl(flagUrl?: string): Promise<string | null> {
42
+ const httpUrl = await resolveHubUrl(flagUrl);
43
+ if (!httpUrl) return null;
44
+ return normalizeToWs(httpUrl);
45
+ }
46
+
47
+ /**
48
+ * Convert any URL form to an HTTP base URL (strip paths, convert ws->http).
49
+ */
50
+ function normalizeToHttp(url: string): string {
51
+ let normalized = url.trim().replace(/\/+$/, '');
52
+
53
+ // ws:// -> http://
54
+ if (normalized.startsWith('ws://')) normalized = 'http://' + normalized.slice(5);
55
+ else if (normalized.startsWith('wss://')) normalized = 'https://' + normalized.slice(6);
56
+
57
+ // Strip /api/ws or /api/hub/* paths to get base URL
58
+ normalized = normalized.replace(/\/api\/ws\b.*$/, '');
59
+ normalized = normalized.replace(/\/api\/hub\b.*$/, '');
60
+
61
+ return normalized.replace(/\/+$/, '');
62
+ }
63
+
64
+ /**
65
+ * Convert an HTTP base URL to a WebSocket URL with /api/ws path.
66
+ */
67
+ function normalizeToWs(httpUrl: string): string {
68
+ let wsUrl = httpUrl;
69
+ if (wsUrl.startsWith('http://')) wsUrl = 'ws://' + wsUrl.slice(7);
70
+ else if (wsUrl.startsWith('https://')) wsUrl = 'wss://' + wsUrl.slice(8);
71
+
72
+ try {
73
+ const parsed = new URL(wsUrl);
74
+ if (parsed.pathname !== '/api/ws') {
75
+ parsed.pathname = '/api/ws';
76
+ wsUrl = parsed.toString().replace(/\/$/, '');
77
+ }
78
+ } catch {
79
+ if (!wsUrl.endsWith('/api/ws')) {
80
+ wsUrl = wsUrl.replace(/\/?$/, '/api/ws');
81
+ }
82
+ }
83
+
84
+ return wsUrl;
85
+ }
86
+
87
+ /**
88
+ * Resolve the API key for Hub authentication.
89
+ * TODO: Remove/Change when we get Agentuity service level auth enabled, this is just temporary
90
+ */
91
+ export function resolveApiKey(): string | null {
92
+ return process.env.AGENTUITY_CODER_API_KEY || null;
93
+ }
94
+
95
+ /**
96
+ * Build headers object with API key if available.
97
+ * TODO: Remove/Change when we get Agentuity service level auth enabled, this is just temporary
98
+ */
99
+ export function hubFetchHeaders(extra?: Record<string, string>): Record<string, string> {
100
+ const headers: Record<string, string> = { ...extra };
101
+ headers['User-Agent'] = `Agentuity Coder/${getVersion()}`;
102
+ const apiKey = resolveApiKey();
103
+ if (apiKey) headers['x-agentuity-auth-api-key'] = apiKey;
104
+ return headers;
105
+ }
@@ -0,0 +1,27 @@
1
+ import { createCommand } from '../../types';
2
+ import { listSubcommand } from './list';
3
+ import { inspectSubcommand } from './inspect';
4
+ import { startSubcommand } from './start';
5
+ import { getCommand } from '../../command-prefix';
6
+
7
+ export const command = createCommand({
8
+ name: 'coder',
9
+ description: 'Coder Hub session management commands',
10
+ tags: ['requires-auth'],
11
+ examples: [
12
+ {
13
+ command: getCommand('coder start'),
14
+ description: 'Start a Pi session connected to the Coder Hub',
15
+ },
16
+ {
17
+ command: getCommand('coder ls'),
18
+ description: 'List all active Coder Hub sessions',
19
+ },
20
+ {
21
+ command: getCommand('coder inspect <session-id>'),
22
+ description: 'Show detailed session information',
23
+ },
24
+ ],
25
+ subcommands: [startSubcommand, listSubcommand, inspectSubcommand],
26
+ optional: { auth: true },
27
+ });
@@ -0,0 +1,200 @@
1
+ import { z } from 'zod';
2
+ import { createSubcommand } from '../../types';
3
+ import * as tui from '../../tui';
4
+ import { getCommand } from '../../command-prefix';
5
+ import { ErrorCode } from '../../errors';
6
+ import { resolveHubUrl, hubFetchHeaders } from './hub-url';
7
+
8
+ function formatRelativeTime(isoDate: string): string {
9
+ const diffMs = Date.now() - new Date(isoDate).getTime();
10
+ const seconds = Math.floor(diffMs / 1000);
11
+ if (seconds < 60) return `${seconds}s ago`;
12
+ const minutes = Math.floor(seconds / 60);
13
+ if (minutes < 60) return `${minutes}m ago`;
14
+ const hours = Math.floor(minutes / 60);
15
+ if (hours < 24) return `${hours}h ago`;
16
+ const days = Math.floor(hours / 24);
17
+ return `${days}d ago`;
18
+ }
19
+
20
+ function formatDuration(ms: number): string {
21
+ const seconds = Math.floor(ms / 1000);
22
+ if (seconds < 60) return `${seconds}s`;
23
+ const minutes = Math.floor(seconds / 60);
24
+ const remainSec = seconds % 60;
25
+ if (minutes < 60) return `${minutes}m ${remainSec}s`;
26
+ const hours = Math.floor(minutes / 60);
27
+ const remainMin = minutes % 60;
28
+ return `${hours}h ${remainMin}m`;
29
+ }
30
+
31
+ export const inspectSubcommand = createSubcommand({
32
+ name: 'inspect',
33
+ description: 'Show detailed information about a Coder Hub session',
34
+ tags: ['read-only', 'fast', 'requires-auth'],
35
+ examples: [
36
+ {
37
+ command: getCommand('coder inspect codesess_abc123'),
38
+ description: 'Inspect a session by ID',
39
+ },
40
+ {
41
+ command: getCommand('coder inspect codesess_abc123 --json'),
42
+ description: 'Get session details as JSON',
43
+ },
44
+ ],
45
+ idempotent: true,
46
+ schema: {
47
+ args: z.object({
48
+ session_id: z.string().describe('Coder session ID to inspect'),
49
+ }),
50
+ options: z.object({
51
+ hubUrl: z.string().optional().describe('Hub URL override'),
52
+ }),
53
+ },
54
+ async handler(ctx) {
55
+ const { args, options, opts } = ctx;
56
+ const sessionId = args.session_id;
57
+ const hubUrl = await resolveHubUrl(opts?.hubUrl);
58
+
59
+ if (!hubUrl) {
60
+ tui.fatal(
61
+ 'Could not find a running Coder Hub.\n\nEither:\n - Start the Hub with: bun run dev\n - Set AGENTUITY_CODER_HUB_URL environment variable\n - Pass --hub-url flag',
62
+ ErrorCode.NETWORK_ERROR
63
+ );
64
+ return;
65
+ }
66
+
67
+ let data: {
68
+ sessionId: string;
69
+ label: string;
70
+ status: string;
71
+ createdAt: string;
72
+ mode: string;
73
+ context: {
74
+ branch?: string;
75
+ workingDirectory?: string;
76
+ };
77
+ participants: Array<{
78
+ id: string;
79
+ role: string;
80
+ transport: string;
81
+ connectedAt: string;
82
+ idle: boolean;
83
+ }>;
84
+ tasks: Array<{
85
+ taskId: string;
86
+ agent: string;
87
+ status: string;
88
+ prompt: string;
89
+ duration?: number;
90
+ startedAt: string;
91
+ completedAt?: string;
92
+ }>;
93
+ agentActivity: Record<
94
+ string,
95
+ {
96
+ name: string;
97
+ status: string;
98
+ currentTool?: string;
99
+ toolCallCount: number;
100
+ lastActivity: number;
101
+ }
102
+ >;
103
+ };
104
+
105
+ try {
106
+ const resp = await fetch(`${hubUrl}/api/hub/session/${encodeURIComponent(sessionId)}`, {
107
+ headers: hubFetchHeaders(),
108
+ signal: AbortSignal.timeout(10_000),
109
+ });
110
+ if (resp.status === 404) {
111
+ tui.fatal(`Session not found: ${sessionId}`, ErrorCode.RESOURCE_NOT_FOUND);
112
+ return;
113
+ }
114
+ if (resp.status === 410) {
115
+ tui.fatal(`Session has shut down: ${sessionId}`, ErrorCode.RESOURCE_NOT_FOUND);
116
+ return;
117
+ }
118
+ if (!resp.ok) {
119
+ tui.fatal(
120
+ `Hub returned ${resp.status}: ${resp.statusText}. Is the Coder Hub running at ${hubUrl}?`,
121
+ ErrorCode.API_ERROR
122
+ );
123
+ return;
124
+ }
125
+ data = (await resp.json()) as typeof data;
126
+ } catch (err) {
127
+ const msg = err instanceof Error ? err.message : String(err);
128
+ tui.fatal(
129
+ `Could not connect to Coder Hub at ${hubUrl}: ${msg}\n\nSet AGENTUITY_CODER_HUB_URL or start the Hub with: bun run dev`,
130
+ ErrorCode.NETWORK_ERROR
131
+ );
132
+ return;
133
+ }
134
+
135
+ if (options.json) {
136
+ return data;
137
+ }
138
+
139
+ // Header
140
+ const label = data.label || data.sessionId;
141
+ console.log();
142
+ console.log(` Session: ${label} (${data.sessionId})`);
143
+ const parts = [`Status: ${data.status}`, `Mode: ${data.mode}`];
144
+ if (data.context.branch) parts.push(`Branch: ${data.context.branch}`);
145
+ console.log(` ${parts.join(' | ')}`);
146
+ console.log(` Created: ${data.createdAt}`);
147
+
148
+ // Participants
149
+ console.log();
150
+ console.log(' Participants:');
151
+ if (data.participants.length === 0) {
152
+ console.log(' (none)');
153
+ } else {
154
+ for (const p of data.participants) {
155
+ const idle = p.idle ? ' (idle)' : '';
156
+ const connected = p.connectedAt
157
+ ? ` connected ${formatRelativeTime(p.connectedAt)}`
158
+ : '';
159
+ console.log(
160
+ ` ${p.id.padEnd(12)} ${p.role.padEnd(10)} ${p.transport}${connected}${idle}`
161
+ );
162
+ }
163
+ }
164
+
165
+ // Tasks
166
+ if (data.tasks.length > 0) {
167
+ console.log();
168
+ console.log(' Tasks:');
169
+ for (const t of data.tasks) {
170
+ const dur = t.duration ? formatDuration(t.duration) : '-';
171
+ const prompt = t.prompt.length > 40 ? t.prompt.slice(0, 37) + '...' : t.prompt;
172
+ console.log(
173
+ ` ${t.taskId.padEnd(10)} ${t.agent.padEnd(10)} ${t.status.padEnd(10)} ${prompt.padEnd(42)} ${dur}`
174
+ );
175
+ }
176
+ }
177
+
178
+ // Agent Activity
179
+ const agents = Object.values(data.agentActivity);
180
+ if (agents.length > 0) {
181
+ console.log();
182
+ console.log(' Agent Activity:');
183
+ for (const a of agents) {
184
+ const tool = a.currentTool
185
+ ? `${a.currentTool} (${a.toolCallCount} calls)`
186
+ : `${a.toolCallCount} calls`;
187
+ const lastAct = a.lastActivity
188
+ ? formatRelativeTime(new Date(a.lastActivity).toISOString())
189
+ : '-';
190
+ console.log(
191
+ ` ${a.name.padEnd(12)} ${a.status.padEnd(8)} ${tool.padEnd(28)} last: ${lastAct}`
192
+ );
193
+ }
194
+ }
195
+
196
+ console.log();
197
+
198
+ return data;
199
+ },
200
+ });
@@ -0,0 +1,143 @@
1
+ import { z } from 'zod';
2
+ import { createSubcommand } from '../../types';
3
+ import * as tui from '../../tui';
4
+ import { getCommand } from '../../command-prefix';
5
+ import { ErrorCode } from '../../errors';
6
+ import { resolveHubUrl, hubFetchHeaders } from './hub-url';
7
+
8
+ function formatRelativeTime(isoDate: string): string {
9
+ const diffMs = Date.now() - new Date(isoDate).getTime();
10
+ const seconds = Math.floor(diffMs / 1000);
11
+ if (seconds < 60) return `${seconds}s ago`;
12
+ const minutes = Math.floor(seconds / 60);
13
+ if (minutes < 60) return `${minutes}m ago`;
14
+ const hours = Math.floor(minutes / 60);
15
+ if (hours < 24) return `${hours}h ago`;
16
+ const days = Math.floor(hours / 24);
17
+ return `${days}d ago`;
18
+ }
19
+
20
+ const SessionListResponseSchema = z.array(
21
+ z.object({
22
+ sessionId: z.string().describe('Session ID'),
23
+ label: z.string().describe('Human-readable session label'),
24
+ status: z.string().describe('Session status'),
25
+ mode: z.string().describe('Session mode (sandbox or tui)'),
26
+ createdAt: z.string().describe('Creation timestamp'),
27
+ taskCount: z.number().describe('Number of tasks'),
28
+ subAgentCount: z.number().describe('Number of sub-agents'),
29
+ observerCount: z.number().describe('Number of observers'),
30
+ participantCount: z.number().describe('Total participant count'),
31
+ })
32
+ );
33
+
34
+ export const listSubcommand = createSubcommand({
35
+ name: 'list',
36
+ description: 'List active Coder Hub sessions',
37
+ tags: ['read-only', 'fast', 'requires-auth'],
38
+ examples: [
39
+ {
40
+ command: getCommand('coder ls'),
41
+ description: 'List all active sessions',
42
+ },
43
+ {
44
+ command: getCommand('coder list --json'),
45
+ description: 'List sessions as JSON',
46
+ },
47
+ ],
48
+ aliases: ['ls'],
49
+ idempotent: true,
50
+ schema: {
51
+ options: z.object({
52
+ hubUrl: z.string().optional().describe('Hub URL override'),
53
+ }),
54
+ response: SessionListResponseSchema,
55
+ },
56
+ async handler(ctx) {
57
+ const { options, opts } = ctx;
58
+ const hubUrl = await resolveHubUrl(opts?.hubUrl);
59
+
60
+ if (!hubUrl) {
61
+ tui.fatal(
62
+ 'Could not find a running Coder Hub.\n\nEither:\n - Start the Hub with: bun run dev\n - Set AGENTUITY_CODER_HUB_URL environment variable\n - Pass --hub-url flag',
63
+ ErrorCode.NETWORK_ERROR
64
+ );
65
+ return [];
66
+ }
67
+
68
+ let data: {
69
+ sessions: {
70
+ websocket: Array<{
71
+ sessionId: string;
72
+ label: string;
73
+ status: string;
74
+ mode: string;
75
+ createdAt: string;
76
+ taskCount: number;
77
+ subAgentCount: number;
78
+ observerCount: number;
79
+ participantCount: number;
80
+ }>;
81
+ sandbox: Array<Record<string, unknown>>;
82
+ };
83
+ total: number;
84
+ };
85
+
86
+ try {
87
+ const resp = await fetch(`${hubUrl}/api/hub/sessions`, {
88
+ headers: hubFetchHeaders(),
89
+ signal: AbortSignal.timeout(10_000),
90
+ });
91
+ if (!resp.ok) {
92
+ tui.fatal(
93
+ `Hub returned ${resp.status}: ${resp.statusText}. Is the Coder Hub running at ${hubUrl}?`,
94
+ ErrorCode.API_ERROR
95
+ );
96
+ return [];
97
+ }
98
+ data = (await resp.json()) as typeof data;
99
+ } catch (err) {
100
+ const msg = err instanceof Error ? err.message : String(err);
101
+ tui.fatal(
102
+ `Could not connect to Coder Hub at ${hubUrl}: ${msg}\n\nSet AGENTUITY_CODER_HUB_URL or start the Hub with: bun run dev`,
103
+ ErrorCode.NETWORK_ERROR
104
+ );
105
+ return [];
106
+ }
107
+
108
+ const sessions = data.sessions.websocket;
109
+
110
+ if (options.json) {
111
+ return sessions;
112
+ }
113
+
114
+ if (sessions.length === 0) {
115
+ tui.info('No active Coder Hub sessions.');
116
+ return [];
117
+ }
118
+
119
+ const tableData = sessions.map((s) => ({
120
+ 'Session ID': s.sessionId.length > 20 ? s.sessionId.slice(0, 17) + '...' : s.sessionId,
121
+ Label: s.label || '-',
122
+ Status: s.status,
123
+ Mode: s.mode,
124
+ Observers: String(s.observerCount),
125
+ Agents: String(s.subAgentCount),
126
+ Tasks: String(s.taskCount),
127
+ Created: formatRelativeTime(s.createdAt),
128
+ }));
129
+
130
+ tui.table(tableData, [
131
+ { name: 'Session ID', alignment: 'left' },
132
+ { name: 'Label', alignment: 'left' },
133
+ { name: 'Status', alignment: 'center' },
134
+ { name: 'Mode', alignment: 'center' },
135
+ { name: 'Observers', alignment: 'right' },
136
+ { name: 'Agents', alignment: 'right' },
137
+ { name: 'Tasks', alignment: 'right' },
138
+ { name: 'Created', alignment: 'right' },
139
+ ]);
140
+
141
+ return sessions;
142
+ },
143
+ });