@tacitai/mcp-server 0.7.0 → 0.8.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.
Files changed (58) hide show
  1. package/dist/api-errors.d.ts +102 -0
  2. package/dist/api-errors.js +165 -0
  3. package/dist/autonomy.d.ts +46 -0
  4. package/dist/autonomy.js +118 -0
  5. package/dist/claude-config.d.ts +139 -0
  6. package/dist/claude-config.js +339 -0
  7. package/dist/cli-launch.d.ts +33 -0
  8. package/dist/cli-launch.js +178 -0
  9. package/dist/cli-login.d.ts +34 -0
  10. package/dist/cli-login.js +200 -0
  11. package/dist/cli-mode.d.ts +47 -0
  12. package/dist/cli-mode.js +170 -0
  13. package/dist/cli-profiles.d.ts +37 -0
  14. package/dist/cli-profiles.js +344 -0
  15. package/dist/cli.d.ts +9 -0
  16. package/dist/cli.js +59 -458
  17. package/dist/client.d.ts +88 -52
  18. package/dist/client.js +195 -295
  19. package/dist/credentials.d.ts +81 -0
  20. package/dist/credentials.js +291 -0
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +37 -89
  23. package/dist/oauth.d.ts +1 -1
  24. package/dist/oauth.js +5 -5
  25. package/dist/profile-store.d.ts +96 -0
  26. package/dist/profile-store.js +382 -0
  27. package/dist/prompt.d.ts +32 -0
  28. package/dist/prompt.js +99 -0
  29. package/dist/prompts.d.ts +2 -2
  30. package/dist/prompts.js +3 -3
  31. package/dist/server-mode.d.ts +65 -0
  32. package/dist/server-mode.js +99 -0
  33. package/dist/setup-migrate.d.ts +35 -0
  34. package/dist/setup-migrate.js +204 -0
  35. package/dist/setup.d.ts +41 -66
  36. package/dist/setup.js +361 -531
  37. package/dist/signin.d.ts +108 -0
  38. package/dist/signin.js +595 -0
  39. package/dist/tools/agents.d.ts +4 -4
  40. package/dist/tools/artifacts.d.ts +2 -0
  41. package/dist/tools/artifacts.js +8 -1
  42. package/dist/tools/errors.d.ts +12 -0
  43. package/dist/tools/errors.js +65 -0
  44. package/dist/tools/exec-route.d.ts +34 -0
  45. package/dist/tools/exec-route.js +101 -27
  46. package/dist/tools/iam.js +2 -3
  47. package/dist/tools/secretary.d.ts +1 -0
  48. package/dist/tools/secretary.js +2 -1
  49. package/dist/tools/synthesize.d.ts +37 -0
  50. package/dist/tools/synthesize.js +126 -7
  51. package/dist/tools/voice.d.ts +3 -2
  52. package/dist/tools/voice.js +70 -18
  53. package/dist/tools/workspaces.js +7 -4
  54. package/dist/version.d.ts +6 -0
  55. package/dist/version.js +18 -0
  56. package/dist/workflow-registry.d.ts +1 -0
  57. package/dist/workflow-registry.js +21 -0
  58. package/package.json +4 -1
