@ctrl-spc/cs 0.1.0 → 0.3.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.
package/dist/mcp.js ADDED
@@ -0,0 +1,1679 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { execFile } from 'node:child_process';
3
+ import { promisify } from 'node:util';
4
+ import { createServer as createHttpServer } from 'node:http';
5
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
7
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
8
+ import { z } from 'zod';
9
+ import { TOOLS_SERVER_PORT, SESSION_TTL_MS } from './env.js';
10
+ import { agentPath } from './agents.js';
11
+ export function attributionFromClientName(name) {
12
+ if (!name)
13
+ return null;
14
+ if (/claude/i.test(name))
15
+ return 'claude';
16
+ if (/codex/i.test(name))
17
+ return 'codex';
18
+ return null;
19
+ }
20
+ /** Awaits a Supabase call and throws on error — callers catch once, at the
21
+ * handler boundary (mirrors v1's `must`). */
22
+ async function must(query) {
23
+ const { data, error } = await query;
24
+ if (error)
25
+ throw new Error(error.message);
26
+ return data;
27
+ }
28
+ function textResult(payload) {
29
+ return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
30
+ }
31
+ function errorResult(message) {
32
+ return { content: [{ type: 'text', text: message }], isError: true };
33
+ }
34
+ /** Columns v1 returns for a freshly created artifact (cli/src/mcp.ts:2239) —
35
+ * reused verbatim so get_task and create_artifact hand back the same shape, plus
36
+ * `revision` so the agent has the optimistic-concurrency token update_artifact
37
+ * needs for `expected_revision` (mirrors how get_task returns tasks.revision). */
38
+ const ARTIFACT_COLUMNS = 'id,task_id,type,format,title,purpose_key,system_kind,content,storage_path,created_by,from_agent,created_at,revision';
39
+ /** Columns a decision row exposes to the agent (D3) — reused verbatim so get_task
40
+ * and ask_question hand back the same shape. RLS `decisions_select` grants the
41
+ * signed-in user read via `app.can_access_task`. */
42
+ const DECISION_COLUMNS = 'id,task_id,state,category,context,question,answer_mode,options,answer,selected_options,answer_note,question_comment_id,related_artifact_id,asked_by,asked_by_agent_run_id,asked_at,decided_by,decided_at';
43
+ /** Tags come from the same `task_tags`→`tags` join the web reads. */
44
+ const TASK_TAGS = 'task_tags:task_tags!task_tags_task_id_fkey(tag:tags!task_tags_tag_id_fkey(id,name))';
45
+ function tagsOf(row) {
46
+ return (row.task_tags ?? [])
47
+ .map((entry) => entry.tag?.name)
48
+ .filter((name) => Boolean(name))
49
+ .sort((a, b) => a.localeCompare(b));
50
+ }
51
+ /**
52
+ * List the signed-in user's tasks across all their projects (RLS-scoped),
53
+ * optionally filtered to one project. No machine/workspace resolver — RLS on
54
+ * `tasks` already confines the rows to the user's own projects.
55
+ */
56
+ async function listTasksHandler(client, args) {
57
+ try {
58
+ const projects = (await must(client.from('projects').select('id, name'))) ?? [];
59
+ let query = client
60
+ .from('tasks')
61
+ .select(`id, project_id, name, status, due_date, ${TASK_TAGS}`)
62
+ .is('archived_at', null);
63
+ if (args.project_id)
64
+ query = query.eq('project_id', args.project_id);
65
+ const rows = (await must(query
66
+ .order('status', { ascending: true })
67
+ .order('position', { ascending: true })
68
+ .order('created_at', { ascending: true })
69
+ .order('id', { ascending: true }))) ?? [];
70
+ const tasks = rows.map((row) => ({
71
+ id: row.id,
72
+ project_id: row.project_id,
73
+ project: projects.find((p) => p.id === row.project_id) ?? { id: row.project_id },
74
+ name: row.name,
75
+ status: row.status,
76
+ due_date: row.due_date,
77
+ tags: tagsOf(row),
78
+ }));
79
+ return textResult({ projects, tasks });
80
+ }
81
+ catch (err) {
82
+ return errorResult(`list_tasks failed: ${err.message}`);
83
+ }
84
+ }
85
+ /**
86
+ * Read one task by id (RLS-scoped) with its tags, comments, live artifacts, and
87
+ * decisions (D3 — so the agent can read the answers to questions it asked).
88
+ * Adapted from v1's `getTaskHandler` for the column shapes, with every
89
+ * topology / checkout / coordination section dropped.
90
+ */
91
+ async function getTaskHandler(client, args) {
92
+ try {
93
+ const row = await must(client
94
+ .from('tasks')
95
+ .select(`*, ${TASK_TAGS}`)
96
+ .eq('id', args.id)
97
+ .is('archived_at', null)
98
+ .maybeSingle());
99
+ if (!row)
100
+ return errorResult(`No task found for id "${args.id}".`);
101
+ const [comments, artifacts, decisions] = await Promise.all([
102
+ must(client
103
+ .from('comments')
104
+ .select('id,task_id,body,author_id,from_agent,agent_run_id,created_at,updated_at')
105
+ .eq('task_id', row.id)
106
+ .order('created_at', { ascending: true })
107
+ .order('id', { ascending: true })),
108
+ must(client
109
+ .from('artifacts')
110
+ .select(ARTIFACT_COLUMNS)
111
+ .eq('task_id', row.id)
112
+ .is('deleted_at', null)
113
+ .order('created_at', { ascending: true })
114
+ .order('id', { ascending: true })),
115
+ // D3: the item's decisions — the questions ask_question opened and the
116
+ // answers the user gave in the web UI, so the agent can read them back.
117
+ must(client
118
+ .from('decisions')
119
+ .select(DECISION_COLUMNS)
120
+ .eq('task_id', row.id)
121
+ .order('asked_at', { ascending: true })
122
+ .order('id', { ascending: true })),
123
+ ]);
124
+ const { task_tags: _drop, ...task } = row;
125
+ return textResult({
126
+ task: { ...task, tags: tagsOf(row) },
127
+ comments: comments ?? [],
128
+ artifacts: artifacts ?? [],
129
+ decisions: decisions ?? [],
130
+ });
131
+ }
132
+ catch (err) {
133
+ return errorResult(`get_task failed: ${err.message}`);
134
+ }
135
+ }
136
+ /**
137
+ * Create an artifact on a task the user owns (via RLS). Adapted from v1's simple
138
+ * (non-agent-run) path (cli/src/mcp.ts:2219): the task is looked up by id under
139
+ * RLS (no bound project), and the artifact is created AS THE USER
140
+ * (`created_by: userId`). `from_agent` is left null because the deployed DB guard
141
+ * `artifact_agent_insert_guard` reserves agent attribution for the coordinated
142
+ * `create_agent_artifact` RPC — the agent-run model this availability-only
143
+ * feature deliberately does not use. A direct `authenticated` insert that sets
144
+ * `from_agent` is rejected ("agent artifacts must be created through
145
+ * create_agent_artifact"), so un-coordinated tool use writes as the user.
146
+ */
147
+ async function createArtifactHandler(client, userId, currentSession, args) {
148
+ try {
149
+ if (!args.task_id)
150
+ return errorResult('create_artifact requires task_id.');
151
+ if (!args.content)
152
+ return errorResult('create_artifact requires content.');
153
+ if (args.purpose_key?.trim().startsWith('context:')) {
154
+ return errorResult('Context is a reserved work-item artifact.');
155
+ }
156
+ const task = await must(client.from('tasks').select('id').eq('id', args.task_id).is('archived_at', null).maybeSingle());
157
+ if (!task)
158
+ return errorResult(`No task found for id "${args.task_id}".`);
159
+ const row = await must(client
160
+ .from('artifacts')
161
+ .insert({
162
+ task_id: args.task_id,
163
+ type: args.type,
164
+ format: args.format ?? 'md',
165
+ ...(args.title?.trim() ? { title: args.title.trim() } : {}),
166
+ ...(args.purpose_key?.trim() ? { purpose_key: args.purpose_key.trim() } : {}),
167
+ content: args.content,
168
+ created_by: userId,
169
+ from_agent: null,
170
+ agent_run_id: null,
171
+ })
172
+ .select(ARTIFACT_COLUMNS)
173
+ .single());
174
+ if (!row)
175
+ throw new Error('Artifact insert returned no row.');
176
+ // D1 attribution: if this connection has an open session for THIS task
177
+ // (the agent called begin_work first), record that the session produced this
178
+ // artifact — one cliv2_agent_outputs row, referencing the artifact BY VALUE.
179
+ // Best-effort: the artifact already exists and is the real return value, so a
180
+ // failed attribution write must NOT fail the tool — but it is surfaced in the
181
+ // returned text rather than silently dropped. With no open session (or a
182
+ // session for a different task) no attribution row is written — backward
183
+ // compatible with un-coordinated tool use.
184
+ let attributionWarning;
185
+ if (currentSession && currentSession.taskId === args.task_id) {
186
+ try {
187
+ await must(client.from('cliv2_agent_outputs').insert({
188
+ user_id: userId,
189
+ session_id: currentSession.sessionId,
190
+ kind: 'artifact',
191
+ product_id: row.id,
192
+ }));
193
+ }
194
+ catch (err) {
195
+ attributionWarning = `Artifact created, but recording session attribution failed: ${err.message}`;
196
+ }
197
+ }
198
+ return textResult(attributionWarning ? { artifact: row, attribution_warning: attributionWarning } : { artifact: row });
199
+ }
200
+ catch (err) {
201
+ return errorResult(`create_artifact failed: ${err.message}`);
202
+ }
203
+ }
204
+ /** Re-fetch one task with the SAME select get_task uses (`*` + the tag join),
205
+ * returning the parsed task object ({ ...row, tags }, task_tags dropped) or null.
206
+ * Shared by update_task and create_task so their result shape matches get_task's
207
+ * `task`. */
208
+ async function fetchTask(client, id) {
209
+ const row = await must(client.from('tasks').select(`*, ${TASK_TAGS}`).eq('id', id).is('archived_at', null).maybeSingle());
210
+ if (!row)
211
+ return null;
212
+ const { task_tags: _drop, ...task } = row;
213
+ return { ...task, tags: tagsOf(row) };
214
+ }
215
+ /**
216
+ * Update a task the user owns (via RLS). Adapted from v1's SIMPLE (non-agent-run)
217
+ * `updateTaskHandler` branch: no bound project (RLS scopes it), status + the plain
218
+ * text fields only — owner / sprint / tags / reorder / before_task_id are all
219
+ * deferred. Optimistic concurrency via `expected_revision` (from get_task) through
220
+ * the same `save_task_if_current` RPC v1 uses; an `edit_conflict` maps to a clear
221
+ * "call get_task again and retry" message. Re-fetches with get_task's select.
222
+ */
223
+ async function updateTaskHandler(client, args) {
224
+ try {
225
+ const { id, fields, expected_revision } = args;
226
+ if (!Number.isInteger(expected_revision) || expected_revision < 1) {
227
+ return errorResult('update_task requires expected_revision (a positive integer) from the most recent get_task response.');
228
+ }
229
+ const current = await must(client.from('tasks').select('id,status,revision').eq('id', id).is('archived_at', null).maybeSingle());
230
+ if (!current)
231
+ return errorResult(`No task found for id "${id}".`);
232
+ const patch = {};
233
+ if (fields.name !== undefined)
234
+ patch.name = fields.name;
235
+ if (fields.description !== undefined)
236
+ patch.description = fields.description;
237
+ if (fields.due_date !== undefined)
238
+ patch.due_date = fields.due_date;
239
+ if (fields.status !== undefined)
240
+ patch.status = fields.status;
241
+ // A status change implies append-to-destination (reorder); a same-value
242
+ // status preserves board position. before_task_id ordering is deferred, so
243
+ // reorder is driven purely by whether the status actually changed.
244
+ const statusChanged = fields.status !== undefined && fields.status !== current.status;
245
+ await must(client.rpc('save_task_if_current', {
246
+ p_task_id: id,
247
+ p_expected_revision: expected_revision,
248
+ p_changes: patch,
249
+ p_tag_ids: null,
250
+ p_reorder: statusChanged,
251
+ p_before_task_id: null,
252
+ }));
253
+ const task = await fetchTask(client, id);
254
+ if (!task)
255
+ throw new Error('Updated task could not be re-fetched.');
256
+ return textResult({ task });
257
+ }
258
+ catch (err) {
259
+ if (err.message === 'edit_conflict') {
260
+ return errorResult('update_task conflict: this work item changed after it was read. Call get_task again, review the latest revision, and retry intentionally.');
261
+ }
262
+ return errorResult(`update_task failed: ${err.message}`);
263
+ }
264
+ }
265
+ /**
266
+ * Edit an artifact the user can access (via RLS). Mirrors updateTaskHandler's
267
+ * optimistic-concurrency shape exactly, over the run-free `save_artifact_if_current`
268
+ * RPC (security invoker, granted authenticated, NO p_run — the coordinated
269
+ * create_agent_artifact path is deliberately unused here). The deployed RPC accepts
270
+ * the artifact BODY keys `title` / `purpose_key` / `type` / `format` / `content`
271
+ * (plus `deleted_at`, which this tool never sends); this tool exposes
272
+ * `title` / `type` / `format` / `content` and deliberately NOT `purpose_key` — an
273
+ * UPDATE that set `purpose_key='context:<task>'` could relabel a normal artifact as
274
+ * canonical context and thereby escape the INSERT-only context-artifact reservation.
275
+ * `from_agent` is never touched. `expected_revision` comes from the most recent
276
+ * get_task; a revision mismatch raises `edit_conflict`, mapped to the same clear
277
+ * "call get_task again and retry" message updateTask uses. Re-fetches the live
278
+ * artifact with ARTIFACT_COLUMNS so the result matches get_task / create_artifact.
279
+ */
280
+ async function updateArtifactHandler(client, args) {
281
+ try {
282
+ const { id, fields, expected_revision } = args;
283
+ if (!Number.isInteger(expected_revision) || expected_revision < 1) {
284
+ return errorResult('update_artifact requires expected_revision (a positive integer) from the most recent get_task response.');
285
+ }
286
+ // Build p_changes from the provided fields only — restricted to the keys this
287
+ // tool exposes (title / type / format / content). purpose_key is deliberately
288
+ // excluded (it could escape the context-artifact reservation), and deleted_at is
289
+ // never sent from here.
290
+ const patch = {};
291
+ if (fields.title !== undefined)
292
+ patch.title = fields.title;
293
+ if (fields.type !== undefined)
294
+ patch.type = fields.type;
295
+ if (fields.format !== undefined)
296
+ patch.format = fields.format;
297
+ if (fields.content !== undefined)
298
+ patch.content = fields.content;
299
+ await must(client.rpc('save_artifact_if_current', {
300
+ p_artifact_id: id,
301
+ p_expected_revision: expected_revision,
302
+ p_changes: patch,
303
+ }));
304
+ const artifact = await must(client.from('artifacts').select(ARTIFACT_COLUMNS).eq('id', id).is('deleted_at', null).maybeSingle());
305
+ if (!artifact)
306
+ throw new Error('Updated artifact could not be re-fetched.');
307
+ return textResult({ artifact });
308
+ }
309
+ catch (err) {
310
+ if (err.message === 'edit_conflict') {
311
+ return errorResult('update_artifact conflict: this artifact changed after it was read. Call get_task again, re-read the latest revision, and retry intentionally.');
312
+ }
313
+ return errorResult(`update_artifact failed: ${err.message}`);
314
+ }
315
+ }
316
+ /**
317
+ * Set the repository role slugs on a task — its role assignments. Replaces
318
+ * tasks.role_slugs with the given list via the run-free `set_task_role_slugs` RPC
319
+ * (security definer, granted authenticated, NO p_run; checks app.is_project_member).
320
+ * The RPC filters the requested slugs down to the project's active repository scopes,
321
+ * so a caller can't assign a slug the project doesn't define. Re-fetches with
322
+ * get_task's select so the result shape matches get_task's `task`.
323
+ *
324
+ * The RPC has no archived guard, but fetchTask filters `archived_at is null`, so
325
+ * without a pre-check a task archived after it was read would be written at the DB
326
+ * yet reported as a re-fetch failure. Mirror updateTaskHandler: confirm the task is
327
+ * live under RLS BEFORE calling the RPC, and return a clean "no task" error if not.
328
+ */
329
+ async function setTaskRoleSlugsHandler(client, args) {
330
+ try {
331
+ const task = await must(client.from('tasks').select('id').eq('id', args.task_id).is('archived_at', null).maybeSingle());
332
+ if (!task)
333
+ return errorResult(`No task found for id "${args.task_id}".`);
334
+ await must(client.rpc('set_task_role_slugs', { p_task: args.task_id, p_role_slugs: args.role_slugs }));
335
+ const updated = await fetchTask(client, args.task_id);
336
+ if (!updated)
337
+ throw new Error('Task could not be re-fetched.');
338
+ return textResult({ task: updated });
339
+ }
340
+ catch (err) {
341
+ return errorResult(`set_task_role_slugs failed: ${err.message}`);
342
+ }
343
+ }
344
+ /**
345
+ * Leave a note on a task the user owns (via RLS). Adapted from v1's
346
+ * `addCommentHandler`, authored AS THE USER: `from_agent` is left null. Like
347
+ * `artifacts`, the `comments` table carries a `comment_agent_insert_guard` that
348
+ * reserves agent attribution for the coordinated path this feature does not use,
349
+ * so a direct `from_agent`-set insert would be rejected — writing as the user is
350
+ * the correct, consistent choice (matches create_artifact).
351
+ */
352
+ async function addCommentHandler(client, userId, currentSession, args) {
353
+ try {
354
+ if (!args.task_id)
355
+ return errorResult('add_comment requires task_id.');
356
+ if (!args.body || !args.body.trim())
357
+ return errorResult('add_comment requires a non-empty body.');
358
+ const task = await must(client.from('tasks').select('id').eq('id', args.task_id).is('archived_at', null).maybeSingle());
359
+ if (!task)
360
+ return errorResult(`No task found for id "${args.task_id}".`);
361
+ const row = await must(client
362
+ .from('comments')
363
+ .insert({
364
+ task_id: args.task_id,
365
+ author_id: userId,
366
+ body: args.body,
367
+ from_agent: null,
368
+ agent_run_id: null,
369
+ })
370
+ .select('id,task_id,body,author_id,from_agent,created_at')
371
+ .single());
372
+ if (!row)
373
+ throw new Error('Comment insert returned no row.');
374
+ // D2a attribution: if this connection has an open session (the agent called
375
+ // begin_work), record that the session produced this comment — one
376
+ // cliv2_agent_outputs row referencing the comment BY VALUE. Unlike
377
+ // create_artifact this does NOT require the session's task to match: a comment
378
+ // produced while a session is open is attributed to it. Best-effort (mirrors
379
+ // D1): the comment already exists and is the real return value, so a failed
380
+ // attribution write must NOT fail the tool — it is surfaced in the returned
381
+ // text rather than silently dropped. With no open session no attribution row is
382
+ // written — backward compatible with un-coordinated tool use.
383
+ let attributionWarning;
384
+ if (currentSession) {
385
+ try {
386
+ await must(client.from('cliv2_agent_outputs').insert({
387
+ user_id: userId,
388
+ session_id: currentSession.sessionId,
389
+ kind: 'comment',
390
+ product_id: row.id,
391
+ }));
392
+ }
393
+ catch (err) {
394
+ attributionWarning = `Comment created, but recording session attribution failed: ${err.message}`;
395
+ }
396
+ }
397
+ return textResult(attributionWarning ? { comment: row, attribution_warning: attributionWarning } : { comment: row });
398
+ }
399
+ catch (err) {
400
+ return errorResult(`add_comment failed: ${err.message}`);
401
+ }
402
+ }
403
+ /**
404
+ * Create a new task in a project the user owns (via RLS), owned by the user.
405
+ * Adapted from v1's `createTaskHandler`, minimal — tags / depends_on /
406
+ * before_task_id are deferred. Uses the workflow-free `create_task` RPC
407
+ * (SECURITY DEFINER; the old `create_task_with_workflow` was removed with the
408
+ * Workflows feature, see 20260721150000_drop_workflows.sql) to insert the task
409
+ * and return its id, then re-fetches with get_task's select.
410
+ */
411
+ async function createTaskHandler(client, userId, currentSession, args) {
412
+ try {
413
+ if (!args.name || !args.name.trim())
414
+ return errorResult('create_task requires a non-empty name.');
415
+ const taskId = await must(client.rpc('create_task', {
416
+ p_project: args.project_id,
417
+ p_name: args.name,
418
+ p_description: args.description ?? '',
419
+ p_owner: userId,
420
+ }));
421
+ if (!taskId)
422
+ throw new Error('Task insert returned no id.');
423
+ const task = await fetchTask(client, taskId);
424
+ if (!task)
425
+ throw new Error('Created task could not be re-fetched.');
426
+ // D2a attribution: if this connection has an open session, record that the
427
+ // session produced this NEW task — one cliv2_agent_outputs row referencing the
428
+ // task BY VALUE. This is a follow-up task the subagent created, NOT the
429
+ // session's anchored task, so there is deliberately NO task-id match to gate
430
+ // on: gate only on there being an open session. Best-effort (mirrors D1): the
431
+ // task already exists and is the real return value, so a failed attribution
432
+ // write must NOT fail the tool — it is surfaced in the returned text rather
433
+ // than silently dropped. With no open session no attribution row is written —
434
+ // backward compatible with un-coordinated tool use.
435
+ let attributionWarning;
436
+ if (currentSession) {
437
+ try {
438
+ await must(client.from('cliv2_agent_outputs').insert({
439
+ user_id: userId,
440
+ session_id: currentSession.sessionId,
441
+ kind: 'task',
442
+ product_id: taskId,
443
+ }));
444
+ }
445
+ catch (err) {
446
+ attributionWarning = `Task created, but recording session attribution failed: ${err.message}`;
447
+ }
448
+ }
449
+ return textResult(attributionWarning ? { task, attribution_warning: attributionWarning } : { task });
450
+ }
451
+ catch (err) {
452
+ return errorResult(`create_task failed: ${err.message}`);
453
+ }
454
+ }
455
+ /**
456
+ * Ask the user a question about the work item the open session is on (D3). Unlike
457
+ * the write tools, this REQUIRES an open session — the question is a decision on
458
+ * the session's task, and the `cliv2_ask_question` RPC resolves that task FROM the
459
+ * session (so there's no task_id arg). The RPC inserts the run-free `decisions`
460
+ * row AS THE USER and returns its id; the decision is the real return value, so
461
+ * (mirroring create_artifact) attribution is a best-effort `cliv2_agent_outputs`
462
+ * write whose failure is surfaced in the returned text, never fatal. The created
463
+ * decision is re-fetched with the SAME columns get_task returns so the agent sees
464
+ * exactly what it made and can later read the user's answer back with get_task.
465
+ */
466
+ async function askQuestionHandler(client, userId, session, args) {
467
+ try {
468
+ if (!session) {
469
+ return errorResult('ask_question needs an open work session — call begin_work first.');
470
+ }
471
+ if (!args.category || !args.category.trim())
472
+ return errorResult('ask_question requires a non-empty category.');
473
+ if (!args.context || !args.context.trim())
474
+ return errorResult('ask_question requires a non-empty context.');
475
+ if (!args.question || !args.question.trim())
476
+ return errorResult('ask_question requires a non-empty question.');
477
+ const mode = args.answer_mode ?? 'free_text';
478
+ const decisionId = await must(client.rpc('cliv2_ask_question', {
479
+ p_session: session.sessionId,
480
+ p_category: args.category,
481
+ p_context: args.context,
482
+ p_question: args.question,
483
+ p_answer_mode: mode,
484
+ p_options: args.options ?? [],
485
+ p_related_artifact: args.related_artifact_id ?? null,
486
+ }));
487
+ if (!decisionId)
488
+ throw new Error('Question insert returned no decision id.');
489
+ // Best-effort attribution (mirrors create_artifact exactly): record that this
490
+ // session asked the question — one cliv2_agent_outputs row referencing the
491
+ // decision BY VALUE. The decision already exists and is the real return value,
492
+ // so a failed attribution write must NOT fail the tool — it is surfaced in the
493
+ // returned text rather than silently dropped.
494
+ let attributionWarning;
495
+ try {
496
+ await must(client.from('cliv2_agent_outputs').insert({
497
+ user_id: userId,
498
+ session_id: session.sessionId,
499
+ kind: 'decision',
500
+ product_id: decisionId,
501
+ }));
502
+ }
503
+ catch (err) {
504
+ attributionWarning = `Question created, but recording session attribution failed: ${err.message}`;
505
+ }
506
+ // Re-fetch the created decision with the SAME columns get_task returns, so the
507
+ // agent sees what it made (and later reads the answer back through get_task).
508
+ const decision = await must(client.from('decisions').select(DECISION_COLUMNS).eq('id', decisionId).maybeSingle());
509
+ if (!decision)
510
+ throw new Error('Created decision could not be re-fetched.');
511
+ return textResult(attributionWarning ? { decision, attribution_warning: attributionWarning } : { decision });
512
+ }
513
+ catch (err) {
514
+ return errorResult(`ask_question failed: ${err.message}`);
515
+ }
516
+ }
517
+ /**
518
+ * Record the user's answer to an OPEN decision on the work item (feature 05 / D4 —
519
+ * the run-free twin of v1's `record_user_input`). Unlike v1, this does NOT go through a
520
+ * run-gated batch RPC (`record_task_decisions` / `record_task_decision_responses`);
521
+ * it uses the exact RPC the web's `answerDecision` (web/src/lib/actions.ts) calls,
522
+ * `answer_task_decision_v2({ p_decision_id, p_selected_options, p_answer_note })`,
523
+ * AS THE USER under RLS — no run, no fencing token. The RPC is security-definer and
524
+ * validates access (`app.can_access_task`) plus the answer shape against the
525
+ * decision's `answer_mode`, so it is the source of truth for deep validation.
526
+ *
527
+ * The web routes EVERY answer_mode through this single v2 RPC; we replicate that
528
+ * mapping exactly:
529
+ * - free_text -> p_selected_options: [], p_answer_note: <answer>
530
+ * - single/multi_select -> p_selected_options: <options>, p_answer_note: <note ?? ''>
531
+ * (`answer_task_decision(id, answer)` is only a thin wrapper for v2 with '{}' — the
532
+ * web never calls it, so neither do we.) We read the decision's `answer_mode` first
533
+ * only to route + give a clean shape error; RLS scopes that read to the user. This
534
+ * MUTATES an existing decision, so there is no attribution row (nothing new is
535
+ * produced). Requires an open session, like ask_question. Re-fetches the decision
536
+ * with DECISION_COLUMNS so the caller sees the now-decided row (it shows answered in
537
+ * the web UI).
538
+ */
539
+ async function recordUserInputHandler(client, session, args) {
540
+ try {
541
+ if (!session) {
542
+ return errorResult('record_user_input needs an open work session — call begin_work first.');
543
+ }
544
+ if (!args.decision_id || !args.decision_id.trim()) {
545
+ return errorResult('record_user_input requires a decision_id.');
546
+ }
547
+ // Read the decision to route by its answer_mode EXACTLY as the web does, and to
548
+ // give a clean shape error before the RPC. RLS (`decisions_select`) scopes this
549
+ // to a decision the signed-in user can access.
550
+ const decision = await must(client.from('decisions').select('id,answer_mode').eq('id', args.decision_id).maybeSingle());
551
+ if (!decision)
552
+ return errorResult(`No decision found for id "${args.decision_id}".`);
553
+ // Replicate the web's answerDecision mapping into answer_task_decision_v2.
554
+ let pSelectedOptions;
555
+ let pAnswerNote;
556
+ if (decision.answer_mode === 'free_text') {
557
+ if (!args.answer || !args.answer.trim()) {
558
+ return errorResult('record_user_input requires answer (the free-text answer) for a free_text decision.');
559
+ }
560
+ pSelectedOptions = [];
561
+ pAnswerNote = args.answer;
562
+ }
563
+ else {
564
+ if (!Array.isArray(args.selected_options) || args.selected_options.length === 0) {
565
+ return errorResult('record_user_input requires selected_options (the chosen option(s)) for a choice decision.');
566
+ }
567
+ pSelectedOptions = args.selected_options;
568
+ pAnswerNote = args.answer_note ?? '';
569
+ }
570
+ await must(client.rpc('answer_task_decision_v2', {
571
+ p_decision_id: args.decision_id,
572
+ p_selected_options: pSelectedOptions,
573
+ p_answer_note: pAnswerNote,
574
+ }));
575
+ // Hand back the now-decided decision in the SAME shape get_task / ask_question use.
576
+ const updated = await must(client.from('decisions').select(DECISION_COLUMNS).eq('id', args.decision_id).maybeSingle());
577
+ if (!updated)
578
+ throw new Error('Answered decision could not be re-fetched.');
579
+ return textResult({ decision: updated });
580
+ }
581
+ catch (err) {
582
+ return errorResult(`record_user_input failed: ${err.message}`);
583
+ }
584
+ }
585
+ /**
586
+ * Record what you explored for the work item as its CANONICAL context document
587
+ * (feature 05 / D4 — the run-free twin of v1's `record_context_exploration`). v1's
588
+ * version wrote the `system_kind='context'` artifact PLUS repository-coverage /
589
+ * topology through the run-gated `record_context_exploration_artifact` RPC; we drop
590
+ * the coverage and topology entirely and write ONLY the context document.
591
+ *
592
+ * The canonical context artifact is DB-reserved: the BEFORE-INSERT trigger
593
+ * `app.guard_agent_artifact_insert` admits a `system_kind='context'` row only when
594
+ * the session GUC `app.context_artifact_write` matches the task. The run-free
595
+ * SECURITY DEFINER RPC `cliv2_record_context(p_session, p_content)` sets that GUC and
596
+ * writes/UPSERTS the ONE canonical "Work item context" artifact for the session's
597
+ * task — task resolved FROM the session, no run / fencing / topology. So this tool
598
+ * takes only `content`: the document's title is fixed ("Work item context") and its
599
+ * task comes from the open session. Requires an open session.
600
+ *
601
+ * Because the RPC UPSERTS the same canonical row, repeated calls return the SAME
602
+ * artifact id. Best-effort attribution mirrors create_artifact (one
603
+ * cliv2_agent_outputs row, kind 'artifact', product_id BY VALUE) — but a second call
604
+ * re-inserting that same (kind, product_id) trips `unique(kind, product_id)` (23505):
605
+ * that is the already-attributed case, so 23505 is treated as success (no warning)
606
+ * and only OTHER failures surface as attribution_warning. Re-fetches with
607
+ * ARTIFACT_COLUMNS and returns { artifact }.
608
+ */
609
+ async function recordContextExplorationHandler(client, userId, session, args) {
610
+ try {
611
+ if (!session) {
612
+ return errorResult('record_context_exploration needs an open work session — call begin_work first.');
613
+ }
614
+ if (!args.content || !args.content.trim())
615
+ return errorResult('record_context_exploration requires content.');
616
+ // Write/upsert the ONE canonical context document for the session's task via the
617
+ // run-free RPC (it resolves the task from p_session and sets the context-write GUC
618
+ // the INSERT guard requires). Returns the canonical artifact's id.
619
+ const artifactId = await must(client.rpc('cliv2_record_context', { p_session: session.sessionId, p_content: args.content }));
620
+ if (!artifactId)
621
+ throw new Error('cliv2_record_context returned no artifact id.');
622
+ // Best-effort session attribution (mirror create_artifact). The RPC UPSERTS the
623
+ // same canonical row, so a repeat call re-inserts the same (kind, product_id) and
624
+ // trips unique(kind, product_id) (23505) — that is "already attributed", not a
625
+ // failure, so 23505 is swallowed silently; any OTHER error is surfaced.
626
+ let attributionWarning;
627
+ const { error: attrError } = await client.from('cliv2_agent_outputs').insert({
628
+ user_id: userId,
629
+ session_id: session.sessionId,
630
+ kind: 'artifact',
631
+ product_id: artifactId,
632
+ });
633
+ if (attrError && attrError.code !== '23505') {
634
+ attributionWarning = `Context recorded, but recording session attribution failed: ${attrError.message}`;
635
+ }
636
+ // Re-fetch the (live) canonical context artifact so the result matches
637
+ // get_task / create_artifact.
638
+ const artifact = await must(client.from('artifacts').select(ARTIFACT_COLUMNS).eq('id', artifactId).is('deleted_at', null).maybeSingle());
639
+ if (!artifact)
640
+ throw new Error('Recorded context artifact could not be re-fetched.');
641
+ return textResult(attributionWarning ? { artifact, attribution_warning: attributionWarning } : { artifact });
642
+ }
643
+ catch (err) {
644
+ return errorResult(`record_context_exploration failed: ${err.message}`);
645
+ }
646
+ }
647
+ /**
648
+ * Reserve repo-relative paths on a codebase (D5) so concurrent agents don't collide.
649
+ * Session-anchored and run-free: every reservation is stamped with the open session's
650
+ * id/task and lives in the owner-scoped `cliv2_work_reservations` table (no agent-run,
651
+ * no fencing token). Reservations are ADVISORY — a conflicting write lease held by
652
+ * another session is REPORTED, never forced or waited on.
653
+ *
654
+ * Per requested path, decide reserve vs conflict vs already-held against the ACTIVE
655
+ * (`released_at is null`) reservations on this codebase+path:
656
+ * - CONFLICT if any active row is by a DIFFERENT session AND at least one side is a
657
+ * 'write' lease (write-write and write-read collide; read-read coexists). Record
658
+ * `{ path, held_by_session_id }` and insert nothing.
659
+ * - ALREADY-HELD if THIS session already holds an active reservation on that path —
660
+ * return its existing id, no duplicate insert. Exception: a read→write UPGRADE (this
661
+ * session holds a read lease and now asks for write) mutates the row's mode to
662
+ * 'write' in place and reports it as RESERVED, so the stronger lease is recorded.
663
+ * - otherwise RESERVE — insert this session's lease and return `{ id, path, mode }`.
664
+ * Paths pass through verbatim; the DB CHECK rejects absolute paths, and that error is
665
+ * surfaced cleanly by the try/catch. Requires an open session.
666
+ */
667
+ async function reserveWorkPathsHandler(client, session, args) {
668
+ try {
669
+ if (!session) {
670
+ return errorResult('reserve_work_paths needs an open work session — call begin_work first.');
671
+ }
672
+ const mode = args.mode ?? 'write';
673
+ const reserved = [];
674
+ const already_held = [];
675
+ const conflicts = [];
676
+ for (const path of args.paths) {
677
+ // Active reservations on this codebase+path, across ALL of the user's sessions
678
+ // (RLS scopes the read to the user's own rows).
679
+ const rows = (await must(client
680
+ .from('cliv2_work_reservations')
681
+ .select('id,session_id,mode')
682
+ .eq('git_remote_url', args.git_remote_url)
683
+ .eq('path', path)
684
+ .is('released_at', null))) ?? [];
685
+ // Conflict FIRST: another session holds an active lease AND at least one side is
686
+ // 'write' (write-write or write-read collide; read-read is fine).
687
+ const conflict = rows.find((r) => r.session_id !== session.sessionId && (r.mode === 'write' || mode === 'write'));
688
+ if (conflict) {
689
+ conflicts.push({ path, held_by_session_id: conflict.session_id });
690
+ continue;
691
+ }
692
+ // Else this session already has an active lease here. A read→write UPGRADE must
693
+ // record the write, else another session's later read would see no conflict and
694
+ // be cleared to read a file this session is rewriting. Reaching this branch with
695
+ // mode==='write' means the conflict check found NO other-session row on this path
696
+ // (with mode==='write' the conflict OR is true for ANY other-session row), so no
697
+ // other session holds it and upgrading in place is safe. A write→read downgrade or
698
+ // a same-mode repeat stays already-held.
699
+ const mine = rows.find((r) => r.session_id === session.sessionId);
700
+ if (mine) {
701
+ if (mine.mode === 'read' && mode === 'write') {
702
+ await must(client
703
+ .from('cliv2_work_reservations')
704
+ .update({ mode: 'write' })
705
+ .eq('id', mine.id)
706
+ .eq('session_id', session.sessionId)
707
+ .select('id')
708
+ .single());
709
+ reserved.push({ id: mine.id, path, mode: 'write' });
710
+ }
711
+ else {
712
+ already_held.push({ id: mine.id, path });
713
+ }
714
+ continue;
715
+ }
716
+ // Else reserve: free (or only compatible reads by others) — insert this
717
+ // session's lease. user_id defaults to auth.uid() in the DB; don't set it.
718
+ const inserted = await must(client
719
+ .from('cliv2_work_reservations')
720
+ .insert({
721
+ session_id: session.sessionId,
722
+ task_id: session.taskId,
723
+ git_remote_url: args.git_remote_url,
724
+ path,
725
+ mode,
726
+ })
727
+ .select('id,path,mode')
728
+ .single());
729
+ if (!inserted)
730
+ throw new Error('Reservation insert returned no row.');
731
+ reserved.push({ id: inserted.id, path: inserted.path, mode: inserted.mode });
732
+ }
733
+ return textResult({ reserved, already_held, conflicts });
734
+ }
735
+ catch (err) {
736
+ return errorResult(`reserve_work_paths failed: ${err.message}`);
737
+ }
738
+ }
739
+ /**
740
+ * Release path reservations by id (D5). Only THIS session's still-active reservations
741
+ * are released: the UPDATE is scoped by `session_id` (plus RLS to the user) and
742
+ * `released_at is null`, so ids belonging to another session, already-released rows, or
743
+ * unknown ids are silently no-ops. Returns the ids actually released. Requires an open
744
+ * session.
745
+ */
746
+ async function releaseWorkPathsHandler(client, session, args) {
747
+ try {
748
+ if (!session) {
749
+ return errorResult('release_work_paths needs an open work session — call begin_work first.');
750
+ }
751
+ const rows = (await must(client
752
+ .from('cliv2_work_reservations')
753
+ .update({ released_at: new Date().toISOString() })
754
+ .in('id', args.reservation_ids)
755
+ .eq('session_id', session.sessionId)
756
+ .is('released_at', null)
757
+ .select('id'))) ?? [];
758
+ return textResult({ released: rows.map((r) => r.id) });
759
+ }
760
+ catch (err) {
761
+ return errorResult(`release_work_paths failed: ${err.message}`);
762
+ }
763
+ }
764
+ /**
765
+ * Hand off coordination of a task to another of the CALLER'S OWN agent sessions (D5). One
766
+ * coordinator per task: the `cliv2_task_coordinators` row is keyed on (user_id, task_id)
767
+ * and UPSERTED to point at the target session. The target is validated to be one of the
768
+ * caller's own sessions first — `cliv2_agent_sessions` carries TWO select policies (owner
769
+ * AND task-read, the latter org-visible via `app.can_access_task`), so an RLS-only read
770
+ * would ALSO admit a teammate's session on a shared task (a confused-deputy seed whose
771
+ * `on delete cascade` could later nuke the caller's coordinator row). The lookup is
772
+ * therefore constrained to `user_id = userId`, not RLS alone. Run-free, owner-scoped
773
+ * (user_id defaults to auth.uid()). Requires an open session.
774
+ */
775
+ async function transferCoordinationHandler(client, userId, session, args) {
776
+ try {
777
+ if (!session) {
778
+ return errorResult('transfer_coordination needs an open work session — call begin_work first.');
779
+ }
780
+ // The target must be one of the CALLER'S OWN sessions. RLS alone is insufficient
781
+ // (the task-read policy would admit a teammate's session on a shared task), so pin
782
+ // the read to user_id = userId.
783
+ const target = await must(client
784
+ .from('cliv2_agent_sessions')
785
+ .select('id')
786
+ .eq('id', args.target_session_id)
787
+ .eq('user_id', userId)
788
+ .maybeSingle());
789
+ if (!target) {
790
+ return errorResult('target_session_id is not a session you can coordinate to.');
791
+ }
792
+ const coordinator = await must(client
793
+ .from('cliv2_task_coordinators')
794
+ .upsert({
795
+ task_id: args.task_id,
796
+ session_id: args.target_session_id,
797
+ updated_at: new Date().toISOString(),
798
+ }, { onConflict: 'user_id,task_id' })
799
+ .select('task_id,session_id,updated_at')
800
+ .single());
801
+ if (!coordinator)
802
+ throw new Error('Coordinator upsert returned no row.');
803
+ return textResult({ coordinator });
804
+ }
805
+ catch (err) {
806
+ return errorResult(`transfer_coordination failed: ${err.message}`);
807
+ }
808
+ }
809
+ /**
810
+ * Record that a codebase's checkout is unavailable to this session (D5) — e.g. it isn't
811
+ * cloned on this machine — with an optional reason. A plain owner-scoped insert into
812
+ * `cliv2_unavailable_checkouts`, stamped with the open session's id (user_id defaults to
813
+ * auth.uid()). Only a path-free git remote URL is stored — never a local filesystem path.
814
+ * Requires an open session.
815
+ */
816
+ async function acknowledgeUnavailableCheckoutHandler(client, session, args) {
817
+ try {
818
+ if (!session) {
819
+ return errorResult('acknowledge_unavailable_checkout needs an open work session — call begin_work first.');
820
+ }
821
+ const row = await must(client
822
+ .from('cliv2_unavailable_checkouts')
823
+ .insert({
824
+ session_id: session.sessionId,
825
+ git_remote_url: args.git_remote_url,
826
+ reason: args.reason ?? null,
827
+ })
828
+ .select('id,git_remote_url,reason,created_at')
829
+ .single());
830
+ if (!row)
831
+ throw new Error('Acknowledgement insert returned no row.');
832
+ return textResult({ acknowledgement: row });
833
+ }
834
+ catch (err) {
835
+ return errorResult(`acknowledge_unavailable_checkout failed: ${err.message}`);
836
+ }
837
+ }
838
+ // ---------------------------------------------------------------------------
839
+ // Credentials (feature 08, Phase 2) — agent MCP fetch. Read-only from the
840
+ // CLI's point of view: `list_credentials` lists names + kinds through the
841
+ // user-session client (RLS `credentials_select` scopes rows to the ones the
842
+ // signed-in user created, in orgs they belong to), and `get_credential`
843
+ // resolves a name case-insensitively then calls the SECURITY DEFINER
844
+ // `reveal_credential` RPC — the ONLY read path for the secret value. The
845
+ // secret goes into the tool RESULT and nowhere else: never console.log'd,
846
+ // never cached, never written to disk.
847
+ // ---------------------------------------------------------------------------
848
+ /** The uniform access error, verbatim from the web RPCs
849
+ * (20260723130000_credentials.sql) — a caller can never distinguish
850
+ * "doesn't exist" from "not yours". */
851
+ const CREDENTIAL_NOT_FOUND = 'credential not found or not accessible';
852
+ /**
853
+ * List the signed-in user's stored credentials — names + kinds ONLY, never
854
+ * values, secret ids, or row ids (ui.html screen 7).
855
+ */
856
+ async function listCredentialsHandler(client) {
857
+ try {
858
+ const rows = (await must(client.from('credentials').select('name, kind').order('name', { ascending: true }))) ?? [];
859
+ return textResult(rows.map((row) => ({ name: row.name, kind: row.kind })));
860
+ }
861
+ catch (err) {
862
+ return errorResult(`list_credentials failed: ${err.message}`);
863
+ }
864
+ }
865
+ /**
866
+ * Fetch one credential's decrypted value by name (ui.html screens 8–9).
867
+ * The name match is case-insensitive, like the web's uniqueness rule
868
+ * (`lower(name)`), and is done in JS over the caller's own RLS-visible rows
869
+ * (row counts are tiny; no pattern-injection surface). Unknown / inaccessible
870
+ * name → the exact uniform error above. On a match, `reveal_credential(p_id)`
871
+ * returns `{secret, username}`; that maps to screen 8's shapes —
872
+ * api_key → `{kind, secret}`, login → `{kind, username, password}`.
873
+ */
874
+ async function getCredentialHandler(client, args) {
875
+ let match;
876
+ try {
877
+ const rows = (await must(client
878
+ .from('credentials')
879
+ .select('id, name, kind, org_id, created_by')
880
+ .order('created_at', { ascending: true }))) ?? [];
881
+ const wanted = args.name.toLowerCase();
882
+ // Uniqueness is per (org, creator): the caller can see two credentials
883
+ // with the same lowercased name across two of their orgs, or within one
884
+ // org (their own plus one shared to them by another creator). Never guess
885
+ // which secret was meant. org_id/created_by are read only to word this
886
+ // error; they never appear in tool output.
887
+ const matches = rows.filter((row) => row.name.toLowerCase() === wanted);
888
+ if (matches.length > 1) {
889
+ const sameOrg = matches.every((row) => row.org_id === matches[0].org_id);
890
+ return errorResult(sameOrg
891
+ ? `credential name "${args.name}" is ambiguous — you can access more than one credential with this name in the same organization (e.g. your own and one shared with you); delete or re-create yours under a different name, or ask an org owner to revoke a shared copy`
892
+ : `credential name "${args.name}" is ambiguous — you have access to credentials with this name in more than one of your organizations; delete or re-create one under a different name`);
893
+ }
894
+ match = matches[0];
895
+ }
896
+ catch (err) {
897
+ return errorResult(`get_credential failed: ${err.message}`);
898
+ }
899
+ if (!match)
900
+ return errorResult(CREDENTIAL_NOT_FOUND);
901
+ try {
902
+ const revealed = await must(client.rpc('reveal_credential', { p_id: match.id }));
903
+ if (!revealed)
904
+ throw new Error(CREDENTIAL_NOT_FOUND);
905
+ return textResult(match.kind === 'login'
906
+ ? { kind: 'login', username: revealed.username, password: revealed.secret }
907
+ : { kind: 'api_key', secret: revealed.secret });
908
+ }
909
+ catch (err) {
910
+ // The RPC's own message, verbatim — it is already uniform (the same
911
+ // 'credential not found or not accessible' on any access failure).
912
+ return errorResult(err.message);
913
+ }
914
+ }
915
+ // ---------------------------------------------------------------------------
916
+ // The nineteen tools this server exposes. Exported for the self-check.
917
+ // ---------------------------------------------------------------------------
918
+ export const TOOL_NAMES = [
919
+ 'list_tasks',
920
+ 'get_task',
921
+ 'create_artifact',
922
+ 'update_task',
923
+ 'update_artifact',
924
+ 'set_task_role_slugs',
925
+ 'add_comment',
926
+ 'create_task',
927
+ 'begin_work',
928
+ 'end_work',
929
+ 'ask_question',
930
+ 'record_user_input',
931
+ 'record_context_exploration',
932
+ 'reserve_work_paths',
933
+ 'release_work_paths',
934
+ 'transfer_coordination',
935
+ 'acknowledge_unavailable_checkout',
936
+ 'list_credentials',
937
+ 'get_credential',
938
+ ];
939
+ /** Build a per-session McpServer with the nineteen tools. A fresh instance per
940
+ * session is what makes `server.server.getClientVersion()` (populated during
941
+ * that session's `initialize`) the right source for attribution — mirroring
942
+ * v1's per-session `buildServer`. `connectionId` is this connection's key into
943
+ * the module-level `openSessions` registry (D2b). */
944
+ export function buildToolsServer(client, userId, machineId, connectionId) {
945
+ const server = new McpServer({ name: 'ctrl-spc', version: '0.1.0' });
946
+ // The MCP connection's open work session lives in the module-level `openSessions`
947
+ // registry, keyed by this connection's `connectionId` (D2b). One McpServer is
948
+ // built per MCP connection (see startToolsServer's per-initialize buildToolsServer),
949
+ // so `connectionId` identifies exactly this agent's session: begin_work sets the
950
+ // entry; create_artifact / add_comment / create_task read it to attribute outputs;
951
+ // end_work (and connection-close / logout) clear it; the presence heartbeat keeps
952
+ // it fresh. Read the entry at call time so each tool sees the latest begin_work.
953
+ // This connection's agent, derived from the `initialize` clientInfo.name once
954
+ // it has been negotiated (/claude/i -> 'claude', /codex/i -> 'codex', else null).
955
+ const attribution = () => attributionFromClientName(server.server.getClientVersion()?.name);
956
+ server.registerTool('list_tasks', {
957
+ description: 'List the tasks in your CTRL+SPC projects, with project identity. Optionally filter to one project.',
958
+ inputSchema: { project_id: z.string().optional() },
959
+ }, async (args) => {
960
+ touchSession(connectionId);
961
+ return listTasksHandler(client, args);
962
+ });
963
+ server.registerTool('get_task', {
964
+ description: 'Read a full task — its tags, comments, artifacts, and decisions (so you can read the answers to questions ' +
965
+ 'you asked). Read-only; it has no status or presence side effects.',
966
+ inputSchema: { id: z.string().describe('Task id') },
967
+ }, async ({ id }) => {
968
+ touchSession(connectionId);
969
+ return getTaskHandler(client, { id });
970
+ });
971
+ server.registerTool('create_artifact', {
972
+ description: 'Create a titled analysis/plan/spec/diagram/mock/wireframe on a task. It appears in the web UI, attributed to you.',
973
+ inputSchema: {
974
+ task_id: z.string(),
975
+ type: z.enum(['analysis', 'plan', 'spec', 'diagram', 'mock', 'wireframe']),
976
+ format: z.enum(['md', 'html', 'json', 'svg']).optional().describe('Defaults to md'),
977
+ title: z.string().min(1).optional(),
978
+ purpose_key: z
979
+ .string()
980
+ .min(1)
981
+ .optional()
982
+ .describe('Stable machine-readable identity for this artifact purpose'),
983
+ content: z.string(),
984
+ },
985
+ }, async (args) => {
986
+ touchSession(connectionId);
987
+ return createArtifactHandler(client, userId, openSessions.get(connectionId) ?? null, args);
988
+ });
989
+ server.registerTool('update_task', {
990
+ description: 'Update a task you own — its status (backlog / in_progress / done), name, description, or due_date. ' +
991
+ 'Pass expected_revision from the most recent get_task for optimistic concurrency; on a conflict, ' +
992
+ 'call get_task again to re-read and retry. The change appears in the web board.',
993
+ inputSchema: {
994
+ id: z.string().describe('Task id'),
995
+ expected_revision: z
996
+ .number()
997
+ .int()
998
+ .positive()
999
+ .describe('The task revision from the most recent get_task (optimistic concurrency)'),
1000
+ fields: z.object({
1001
+ status: z.enum(['backlog', 'in_progress', 'done']).optional(),
1002
+ name: z.string().optional(),
1003
+ description: z.string().optional(),
1004
+ due_date: z.string().nullable().optional().describe('ISO date, or null to clear'),
1005
+ }),
1006
+ },
1007
+ }, async (args) => {
1008
+ touchSession(connectionId);
1009
+ return updateTaskHandler(client, args);
1010
+ });
1011
+ server.registerTool('update_artifact', {
1012
+ description: 'Edit an artifact you can access — its title, content, type, or format. Pass expected_revision from the ' +
1013
+ 'most recent get_task (optimistic concurrency); on a conflict, call get_task again and retry. ' +
1014
+ 'The change appears in the web UI.',
1015
+ inputSchema: {
1016
+ id: z.string(),
1017
+ expected_revision: z
1018
+ .number()
1019
+ .int()
1020
+ .positive()
1021
+ .describe('The artifact revision from the most recent get_task (optimistic concurrency)'),
1022
+ fields: z.object({
1023
+ title: z.string().min(1).optional(),
1024
+ type: z.enum(['analysis', 'plan', 'spec', 'diagram', 'mock', 'wireframe']).optional(),
1025
+ format: z.enum(['md', 'html', 'json', 'svg']).optional(),
1026
+ content: z.string().optional(),
1027
+ }),
1028
+ },
1029
+ }, async (args) => {
1030
+ touchSession(connectionId);
1031
+ return updateArtifactHandler(client, args);
1032
+ });
1033
+ server.registerTool('set_task_role_slugs', {
1034
+ description: 'Set the repository role slugs on a task (its role assignments). Replaces the task\'s role_slugs with ' +
1035
+ 'the given list. The change appears in the web UI.',
1036
+ inputSchema: {
1037
+ task_id: z.string(),
1038
+ role_slugs: z.array(z.string()),
1039
+ },
1040
+ }, async (args) => {
1041
+ touchSession(connectionId);
1042
+ return setTaskRoleSlugsHandler(client, args);
1043
+ });
1044
+ server.registerTool('add_comment', {
1045
+ description: 'Leave a note on a task. The comment appears in the web UI, authored by you.',
1046
+ inputSchema: {
1047
+ task_id: z.string().describe('Task id'),
1048
+ body: z.string().min(1),
1049
+ },
1050
+ }, async (args) => {
1051
+ touchSession(connectionId);
1052
+ return addCommentHandler(client, userId, openSessions.get(connectionId) ?? null, args);
1053
+ });
1054
+ server.registerTool('create_task', {
1055
+ description: 'Create a new task in one of your projects — for splitting work or leaving follow-ups. ' +
1056
+ 'It appears on the web board, owned by you.',
1057
+ inputSchema: {
1058
+ project_id: z.string().describe('Project id the task belongs to'),
1059
+ name: z.string().min(1),
1060
+ description: z.string().optional(),
1061
+ },
1062
+ }, async (args) => {
1063
+ touchSession(connectionId);
1064
+ return createTaskHandler(client, userId, openSessions.get(connectionId) ?? null, args);
1065
+ });
1066
+ server.registerTool('begin_work', {
1067
+ description: 'Open a work session on a task so the outputs you create afterward are attributed to this run. ' +
1068
+ 'Call it once, before create_artifact, for the task you are about to work. ' +
1069
+ 'Requires a supported agent (Claude or Codex). Reusing the same task returns the existing session.',
1070
+ inputSchema: {
1071
+ task_id: z.string().describe('Task id you are about to work on'),
1072
+ model: z.string().optional().describe('Optional model identifier for this session (e.g. the agent model)'),
1073
+ },
1074
+ }, async (args) => {
1075
+ touchSession(connectionId);
1076
+ try {
1077
+ // begin_work needs a supported agent — the session's `provider` is a NOT
1078
+ // NULL, checked ('claude'|'codex') column. An unrecognized client can't
1079
+ // open one.
1080
+ const provider = attribution();
1081
+ if (!provider) {
1082
+ return errorResult('begin_work needs a supported agent (Claude or Codex); this client is not recognized as one.');
1083
+ }
1084
+ // The task must exist and be live under the user's RLS.
1085
+ const task = await must(client.from('tasks').select('id').eq('id', args.task_id).is('archived_at', null).maybeSingle());
1086
+ if (!task)
1087
+ return errorResult(`No task found for id "${args.task_id}".`);
1088
+ // Already have a session on THIS connection for THIS task: refresh its
1089
+ // liveness (and model, if newly provided) and reuse it — no second row.
1090
+ const prev = openSessions.get(connectionId);
1091
+ if (prev && prev.taskId === args.task_id) {
1092
+ const patch = { last_seen_at: new Date().toISOString() };
1093
+ if (args.model !== undefined)
1094
+ patch.model = args.model;
1095
+ const updated = await must(client
1096
+ .from('cliv2_agent_sessions')
1097
+ .update(patch)
1098
+ .eq('id', prev.sessionId)
1099
+ .select('id,task_id,provider,model,status')
1100
+ .single());
1101
+ if (!updated)
1102
+ throw new Error('Session update returned no row.');
1103
+ return textResult({ session: updated });
1104
+ }
1105
+ // Open the NEW session FIRST (FIX 3): if this insert throws, the registry
1106
+ // still points at the previous (valid) session rather than an ended one.
1107
+ // `prev`, if present here, is on a DIFFERENT task (same-task returned above).
1108
+ const session = await must(client
1109
+ .from('cliv2_agent_sessions')
1110
+ .insert({
1111
+ user_id: userId,
1112
+ machine_id: machineId,
1113
+ task_id: args.task_id,
1114
+ provider,
1115
+ model: args.model ?? null,
1116
+ status: 'active',
1117
+ })
1118
+ .select('id,task_id,provider,model,status')
1119
+ .single());
1120
+ if (!session)
1121
+ throw new Error('Session insert returned no row.');
1122
+ // The new session opened: if this connection was on a DIFFERENT task,
1123
+ // best-effort mark that PREVIOUS session ended so its board "working" chip
1124
+ // clears promptly. Best-effort — a failure must NOT fail begin_work (the new
1125
+ // session is the real result); the old row lapses via its own TTL/freshness.
1126
+ if (prev) {
1127
+ try {
1128
+ await must(client.from('cliv2_agent_sessions').update({ status: 'ended' }).eq('id', prev.sessionId));
1129
+ }
1130
+ catch (err) {
1131
+ console.warn(`begin_work: ending previous session failed: ${err.message}`);
1132
+ }
1133
+ }
1134
+ // Record the new session in the registry keyed by connectionId, with a
1135
+ // fresh activity-TTL (extended by every subsequent tool call).
1136
+ openSessions.set(connectionId, {
1137
+ sessionId: session.id,
1138
+ taskId: session.task_id,
1139
+ expiresAt: Date.now() + SESSION_TTL_MS,
1140
+ });
1141
+ return textResult({ session });
1142
+ }
1143
+ catch (err) {
1144
+ return errorResult(`begin_work failed: ${err.message}`);
1145
+ }
1146
+ });
1147
+ server.registerTool('end_work', {
1148
+ description: 'Close the work session you opened with begin_work, when you finish the item. ' +
1149
+ 'After this, the board no longer shows you as working it. Safe to call with no open session.',
1150
+ inputSchema: {},
1151
+ }, async () => {
1152
+ touchSession(connectionId);
1153
+ try {
1154
+ const s = openSessions.get(connectionId);
1155
+ if (!s) {
1156
+ return textResult({ ended: false, message: 'No open work session on this connection.' });
1157
+ }
1158
+ await must(client.from('cliv2_agent_sessions').update({ status: 'ended' }).eq('id', s.sessionId));
1159
+ openSessions.delete(connectionId);
1160
+ return textResult({ ended: true, session_id: s.sessionId });
1161
+ }
1162
+ catch (err) {
1163
+ return errorResult(`end_work failed: ${err.message}`);
1164
+ }
1165
+ });
1166
+ server.registerTool('ask_question', {
1167
+ description: "Ask the user a question about the work item you're on. It appears as a decision on the item in the web UI; " +
1168
+ 'the user answers it there, and you read the answer back with get_task. Requires an open session (begin_work).',
1169
+ inputSchema: {
1170
+ category: z.string().min(1),
1171
+ context: z.string().min(1),
1172
+ question: z.string().min(1),
1173
+ answer_mode: z.enum(['free_text', 'single_select', 'multi_select']).optional(),
1174
+ options: z.array(z.string()).optional(),
1175
+ related_artifact_id: z.string().optional(),
1176
+ },
1177
+ }, async (args) => {
1178
+ touchSession(connectionId);
1179
+ return askQuestionHandler(client, userId, openSessions.get(connectionId) ?? null, args);
1180
+ });
1181
+ server.registerTool('record_user_input', {
1182
+ description: "Record the user's answer to an open decision on your work item (e.g. an answer they gave you directly). " +
1183
+ 'Updates the decision to decided; it then shows answered in the web UI.',
1184
+ inputSchema: {
1185
+ decision_id: z.string().describe('The decision id to answer'),
1186
+ answer: z.string().optional().describe('The free-text answer (for a free_text decision)'),
1187
+ selected_options: z
1188
+ .array(z.string())
1189
+ .optional()
1190
+ .describe('The chosen option(s) (for a single_select / multi_select decision)'),
1191
+ answer_note: z.string().optional().describe('Optional note alongside a choice answer'),
1192
+ },
1193
+ }, async (args) => {
1194
+ touchSession(connectionId);
1195
+ return recordUserInputHandler(client, openSessions.get(connectionId) ?? null, args);
1196
+ });
1197
+ server.registerTool('record_context_exploration', {
1198
+ description: "Record what you explored for this work item as its context document (the canonical 'Work item context' " +
1199
+ 'for the item). Repeated calls update the same document. Appears in the web UI.',
1200
+ inputSchema: {
1201
+ content: z.string().min(1),
1202
+ },
1203
+ }, async (args) => {
1204
+ touchSession(connectionId);
1205
+ return recordContextExplorationHandler(client, userId, openSessions.get(connectionId) ?? null, args);
1206
+ });
1207
+ server.registerTool('reserve_work_paths', {
1208
+ description: "Reserve repo-relative paths you're about to edit on a codebase, so concurrent agents don't collide. " +
1209
+ 'Conflicts (a write lease another session holds) are reported, not forced. ' +
1210
+ 'Paths must be repo-relative, never absolute.',
1211
+ inputSchema: {
1212
+ git_remote_url: z.string().min(1),
1213
+ paths: z.array(z.string().min(1)).min(1),
1214
+ mode: z.enum(['read', 'write']).optional().describe('Defaults to write'),
1215
+ },
1216
+ }, async (args) => {
1217
+ touchSession(connectionId);
1218
+ return reserveWorkPathsHandler(client, openSessions.get(connectionId) ?? null, args);
1219
+ });
1220
+ server.registerTool('release_work_paths', {
1221
+ description: 'Release path reservations you previously made (by id). Only your own active reservations are released.',
1222
+ inputSchema: {
1223
+ reservation_ids: z.array(z.string()).min(1),
1224
+ },
1225
+ }, async (args) => {
1226
+ touchSession(connectionId);
1227
+ return releaseWorkPathsHandler(client, openSessions.get(connectionId) ?? null, args);
1228
+ });
1229
+ server.registerTool('transfer_coordination', {
1230
+ description: 'Hand off coordination of a task to another of your agent sessions (by session id). One coordinator per task.',
1231
+ inputSchema: {
1232
+ task_id: z.string(),
1233
+ target_session_id: z.string(),
1234
+ },
1235
+ }, async (args) => {
1236
+ touchSession(connectionId);
1237
+ return transferCoordinationHandler(client, userId, openSessions.get(connectionId) ?? null, args);
1238
+ });
1239
+ server.registerTool('acknowledge_unavailable_checkout', {
1240
+ description: "Record that a codebase's checkout is unavailable to you (e.g. not cloned on this machine), with an optional reason.",
1241
+ inputSchema: {
1242
+ git_remote_url: z.string().min(1),
1243
+ reason: z.string().optional(),
1244
+ },
1245
+ }, async (args) => {
1246
+ touchSession(connectionId);
1247
+ return acknowledgeUnavailableCheckoutHandler(client, openSessions.get(connectionId) ?? null, args);
1248
+ });
1249
+ server.registerTool('list_credentials', {
1250
+ description: 'List the credentials the user has stored in CTRL+SPC — the names (and kinds: api_key or login) you can ' +
1251
+ 'fetch a value for with get_credential. Names and kinds only, never values.',
1252
+ inputSchema: {},
1253
+ }, async () => {
1254
+ touchSession(connectionId);
1255
+ return listCredentialsHandler(client);
1256
+ });
1257
+ server.registerTool('get_credential', {
1258
+ description: "Fetch a stored credential's value by name (case-insensitive): an api_key's secret, or a login's " +
1259
+ 'username + password. The value is for runtime use in this session only — never write it into a file, ' +
1260
+ 'commit, log, or code, and never echo it back to the user unless they explicitly ask for it.',
1261
+ inputSchema: {
1262
+ name: z.string().min(1).describe('Credential name, as listed by list_credentials'),
1263
+ },
1264
+ }, async (args) => {
1265
+ touchSession(connectionId);
1266
+ return getCredentialHandler(client, args);
1267
+ });
1268
+ return server;
1269
+ }
1270
+ let handle = null;
1271
+ // D2b: the open work session per live MCP connection, so the presence
1272
+ // heartbeat can keep it fresh and connection-close / logout can end it. Each
1273
+ // entry carries an activity-TTL `expiresAt` (ms epoch): begin_work sets it and
1274
+ // EVERY tool call extends it (touchSession), because a tool call proves the
1275
+ // agent is alive. The companion — not the agent — drives the heartbeat, and the
1276
+ // MCP SDK only fires transport.onclose on an explicit DELETE / server stop (NOT
1277
+ // on Ctrl-C / crash / kill / sleep). Without the TTL a dead agent would stay
1278
+ // "working" forever; heartbeatOpenSessions instead lapses an entry once its TTL
1279
+ // passes, flipping the row to 'ended' so the board chip clears.
1280
+ const openSessions = new Map();
1281
+ let toolsClient = null;
1282
+ /** Extend the activity-TTL of this connection's open session, if any. Called at
1283
+ * the very start of every tool callback — any tool call proves the agent is
1284
+ * alive, so its session should stay "working" for another TTL window. No-op when
1285
+ * no session is open. */
1286
+ function touchSession(connectionId) {
1287
+ const s = openSessions.get(connectionId);
1288
+ if (s)
1289
+ s.expiresAt = Date.now() + SESSION_TTL_MS;
1290
+ }
1291
+ /** Set (or replace) the module client the session-lifecycle helpers use, so a
1292
+ * token the presence loop rebuilt after a wedge/refresh flows into the session
1293
+ * heartbeat too (FIX 2 — the CLI-v1 stale-token root cause). Only takes effect
1294
+ * while the tools server is running; the per-connection tool handlers keep their
1295
+ * own captured client, which is acceptable — the session heartbeat is what must
1296
+ * stay healthy for the presence chip. */
1297
+ export function setToolsClient(client) {
1298
+ if (handle)
1299
+ toolsClient = client;
1300
+ }
1301
+ /** Keep every LIVE open session's last_seen_at fresh, and lapse EXPIRED ones to
1302
+ * 'ended', so the web presence chip stays lit while an agent works and clears
1303
+ * once it goes quiet past its TTL (finished / Ctrl-C'd / crashed / asleep).
1304
+ * Called from the presence heartbeat. Partitions the registry by `expiresAt`,
1305
+ * deletes expired entries locally, then does up to two batched best-effort
1306
+ * writes. `.eq('status','active')` keeps end_work / onclose races safe (never
1307
+ * re-touches or re-ends a row another path already ended). Never throws. */
1308
+ export async function heartbeatOpenSessions() {
1309
+ if (!toolsClient || openSessions.size === 0)
1310
+ return;
1311
+ const now = Date.now();
1312
+ const liveIds = [];
1313
+ const expiredIds = [];
1314
+ for (const [connectionId, s] of openSessions) {
1315
+ if (now < s.expiresAt) {
1316
+ liveIds.push(s.sessionId);
1317
+ }
1318
+ else {
1319
+ expiredIds.push(s.sessionId);
1320
+ openSessions.delete(connectionId);
1321
+ }
1322
+ }
1323
+ if (liveIds.length) {
1324
+ try {
1325
+ const { error } = await toolsClient
1326
+ .from('cliv2_agent_sessions')
1327
+ .update({ last_seen_at: new Date().toISOString() })
1328
+ .in('id', liveIds)
1329
+ .eq('status', 'active');
1330
+ if (error)
1331
+ throw error;
1332
+ }
1333
+ catch (err) {
1334
+ console.warn(`open-session heartbeat failed, will retry: ${err.message}`);
1335
+ }
1336
+ }
1337
+ if (expiredIds.length) {
1338
+ try {
1339
+ const { error } = await toolsClient
1340
+ .from('cliv2_agent_sessions')
1341
+ .update({ status: 'ended' })
1342
+ .in('id', expiredIds)
1343
+ .eq('status', 'active');
1344
+ if (error)
1345
+ throw error;
1346
+ }
1347
+ catch (err) {
1348
+ console.warn(`lapsing expired sessions failed: ${err.message}`);
1349
+ }
1350
+ }
1351
+ }
1352
+ /** Mark ONE connection's open session ended (connection closed). Best-effort. */
1353
+ export async function endConnectionSession(connectionId) {
1354
+ const s = openSessions.get(connectionId);
1355
+ if (!toolsClient || !s) {
1356
+ openSessions.delete(connectionId);
1357
+ return;
1358
+ }
1359
+ openSessions.delete(connectionId);
1360
+ try {
1361
+ const { error } = await toolsClient
1362
+ .from('cliv2_agent_sessions')
1363
+ .update({ status: 'ended' })
1364
+ .eq('id', s.sessionId);
1365
+ if (error)
1366
+ throw error;
1367
+ }
1368
+ catch (err) {
1369
+ console.warn(`ending session on connection close failed: ${err.message}`);
1370
+ }
1371
+ }
1372
+ /** Mark ALL open sessions ended and clear the registry (server stop / logout). */
1373
+ export async function endAllOpenSessions() {
1374
+ if (openSessions.size === 0) {
1375
+ return;
1376
+ }
1377
+ const sessionIds = [...openSessions.values()].map((s) => s.sessionId);
1378
+ openSessions.clear();
1379
+ if (!toolsClient)
1380
+ return;
1381
+ try {
1382
+ const { error } = await toolsClient
1383
+ .from('cliv2_agent_sessions')
1384
+ .update({ status: 'ended' })
1385
+ .in('id', sessionIds);
1386
+ if (error)
1387
+ throw error;
1388
+ }
1389
+ catch (err) {
1390
+ console.warn(`ending all open sessions failed: ${err.message}`);
1391
+ }
1392
+ }
1393
+ async function readJsonBody(req) {
1394
+ const chunks = [];
1395
+ for await (const chunk of req)
1396
+ chunks.push(chunk);
1397
+ const raw = Buffer.concat(chunks).toString('utf8');
1398
+ return raw ? JSON.parse(raw) : undefined;
1399
+ }
1400
+ /** Start the local tools server. No-op if already running. Binds loopback-only;
1401
+ * rejects if the port is taken (caller treats a failure as best-effort). */
1402
+ export async function startToolsServer(deps) {
1403
+ if (handle)
1404
+ return;
1405
+ // D2b: capture the client so the session-lifecycle helpers (heartbeat / end)
1406
+ // can reach Supabase without a live MCP connection in hand.
1407
+ toolsClient = deps.client;
1408
+ const port = TOOLS_SERVER_PORT;
1409
+ const sessions = new Map();
1410
+ async function handleHttp(req, res) {
1411
+ const url = new URL(req.url ?? '/', 'http://localhost');
1412
+ if (url.pathname === '/health' && req.method === 'GET') {
1413
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
1414
+ res.end(JSON.stringify({ status: 'ok', server: 'ctrl-spc', process_id: process.pid }));
1415
+ return;
1416
+ }
1417
+ if (url.pathname !== '/mcp') {
1418
+ res.writeHead(404).end('Not found');
1419
+ return;
1420
+ }
1421
+ try {
1422
+ const sessionIdHeader = req.headers['mcp-session-id'];
1423
+ const sessionId = typeof sessionIdHeader === 'string' ? sessionIdHeader : undefined;
1424
+ const existing = sessionId ? sessions.get(sessionId) : undefined;
1425
+ if (existing) {
1426
+ await existing.handleRequest(req, res);
1427
+ return;
1428
+ }
1429
+ if (req.method !== 'POST') {
1430
+ res.writeHead(400, { 'Content-Type': 'text/plain' }).end('Bad Request: no valid session ID provided');
1431
+ return;
1432
+ }
1433
+ const body = await readJsonBody(req);
1434
+ if (!isInitializeRequest(body)) {
1435
+ res.writeHead(400, { 'Content-Type': 'text/plain' }).end('Bad Request: no valid session ID provided');
1436
+ return;
1437
+ }
1438
+ const transport = new StreamableHTTPServerTransport({
1439
+ sessionIdGenerator: () => randomUUID(),
1440
+ onsessioninitialized: (sid) => {
1441
+ sessions.set(sid, transport);
1442
+ },
1443
+ // Same DNS-rebinding guard as v1: reject any Host header that isn't the
1444
+ // loopback address we actually bound, so a page on a public domain that
1445
+ // re-resolves to 127.0.0.1 can't drive this server from the browser.
1446
+ enableDnsRebindingProtection: true,
1447
+ allowedHosts: [`localhost:${port}`, `127.0.0.1:${port}`],
1448
+ });
1449
+ // D2b: one connectionId per MCP connection, keying this connection's entry
1450
+ // in openSessions. Generated before building the server so begin_work and
1451
+ // onclose share the same key.
1452
+ const connectionId = randomUUID();
1453
+ transport.onclose = () => {
1454
+ const sid = transport.sessionId;
1455
+ if (sid)
1456
+ sessions.delete(sid);
1457
+ // Connection dropped: end this connection's open session (best-effort).
1458
+ void endConnectionSession(connectionId);
1459
+ };
1460
+ const server = buildToolsServer(deps.client, deps.userId, deps.machineId, connectionId);
1461
+ await server.connect(transport);
1462
+ await transport.handleRequest(req, res, body);
1463
+ }
1464
+ catch (err) {
1465
+ if (!res.headersSent) {
1466
+ res
1467
+ .writeHead(500, { 'Content-Type': 'application/json' })
1468
+ .end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32603, message: err.message }, id: null }));
1469
+ }
1470
+ }
1471
+ }
1472
+ const httpServer = createHttpServer((req, res) => void handleHttp(req, res));
1473
+ // Bind loopback-only (never all interfaces) and turn the EADDRINUSE 'error'
1474
+ // race into a rejected promise so the caller stays best-effort.
1475
+ await new Promise((resolve, reject) => {
1476
+ const onError = (err) => {
1477
+ httpServer.off('listening', onListening);
1478
+ reject(err);
1479
+ };
1480
+ const onListening = () => {
1481
+ httpServer.off('error', onError);
1482
+ resolve();
1483
+ };
1484
+ httpServer.once('error', onError);
1485
+ httpServer.once('listening', onListening);
1486
+ httpServer.listen(port, '127.0.0.1');
1487
+ });
1488
+ handle = {
1489
+ async close() {
1490
+ await Promise.all([...sessions.values()].map((t) => t.close().catch(() => { })));
1491
+ sessions.clear();
1492
+ await new Promise((resolve, reject) => {
1493
+ httpServer.close((err) => (err ? reject(err) : resolve()));
1494
+ });
1495
+ },
1496
+ };
1497
+ }
1498
+ /** Stop the tools server. Best-effort; safe to call when not running. */
1499
+ export async function stopToolsServer() {
1500
+ const h = handle;
1501
+ if (!h)
1502
+ return;
1503
+ handle = null;
1504
+ regStatus.claude = 'idle';
1505
+ regStatus.codex = 'idle';
1506
+ // D2b: flip every open work session to ended (this needs toolsClient) BEFORE
1507
+ // dropping the client reference, so the board's "working" chips clear on server
1508
+ // stop / logout; then release the client alongside the reg-status resets.
1509
+ await endAllOpenSessions();
1510
+ toolsClient = null;
1511
+ await h.close();
1512
+ }
1513
+ /** Whether the tools server is currently listening, and its fixed port. */
1514
+ export function toolsServerStatus() {
1515
+ return { running: handle !== null, port: TOOLS_SERVER_PORT };
1516
+ }
1517
+ const regStatus = { claude: 'idle', codex: 'idle' };
1518
+ /**
1519
+ * Per-agent SERIAL operation chain. register and unregister for the same agent
1520
+ * must never interleave. `runRegister` does a slow (~7s) `mcp remove` then
1521
+ * `mcp add`; a logout `unregisterFromX` issues its own `mcp remove`. With no
1522
+ * ordering, an in-flight register's `add` can land AFTER logout's `remove`,
1523
+ * re-writing a dead `ctrl-spc` entry into the agent config after the tools
1524
+ * server is already gone — the exact dangling entry this feature prevents.
1525
+ * Enqueuing every register/unregister onto this chain forces them to run in call
1526
+ * order, so a logout queued mid-register runs AFTER the register's `add`
1527
+ * completes → the entry ends up removed. Both queued ops never throw
1528
+ * (`runRegister` and `actualUnregister` catch internally), so the chain always
1529
+ * stays resolved.
1530
+ */
1531
+ const opChain = {
1532
+ claude: Promise.resolve(),
1533
+ codex: Promise.resolve(),
1534
+ };
1535
+ const execFileAsync = promisify(execFile);
1536
+ /** Snapshot of each agent's registration lifecycle state (copy — callers can't
1537
+ * mutate the module's map). Drives the companion's connecting/connected/failed
1538
+ * badge (see badgeReason). */
1539
+ export function agentRegStatus() {
1540
+ return { ...regStatus };
1541
+ }
1542
+ /** True once the ctrl-spc server has been registered into Claude this run. */
1543
+ export function isClaudeRegistered() {
1544
+ return regStatus.claude === 'registered';
1545
+ }
1546
+ /** True once the ctrl-spc server has been registered into Codex this run. */
1547
+ export function isCodexRegistered() {
1548
+ return regStatus.codex === 'registered';
1549
+ }
1550
+ /** The remove-then-add itself, run in the background off a fire-and-forget
1551
+ * register call. Ignores the remove result (a not-found exits non-zero), then
1552
+ * runs the add: success → 'registered', any error/timeout → 'failed'. Never
1553
+ * throws — it's caught here and reflected only in regStatus. */
1554
+ async function runRegister(agent, bin, removeArgs, addArgs) {
1555
+ try {
1556
+ await execFileAsync(bin, removeArgs, { timeout: 15000 });
1557
+ }
1558
+ catch {
1559
+ /* not registered yet — fine */
1560
+ }
1561
+ try {
1562
+ await execFileAsync(bin, addArgs, { timeout: 15000 });
1563
+ regStatus[agent] = 'registered';
1564
+ }
1565
+ catch (err) {
1566
+ console.warn(`Could not register ctrl-spc tools with ${agent}: ${err.message}`);
1567
+ regStatus[agent] = 'failed';
1568
+ }
1569
+ }
1570
+ /**
1571
+ * Register the running tools server into Claude Code's user config. Non-blocking:
1572
+ * resolves the `claude` binary the same way agents.ts does, marks 'registering'
1573
+ * synchronously, then kicks off the async remove-then-add and returns immediately
1574
+ * (the CLI's ~7s latency runs off the event loop, so sign-in no longer freezes).
1575
+ * Best-effort — never throws. Registers the loopback `/mcp` endpoint (the only
1576
+ * path handleHttp serves the MCP protocol on). Only that loopback URL reaches the
1577
+ * LOCAL `~/.claude.json`; no absolute filesystem path and nothing cloud-bound is
1578
+ * written.
1579
+ */
1580
+ export function registerWithClaude(port) {
1581
+ const bin = agentPath('claude');
1582
+ if (!bin) {
1583
+ regStatus.claude = 'failed';
1584
+ return;
1585
+ }
1586
+ // Double-kick guard: a register is already queued/in-flight for this agent, so
1587
+ // don't enqueue a second one. This makes the heartbeat retry (presence.ts) safe
1588
+ // to fire every tick — it can't stack a second `mcp add` while one is running.
1589
+ if (regStatus.claude === 'registering')
1590
+ return;
1591
+ regStatus.claude = 'registering';
1592
+ const target = `http://127.0.0.1:${port}/mcp`;
1593
+ opChain.claude = opChain.claude.then(() => runRegister('claude', bin, ['mcp', 'remove', '--scope', 'user', 'ctrl-spc'], ['mcp', 'add', '--scope', 'user', '--transport', 'http', 'ctrl-spc', target]));
1594
+ }
1595
+ /**
1596
+ * Register the running tools server into Codex's config (Phase 2). Codex's
1597
+ * `mcp add` is global (no `--scope`) and takes `--url` for a streamable HTTP
1598
+ * server: `codex mcp add <name> --url <url>` / `codex mcp remove <name>`. Same
1599
+ * non-blocking, best-effort, idempotent contract as Claude's.
1600
+ */
1601
+ export function registerWithCodex(port) {
1602
+ const bin = agentPath('codex');
1603
+ if (!bin) {
1604
+ regStatus.codex = 'failed';
1605
+ return;
1606
+ }
1607
+ // Double-kick guard — see registerWithClaude.
1608
+ if (regStatus.codex === 'registering')
1609
+ return;
1610
+ regStatus.codex = 'registering';
1611
+ const target = `http://127.0.0.1:${port}/mcp`;
1612
+ opChain.codex = opChain.codex.then(() => runRegister('codex', bin, ['mcp', 'remove', 'ctrl-spc'], ['mcp', 'add', 'ctrl-spc', '--url', target]));
1613
+ }
1614
+ /** The actual `mcp remove` for logout cleanup, run ON the agent's op chain so it
1615
+ * can never interleave with an in-flight register's `add`. Best-effort — swallows
1616
+ * errors and always lands the status back at 'idle'. Never throws (keeps the
1617
+ * chain resolved). Claude's remove is user-scoped; Codex's is global. */
1618
+ async function actualUnregister(agent) {
1619
+ const bin = agentPath(agent);
1620
+ if (bin) {
1621
+ const removeArgs = agent === 'claude'
1622
+ ? ['mcp', 'remove', '--scope', 'user', 'ctrl-spc']
1623
+ : ['mcp', 'remove', 'ctrl-spc'];
1624
+ try {
1625
+ await execFileAsync(bin, removeArgs, { timeout: 15000 });
1626
+ }
1627
+ catch {
1628
+ /* best-effort — a leftover entry is the pre-fix state */
1629
+ }
1630
+ }
1631
+ regStatus[agent] = 'idle';
1632
+ }
1633
+ /**
1634
+ * Remove the ctrl-spc entry from Claude's user config (logout cleanup). Enqueues
1635
+ * the removal on the SAME per-agent op chain as register and returns that promise,
1636
+ * so a logout queued while a register is in flight runs AFTER the register's `add`
1637
+ * completes → the entry ends up removed (never re-written after the server is
1638
+ * gone). Best-effort — swallows errors and always lands the status back at 'idle',
1639
+ * so a logged-out machine leaves no dead ctrl-spc server that would show "failed to
1640
+ * connect" the next time the user runs an agent. If Claude isn't installed there's
1641
+ * nothing to remove; the status is reset regardless.
1642
+ */
1643
+ export function unregisterFromClaude() {
1644
+ return (opChain.claude = opChain.claude.then(() => actualUnregister('claude')));
1645
+ }
1646
+ /** Remove the ctrl-spc entry from Codex's config (logout cleanup). Same op-chain
1647
+ * ordering, best-effort, reset-to-'idle' contract as Claude's. */
1648
+ export function unregisterFromCodex() {
1649
+ return (opChain.codex = opChain.codex.then(() => actualUnregister('codex')));
1650
+ }
1651
+ const CAP = { claude: 'Claude', codex: 'Codex' };
1652
+ /**
1653
+ * Decide the badge state from the live signals:
1654
+ * - not signed in → signed-out
1655
+ * - no supported agent installed → no-agent
1656
+ * - tools server not running → failed
1657
+ * - any installed agent still idle/registering → connecting (lists all installed)
1658
+ * - else any registered → connected (lists the registered ones)
1659
+ * - else (all installed failed) → failed
1660
+ */
1661
+ export function badgeReason(input) {
1662
+ const server = 'ctrl-spc';
1663
+ const { signedIn, installed, serverRunning, status } = input;
1664
+ if (!signedIn)
1665
+ return { connected: false, reason: 'signed-out', agent: '', server };
1666
+ if (installed.length === 0)
1667
+ return { connected: false, reason: 'no-agent', agent: '', server };
1668
+ if (!serverRunning)
1669
+ return { connected: false, reason: 'failed', agent: '', server };
1670
+ const pending = installed.filter((a) => status[a] === 'registering' || status[a] === 'idle');
1671
+ const registered = installed.filter((a) => status[a] === 'registered');
1672
+ if (pending.length) {
1673
+ return { connected: false, reason: 'connecting', agent: installed.map((a) => CAP[a]).join(', '), server };
1674
+ }
1675
+ if (registered.length) {
1676
+ return { connected: true, reason: 'connected', agent: registered.map((a) => CAP[a]).join(', '), server };
1677
+ }
1678
+ return { connected: false, reason: 'failed', agent: '', server };
1679
+ }