@aivin-labs/cli 1.0.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,204 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import chalk from 'chalk';
5
+ import axios from 'axios';
6
+ import inquirer from 'inquirer';
7
+ import { withSpinner } from './util.mjs';
8
+
9
+ // ── Plugin store (self-host aivin-service worker) — attach/create/ls/enable/disable/detach ──────
10
+ //
11
+ // Xem service/docs/self-host-worker-plan.md — "store" là kho chức năng hiển thị trong FE modal
12
+ // "Trung tâm điều khiển > Hạ tầng", 1 store có thể có nhiều node (nhiều máy `aivin-service` cùng
13
+ // attach). CLI chỉ lo: gọi REST của BE (mint token/tạo store), rồi ghi `worker-identity.json` vào
14
+ // thư mục đã mount volume của container `aivin-service` — service tự pair khi thấy file (fs.watch),
15
+ // không cần CLI biết service đang chạy hay chưa, không cần restart container.
16
+
17
+ export function storeAuthHeaders() {
18
+ const apiKey = process.env.API_KEY;
19
+ if (!apiKey) {
20
+ console.log(chalk.yellow('⚠️ API_KEY not set - run `aivin login` first'));
21
+ }
22
+ return { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } };
23
+ }
24
+
25
+ export function storeBaseUrl() {
26
+ return process.env.AIVIN_BASE_URL || 'https://api.aivin.cloud';
27
+ }
28
+
29
+ function defaultDataDir() {
30
+ return path.join(os.homedir(), '.aivin', 'service-data');
31
+ }
32
+
33
+ /** Ghi `worker-identity.json` — schema PHẢI khớp CHÍNH XÁC với `WorkerIdentity.ts` (repo
34
+ * `aivin-service`) đọc, không thêm/bớt field tuỳ tiện ở 1 phía mà không sửa phía kia. */
35
+ function writeWorkerIdentity(dataDir, { beEndpoint, orgId, storeId, nodeId, nodeLabel, workerToken }) {
36
+ fs.mkdirSync(dataDir, { recursive: true });
37
+ const filePath = path.join(dataDir, 'worker-identity.json');
38
+ const payload = {
39
+ version: 1,
40
+ be_endpoint: beEndpoint,
41
+ org_id: orgId,
42
+ store_id: storeId,
43
+ node_id: nodeId,
44
+ node_label: nodeLabel || '',
45
+ worker_token: workerToken,
46
+ paired_at: new Date().toISOString(),
47
+ };
48
+ fs.writeFileSync(filePath, JSON.stringify(payload, null, 2) + '\n', { mode: 0o600 });
49
+ return filePath;
50
+ }
51
+
52
+ function printAttachResult(res, dataDir) {
53
+ const { store, node, worker_token, worker_hub_endpoint } = res.data;
54
+ const filePath = writeWorkerIdentity(dataDir, {
55
+ beEndpoint: worker_hub_endpoint,
56
+ orgId: store.owner_org_id,
57
+ storeId: store.store_id,
58
+ nodeId: node.node_id,
59
+ nodeLabel: node.label,
60
+ workerToken: worker_token,
61
+ });
62
+ console.log(chalk.green(`\n✅ Node "${node.node_id}" attached to store "${store.store_id}"`));
63
+ console.log(chalk.gray(` Credential written to ${filePath}`));
64
+ console.log(
65
+ chalk.gray(
66
+ ` If aivin-service isn't running yet: docker run -v ${dataDir}:/app/data ... (mount this exact directory as WORKER_DATA_DIR)`,
67
+ ),
68
+ );
69
+ console.log(chalk.gray(' Already running? Nothing else to do - it picks up this file within ~200ms, no restart needed.'));
70
+ }
71
+
72
+ export async function createStore(storeId, options) {
73
+ if (!storeId) {
74
+ const { answer } = await inquirer.prompt([{ type: 'input', name: 'answer', message: 'Store id (slug, e.g. phong-ban-a):' }]);
75
+ storeId = answer;
76
+ }
77
+ let label = options.label;
78
+ if (!label && process.stdout.isTTY && process.stdin.isTTY) {
79
+ const { answer } = await inquirer.prompt([{ type: 'input', name: 'answer', message: 'Display label:', default: storeId }]);
80
+ label = answer;
81
+ }
82
+
83
+ try {
84
+ const res = await withSpinner(`📦 Creating store "${storeId}"`, () =>
85
+ axios.post(`${storeBaseUrl()}/stores`, { store_id: storeId, label, node_label: options.nodeLabel }, storeAuthHeaders()),
86
+ );
87
+ printAttachResult(res, options.dataDir || defaultDataDir());
88
+ } catch (error) {
89
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
90
+ throw new Error(`Create store failed: ${message}`, { cause: error });
91
+ }
92
+ }
93
+
94
+ /** `attach` — nếu `store_id` chưa tồn tại (BE trả 404), hỏi tương tác tạo mới thay vì tự động tạo
95
+ * (tránh gõ nhầm store_id tạo ra 1 store rác không ai định tạo) — xem doc thiết kế mục 7. */
96
+ export async function attachStore(storeId, options) {
97
+ if (!storeId) {
98
+ const { answer } = await inquirer.prompt([{ type: 'input', name: 'answer', message: 'Store id to attach to:' }]);
99
+ storeId = answer;
100
+ }
101
+
102
+ try {
103
+ const res = await withSpinner(`🔗 Attaching to store "${storeId}"`, () =>
104
+ axios.post(`${storeBaseUrl()}/stores/${encodeURIComponent(storeId)}/attach`, { node_label: options.nodeLabel }, storeAuthHeaders()),
105
+ );
106
+ printAttachResult(res, options.dataDir || defaultDataDir());
107
+ } catch (error) {
108
+ if (error.response?.status === 404) {
109
+ console.log(chalk.yellow(`Store "${storeId}" doesn't exist yet.`));
110
+ if (process.stdout.isTTY && process.stdin.isTTY) {
111
+ const { proceed } = await inquirer.prompt([{ type: 'confirm', name: 'proceed', message: 'Create it now?', default: true }]);
112
+ if (proceed) return createStore(storeId, options);
113
+ }
114
+ console.log(chalk.gray('Cancelled - run `aivin pluginstore create <store_id>` to create it explicitly.'));
115
+ return;
116
+ }
117
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
118
+ throw new Error(`Attach failed: ${message}`, { cause: error });
119
+ }
120
+ }
121
+
122
+ export async function listStores(options) {
123
+ let response;
124
+ try {
125
+ response = await axios.get(`${storeBaseUrl()}/stores`, storeAuthHeaders());
126
+ } catch (error) {
127
+ const message = error.response?.data?.message || error.message;
128
+ throw new Error(`List failed: ${message}`, { cause: error });
129
+ }
130
+
131
+ const stores = response.data || [];
132
+ if (stores.length === 0) {
133
+ console.log(chalk.yellow('No plugin stores found.'));
134
+ return;
135
+ }
136
+
137
+ console.log(chalk.blue(`${stores.length} store(s):\n`));
138
+ for (const s of stores) {
139
+ const online = s.nodes?.some((n) => n.status === 'online');
140
+ const statusBadge = online ? chalk.green('● online') : chalk.gray('○ offline');
141
+ const enabledBadge = s.enabled ? '' : chalk.red(' [disabled]');
142
+ const kindBadge = s.kind === 'system' ? chalk.cyan(' [aivin default]') : '';
143
+ console.log(`${chalk.bold(s.label || s.store_id)} ${chalk.gray(`(${s.store_id})`)} ${statusBadge}${enabledBadge}${kindBadge}`);
144
+ for (const n of s.nodes || []) {
145
+ const nodeStatus = n.status === 'online' ? chalk.green('online') : chalk.gray('offline');
146
+ console.log(chalk.gray(` - ${n.label || n.node_id} (${n.node_id}) ${nodeStatus}`));
147
+ }
148
+ if (options.plain !== true && (s.nodes || []).length === 0) console.log(chalk.gray(' (no nodes attached)'));
149
+ console.log();
150
+ }
151
+ }
152
+
153
+ export async function setStoreEnabled(storeId, enabled) {
154
+ try {
155
+ await withSpinner(`${enabled ? '▶️ Enabling' : '⏸ Disabling'} store "${storeId}"`, () =>
156
+ axios.patch(`${storeBaseUrl()}/stores/${encodeURIComponent(storeId)}`, { enabled }, storeAuthHeaders()),
157
+ );
158
+ console.log(chalk.green(`✅ Store "${storeId}" ${enabled ? 'enabled' : 'disabled'}.`));
159
+ } catch (error) {
160
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
161
+ if (error.response?.status === 401 || error.response?.status === 403) {
162
+ throw new Error(`${message} - this action requires org admin.`, { cause: error });
163
+ }
164
+ throw new Error(`${enabled ? 'Enable' : 'Disable'} failed: ${message}`, { cause: error });
165
+ }
166
+ }
167
+
168
+ export async function deleteStore(storeId, options) {
169
+ if (!options.yes) {
170
+ const { confirmId } = await inquirer.prompt([
171
+ {
172
+ type: 'input',
173
+ name: 'confirmId',
174
+ message: chalk.red(`This revokes EVERY node attached to "${storeId}" (not just this machine). Type the store id to confirm:`),
175
+ },
176
+ ]);
177
+ if (confirmId !== storeId) {
178
+ console.log(chalk.gray('Cancelled - store id did not match.'));
179
+ return;
180
+ }
181
+ }
182
+
183
+ try {
184
+ await withSpinner(`🗑 Deleting store "${storeId}"`, () => axios.delete(`${storeBaseUrl()}/stores/${encodeURIComponent(storeId)}`, storeAuthHeaders()));
185
+ console.log(chalk.green(`✅ Store "${storeId}" deleted - all nodes revoked.`));
186
+ } catch (error) {
187
+ const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
188
+ throw new Error(`Delete failed: ${message}`, { cause: error });
189
+ }
190
+ }
191
+
192
+ /** `detach` — THUẦN CỤC BỘ, không gọi BE (xem doc thiết kế mục 7): chỉ xoá file credential của
193
+ * ĐÚNG máy này. `aivin-service`'s `WorkerIdentity.ts` tự bắt được qua `fs.watch` và disconnect. */
194
+ export function detachStore(options) {
195
+ const dataDir = options.dataDir || defaultDataDir();
196
+ const filePath = path.join(dataDir, 'worker-identity.json');
197
+ if (!fs.existsSync(filePath)) {
198
+ console.log(chalk.yellow(`No worker-identity.json found at ${filePath} - nothing to detach.`));
199
+ return;
200
+ }
201
+ fs.unlinkSync(filePath);
202
+ console.log(chalk.green(`✅ Detached - removed ${filePath}`));
203
+ console.log(chalk.gray(' The running aivin-service (if any) will disconnect automatically - no restart needed.'));
204
+ }
@@ -0,0 +1,345 @@
1
+ import chalk from 'chalk';
2
+ import axios from 'axios';
3
+ import inquirer from 'inquirer';
4
+ import { missionServerUrl, missionAuthHeaders, resolveWorkspace, resolveAgentId, listWorkspaces } from './workspace.mjs';
5
+
6
+ export async function createAutomationJob(description, options) {
7
+ const serverUrl = missionServerUrl();
8
+ const authHeaders = missionAuthHeaders();
9
+
10
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
11
+ const agentId = resolveAgentId(workspace, options.agent);
12
+
13
+ console.log(chalk.blue('🔄 Creating automation job...'));
14
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
15
+
16
+ let response;
17
+ try {
18
+ response = await axios.post(
19
+ `${serverUrl}/automation/jobs/create`,
20
+ {
21
+ mission: description.length > 60 ? `${description.slice(0, 57)}...` : description,
22
+ prompt: description,
23
+ agent_id: agentId,
24
+ workspace_id: workspace.id || workspace._id,
25
+ project_id: options.project,
26
+ schedule_condition: options.schedule,
27
+ },
28
+ authHeaders,
29
+ );
30
+ } catch (error) {
31
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
32
+ throw new Error(`Failed to create automation job: ${message}`, { cause: error });
33
+ }
34
+
35
+ const job = response.data ?? {};
36
+ console.log(chalk.green('✅ Automation job created!'));
37
+ console.log(chalk.gray(` ID: ${job.id}`));
38
+ console.log(chalk.gray(` Mission: ${job.mission}`));
39
+ if (job.schedule_condition) console.log(chalk.gray(` Schedule: ${job.schedule_condition}`));
40
+ if (job.next_run) console.log(chalk.gray(` Next run: ${job.next_run}`));
41
+ }
42
+
43
+ /**
44
+ * A workspace's `projects` array has no guaranteed "default" entry the way `agents`/Personal do -
45
+ * just take the first one when --project is omitted, and say so explicitly if there isn't one
46
+ * (list/mine are scoped by project on the backend, unlike create/get/update/delete which take a
47
+ * bare task id or no project at all).
48
+ */
49
+ export function resolveProjectId(workspace, explicitProjectId) {
50
+ if (explicitProjectId) return explicitProjectId;
51
+ const projectId = workspace.projects?.[0]?.id;
52
+ if (!projectId) {
53
+ throw new Error(
54
+ `Workspace "${workspace.name || workspace.id}" has no projects - pass --project <id> (see \`aivin workspace\`).`,
55
+ );
56
+ }
57
+ return projectId;
58
+ }
59
+
60
+ export async function listTasks(options) {
61
+ const serverUrl = missionServerUrl();
62
+ const authHeaders = missionAuthHeaders();
63
+
64
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
65
+ const projectId = resolveProjectId(workspace, options.project);
66
+
67
+ const params = {};
68
+ if (options.status) params.status = options.status;
69
+ if (options.assignee) params.assign_id = options.assignee;
70
+ if (options.search) params.search = options.search;
71
+
72
+ let response;
73
+ try {
74
+ response = await axios.get(`${serverUrl}/task/${projectId}/list`, { ...authHeaders, params });
75
+ } catch (error) {
76
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
77
+ throw new Error(`Failed to list tasks: ${message}`, { cause: error });
78
+ }
79
+
80
+ const tasks = Array.isArray(response.data) ? response.data : response.data?.items || [];
81
+ if (tasks.length === 0) {
82
+ console.log(chalk.yellow('No tasks found.'));
83
+ return;
84
+ }
85
+ console.log(chalk.blue(`${tasks.length} task(s) in project ${projectId}:\n`));
86
+ tasks.forEach((t) => {
87
+ console.log(`${chalk.bold(t.title || t.id)} ${chalk.gray(`(${t.id})`)}`);
88
+ console.log(
89
+ chalk.gray(
90
+ ` status: ${t.status}${t.priority ? ` priority: ${t.priority}` : ''}${t.assign_id ? ` assignee: ${t.assign_id}` : ''}`,
91
+ ),
92
+ );
93
+ });
94
+ }
95
+
96
+ export async function listMyTasks(options) {
97
+ const serverUrl = missionServerUrl();
98
+ const authHeaders = missionAuthHeaders();
99
+
100
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
101
+ const projectId = resolveProjectId(workspace, options.project);
102
+
103
+ let response;
104
+ try {
105
+ response = await axios.get(`${serverUrl}/task/${projectId}/my-task`, authHeaders);
106
+ } catch (error) {
107
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
108
+ throw new Error(`Failed to list your tasks: ${message}`, { cause: error });
109
+ }
110
+
111
+ const tasks = Array.isArray(response.data) ? response.data : response.data?.items || [];
112
+ if (tasks.length === 0) {
113
+ console.log(chalk.yellow('No tasks assigned to you in this project.'));
114
+ return;
115
+ }
116
+ console.log(chalk.blue(`${tasks.length} task(s) assigned to you:\n`));
117
+ tasks.forEach((t) => {
118
+ console.log(`${chalk.bold(t.title || t.id)} ${chalk.gray(`(${t.id})`)} ${chalk.gray(t.status)}`);
119
+ });
120
+ }
121
+
122
+ export async function getTaskById(id) {
123
+ const serverUrl = missionServerUrl();
124
+ const authHeaders = missionAuthHeaders();
125
+
126
+ let response;
127
+ try {
128
+ response = await axios.get(`${serverUrl}/task/${id}`, authHeaders);
129
+ } catch (error) {
130
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
131
+ throw new Error(`Failed to get task: ${message}`, { cause: error });
132
+ }
133
+
134
+ console.log(JSON.stringify(response.data ?? {}, null, 2));
135
+ }
136
+
137
+ export async function updateTaskById(id, options) {
138
+ const serverUrl = missionServerUrl();
139
+ const authHeaders = missionAuthHeaders();
140
+
141
+ const data = {};
142
+ if (options.status) data.status = options.status;
143
+ if (options.title) data.title = options.title;
144
+ if (options.description) data.description = options.description;
145
+ if (options.assignee) data.assign_id = options.assignee;
146
+ if (options.priority) data.priority = options.priority;
147
+ if (Object.keys(data).length === 0) {
148
+ throw new Error('Nothing to update - pass at least one of --status/--title/--description/--assignee/--priority.');
149
+ }
150
+
151
+ let response;
152
+ try {
153
+ response = await axios.post(`${serverUrl}/task/${id}/update`, data, authHeaders);
154
+ } catch (error) {
155
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
156
+ throw new Error(`Failed to update task: ${message}`, { cause: error });
157
+ }
158
+
159
+ const task = response.data ?? {};
160
+ console.log(chalk.green('✅ Task updated!'));
161
+ console.log(chalk.gray(` Status: ${task.status}`));
162
+ }
163
+
164
+ export async function deleteTaskById(id) {
165
+ const serverUrl = missionServerUrl();
166
+ const authHeaders = missionAuthHeaders();
167
+
168
+ try {
169
+ await axios.delete(`${serverUrl}/task/${id}/delete`, authHeaders);
170
+ } catch (error) {
171
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
172
+ throw new Error(`Failed to delete task: ${message}`, { cause: error });
173
+ }
174
+
175
+ console.log(chalk.green(`✅ Task ${id} deleted.`));
176
+ }
177
+
178
+ export async function createTask(description, options) {
179
+ const serverUrl = missionServerUrl();
180
+ const authHeaders = missionAuthHeaders();
181
+
182
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
183
+
184
+ console.log(chalk.blue('📋 Creating task...'));
185
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
186
+
187
+ let response;
188
+ try {
189
+ response = await axios.post(
190
+ `${serverUrl}/task/create`,
191
+ {
192
+ title: description.length > 80 ? `${description.slice(0, 77)}...` : description,
193
+ content: description,
194
+ workspace_id: workspace.id || workspace._id,
195
+ project_id: options.project,
196
+ assign_id: options.assignee,
197
+ },
198
+ authHeaders,
199
+ );
200
+ } catch (error) {
201
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
202
+ throw new Error(`Failed to create task: ${message}`, { cause: error });
203
+ }
204
+
205
+ const task = response.data ?? {};
206
+ console.log(chalk.green('✅ Task created!'));
207
+ console.log(chalk.gray(` ID: ${task.id}`));
208
+ console.log(chalk.gray(` Title: ${task.title}`));
209
+ console.log(chalk.gray(` Status: ${task.status}`));
210
+ }
211
+
212
+ /**
213
+ * `aivin workspace` - interactive workspace + project picker (arrow-key inquirer prompts, matching
214
+ * `aivin create`'s existing interactive style) so a user can find a workspace/project id to pass
215
+ * as --workspace/--project to `aivin do`/`do job`/`task`, without memorizing them upfront.
216
+ */
217
+ export async function pickWorkspaceAndProject(options) {
218
+ const serverUrl = missionServerUrl();
219
+ const authHeaders = missionAuthHeaders();
220
+ const workspaces = await listWorkspaces(serverUrl, authHeaders);
221
+
222
+ if (workspaces.length === 0) {
223
+ console.log(chalk.yellow('No workspace found for this account.'));
224
+ return;
225
+ }
226
+
227
+ if (!process.stdout.isTTY || !process.stdin.isTTY || options.plain) {
228
+ for (const ws of workspaces) {
229
+ console.log(chalk.bold(ws.name || ws.id) + chalk.gray(` (${ws.id})${ws.name === 'Personal' ? ' [personal]' : ''}`));
230
+ (ws.projects || []).forEach((p) => console.log(chalk.gray(` - ${p.name || p.id} (${p.id})`)));
231
+ }
232
+ return;
233
+ }
234
+
235
+ const { workspaceId } = await inquirer.prompt([
236
+ {
237
+ type: 'select',
238
+ name: 'workspaceId',
239
+ message: 'Select a workspace:',
240
+ choices: workspaces.map((ws) => ({
241
+ name: `${ws.name || ws.id}${ws.name === 'Personal' ? chalk.gray(' (personal)') : ''}`,
242
+ value: ws.id || ws._id,
243
+ })),
244
+ },
245
+ ]);
246
+ const workspace = workspaces.find((ws) => (ws.id || ws._id) === workspaceId);
247
+
248
+ let projectId;
249
+ if (workspace.projects?.length > 0) {
250
+ const { pickedProjectId } = await inquirer.prompt([
251
+ {
252
+ type: 'select',
253
+ name: 'pickedProjectId',
254
+ message: 'Select a project:',
255
+ choices: [
256
+ { name: chalk.gray('(none - workspace level)'), value: null },
257
+ ...workspace.projects.map((p) => ({ name: p.name || p.id, value: p.id })),
258
+ ],
259
+ },
260
+ ]);
261
+ projectId = pickedProjectId;
262
+ } else {
263
+ console.log(chalk.gray(`\n"${workspace.name || workspace.id}" has no projects yet - staying at workspace level (no --project needed).`));
264
+ }
265
+
266
+ console.log(chalk.green('\n✅ Selected:'));
267
+ console.log(` ${chalk.gray('Workspace:')} ${chalk.bold(workspace.name || 'unnamed')}`);
268
+ if (projectId) {
269
+ const project = workspace.projects.find((p) => p.id === projectId);
270
+ console.log(` ${chalk.gray('Project:')} ${chalk.bold(project?.name || 'unnamed')}`);
271
+ }
272
+ console.log(chalk.gray('\nUse with `aivin do`/`aivin do job`/`aivin task`:'));
273
+ console.log(` --workspace ${workspace.id || workspace._id}${projectId ? ` --project ${projectId}` : ''}`);
274
+ }
275
+
276
+ // ── Projects within a workspace - create/update/delete ─────────────────────────────────────────
277
+ //
278
+ // `POST /project/:workspaceId/project/edit` is a real upsert on the backend: omit `id` to create a
279
+ // new project, include it to update the matching one - there's no separate create endpoint.
280
+
281
+ export async function upsertProject(serverUrl, authHeaders, { workspaceId, id, name }) {
282
+ let response;
283
+ try {
284
+ response = await axios.post(`${serverUrl}/project/${workspaceId}/project/edit`, { id, name }, authHeaders);
285
+ } catch (error) {
286
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
287
+ throw new Error(`Failed to save project: ${message}`, { cause: error });
288
+ }
289
+ return response.data ?? {};
290
+ }
291
+
292
+ export async function deleteProjectById(serverUrl, authHeaders, { workspaceId, projectId }) {
293
+ try {
294
+ await axios.delete(`${serverUrl}/project/${workspaceId}/project/${projectId}/delete`, authHeaders);
295
+ } catch (error) {
296
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
297
+ throw new Error(`Failed to delete project: ${message}`, { cause: error });
298
+ }
299
+ }
300
+
301
+ export async function listProjectsCmd(options) {
302
+ const serverUrl = missionServerUrl();
303
+ const authHeaders = missionAuthHeaders();
304
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
305
+
306
+ const projects = workspace.projects || [];
307
+ if (projects.length === 0) {
308
+ console.log(chalk.yellow(`No projects in workspace "${workspace.name || workspace.id}".`));
309
+ return;
310
+ }
311
+ console.log(chalk.blue(`${projects.length} project(s) in "${workspace.name || workspace.id}":\n`));
312
+ projects.forEach((p) => {
313
+ console.log(`${chalk.bold(p.name || p.id)} ${chalk.gray(`(${p.id})`)}`);
314
+ });
315
+ }
316
+
317
+ export async function createProjectCmd(name, options) {
318
+ const serverUrl = missionServerUrl();
319
+ const authHeaders = missionAuthHeaders();
320
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
321
+ const project = await upsertProject(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, name });
322
+ console.log(chalk.green('✅ Project created!'));
323
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
324
+ console.log(chalk.gray(` Name: ${project.name || name}`));
325
+ if (project.id) console.log(chalk.gray(` ID: ${project.id}`));
326
+ }
327
+
328
+ export async function updateProjectCmd(projectId, options) {
329
+ const serverUrl = missionServerUrl();
330
+ const authHeaders = missionAuthHeaders();
331
+ if (!options.name) {
332
+ throw new Error('Nothing to update - pass --name <new name>.');
333
+ }
334
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
335
+ await upsertProject(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, id: projectId, name: options.name });
336
+ console.log(chalk.green(`✅ Project ${projectId} updated.`));
337
+ }
338
+
339
+ export async function deleteProjectCmd(projectId, options) {
340
+ const serverUrl = missionServerUrl();
341
+ const authHeaders = missionAuthHeaders();
342
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
343
+ await deleteProjectById(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, projectId });
344
+ console.log(chalk.green(`✅ Project ${projectId} deleted.`));
345
+ }
@@ -0,0 +1,40 @@
1
+ import chalk from 'chalk';
2
+ import readline from 'readline';
3
+ import inquirer from 'inquirer';
4
+
5
+ // Same spinner deployPlugin has always had, factored out so other long-running network calls
6
+ // (AI codegen, connector register) get the same "still working, not hung" feedback instead of a
7
+ // static line that just sits there for however many seconds the request takes.
8
+ export async function withSpinner(label, fn) {
9
+ if (!process.stdout.isTTY) {
10
+ console.log(chalk.blue(`${label}...`));
11
+ return fn();
12
+ }
13
+ const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
14
+ let i = 0;
15
+ const timer = setInterval(() => {
16
+ process.stdout.write(`\r${chalk.cyan(frames[i])} ${label}...`);
17
+ i = (i + 1) % frames.length;
18
+ }, 100);
19
+ try {
20
+ return await fn();
21
+ } finally {
22
+ clearInterval(timer);
23
+ readline.cursorTo(process.stdout, 0);
24
+ readline.clearLine(process.stdout, 0);
25
+ }
26
+ }
27
+
28
+ // Positional CLI args are declared optional ([arg]) everywhere, not required (<arg>), so Commander
29
+ // never hard-fails before the action() runs - every command instead calls this to fill a missing
30
+ // value interactively. Falls back to throwing `usage` when there's no TTY to prompt on (scripts/
31
+ // CI) or the user leaves the prompt blank, so non-interactive callers still fail fast and loud
32
+ // instead of hanging on a prompt nothing will ever answer.
33
+ export async function requireArg(value, { prompt, usage }) {
34
+ if (value) return value;
35
+ if (process.stdin.isTTY && process.stdout.isTTY) {
36
+ const { answer } = await inquirer.prompt([{ type: 'input', name: 'answer', message: prompt }]);
37
+ if (answer) return answer;
38
+ }
39
+ throw new Error(usage);
40
+ }