package/dist/signin.js ADDED
@@ -0,0 +1,595 @@
1
+ /**
2
+ * The one shared CLI sign-in flow (MV-1542c step 1.2).
3
+ *
4
+ * device (S-1): status check -> 5 s preflight -> PKCE -> loopback listener -> browser -> exchange
5
+ * password (S-2): status check -> email + hidden password -> login -> workspace picker -> self-issue
6
+ *
7
+ * Every path ends in `validateIssued` then a confirming `whoami`. This module
8
+ * never touches the file system: writing the profile is the caller's job
9
+ * (setup.ts, cli-login.ts). The password-path session JWT lives in one local
10
+ * variable, is only ever sent in an Authorization header, and is cleared in a
11
+ * `finally`. It is never written to disk, never passed to `execFile`, never
12
+ * logged.
13
+ */
14
+ import * as http from 'node:http';
15
+ import * as crypto from 'node:crypto';
16
+ import { execFile } from 'node:child_process';
17
+ import { PromptError } from './prompt.js';
18
+ import { printable } from './api-errors.js';
19
+ export class SignInError extends Error {
20
+ code;
21
+ exitCode;
22
+ /**
23
+ * true when `message` was already written through `io.log` (a declined password
24
+ * offer): the caller should only set the exit code, not print it again.
25
+ */
26
+ reported = false;
27
+ constructor(code, message, exitCode = 1) {
28
+ super(message);
29
+ this.code = code;
30
+ this.exitCode = exitCode;
31
+ this.name = 'SignInError';
32
+ }
33
+ }
34
+ // ─── Constants and messages ─────────────────────────────────────────────────
35
+ export const SIGNIN_DISABLED_MESSAGE = 'TACIT CLI sign-in is turned off on this server. Ask your workspace owner.';
36
+ export const PIN_OFFER_QUESTION = 'Sign in with your email and password instead? (y/N) ';
37
+ export const NO_TTY_HINT = 'Use --no-browser from a terminal to sign in with email and password';
38
+ const DEFAULT_CALLBACK_PORT = 9123;
39
+ const DEFAULT_APPROVAL_TIMEOUT_MS = 180_000;
40
+ const DEFAULT_PREFLIGHT_TIMEOUT_MS = 5_000;
41
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
42
+ const MAX_LIFETIME_MS = 91 * 24 * 60 * 60 * 1000;
43
+ const TOKEN_RE = /^tk_[0-9a-f]{32}$/;
44
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
45
+ const DEVICE_LABEL_RE = /^[A-Za-z0-9 ._-]{1,64}$/;
46
+ const INACTIVE_MESSAGE = "Your access to that workspace isn't active.";
47
+ // ─── PKCE ────────────────────────────────────────────────────────────────────
48
+ /** RFC 7636 §4.2, S256. */
49
+ export function s256Challenge(verifier) {
50
+ return crypto.createHash('sha256').update(verifier).digest('base64url');
51
+ }
52
+ /** verifier = 32 random bytes, base64url (43 chars). */
53
+ export function newPkcePair() {
54
+ const verifier = crypto.randomBytes(32).toString('base64url');
55
+ return { verifier, challenge: s256Challenge(verifier) };
56
+ }
57
+ function safeEqual(a, b) {
58
+ const ab = Buffer.from(a, 'utf8');
59
+ const bb = Buffer.from(b, 'utf8');
60
+ if (ab.length !== bb.length)
61
+ return false;
62
+ return crypto.timingSafeEqual(ab, bb);
63
+ }
64
+ // ─── HTTP helpers ────────────────────────────────────────────────────────────
65
+ function normaliseBase(url) {
66
+ return url.replace(/\/+$/, '').replace(/\/api\/v1$/, '');
67
+ }
68
+ function hostOf(url) {
69
+ try {
70
+ return new URL(url).host;
71
+ }
72
+ catch {
73
+ return url;
74
+ }
75
+ }
76
+ function causeText(err) {
77
+ const e = err;
78
+ return e?.cause?.code ?? e?.code ?? (e?.name === 'TimeoutError' || e?.name === 'AbortError' ? 'timed out' : e?.message ?? 'network error');
79
+ }
80
+ async function callApi(fetchFn, url, init, timeoutMs) {
81
+ let res;
82
+ try {
83
+ // L-7: these requests carry a password, a verifier or a session header; never follow a redirect with them.
84
+ res = await fetchFn(url, { ...init, redirect: 'manual', signal: AbortSignal.timeout(timeoutMs) });
85
+ }
86
+ catch (err) {
87
+ throw new SignInError('NETWORK', `Can't reach ${hostOf(url)} (${causeText(err)}).`);
88
+ }
89
+ if (res.status >= 300 && res.status < 400) {
90
+ throw new SignInError('NETWORK', `${hostOf(url)} answered with a redirect (HTTP ${res.status}). Sign-in does not follow redirects. Check --api-url.`);
91
+ }
92
+ return res;
93
+ }
94
+ async function readFailure(res) {
95
+ const text = await res.text().catch(() => '');
96
+ const html = /^\s*<(!doctype|html)/i.test(text);
97
+ let code = '';
98
+ let message = '';
99
+ try {
100
+ const body = JSON.parse(text);
101
+ const err = typeof body.error === 'object' && body.error !== null ? body.error : body;
102
+ if (typeof err.code === 'string')
103
+ code = err.code;
104
+ if (typeof err.message === 'string')
105
+ message = err.message;
106
+ }
107
+ catch { /* not JSON */ }
108
+ return { status: res.status, code, message, html };
109
+ }
110
+ async function readJson(res, what) {
111
+ const text = await res.text().catch(() => '');
112
+ try {
113
+ const parsed = JSON.parse(text);
114
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
115
+ return parsed;
116
+ }
117
+ catch { /* fall through */ }
118
+ const html = /^\s*<(!doctype|html)/i.test(text);
119
+ throw new SignInError('BAD_ISSUE_RESPONSE', html
120
+ ? `The server returned a web page instead of ${what}. --api-url probably points at the web app, not the API.`
121
+ : `The server returned something other than ${what}.`);
122
+ }
123
+ /** Shared by device-exchange and iam/tokens/self (rows 9-16 of P1.2, D-96). */
124
+ function mapIssueFailure(f) {
125
+ if (f.code === 'IAM_SIGNIN_DISABLED')
126
+ return new SignInError('SIGNIN_DISABLED', SIGNIN_DISABLED_MESSAGE, 1);
127
+ if (f.code === 'INVALID_CODE' || f.code === 'CODE_EXPIRED') {
128
+ return new SignInError('CODE_INVALID', 'Sign-in expired or the server restarted. Run tacit login again.', 1);
129
+ }
130
+ if (f.code === 'PKCE_MISMATCH' || f.code === 'INVALID_CODE_VERIFIER') {
131
+ return new SignInError('PKCE_MISMATCH', 'Sign-in verification failed. Run tacit login again; if it repeats, update @tacitai/mcp-server.', 2);
132
+ }
133
+ if (f.code === 'NOT_A_MEMBER' || f.code === 'WORKSPACE_INACTIVE' || f.code === 'MEMBERSHIP_INACTIVE') {
134
+ return new SignInError(f.code, INACTIVE_MESSAGE, 1);
135
+ }
136
+ if (f.code === 'MUST_CHANGE_PIN')
137
+ return new SignInError('MUST_CHANGE_PIN', 'Change your password in TACIT first.', 1);
138
+ if (f.code === 'TOKEN_NOT_OWNED') {
139
+ return new SignInError('TOKEN_NOT_OWNED', "That saved login doesn't belong to this account. Run tacit login again.", 1);
140
+ }
141
+ if (f.code === 'SESSION_LOGIN_REQUIRED') {
142
+ return new SignInError('LOGIN_FAILED', 'For your security this needs a recent sign-in (within 15 minutes). Sign in again in the browser, then retry.', 1);
143
+ }
144
+ if (f.status === 429) {
145
+ return new SignInError('RATE_LIMITED', 'Too many sign-ins for your account in the last hour. Try again later.', 1);
146
+ }
147
+ if (f.status === 404 || f.status === 405 || f.code === 'MISSING_FIELD') {
148
+ return new SignInError('SERVER_TOO_OLD', "This TACIT server is older than this version of tacit and can't issue CLI logins. Ask your admin to update it.", 1);
149
+ }
150
+ if (f.code === 'AUTH_BACKEND_UNAVAILABLE') {
151
+ return new SignInError('LOGIN_FAILED', "TACIT is busy and couldn't check your login. Try again shortly.", 1);
152
+ }
153
+ return new SignInError('LOGIN_FAILED', `Sign-in failed (HTTP ${f.status}${f.code ? ` ${f.code}` : ''}).`, 1);
154
+ }
155
+ // ─── cli-signin-status (D-66) ────────────────────────────────────────────────
156
+ /**
157
+ * First call of every sign-in. Returns only when sign-in is enabled.
158
+ * `enabled:false` throws SIGNIN_DISABLED (exit 1, no browser, no password offer);
159
+ * a 404 (server older than this mission) throws SERVER_TOO_OLD.
160
+ */
161
+ export async function checkCliSigninStatus(apiUrl, fetchFn = fetch) {
162
+ const base = normaliseBase(apiUrl);
163
+ const res = await callApi(fetchFn, `${base}/api/v1/auth/cli-signin-status`, { method: 'GET' }, DEFAULT_REQUEST_TIMEOUT_MS);
164
+ if (res.status === 404) {
165
+ throw new SignInError('SERVER_TOO_OLD', "This TACIT server is older than this version of tacit and can't issue CLI logins. Ask your admin to update it.", 1);
166
+ }
167
+ if (!res.ok) {
168
+ throw new SignInError('NETWORK', `Can't reach ${hostOf(base)} (HTTP ${res.status}).`);
169
+ }
170
+ const body = await readJson(res, 'a sign-in status');
171
+ if (body['enabled'] === false)
172
+ throw new SignInError('SIGNIN_DISABLED', SIGNIN_DISABLED_MESSAGE, 1);
173
+ if (body['enabled'] !== true) {
174
+ throw new SignInError('SERVER_TOO_OLD', "This TACIT server is older than this version of tacit and can't issue CLI logins. Ask your admin to update it.", 1);
175
+ }
176
+ const ttl = typeof body['cli_login_ttl_days'] === 'number' ? body['cli_login_ttl_days'] : 90;
177
+ return { enabled: true, cli_login_ttl_days: ttl };
178
+ }
179
+ // ─── validateIssued (P1.3: refuse, never coerce) ─────────────────────────────
180
+ function refuse(reason) {
181
+ throw new SignInError('BAD_ISSUE_RESPONSE', `The server returned a login this version won't store (${reason}). Nothing was saved.`, 1);
182
+ }
183
+ /**
184
+ * `now` is epoch ms and should come from the response `Date` header, not the
185
+ * local clock (AR-17); the server decides real expiry.
186
+ */
187
+ export function validateIssued(resp, now) {
188
+ if (!resp || typeof resp !== 'object' || Array.isArray(resp))
189
+ refuse('not an object');
190
+ const r = resp;
191
+ const str = (k) => (typeof r[k] === 'string' ? r[k] : '');
192
+ for (const key of ['token', 'token_id', 'expires_at', 'workspace_id', 'workspace_name', 'identity_email']) {
193
+ if (!str(key).trim())
194
+ refuse(`missing ${key}`);
195
+ }
196
+ const token = str('token');
197
+ if (!TOKEN_RE.test(token))
198
+ refuse('token is not a per-user CLI token');
199
+ const expires = Date.parse(str('expires_at'));
200
+ if (Number.isNaN(expires))
201
+ refuse('expiry is not a date');
202
+ if (expires <= now)
203
+ refuse('already expired');
204
+ if (expires > now + MAX_LIFETIME_MS)
205
+ refuse('expiry is more than 91 days away');
206
+ if (!UUID_RE.test(str('workspace_id')))
207
+ refuse('workspace id is not a UUID');
208
+ return {
209
+ token,
210
+ tokenId: str('token_id'),
211
+ expiresAt: str('expires_at'),
212
+ workspaceId: str('workspace_id'),
213
+ workspaceName: printable(str('workspace_name')),
214
+ identityEmail: printable(str('identity_email')),
215
+ deviceLabel: printable(str('device_label')),
216
+ };
217
+ }
218
+ function serverNow(res) {
219
+ const parsed = Date.parse(res.headers.get('date') ?? '');
220
+ return Number.isNaN(parsed) ? Date.now() : parsed;
221
+ }
222
+ /** validateIssued + confirming whoami (credential_type iam_token, same workspace). */
223
+ async function finishIssue(opts, fetchFn, res, channel) {
224
+ const body = await readJson(res, 'a login');
225
+ const issued = validateIssued(body, serverNow(res));
226
+ const base = normaliseBase(opts.apiUrl);
227
+ const who = await callApi(fetchFn, `${base}/api/v1/auth/whoami`, { method: 'GET', headers: { Authorization: `Bearer ${issued.token}` } }, opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);
228
+ if (!who.ok)
229
+ refuse(`the new login was not accepted (HTTP ${who.status})`);
230
+ const w = await readJson(who, 'an identity');
231
+ if (w['credential_type'] !== 'iam_token')
232
+ refuse('the new login is not a per-user token');
233
+ if (String(w['workspace_id'] ?? '').toLowerCase() !== issued.workspaceId.toLowerCase())
234
+ refuse('workspace mismatch');
235
+ return { ...issued, deviceLabel: issued.deviceLabel || opts.deviceLabel, channel };
236
+ }
237
+ // ─── Browser opener (BROWSER seam) ───────────────────────────────────────────
238
+ /**
239
+ * Honours the standard `BROWSER` env: the command is run with execFile and the
240
+ * URL as its only argument, never through a shell. Unset = platform default.
241
+ * Only http(s) URLs are ever passed.
242
+ */
243
+ export function openBrowser(url, env = process.env, platform = process.platform) {
244
+ if (!/^https?:\/\//i.test(url))
245
+ return Promise.resolve('failed');
246
+ const fromEnv = (env['BROWSER'] ?? '').split(':').map((s) => s.trim()).find((s) => s.length > 0);
247
+ let command;
248
+ let args;
249
+ if (fromEnv) {
250
+ command = fromEnv;
251
+ args = [url];
252
+ }
253
+ else if (platform === 'darwin') {
254
+ command = 'open';
255
+ args = [url];
256
+ }
257
+ else if (platform === 'win32') {
258
+ command = 'rundll32';
259
+ args = ['url.dll,FileProtocolHandler', url];
260
+ }
261
+ else {
262
+ command = 'xdg-open';
263
+ args = [url];
264
+ }
265
+ return new Promise((resolve) => {
266
+ let settled = false;
267
+ const done = (v) => { if (!settled) {
268
+ settled = true;
269
+ resolve(v);
270
+ } };
271
+ try {
272
+ const child = execFile(command, args, { windowsHide: true }, (err) => done(err ? 'failed' : 'opened'));
273
+ // A launcher that stays in the foreground (BROWSER=firefox) must not stall sign-in.
274
+ const timer = setTimeout(() => { done('opened'); child?.unref?.(); }, 2000);
275
+ timer.unref?.();
276
+ }
277
+ catch {
278
+ done('failed');
279
+ }
280
+ });
281
+ }
282
+ function isRemoteOrHeadless(env, platform) {
283
+ if (env['SSH_CONNECTION'] || env['SSH_TTY'])
284
+ return true;
285
+ return platform === 'linux' && !env['DISPLAY'] && !env['WAYLAND_DISPLAY'];
286
+ }
287
+ // ─── Failure classification ──────────────────────────────────────────────────
288
+ /** Rows 2-5 of P1.2 are the only paths to a password offer (D-96: default N). */
289
+ export function deviceFailureAction(e) {
290
+ switch (e.code) {
291
+ case 'APP_UNREACHABLE':
292
+ case 'PORT_BUSY':
293
+ case 'NO_BROWSER':
294
+ case 'TIMEOUT':
295
+ return 'offer-pin-default-no';
296
+ default:
297
+ return 'abort';
298
+ }
299
+ }
300
+ function startLoopback(wantedPort, state, timeoutMs) {
301
+ return new Promise((resolveStart, rejectStart) => {
302
+ let settleHit;
303
+ const hit = new Promise((resolve, reject) => { settleHit = { resolve, reject }; });
304
+ hit.catch(() => undefined); // rejection is consumed by whoever awaits `hit`
305
+ let handled = false;
306
+ let timer;
307
+ let boundPort = wantedPort;
308
+ const server = http.createServer((req, res) => {
309
+ const plain = (status, text) => {
310
+ res.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', Connection: 'close' });
311
+ res.end(text);
312
+ };
313
+ const host = (req.headers.host ?? '').toLowerCase();
314
+ if (host !== `127.0.0.1:${boundPort}` && host !== `localhost:${boundPort}`) {
315
+ plain(400, 'Bad request.');
316
+ return;
317
+ }
318
+ let url;
319
+ try {
320
+ url = new URL(req.url ?? '/', `http://127.0.0.1:${boundPort}`);
321
+ }
322
+ catch {
323
+ plain(400, 'Bad request.');
324
+ return;
325
+ }
326
+ if (req.method !== 'GET' || url.pathname !== '/callback') {
327
+ plain(404, 'Not found.');
328
+ return;
329
+ }
330
+ if (handled) {
331
+ plain(409, 'This sign-in was already used.');
332
+ return;
333
+ }
334
+ handled = true;
335
+ if (timer)
336
+ clearTimeout(timer);
337
+ const fail = (e) => { plain(400, 'Sign-in failed. See your terminal.'); settleHit.reject(e); };
338
+ const got = url.searchParams.get('state');
339
+ if (got === null || !safeEqual(got, state)) {
340
+ fail(new SignInError('STATE_MISMATCH', 'Sign-in check failed. Try again. The browser reply did not match this request.', 2));
341
+ return;
342
+ }
343
+ const error = url.searchParams.get('error');
344
+ if (error !== null) {
345
+ if (error === 'access_denied') {
346
+ fail(new SignInError('DENIED', 'Sign-in was denied in the browser.', 2));
347
+ return;
348
+ }
349
+ const shown = error.replace(/[^a-z_]/g, '').slice(0, 40) || 'unknown';
350
+ fail(new SignInError('CALLBACK_ERROR', `The browser reported an error (${shown}).`, 1));
351
+ return;
352
+ }
353
+ const code = url.searchParams.get('code');
354
+ if (!code) {
355
+ fail(new SignInError('STATE_MISMATCH', 'Sign-in check failed. Try again. The browser reply did not match this request.', 2));
356
+ return;
357
+ }
358
+ settleHit.resolve({
359
+ code,
360
+ respond: (ok) => (ok
361
+ ? plain(200, 'You can return to your terminal.')
362
+ : plain(400, 'Sign-in failed. See your terminal.')),
363
+ });
364
+ });
365
+ server.headersTimeout = 10_000;
366
+ server.requestTimeout = 0; // the callback response is held until the exchange finishes
367
+ const close = () => {
368
+ if (timer)
369
+ clearTimeout(timer);
370
+ server.close();
371
+ server.closeAllConnections?.();
372
+ };
373
+ server.once('error', (err) => {
374
+ rejectStart(new SignInError('PORT_BUSY', err.code === 'EADDRINUSE'
375
+ ? `Port ${wantedPort} is busy (another sign-in running?).`
376
+ : `Could not listen on port ${wantedPort} (${err.code ?? 'error'}).`));
377
+ });
378
+ server.listen(wantedPort, '127.0.0.1', () => {
379
+ const addr = server.address();
380
+ boundPort = typeof addr === 'object' && addr ? addr.port : wantedPort;
381
+ timer = setTimeout(() => {
382
+ if (handled)
383
+ return;
384
+ handled = true;
385
+ settleHit.reject(new SignInError('TIMEOUT', timeoutMs === DEFAULT_APPROVAL_TIMEOUT_MS
386
+ ? 'No approval received after 3 minutes.'
387
+ : `No approval received after ${Math.max(1, Math.round(timeoutMs / 1000))} seconds.`, 1));
388
+ }, timeoutMs);
389
+ resolveStart({ port: boundPort, hit, close });
390
+ });
391
+ });
392
+ }
393
+ // ─── Device flow (S-1) ───────────────────────────────────────────────────────
394
+ async function deviceFlow(opts, fetchFn) {
395
+ const env = opts.env ?? process.env;
396
+ const platform = opts.platform ?? process.platform;
397
+ const apiBase = normaliseBase(opts.apiUrl);
398
+ const appBase = opts.appUrl.replace(/\/+$/, '');
399
+ // 1. Page preflight (best effort). A HEAD cannot tell a missing SPA route, so GET.
400
+ try {
401
+ const pre = await fetchFn(`${appBase}/auth/device`, {
402
+ method: 'GET', redirect: 'manual', signal: AbortSignal.timeout(opts.preflightTimeoutMs ?? DEFAULT_PREFLIGHT_TIMEOUT_MS),
403
+ });
404
+ if (pre.status === 404 || pre.status >= 500) {
405
+ throw new SignInError('APP_UNREACHABLE', `Can't reach the sign-in page at ${appBase}/auth/device (HTTP ${pre.status}).`);
406
+ }
407
+ }
408
+ catch (err) {
409
+ if (err instanceof SignInError)
410
+ throw err;
411
+ throw new SignInError('APP_UNREACHABLE', `Can't reach the sign-in page at ${appBase}/auth/device (${causeText(err)}).`);
412
+ }
413
+ // 2. Remote or headless sessions cannot reach this computer's loopback.
414
+ if (isRemoteOrHeadless(env, platform)) {
415
+ throw new SignInError('NO_BROWSER', "This looks like a remote session: a browser elsewhere can't reach this computer's port.");
416
+ }
417
+ // 3. PKCE + state, then the loopback listener (before the browser opens).
418
+ const { verifier, challenge } = newPkcePair();
419
+ const state = crypto.randomBytes(32).toString('hex');
420
+ const loop = await startLoopback(opts.callbackPort ?? DEFAULT_CALLBACK_PORT, state, opts.approvalTimeoutMs ?? DEFAULT_APPROVAL_TIMEOUT_MS);
421
+ let respond;
422
+ let success = false;
423
+ try {
424
+ const callback = `http://127.0.0.1:${loop.port}/callback`;
425
+ const url = `${appBase}/auth/device?callback=${encodeURIComponent(callback)}&state=${state}`
426
+ + `&code_challenge=${challenge}&code_challenge_method=S256`;
427
+ const opened = opts.io.openBrowser ? await opts.io.openBrowser(url) : await openBrowser(url, env, platform);
428
+ if (opened === 'failed') {
429
+ opts.io.log(`Could not open a browser. Open this URL to approve the sign-in: ${url}`);
430
+ }
431
+ else {
432
+ opts.io.log('Opened your browser to approve this sign-in. Waiting for approval...');
433
+ }
434
+ const got = await loop.hit;
435
+ respond = got.respond;
436
+ // 4. Exchange. Nothing is sent to the browser until this succeeds.
437
+ const res = await callApi(fetchFn, `${apiBase}/api/v1/auth/device-exchange`, {
438
+ method: 'POST',
439
+ headers: { 'Content-Type': 'application/json' },
440
+ body: JSON.stringify({ code: got.code, code_verifier: verifier, device_label: opts.deviceLabel }),
441
+ }, opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);
442
+ if (!res.ok)
443
+ throw mapIssueFailure(await readFailure(res));
444
+ const issued = await finishIssue(opts, fetchFn, res, 'device');
445
+ success = true;
446
+ return issued;
447
+ }
448
+ finally {
449
+ respond?.(success);
450
+ loop.close();
451
+ }
452
+ }
453
+ async function pinFlow(opts, fetchFn) {
454
+ const { io } = opts;
455
+ if (!io.isTTY)
456
+ throw new SignInError('NO_TTY', 'Password sign-in needs an interactive terminal.', 1);
457
+ const apiBase = normaliseBase(opts.apiUrl);
458
+ const timeout = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
459
+ let jwt = '';
460
+ let pin = '';
461
+ try {
462
+ let email;
463
+ try {
464
+ email = (await io.promptLine('Email: ')).trim();
465
+ pin = await io.promptHidden('Password: ');
466
+ }
467
+ catch (err) {
468
+ if (err instanceof PromptError) {
469
+ throw err.code === 'NO_TTY'
470
+ ? new SignInError('NO_TTY', 'Password sign-in needs an interactive terminal.', 1)
471
+ : new SignInError('CANCELLED', 'Cancelled.', 1);
472
+ }
473
+ throw err;
474
+ }
475
+ if (!email || !pin)
476
+ throw new SignInError('LOGIN_FAILED', 'Email and password are required.', 1);
477
+ const loginRes = await callApi(fetchFn, `${apiBase}/api/v1/auth/login`, {
478
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, pin }),
479
+ }, timeout);
480
+ pin = '';
481
+ if (!loginRes.ok) {
482
+ const f = await readFailure(loginRes);
483
+ if (f.status === 401)
484
+ throw new SignInError('LOGIN_FAILED', 'Login failed. Check your email and password.', 1);
485
+ if (f.html) {
486
+ throw new SignInError('LOGIN_FAILED', 'The server returned a web page instead of a login response. --api-url probably points at the web app, not the API.', 1);
487
+ }
488
+ throw mapIssueFailure(f);
489
+ }
490
+ const login = await readJson(loginRes, 'a login');
491
+ jwt = typeof login['session_token'] === 'string' ? login['session_token'] : '';
492
+ if (!jwt)
493
+ throw new SignInError('LOGIN_FAILED', 'Login returned no session.', 1);
494
+ if (login['must_change_pin'] === true) {
495
+ throw new SignInError('MUST_CHANGE_PIN', 'Change your password in TACIT first.', 1);
496
+ }
497
+ const loginWorkspace = typeof login['workspace_id'] === 'string' ? login['workspace_id'] : '';
498
+ const mineRes = await callApi(fetchFn, `${apiBase}/api/v1/workspaces/mine`, { method: 'GET', headers: { Authorization: `Bearer ${jwt}` } }, timeout);
499
+ if (!mineRes.ok)
500
+ throw mapIssueFailure(await readFailure(mineRes));
501
+ const mine = await readJson(mineRes, 'a workspace list');
502
+ const items = (Array.isArray(mine['workspaces']) ? mine['workspaces'] : [])
503
+ .filter((w) => !!w && typeof w === 'object')
504
+ .map((w) => ({ workspace_id: String(w['workspace_id'] ?? ''), display_name: printable(String(w['display_name'] ?? w['workspace_id'] ?? '')) }))
505
+ .filter((w) => w.workspace_id.length > 0);
506
+ if (items.length === 0) {
507
+ throw new SignInError('NOT_A_MEMBER', "You don't have an active membership in any workspace on this server.", 1);
508
+ }
509
+ let chosen = items[0];
510
+ if (items.length > 1) {
511
+ const def = Math.max(0, items.findIndex((w) => w.workspace_id.toLowerCase() === loginWorkspace.toLowerCase()));
512
+ let idx;
513
+ try {
514
+ idx = await io.choose('Choose a workspace:', items.map((w) => w.display_name), def);
515
+ }
516
+ catch (err) {
517
+ if (err instanceof PromptError)
518
+ throw new SignInError('CANCELLED', 'Cancelled.', 1);
519
+ throw err;
520
+ }
521
+ if (!Number.isInteger(idx) || idx < 0 || idx >= items.length)
522
+ throw new SignInError('CANCELLED', 'Cancelled.', 1);
523
+ chosen = items[idx];
524
+ }
525
+ // D-17: self-issue for the chosen workspace; no switch-workspace call.
526
+ const body = { workspace_id: chosen.workspace_id, device_label: opts.deviceLabel };
527
+ if (opts.rotateTokenId)
528
+ body['rotate_token_id'] = opts.rotateTokenId;
529
+ const issueRes = await callApi(fetchFn, `${apiBase}/api/v1/iam/tokens/self`, {
530
+ method: 'POST',
531
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${jwt}` },
532
+ body: JSON.stringify(body),
533
+ }, timeout);
534
+ if (!issueRes.ok)
535
+ throw mapIssueFailure(await readFailure(issueRes));
536
+ return await finishIssue(opts, fetchFn, issueRes, 'pin');
537
+ }
538
+ finally {
539
+ jwt = '';
540
+ pin = '';
541
+ }
542
+ }
543
+ // ─── Entry point ─────────────────────────────────────────────────────────────
544
+ function validateOptions(opts) {
545
+ if (!DEVICE_LABEL_RE.test(opts.deviceLabel)) {
546
+ throw new SignInError('LOGIN_FAILED', 'The device label may only use letters, digits, space, dot, underscore and dash (1-64 characters).', 1);
547
+ }
548
+ for (const [name, value] of [['API', opts.apiUrl], ['app', opts.appUrl]]) {
549
+ let ok = false;
550
+ try {
551
+ const u = new URL(value);
552
+ ok = u.protocol === 'http:' || u.protocol === 'https:';
553
+ }
554
+ catch { /* invalid */ }
555
+ if (!ok)
556
+ throw new SignInError('LOGIN_FAILED', `The ${name} URL must be a full http(s) URL.`, 1);
557
+ }
558
+ }
559
+ async function offerPin(opts, fetchFn, cause) {
560
+ const { io } = opts;
561
+ if (!io.isTTY)
562
+ throw new SignInError(cause.code, `${cause.message} ${NO_TTY_HINT}`, 1);
563
+ io.log(cause.message);
564
+ const yes = await io.confirm(PIN_OFFER_QUESTION, false);
565
+ if (!yes) {
566
+ cause.reported = true;
567
+ throw cause;
568
+ }
569
+ return pinFlow(opts, fetchFn);
570
+ }
571
+ /**
572
+ * Throws SignInError. Order: cli-signin-status, then device or password.
573
+ * Success logs `Signed in as <email> to <workspace> (expires <date>).`
574
+ */
575
+ export async function signIn(opts) {
576
+ validateOptions(opts);
577
+ const fetchFn = opts.fetchFn ?? fetch;
578
+ await checkCliSigninStatus(opts.apiUrl, fetchFn);
579
+ let issued;
580
+ if (opts.mode === 'pin') {
581
+ issued = await pinFlow(opts, fetchFn);
582
+ }
583
+ else {
584
+ try {
585
+ issued = await deviceFlow(opts, fetchFn);
586
+ }
587
+ catch (err) {
588
+ if (!(err instanceof SignInError) || deviceFailureAction(err) !== 'offer-pin-default-no')
589
+ throw err;
590
+ issued = await offerPin(opts, fetchFn, err);
591
+ }
592
+ }
593
+ opts.io.log(`Signed in as ${issued.identityEmail} to ${issued.workspaceName} (expires ${issued.expiresAt.slice(0, 10)}).`);
594
+ return issued;
595
+ }
@@ -62,8 +62,8 @@ export declare const agentDelegateInputSchema: z.ZodEffects<z.ZodObject<{
62
62
  wait: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
63
63
  wait_timeout: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
64
64
  }, "strip", z.ZodTypeAny, {
65
- task: string;
66
65
  kind: "task" | "goal" | "schedule";
66
+ task: string;
67
67
  wait: boolean;
68
68
  wait_timeout: number;
69
69
  dossier_ids?: string[] | undefined;
@@ -73,17 +73,17 @@ export declare const agentDelegateInputSchema: z.ZodEffects<z.ZodObject<{
73
73
  target_ids?: string[] | undefined;
74
74
  }, {
75
75
  task: string;
76
+ kind?: "task" | "goal" | "schedule" | undefined;
76
77
  dossier_ids?: string[] | undefined;
77
78
  program_ids?: string[] | undefined;
78
79
  role_slug?: string | undefined;
79
80
  agent_id?: string | undefined;
80
- kind?: "task" | "goal" | "schedule" | undefined;
81
81
  target_ids?: string[] | undefined;
82
82
  wait?: boolean | undefined;
83
83
  wait_timeout?: number | undefined;
84
84
  }>, {
85
- task: string;
86
85
  kind: "task" | "goal" | "schedule";
86
+ task: string;
87
87
  wait: boolean;
88
88
  wait_timeout: number;
89
89
  dossier_ids?: string[] | undefined;
@@ -93,11 +93,11 @@ export declare const agentDelegateInputSchema: z.ZodEffects<z.ZodObject<{
93
93
  target_ids?: string[] | undefined;
94
94
  }, {
95
95
  task: string;
96
+ kind?: "task" | "goal" | "schedule" | undefined;
96
97
  dossier_ids?: string[] | undefined;
97
98
  program_ids?: string[] | undefined;
98
99
  role_slug?: string | undefined;
99
100
  agent_id?: string | undefined;
100
- kind?: "task" | "goal" | "schedule" | undefined;
101
101
  target_ids?: string[] | undefined;
102
102
  wait?: boolean | undefined;
103
103
  wait_timeout?: number | undefined;
@@ -417,4 +417,6 @@ export declare function handleArtifactDelete(args: unknown): Promise<{
417
417
  }>;
418
418
  isError?: boolean;
419
419
  }>;
420
+ /** Share links made by a non-JWT credential expire (D-83, AR-11); a browser link has `expires_at: null`. Always show the field. */
421
+ export declare function withExpiresAt(data: unknown): unknown;
420
422
  export declare function registerArtifactTools(server: McpServer, getClientFn: () => Promise<TacitClient>): void;
@@ -459,6 +459,13 @@ export async function handleArtifactDelete(args) {
459
459
  }
460
460
  return buildArtifactDeleteRequest(getClient(), parsed.data).execute();
461
461
  }
462
+ /** Share links made by a non-JWT credential expire (D-83, AR-11); a browser link has `expires_at: null`. Always show the field. */
463
+ export function withExpiresAt(data) {
464
+ if (!data || typeof data !== 'object' || Array.isArray(data))
465
+ return data;
466
+ const obj = data;
467
+ return { ...obj, expires_at: obj['expires_at'] ?? null };
468
+ }
462
469
  export function registerArtifactTools(server, getClientFn) {
463
470
  server.tool('tacit_artifact_list', 'List/search artifacts from the Tacit workspace. Route: GET /api/v1/artifacts.', {
464
471
  q: z.string().optional().describe('Full-text search over title and body'),
@@ -581,7 +588,7 @@ export function registerArtifactTools(server, getClientFn) {
581
588
  try {
582
589
  const client = await getClientFn();
583
590
  const data = await client.post(`/api/v1/artifacts/${args.artifact_id}/share-token`, {});
584
- return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
591
+ return { content: [{ type: 'text', text: JSON.stringify(withExpiresAt(data), null, 2) }] };
585
592
  }
586
593
  catch (err) {
587
594
  return apiErrorResult(err, `/api/v1/artifacts/${args.artifact_id}/share-token`);