@aivin-labs/cli 1.0.66 → 1.0.68

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.
package/bin/lib/tasks.mjs CHANGED
@@ -1,389 +1,391 @@
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
- // āœ… FIX: had no confirmation at all before - unlike every other destructive command in this CLI
165
- // (`plugin delete`, `pluginstore rm`/`rm-node`), a typo'd id here deleted immediately with nothing
166
- // to catch it. Same `-y/--yes` escape hatch for scripts/CI as those commands.
167
- export async function deleteTaskById(id, options = {}) {
168
- const serverUrl = missionServerUrl();
169
- const authHeaders = missionAuthHeaders();
170
-
171
- if (!options.yes) {
172
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
173
- throw new Error('Refusing to delete without confirmation in a non-interactive session - pass --yes to delete anyway.');
174
- }
175
- const { confirm } = await inquirer.prompt([
176
- { type: 'confirm', name: 'confirm', message: `Delete task "${id}"? This can't be undone.`, default: false },
177
- ]);
178
- if (!confirm) {
179
- console.log(chalk.gray('Cancelled.'));
180
- return;
181
- }
182
- }
183
-
184
- try {
185
- await axios.delete(`${serverUrl}/task/${id}/delete`, authHeaders);
186
- } catch (error) {
187
- const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
188
- throw new Error(`Failed to delete task: ${message}`, { cause: error });
189
- }
190
-
191
- console.log(chalk.green(`āœ… Task ${id} deleted.`));
192
- }
193
-
194
- /**
195
- * Pure assembly of `POST /task/create`'s body, split out of createTask() so it's unit-testable
196
- * without stubbing axios/inquirer. Backend's TaskService._sanitizeCreateTaskInput whitelists
197
- * `description`, not `content` - sending the wrong key here used to look like success (200 + a
198
- * task id back) while silently dropping the user's actual text, which is exactly the kind of drift
199
- * a regression test on this function's output shape catches going forward.
200
- */
201
- export function buildCreateTaskPayload(description, workspaceId, options = {}) {
202
- return {
203
- title: description.length > 80 ? `${description.slice(0, 77)}...` : description,
204
- description,
205
- workspace_id: workspaceId,
206
- project_id: options.project,
207
- assign_id: options.assignee,
208
- };
209
- }
210
-
211
- export async function createTask(description, options) {
212
- const serverUrl = missionServerUrl();
213
- const authHeaders = missionAuthHeaders();
214
-
215
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
216
-
217
- console.log(chalk.blue('šŸ“‹ Creating task...'));
218
- console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
219
-
220
- let response;
221
- try {
222
- response = await axios.post(
223
- `${serverUrl}/task/create`,
224
- buildCreateTaskPayload(description, workspace.id || workspace._id, options),
225
- authHeaders,
226
- );
227
- } catch (error) {
228
- const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
229
- throw new Error(`Failed to create task: ${message}`, { cause: error });
230
- }
231
-
232
- const task = response.data ?? {};
233
- console.log(chalk.green('āœ… Task created!'));
234
- console.log(chalk.gray(` ID: ${task.id}`));
235
- console.log(chalk.gray(` Title: ${task.title}`));
236
- console.log(chalk.gray(` Status: ${task.status}`));
237
- }
238
-
239
- /**
240
- * `aivin workspace` - interactive workspace + project picker (arrow-key inquirer prompts, matching
241
- * `aivin create`'s existing interactive style) so a user can find a workspace/project id to pass
242
- * as --workspace/--project to `aivin do`/`do job`/`task`, without memorizing them upfront.
243
- */
244
- export async function pickWorkspaceAndProject(options) {
245
- const serverUrl = missionServerUrl();
246
- const authHeaders = missionAuthHeaders();
247
- const workspaces = await listWorkspaces(serverUrl, authHeaders);
248
-
249
- if (workspaces.length === 0) {
250
- console.log(chalk.yellow('No workspace found for this account.'));
251
- return;
252
- }
253
-
254
- if (!process.stdout.isTTY || !process.stdin.isTTY || options.plain) {
255
- for (const ws of workspaces) {
256
- console.log(chalk.bold(ws.name || ws.id) + chalk.gray(` (${ws.id})${ws.name === 'Personal' ? ' [personal]' : ''}`));
257
- (ws.projects || []).forEach((p) => console.log(chalk.gray(` - ${p.name || p.id} (${p.id})`)));
258
- }
259
- return;
260
- }
261
-
262
- const { workspaceId } = await inquirer.prompt([
263
- {
264
- type: 'select',
265
- name: 'workspaceId',
266
- message: 'Select a workspace:',
267
- choices: workspaces.map((ws) => ({
268
- name: `${ws.name || ws.id}${ws.name === 'Personal' ? chalk.gray(' (personal)') : ''}`,
269
- value: ws.id || ws._id,
270
- })),
271
- },
272
- ]);
273
- const workspace = workspaces.find((ws) => (ws.id || ws._id) === workspaceId);
274
-
275
- let projectId;
276
- if (workspace.projects?.length > 0) {
277
- const { pickedProjectId } = await inquirer.prompt([
278
- {
279
- type: 'select',
280
- name: 'pickedProjectId',
281
- message: 'Select a project:',
282
- choices: [
283
- { name: chalk.gray('(none - workspace level)'), value: null },
284
- ...workspace.projects.map((p) => ({ name: p.name || p.id, value: p.id })),
285
- ],
286
- },
287
- ]);
288
- projectId = pickedProjectId;
289
- } else {
290
- console.log(chalk.gray(`\n"${workspace.name || workspace.id}" has no projects yet - staying at workspace level (no --project needed).`));
291
- }
292
-
293
- console.log(chalk.green('\nāœ… Selected:'));
294
- console.log(` ${chalk.gray('Workspace:')} ${chalk.bold(workspace.name || 'unnamed')}`);
295
- if (projectId) {
296
- const project = workspace.projects.find((p) => p.id === projectId);
297
- console.log(` ${chalk.gray('Project:')} ${chalk.bold(project?.name || 'unnamed')}`);
298
- }
299
- console.log(chalk.gray('\nUse with `aivin do`/`aivin do job`/`aivin task`:'));
300
- console.log(` --workspace ${workspace.id || workspace._id}${projectId ? ` --project ${projectId}` : ''}`);
301
- }
302
-
303
- // ── Projects within a workspace - create/update/delete ─────────────────────────────────────────
304
- //
305
- // `POST /project/:workspaceId/project/edit` is a real upsert on the backend: omit `id` to create a
306
- // new project, include it to update the matching one - there's no separate create endpoint.
307
-
308
- export async function upsertProject(serverUrl, authHeaders, { workspaceId, id, name }) {
309
- let response;
310
- try {
311
- response = await axios.post(`${serverUrl}/project/${workspaceId}/project/edit`, { id, name }, authHeaders);
312
- } catch (error) {
313
- const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
314
- throw new Error(`Failed to save project: ${message}`, { cause: error });
315
- }
316
- return response.data ?? {};
317
- }
318
-
319
- export async function deleteProjectById(serverUrl, authHeaders, { workspaceId, projectId }) {
320
- try {
321
- await axios.delete(`${serverUrl}/project/${workspaceId}/project/${projectId}/delete`, authHeaders);
322
- } catch (error) {
323
- const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
324
- throw new Error(`Failed to delete project: ${message}`, { cause: error });
325
- }
326
- }
327
-
328
- export async function listProjectsCmd(options) {
329
- const serverUrl = missionServerUrl();
330
- const authHeaders = missionAuthHeaders();
331
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
332
-
333
- const projects = workspace.projects || [];
334
- if (projects.length === 0) {
335
- console.log(chalk.yellow(`No projects in workspace "${workspace.name || workspace.id}".`));
336
- return;
337
- }
338
- console.log(chalk.blue(`${projects.length} project(s) in "${workspace.name || workspace.id}":\n`));
339
- projects.forEach((p) => {
340
- console.log(`${chalk.bold(p.name || p.id)} ${chalk.gray(`(${p.id})`)}`);
341
- });
342
- }
343
-
344
- export async function createProjectCmd(name, options) {
345
- const serverUrl = missionServerUrl();
346
- const authHeaders = missionAuthHeaders();
347
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
348
- const project = await upsertProject(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, name });
349
- console.log(chalk.green('āœ… Project created!'));
350
- console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
351
- console.log(chalk.gray(` Name: ${project.name || name}`));
352
- if (project.id) console.log(chalk.gray(` ID: ${project.id}`));
353
- }
354
-
355
- export async function updateProjectCmd(projectId, options) {
356
- const serverUrl = missionServerUrl();
357
- const authHeaders = missionAuthHeaders();
358
- if (!options.name) {
359
- throw new Error('Nothing to update - pass --name <new name>.');
360
- }
361
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
362
- await upsertProject(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, id: projectId, name: options.name });
363
- console.log(chalk.green(`āœ… Project ${projectId} updated.`));
364
- }
365
-
366
- // āœ… FIX: had no confirmation at all before, and deleting a project is more consequential than
367
- // deleting a single task (its tasks go with it) - same missing-protection issue as deleteTaskById
368
- // above, same `-y/--yes` fix.
369
- export async function deleteProjectCmd(projectId, options) {
370
- const serverUrl = missionServerUrl();
371
- const authHeaders = missionAuthHeaders();
372
-
373
- if (!options.yes) {
374
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
375
- throw new Error('Refusing to delete without confirmation in a non-interactive session - pass --yes to delete anyway.');
376
- }
377
- const { confirm } = await inquirer.prompt([
378
- { type: 'confirm', name: 'confirm', message: `Delete project "${projectId}"? Its tasks go with it. This can't be undone.`, default: false },
379
- ]);
380
- if (!confirm) {
381
- console.log(chalk.gray('Cancelled.'));
382
- return;
383
- }
384
- }
385
-
386
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
387
- await deleteProjectById(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, projectId });
388
- console.log(chalk.green(`āœ… Project ${projectId} deleted.`));
389
- }
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
+ // āœ… FIX: had no confirmation at all before - unlike every other destructive command in this CLI
165
+ // (`plugin delete`, `pluginstore rm`/`rm-node`), a typo'd id here deleted immediately with nothing
166
+ // to catch it. Same `-y/--yes` escape hatch for scripts/CI as those commands.
167
+ export async function deleteTaskById(id, options = {}) {
168
+ const serverUrl = missionServerUrl();
169
+ const authHeaders = missionAuthHeaders();
170
+
171
+ if (!options.yes) {
172
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
173
+ throw new Error('Refusing to delete without confirmation in a non-interactive session - pass --yes to delete anyway.');
174
+ }
175
+ const { confirm } = await inquirer.prompt([
176
+ { type: 'confirm', name: 'confirm', message: `Delete task "${id}"? This can't be undone.`, default: false },
177
+ ]);
178
+ if (!confirm) {
179
+ console.log(chalk.gray('Cancelled.'));
180
+ return;
181
+ }
182
+ }
183
+
184
+ try {
185
+ await axios.delete(`${serverUrl}/task/${id}/delete`, authHeaders);
186
+ } catch (error) {
187
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
188
+ throw new Error(`Failed to delete task: ${message}`, { cause: error });
189
+ }
190
+
191
+ console.log(chalk.green(`āœ… Task ${id} deleted.`));
192
+ }
193
+
194
+ /**
195
+ * Pure assembly of `POST /task/create`'s body, split out of createTask() so it's unit-testable
196
+ * without stubbing axios/inquirer. Backend's TaskService._sanitizeCreateTaskInput whitelists
197
+ * `description`, not `content` - sending the wrong key here used to look like success (200 + a
198
+ * task id back) while silently dropping the user's actual text, which is exactly the kind of drift
199
+ * a regression test on this function's output shape catches going forward.
200
+ */
201
+ export function buildCreateTaskPayload(description, workspaceId, options = {}) {
202
+ return {
203
+ title: description.length > 80 ? `${description.slice(0, 77)}...` : description,
204
+ description,
205
+ workspace_id: workspaceId,
206
+ project_id: options.project,
207
+ assign_id: options.assignee,
208
+ };
209
+ }
210
+
211
+ export async function createTask(description, options) {
212
+ const serverUrl = missionServerUrl();
213
+ const authHeaders = missionAuthHeaders();
214
+
215
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
216
+
217
+ console.log(chalk.blue('šŸ“‹ Creating task...'));
218
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
219
+
220
+ let response;
221
+ try {
222
+ response = await axios.post(
223
+ `${serverUrl}/task/create`,
224
+ buildCreateTaskPayload(description, workspace.id || workspace._id, options),
225
+ authHeaders,
226
+ );
227
+ } catch (error) {
228
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
229
+ throw new Error(`Failed to create task: ${message}`, { cause: error });
230
+ }
231
+
232
+ const task = response.data ?? {};
233
+ console.log(chalk.green('āœ… Task created!'));
234
+ console.log(chalk.gray(` ID: ${task.id}`));
235
+ console.log(chalk.gray(` Title: ${task.title}`));
236
+ console.log(chalk.gray(` Status: ${task.status}`));
237
+ }
238
+
239
+ /**
240
+ * `aivin workspace` - interactive workspace + project picker (arrow-key inquirer prompts, matching
241
+ * `aivin create`'s existing interactive style) so a user can find a workspace/project id to pass
242
+ * as --workspace/--project to `aivin do`/`do job`/`task`, without memorizing them upfront.
243
+ */
244
+ export async function pickWorkspaceAndProject(options) {
245
+ const serverUrl = missionServerUrl();
246
+ const authHeaders = missionAuthHeaders();
247
+ const workspaces = await listWorkspaces(serverUrl, authHeaders);
248
+
249
+ if (workspaces.length === 0) {
250
+ console.log(chalk.yellow('No workspace found for this account.'));
251
+ return;
252
+ }
253
+
254
+ if (!process.stdout.isTTY || !process.stdin.isTTY || options.plain) {
255
+ for (const ws of workspaces) {
256
+ console.log(chalk.bold(ws.name || ws.id) + chalk.gray(` (${ws.id})${ws.name === 'Personal' ? ' [personal]' : ''}`));
257
+ (ws.projects || []).forEach((p) => console.log(chalk.gray(` - ${p.name || p.id} (${p.id})`)));
258
+ }
259
+ return;
260
+ }
261
+
262
+ const { workspaceId } = await inquirer.prompt([
263
+ {
264
+ type: 'select',
265
+ name: 'workspaceId',
266
+ message: 'Select a workspace:',
267
+ choices: workspaces.map((ws) => ({
268
+ name: `${ws.name || ws.id}${ws.name === 'Personal' ? chalk.gray(' (personal)') : ''}`,
269
+ value: ws.id || ws._id,
270
+ })),
271
+ },
272
+ ]);
273
+ const workspace = workspaces.find((ws) => (ws.id || ws._id) === workspaceId);
274
+
275
+ let projectId;
276
+ if (workspace.projects?.length > 0) {
277
+ const { pickedProjectId } = await inquirer.prompt([
278
+ {
279
+ type: 'select',
280
+ name: 'pickedProjectId',
281
+ message: 'Select a project:',
282
+ choices: [
283
+ { name: chalk.gray('(none - workspace level)'), value: null },
284
+ ...workspace.projects.map((p) => ({ name: p.name || p.id, value: p.id })),
285
+ ],
286
+ },
287
+ ]);
288
+ projectId = pickedProjectId;
289
+ } else {
290
+ console.log(chalk.gray(`\n"${workspace.name || workspace.id}" has no projects yet - staying at workspace level (no --project needed).`));
291
+ }
292
+
293
+ console.log(chalk.green('\nāœ… Selected:'));
294
+ console.log(` ${chalk.gray('Workspace:')} ${chalk.bold(workspace.name || 'unnamed')}`);
295
+ if (projectId) {
296
+ const project = workspace.projects.find((p) => p.id === projectId);
297
+ console.log(` ${chalk.gray('Project:')} ${chalk.bold(project?.name || 'unnamed')}`);
298
+ }
299
+ console.log(chalk.gray('\nUse with `aivin do`/`aivin do job`/`aivin task`:'));
300
+ console.log(` --workspace ${workspace.id || workspace._id}${projectId ? ` --project ${projectId}` : ''}`);
301
+ }
302
+
303
+ // ── Projects within a workspace - create/update/delete ─────────────────────────────────────────
304
+ //
305
+ // `POST /project/:workspaceId/project/edit` is a real upsert on the backend: omit `id` to create a
306
+ // new project, include it to update the matching one - there's no separate create endpoint.
307
+ // `workspace_id` must also be in the body: the backend's ValidationPipe checks `ProjectRequest` (workspace_id required) before the
308
+ // handler copies it from the URL, so a body without it is rejected with "workspace_id should not be empty" (found 17/11/2026).
309
+
310
+ export async function upsertProject(serverUrl, authHeaders, { workspaceId, id, name }) {
311
+ let response;
312
+ try {
313
+ response = await axios.post(`${serverUrl}/project/${workspaceId}/project/edit`, { workspace_id: workspaceId, id, name }, authHeaders);
314
+ } catch (error) {
315
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
316
+ throw new Error(`Failed to save project: ${message}`, { cause: error });
317
+ }
318
+ return response.data ?? {};
319
+ }
320
+
321
+ export async function deleteProjectById(serverUrl, authHeaders, { workspaceId, projectId }) {
322
+ try {
323
+ await axios.delete(`${serverUrl}/project/${workspaceId}/project/${projectId}/delete`, authHeaders);
324
+ } catch (error) {
325
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
326
+ throw new Error(`Failed to delete project: ${message}`, { cause: error });
327
+ }
328
+ }
329
+
330
+ export async function listProjectsCmd(options) {
331
+ const serverUrl = missionServerUrl();
332
+ const authHeaders = missionAuthHeaders();
333
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
334
+
335
+ const projects = workspace.projects || [];
336
+ if (projects.length === 0) {
337
+ console.log(chalk.yellow(`No projects in workspace "${workspace.name || workspace.id}".`));
338
+ return;
339
+ }
340
+ console.log(chalk.blue(`${projects.length} project(s) in "${workspace.name || workspace.id}":\n`));
341
+ projects.forEach((p) => {
342
+ console.log(`${chalk.bold(p.name || p.id)} ${chalk.gray(`(${p.id})`)}`);
343
+ });
344
+ }
345
+
346
+ export async function createProjectCmd(name, options) {
347
+ const serverUrl = missionServerUrl();
348
+ const authHeaders = missionAuthHeaders();
349
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
350
+ const project = await upsertProject(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, name });
351
+ console.log(chalk.green('āœ… Project created!'));
352
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
353
+ console.log(chalk.gray(` Name: ${project.name || name}`));
354
+ if (project.id) console.log(chalk.gray(` ID: ${project.id}`));
355
+ }
356
+
357
+ export async function updateProjectCmd(projectId, options) {
358
+ const serverUrl = missionServerUrl();
359
+ const authHeaders = missionAuthHeaders();
360
+ if (!options.name) {
361
+ throw new Error('Nothing to update - pass --name <new name>.');
362
+ }
363
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
364
+ await upsertProject(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, id: projectId, name: options.name });
365
+ console.log(chalk.green(`āœ… Project ${projectId} updated.`));
366
+ }
367
+
368
+ // āœ… FIX: had no confirmation at all before, and deleting a project is more consequential than
369
+ // deleting a single task (its tasks go with it) - same missing-protection issue as deleteTaskById
370
+ // above, same `-y/--yes` fix.
371
+ export async function deleteProjectCmd(projectId, options) {
372
+ const serverUrl = missionServerUrl();
373
+ const authHeaders = missionAuthHeaders();
374
+
375
+ if (!options.yes) {
376
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
377
+ throw new Error('Refusing to delete without confirmation in a non-interactive session - pass --yes to delete anyway.');
378
+ }
379
+ const { confirm } = await inquirer.prompt([
380
+ { type: 'confirm', name: 'confirm', message: `Delete project "${projectId}"? Its tasks go with it. This can't be undone.`, default: false },
381
+ ]);
382
+ if (!confirm) {
383
+ console.log(chalk.gray('Cancelled.'));
384
+ return;
385
+ }
386
+ }
387
+
388
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
389
+ await deleteProjectById(serverUrl, authHeaders, { workspaceId: workspace.id || workspace._id, projectId });
390
+ console.log(chalk.green(`āœ… Project ${projectId} deleted.`));
391
+ }