@agentuity/cli 1.0.36 → 1.0.38

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 (79) hide show
  1. package/dist/cmd/cloud/sandbox/cp.d.ts.map +1 -1
  2. package/dist/cmd/cloud/sandbox/cp.js +31 -0
  3. package/dist/cmd/cloud/sandbox/cp.js.map +1 -1
  4. package/dist/cmd/cloud/sandbox/exec.d.ts.map +1 -1
  5. package/dist/cmd/cloud/sandbox/exec.js +44 -11
  6. package/dist/cmd/cloud/sandbox/exec.js.map +1 -1
  7. package/dist/cmd/cloud/task/create.js +1 -1
  8. package/dist/cmd/cloud/task/create.js.map +1 -1
  9. package/dist/cmd/cloud/task/delete.js +3 -3
  10. package/dist/cmd/cloud/task/delete.js.map +1 -1
  11. package/dist/cmd/cloud/task/get.d.ts.map +1 -1
  12. package/dist/cmd/cloud/task/get.js +58 -4
  13. package/dist/cmd/cloud/task/get.js.map +1 -1
  14. package/dist/cmd/cloud/task/index.d.ts.map +1 -1
  15. package/dist/cmd/cloud/task/index.js +14 -2
  16. package/dist/cmd/cloud/task/index.js.map +1 -1
  17. package/dist/cmd/cloud/task/list.d.ts.map +1 -1
  18. package/dist/cmd/cloud/task/list.js +1 -2
  19. package/dist/cmd/cloud/task/list.js.map +1 -1
  20. package/dist/cmd/cloud/task/project.d.ts +2 -0
  21. package/dist/cmd/cloud/task/project.d.ts.map +1 -0
  22. package/dist/cmd/cloud/task/project.js +206 -0
  23. package/dist/cmd/cloud/task/project.js.map +1 -0
  24. package/dist/cmd/cloud/task/update.d.ts.map +1 -1
  25. package/dist/cmd/cloud/task/update.js +4 -1
  26. package/dist/cmd/cloud/task/update.js.map +1 -1
  27. package/dist/cmd/cloud/task/user.d.ts +2 -0
  28. package/dist/cmd/cloud/task/user.d.ts.map +1 -0
  29. package/dist/cmd/cloud/task/user.js +179 -0
  30. package/dist/cmd/cloud/task/user.js.map +1 -0
  31. package/dist/cmd/cloud/task/util.d.ts +1 -0
  32. package/dist/cmd/cloud/task/util.d.ts.map +1 -1
  33. package/dist/cmd/cloud/task/util.js +13 -0
  34. package/dist/cmd/cloud/task/util.js.map +1 -1
  35. package/dist/cmd/coder/hub-url.d.ts +35 -0
  36. package/dist/cmd/coder/hub-url.d.ts.map +1 -0
  37. package/dist/cmd/coder/hub-url.js +101 -0
  38. package/dist/cmd/coder/hub-url.js.map +1 -0
  39. package/dist/cmd/coder/index.d.ts +2 -0
  40. package/dist/cmd/coder/index.d.ts.map +1 -0
  41. package/dist/cmd/coder/index.js +27 -0
  42. package/dist/cmd/coder/index.js.map +1 -0
  43. package/dist/cmd/coder/inspect.d.ts +2 -0
  44. package/dist/cmd/coder/inspect.d.ts.map +1 -0
  45. package/dist/cmd/coder/inspect.js +145 -0
  46. package/dist/cmd/coder/inspect.js.map +1 -0
  47. package/dist/cmd/coder/list.d.ts +2 -0
  48. package/dist/cmd/coder/list.d.ts.map +1 -0
  49. package/dist/cmd/coder/list.js +109 -0
  50. package/dist/cmd/coder/list.js.map +1 -0
  51. package/dist/cmd/coder/start.d.ts +2 -0
  52. package/dist/cmd/coder/start.d.ts.map +1 -0
  53. package/dist/cmd/coder/start.js +384 -0
  54. package/dist/cmd/coder/start.js.map +1 -0
  55. package/dist/cmd/dev/index.d.ts.map +1 -1
  56. package/dist/cmd/dev/index.js +4 -0
  57. package/dist/cmd/dev/index.js.map +1 -1
  58. package/dist/cmd/index.d.ts.map +1 -1
  59. package/dist/cmd/index.js +1 -0
  60. package/dist/cmd/index.js.map +1 -1
  61. package/package.json +6 -6
  62. package/src/cmd/cloud/sandbox/cp.ts +32 -0
  63. package/src/cmd/cloud/sandbox/exec.ts +62 -13
  64. package/src/cmd/cloud/task/create.ts +1 -1
  65. package/src/cmd/cloud/task/delete.ts +3 -3
  66. package/src/cmd/cloud/task/get.ts +68 -4
  67. package/src/cmd/cloud/task/index.ts +14 -2
  68. package/src/cmd/cloud/task/list.ts +1 -2
  69. package/src/cmd/cloud/task/project.ts +227 -0
  70. package/src/cmd/cloud/task/update.ts +4 -1
  71. package/src/cmd/cloud/task/user.ts +202 -0
  72. package/src/cmd/cloud/task/util.ts +18 -0
  73. package/src/cmd/coder/hub-url.ts +105 -0
  74. package/src/cmd/coder/index.ts +27 -0
  75. package/src/cmd/coder/inspect.ts +200 -0
  76. package/src/cmd/coder/list.ts +143 -0
  77. package/src/cmd/coder/start.ts +419 -0
  78. package/src/cmd/dev/index.ts +5 -0
  79. package/src/cmd/index.ts +1 -0
@@ -0,0 +1,202 @@
1
+ import { z } from 'zod';
2
+ import { createCommand } from '../../../types';
3
+ import * as tui from '../../../tui';
4
+ import { createStorageAdapter } from './util';
5
+ import { getCommand } from '../../../command-prefix';
6
+
7
+ // ── List ────────────────────────────────────────────────────────────────
8
+
9
+ const listUsersSubcommand = createCommand({
10
+ name: 'list',
11
+ aliases: ['ls'],
12
+ description: 'List all task users',
13
+ tags: ['read-only', 'slow', 'requires-auth'],
14
+ requires: { auth: true },
15
+ idempotent: true,
16
+ examples: [
17
+ {
18
+ command: getCommand('cloud task user list'),
19
+ description: 'List all users',
20
+ },
21
+ ],
22
+ schema: {
23
+ response: z.object({
24
+ success: z.boolean(),
25
+ users: z.array(
26
+ z.object({
27
+ id: z.string(),
28
+ name: z.string(),
29
+ type: z.string().optional(),
30
+ })
31
+ ),
32
+ total: z.number(),
33
+ durationMs: z.number(),
34
+ }),
35
+ },
36
+
37
+ async handler(ctx) {
38
+ const { options } = ctx;
39
+ const started = Date.now();
40
+ const storage = await createStorageAdapter(ctx);
41
+ const result = await storage.listUsers();
42
+ const durationMs = Date.now() - started;
43
+
44
+ if (!options.json) {
45
+ if (result.users.length === 0) {
46
+ tui.info('No users found.');
47
+ } else {
48
+ tui.table(
49
+ result.users.map((u) => ({
50
+ id: u.id,
51
+ name: u.name,
52
+ type: (u as { type?: string }).type ?? 'human',
53
+ })),
54
+ ['id', 'name', 'type']
55
+ );
56
+ tui.info(`${result.users.length} user(s) (${durationMs.toFixed(1)}ms)`);
57
+ }
58
+ }
59
+
60
+ return { success: true, users: result.users, total: result.users.length, durationMs };
61
+ },
62
+ });
63
+
64
+ // ── Create ──────────────────────────────────────────────────────────────
65
+
66
+ const createUserSubcommand = createCommand({
67
+ name: 'create',
68
+ description: 'Create a new task user',
69
+ tags: ['mutating', 'slow', 'requires-auth'],
70
+ requires: { auth: true },
71
+ examples: [
72
+ {
73
+ command: getCommand('cloud task user create "Jane Doe"'),
74
+ description: 'Create a human user',
75
+ },
76
+ {
77
+ command: getCommand('cloud task user create "My Agent" --type agent'),
78
+ description: 'Create an agent user',
79
+ },
80
+ ],
81
+ schema: {
82
+ args: z.object({
83
+ name: z.string().min(1).describe('the user display name'),
84
+ }),
85
+ options: z.object({
86
+ type: z.enum(['human', 'agent']).optional().describe('user type (human or agent)'),
87
+ }),
88
+ response: z.object({
89
+ success: z.boolean(),
90
+ user: z.object({
91
+ id: z.string(),
92
+ name: z.string(),
93
+ type: z.string().optional(),
94
+ }),
95
+ durationMs: z.number(),
96
+ }),
97
+ },
98
+
99
+ async handler(ctx) {
100
+ const { args, opts, options } = ctx;
101
+ const started = Date.now();
102
+ const storage = await createStorageAdapter(ctx);
103
+ const user = await storage.createUser({ name: args.name, type: opts.type });
104
+ const durationMs = Date.now() - started;
105
+
106
+ if (!options.json) {
107
+ tui.success(`Created user: ${user.name} (${user.id})`);
108
+ }
109
+
110
+ return { success: true, user, durationMs };
111
+ },
112
+ });
113
+
114
+ // ── Get ─────────────────────────────────────────────────────────────────
115
+
116
+ const getUserSubcommand = createCommand({
117
+ name: 'get',
118
+ description: 'Get a task user by ID',
119
+ tags: ['read-only', 'slow', 'requires-auth'],
120
+ requires: { auth: true },
121
+ idempotent: true,
122
+ examples: [
123
+ {
124
+ command: getCommand('cloud task user get usr_abc123'),
125
+ description: 'Get user details',
126
+ },
127
+ ],
128
+ schema: {
129
+ args: z.object({
130
+ id: z.string().min(1).describe('the user ID'),
131
+ }),
132
+ response: z.object({
133
+ success: z.boolean(),
134
+ user: z.object({
135
+ id: z.string(),
136
+ name: z.string(),
137
+ type: z.string().optional(),
138
+ }),
139
+ durationMs: z.number(),
140
+ }),
141
+ },
142
+
143
+ async handler(ctx) {
144
+ const { args, options } = ctx;
145
+ const started = Date.now();
146
+ const storage = await createStorageAdapter(ctx);
147
+ try {
148
+ const user = await storage.getUser(args.id);
149
+ const durationMs = Date.now() - started;
150
+
151
+ if (!options.json) {
152
+ tui.table(
153
+ [
154
+ {
155
+ id: user.id,
156
+ name: user.name,
157
+ type: (user as { type?: string }).type ?? 'human',
158
+ },
159
+ ],
160
+ ['id', 'name', 'type'],
161
+ { layout: 'vertical' }
162
+ );
163
+ }
164
+
165
+ return { success: true, user, durationMs };
166
+ } catch (_err) {
167
+ const durationMs = Date.now() - started;
168
+ if (!options.json) {
169
+ tui.error(`User not found: ${args.id}`);
170
+ }
171
+ return {
172
+ success: false,
173
+ user: { id: args.id, name: '', type: 'human' as const },
174
+ durationMs,
175
+ };
176
+ }
177
+ },
178
+ });
179
+
180
+ // ── Parent command ──────────────────────────────────────────────────────
181
+
182
+ export const userSubcommand = createCommand({
183
+ name: 'user',
184
+ description: 'Manage task users',
185
+ tags: ['requires-auth'],
186
+ requires: { auth: true },
187
+ examples: [
188
+ {
189
+ command: getCommand('cloud task user list'),
190
+ description: 'List all users',
191
+ },
192
+ {
193
+ command: getCommand('cloud task user create "Jane Doe"'),
194
+ description: 'Create a new user',
195
+ },
196
+ {
197
+ command: getCommand('cloud task user get usr_abc123'),
198
+ description: 'Get user details',
199
+ },
200
+ ],
201
+ subcommands: [listUsersSubcommand, createUserSubcommand, getUserSubcommand],
202
+ });
@@ -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
+ });