@tacitai/mcp-server 0.7.0 → 0.8.1

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 (73) 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 +90 -52
  18. package/dist/client.js +198 -296
  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 +6 -4
  40. package/dist/tools/agents.js +15 -4
  41. package/dist/tools/artifacts.d.ts +2 -0
  42. package/dist/tools/artifacts.js +8 -1
  43. package/dist/tools/capture.js +2 -2
  44. package/dist/tools/career.js +2 -2
  45. package/dist/tools/chronicle.js +7 -7
  46. package/dist/tools/crews.js +8 -8
  47. package/dist/tools/errors.d.ts +18 -0
  48. package/dist/tools/errors.js +73 -1
  49. package/dist/tools/exec-route.d.ts +34 -0
  50. package/dist/tools/exec-route.js +101 -27
  51. package/dist/tools/github.js +2 -2
  52. package/dist/tools/gm.js +2 -2
  53. package/dist/tools/iam.js +2 -3
  54. package/dist/tools/kb.js +2 -2
  55. package/dist/tools/lake-structure.js +8 -8
  56. package/dist/tools/lake.js +2 -2
  57. package/dist/tools/onboarding.js +2 -2
  58. package/dist/tools/people.js +7 -7
  59. package/dist/tools/pyramid.js +2 -2
  60. package/dist/tools/recall.js +2 -2
  61. package/dist/tools/secretary.d.ts +1 -0
  62. package/dist/tools/secretary.js +2 -1
  63. package/dist/tools/synthesize.d.ts +37 -0
  64. package/dist/tools/synthesize.js +128 -9
  65. package/dist/tools/voice.d.ts +3 -2
  66. package/dist/tools/voice.js +70 -18
  67. package/dist/tools/wiki.js +2 -2
  68. package/dist/tools/workspaces.js +20 -6
  69. package/dist/version.d.ts +6 -0
  70. package/dist/version.js +18 -0
  71. package/dist/workflow-registry.d.ts +1 -0
  72. package/dist/workflow-registry.js +21 -0
  73. package/package.json +4 -1
package/dist/client.js CHANGED
@@ -1,35 +1,44 @@
1
1
  /**
2
- * TacitClient — REST/SSE client over TACIT_API_URL.
2
+ * TacitClient — REST/SSE client over an API URL it is GIVEN.
3
3
  *
4
4
  * Security invariants (enforced here and NEVER relaxed):
5
- * - TACIT_TOKEN is NEVER written to any output stream (stdout, stderr, logs).
5
+ * - The token is NEVER written to any output stream (stdout, stderr, logs).
6
6
  * - The Authorization header value is NEVER logged at any level.
7
7
  * - No anthropic/openai SDK import.
8
- * - Token sourced from process.env.TACIT_TOKEN or v2 profile files (~/.tacit/profiles/).
8
+ * - This module reads no credential from the environment. Credentials arrive as
9
+ * constructor options from credentials.ts (levels 0/1/2/4/5), the only
10
+ * module that reads them (MV-1542c step 1.4).
9
11
  */
10
12
  import * as fs from 'fs';
11
13
  import * as path from 'path';
12
- import * as os from 'os';
13
14
  import { AsyncLocalStorage } from 'node:async_hooks';
15
+ import { clearAutonomyCache } from './autonomy.js';
16
+ import { messageForResponse, SWITCH_NOT_SUPPORTED } from './api-errors.js';
17
+ // Autonomy lives in autonomy.ts; re-exported so existing importers keep working.
18
+ export { parseAutonomyLevel, autonomyAtLeast, getCachedAutonomy, ensureAutonomy, } from './autonomy.js';
14
19
  function isHmacSessionToken(token) {
15
20
  const parts = token.split('.');
16
21
  return parts.length === 2 && /^[0-9a-f]{64}$/.test(parts[1]);
17
22
  }
23
+ const JWT_SHAPE_RE = /^eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;
24
+ /** Default API URL when a caller supplies none. Only level-2 env credentials and tests rely on it. */
25
+ const FALLBACK_API_URL = 'http://localhost:7473';
18
26
  export class TacitClient {
19
27
  apiUrl;
20
28
  _appUrl;
21
29
  token;
30
+ sessionToken;
22
31
  _fetch;
23
32
  _rootDir;
24
33
  _workspaceId;
25
- _workspaceName = null;
34
+ _workspaceName;
35
+ _credentialSource;
36
+ _envVar;
26
37
  _initialized = false;
27
38
  /**
28
- * @param fetchOrOpts - Optional: a custom fetch implementation (for testing),
29
- * or a TacitClientOptions object. If a function is provided it overrides
30
- * global fetch. Configuration falls back to environment variables.
31
- * @param opts - Additional options (apiUrl, token, workspaceId, rootDir).
32
- * Only used when fetchOrOpts is a fetch function.
39
+ * @param fetchOrOpts - A custom fetch implementation (for testing) or a
40
+ * TacitClientOptions object.
41
+ * @param opts - Options when the first argument is a fetch function.
33
42
  */
34
43
  constructor(fetchOrOpts, opts = {}) {
35
44
  let resolvedOpts = {};
@@ -42,13 +51,17 @@ export class TacitClient {
42
51
  resolvedOpts = fetchOrOpts;
43
52
  this._fetch = globalThis.fetch.bind(globalThis);
44
53
  }
45
- this.apiUrl = (resolvedOpts.apiUrl ?? process.env['TACIT_API_URL'] ?? 'http://localhost:7473').replace(/\/$/, '');
46
- this._appUrl = (resolvedOpts.appUrl ?? process.env['TACIT_APP_URL'] ?? '').replace(/\/$/, '');
47
- // Token from env only — NEVER log this value.
48
- this.token = resolvedOpts.token ?? process.env['TACIT_TOKEN'] ?? '';
54
+ this.apiUrl = (resolvedOpts.apiUrl ?? FALLBACK_API_URL).replace(/\/$/, '');
55
+ this._appUrl = (resolvedOpts.appUrl ?? '').replace(/\/$/, '');
56
+ // NEVER log these values.
57
+ this.token = resolvedOpts.token ?? '';
58
+ this.sessionToken = resolvedOpts.sessionToken ?? '';
49
59
  this._rootDir = resolvedOpts.rootDir ?? process.cwd();
50
- let resolvedWorkspaceId = resolvedOpts.workspaceId ?? process.env['TACIT_WORKSPACE_ID'] ?? '';
51
- // BUG-369: sync.json is a FALLBACK, not an override. Only use when opts/env didn't provide a value.
60
+ this._workspaceName = resolvedOpts.workspaceName ?? null;
61
+ this._credentialSource = resolvedOpts.credentialSource ?? 'profile';
62
+ this._envVar = resolvedOpts.envVar ?? null;
63
+ let resolvedWorkspaceId = resolvedOpts.workspaceId ?? '';
64
+ // BUG-369: sync.json is a FALLBACK, not an override. Only used when no workspace id was supplied.
52
65
  if (!resolvedWorkspaceId) {
53
66
  try {
54
67
  const syncPath = path.join(this._rootDir, '.tacit', 'sync.json');
@@ -65,35 +78,71 @@ export class TacitClient {
65
78
  }
66
79
  this._workspaceId = resolvedWorkspaceId;
67
80
  }
81
+ /** Values that fill the `<workspace>` / credential slots of api-errors.ts messages. */
82
+ errorContext() {
83
+ return { workspace: this._workspaceName, credentialSource: this._credentialSource, envVar: this._envVar };
84
+ }
68
85
  get workspaceId() {
69
86
  return this._workspaceId;
70
87
  }
71
88
  get workspaceName() {
72
89
  return this._workspaceName;
73
90
  }
91
+ /** GET /api/v1/auth/whoami. Throws TokenExpiredError (401) or TacitApiError. */
92
+ async whoami(timeoutMs = 10_000) {
93
+ return this.get('/api/v1/auth/whoami', undefined, timeoutMs);
94
+ }
95
+ /** Adopt a verified identity: fills a missing workspace id and the name; skips the /workspaces/mine lookup. */
96
+ applyIdentity(who) {
97
+ if (!this._workspaceId)
98
+ this._workspaceId = who.workspace_id;
99
+ if (who.workspace_name)
100
+ this._workspaceName = who.workspace_name;
101
+ this._initialized = true;
102
+ }
103
+ /**
104
+ * Decoded payload of an HMAC session credential (carries the autonomy claim), or null
105
+ * when the client does not hold one. Never returns the token itself.
106
+ */
107
+ hmacSessionClaims() {
108
+ const hmac = this.sessionToken || (isHmacSessionToken(this.token) ? this.token : '');
109
+ if (!hmac)
110
+ return null;
111
+ try {
112
+ const payload = JSON.parse(Buffer.from(hmac.split('.')[0], 'base64url').toString('utf-8'));
113
+ return payload && typeof payload === 'object' ? payload : null;
114
+ }
115
+ catch {
116
+ return null;
117
+ }
118
+ }
119
+ /**
120
+ * Fill in the workspace name for a client built without one (level-2 env credentials on an
121
+ * old server). Never replaces a workspace id that is already set.
122
+ */
74
123
  async initialize() {
75
124
  if (this._initialized)
76
125
  return;
126
+ if (this._workspaceId && this._workspaceName) {
127
+ this._initialized = true;
128
+ return;
129
+ }
77
130
  try {
78
131
  const data = await this.get('/api/v1/workspaces/mine');
79
132
  if (data && typeof data === 'object') {
80
- if ('active_workspace_id' in data && typeof data.active_workspace_id === 'string') {
133
+ if (!this._workspaceId && typeof data.active_workspace_id === 'string') {
81
134
  this._workspaceId = data.active_workspace_id;
82
135
  }
83
136
  if (Array.isArray(data.workspaces) && data.workspaces.length > 0) {
84
- const active = data.workspaces.find((w) => w.workspace_id === this._workspaceId || w.id === this._workspaceId);
137
+ const list = data.workspaces;
138
+ const active = list.find((w) => (w.workspace_id ?? w.id) === this._workspaceId) ?? (this._workspaceId ? undefined : list[0]);
85
139
  if (active) {
140
+ if (!this._workspaceId)
141
+ this._workspaceId = (active.workspace_id ?? active.id);
86
142
  const name = active.display_name ?? active.name;
87
143
  if (typeof name === 'string')
88
144
  this._workspaceName = name;
89
145
  }
90
- if (!this._workspaceId) {
91
- const first = data.workspaces[0];
92
- this._workspaceId = (first.workspace_id ?? first.id);
93
- const name = first.display_name ?? first.name;
94
- if (typeof name === 'string')
95
- this._workspaceName = name;
96
- }
97
146
  }
98
147
  }
99
148
  this._initialized = true;
@@ -102,39 +151,37 @@ export class TacitClient {
102
151
  this._initialized = true;
103
152
  }
104
153
  }
154
+ /**
155
+ * Switch workspace. Session JWT credentials only (G4, D-45): any other credential kind
156
+ * switches by choosing another saved login, so it gets a named error instead of a 401.
157
+ */
105
158
  async switchWorkspace(workspaceId) {
159
+ if (!JWT_SHAPE_RE.test(this.token))
160
+ throw new SwitchNotSupportedError();
106
161
  const data = await this.post('/api/v1/auth/switch-workspace', {
107
162
  workspace_id: workspaceId,
108
163
  });
109
- if (data && typeof data === 'object' && 'token' in data && typeof data.token === 'string') {
110
- this.token = data.token;
111
- }
112
- this._workspaceId = workspaceId;
113
- if (data && typeof data === 'object' && 'name' in data && typeof data.name === 'string') {
114
- this._workspaceName = data.name;
115
- }
116
- else {
117
- this._workspaceName = null;
164
+ if (!data || typeof data !== 'object' || typeof data['session_token'] !== 'string') {
165
+ throw new Error('TACIT returned no session token for the workspace switch.');
118
166
  }
167
+ this.token = data['session_token'];
168
+ this._workspaceId = typeof data['workspace_id'] === 'string' ? data['workspace_id'] : workspaceId;
169
+ this._workspaceName = typeof data['workspace_name'] === 'string' ? data['workspace_name'] : null;
170
+ clearAutonomyCache();
119
171
  return {
120
- workspace_id: workspaceId,
172
+ workspace_id: this._workspaceId,
121
173
  name: this._workspaceName ?? 'unknown',
122
174
  };
123
175
  }
124
176
  /**
125
177
  * Resolve the workspace ID:
126
- * 1. Return this._workspaceId if already set (from constructor opts/profile).
127
- * 2. TACIT_WORKSPACE_ID env var (BUG-369: takes priority over sync.json).
128
- * 3. Fall back to <rootDir>/.tacit/sync.json.
129
- * 4. Return null if no source is available.
178
+ * 1. Return this._workspaceId if already set (constructor options / profile / whoami).
179
+ * 2. Fall back to <rootDir>/.tacit/sync.json.
180
+ * 3. Return null if no source is available.
130
181
  */
131
182
  async resolveWorkspaceId() {
132
183
  if (this._workspaceId)
133
184
  return this._workspaceId;
134
- // BUG-369: env takes precedence over sync.json
135
- const envId = process.env['TACIT_WORKSPACE_ID'];
136
- if (envId && envId.length > 0)
137
- return envId;
138
185
  try {
139
186
  const syncPath = path.join(this._rootDir, '.tacit', 'sync.json');
140
187
  if (fs.existsSync(syncPath)) {
@@ -151,7 +198,7 @@ export class TacitClient {
151
198
  }
152
199
  /**
153
200
  * Build a user-facing URL for an entity in the TACIT web app.
154
- * Returns null when TACIT_APP_URL is not configured.
201
+ * Returns null when no app URL is configured.
155
202
  *
156
203
  * Route patterns (TanStack file-based routing in tacitai.app.beta):
157
204
  * artifact → /view/:id
@@ -190,19 +237,15 @@ export class TacitClient {
190
237
  /**
191
238
  * Build auth headers. Value is NEVER written to logs.
192
239
  *
193
- * MV-1515n (W5 harness): when TACIT_SESSION_TOKEN is set (an HMAC
194
- * X-Tacit-Session token, per tacit-internal-token-auth §HMAC session token
195
- * format), it takes precedence and is sent as X-Tacit-Session instead of
196
- * Authorization — this is additive and does not change default behavior
197
- * (Bearer via TACIT_TOKEN) when TACIT_SESSION_TOKEN is unset.
240
+ * An HMAC session credential (explicit `sessionToken`, MV-1515n harness, or an HMAC-shaped
241
+ * token) is sent as X-Tacit-Session; everything else as a Bearer token.
198
242
  */
199
243
  authHeaders(extra) {
200
244
  const headers = {
201
245
  'Content-Type': 'application/json',
202
246
  };
203
- const sessionToken = process.env['TACIT_SESSION_TOKEN'];
204
- if (sessionToken) {
205
- headers['X-Tacit-Session'] = sessionToken;
247
+ if (this.sessionToken) {
248
+ headers['X-Tacit-Session'] = this.sessionToken;
206
249
  }
207
250
  else if (this.token) {
208
251
  if (isHmacSessionToken(this.token)) {
@@ -216,8 +259,24 @@ export class TacitClient {
216
259
  Object.assign(headers, extra);
217
260
  return headers;
218
261
  }
262
+ /**
263
+ * Every request carries a credential, so none may follow a redirect (L-7): a 307/308 would re-send
264
+ * the Authorization / X-Tacit-Session header and body to another origin. A 3xx is an error.
265
+ */
266
+ async send(url, init) {
267
+ const res = await this._fetch(url, { ...init, redirect: 'manual' });
268
+ if (res.status >= 300 && res.status < 400) {
269
+ let host = url;
270
+ try {
271
+ host = new URL(url).host;
272
+ }
273
+ catch { /* keep raw */ }
274
+ throw new TacitApiError(res.status, `${host} answered with a redirect (HTTP ${res.status}). TACIT does not follow redirects with a login attached.`, new URL(url, 'http://x').pathname);
275
+ }
276
+ return res;
277
+ }
219
278
  /** GET request returning parsed JSON. */
220
- async get(endpoint, params) {
279
+ async get(endpoint, params, timeoutMs) {
221
280
  const url = new URL(`${this.apiUrl}${endpoint}`);
222
281
  if (params) {
223
282
  for (const [k, v] of Object.entries(params)) {
@@ -225,17 +284,12 @@ export class TacitClient {
225
284
  url.searchParams.set(k, String(v));
226
285
  }
227
286
  }
228
- const res = await this._fetch(url.toString(), {
229
- method: 'GET',
230
- headers: this.authHeaders(),
231
- });
232
- if (!res.ok) {
233
- const body = await res.text().catch(() => '');
234
- if (res.status === 401) {
235
- throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
236
- }
237
- throw new TacitApiError(res.status, body, endpoint);
238
- }
287
+ const init = { method: 'GET', headers: this.authHeaders() };
288
+ if (timeoutMs)
289
+ init.signal = AbortSignal.timeout(timeoutMs);
290
+ const res = await this.send(url.toString(), init);
291
+ if (!res.ok)
292
+ await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
239
293
  return res.json();
240
294
  }
241
295
  /** POST request returning parsed JSON. `extraHeaders` merges on top of auth headers (e.g. If-Match). */
@@ -247,45 +301,30 @@ export class TacitClient {
247
301
  };
248
302
  if (timeoutMs)
249
303
  opts.signal = AbortSignal.timeout(timeoutMs);
250
- const res = await this._fetch(`${this.apiUrl}${endpoint}`, opts);
251
- if (!res.ok) {
252
- const text = await res.text().catch(() => '');
253
- if (res.status === 401) {
254
- throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
255
- }
256
- throw new TacitApiError(res.status, text, endpoint);
257
- }
304
+ const res = await this.send(`${this.apiUrl}${endpoint}`, opts);
305
+ if (!res.ok)
306
+ await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
258
307
  return res.json();
259
308
  }
260
309
  /** PUT request returning parsed JSON. */
261
310
  async put(endpoint, body) {
262
- const res = await this._fetch(`${this.apiUrl}${endpoint}`, {
311
+ const res = await this.send(`${this.apiUrl}${endpoint}`, {
263
312
  method: 'PUT',
264
313
  headers: this.authHeaders(),
265
314
  body: JSON.stringify(body),
266
315
  });
267
- if (!res.ok) {
268
- const text = await res.text().catch(() => '');
269
- if (res.status === 401) {
270
- throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
271
- }
272
- throw new TacitApiError(res.status, text, endpoint);
273
- }
316
+ if (!res.ok)
317
+ await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
274
318
  return res.json();
275
319
  }
276
320
  /** DELETE request returning parsed JSON (or empty on 204). */
277
321
  async delete(endpoint) {
278
- const res = await this._fetch(`${this.apiUrl}${endpoint}`, {
322
+ const res = await this.send(`${this.apiUrl}${endpoint}`, {
279
323
  method: 'DELETE',
280
324
  headers: this.authHeaders(),
281
325
  });
282
- if (!res.ok) {
283
- const text = await res.text().catch(() => '');
284
- if (res.status === 401) {
285
- throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
286
- }
287
- throw new TacitApiError(res.status, text, endpoint);
288
- }
326
+ if (!res.ok)
327
+ await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
289
328
  if (res.status === 204)
290
329
  return null;
291
330
  return res.json();
@@ -302,18 +341,13 @@ export class TacitClient {
302
341
  }
303
342
  /** PATCH request returning parsed JSON. */
304
343
  async patch(endpoint, body) {
305
- const res = await this._fetch(`${this.apiUrl}${endpoint}`, {
344
+ const res = await this.send(`${this.apiUrl}${endpoint}`, {
306
345
  method: 'PATCH',
307
346
  headers: this.authHeaders(),
308
347
  body: JSON.stringify(body),
309
348
  });
310
- if (!res.ok) {
311
- const text = await res.text().catch(() => '');
312
- if (res.status === 401) {
313
- throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
314
- }
315
- throw new TacitApiError(res.status, text, endpoint);
316
- }
349
+ if (!res.ok)
350
+ await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
317
351
  if (res.status === 204) {
318
352
  return {};
319
353
  }
@@ -324,7 +358,7 @@ export class TacitClient {
324
358
  * The Authorization header value is never written to process.stderr or stdout.
325
359
  */
326
360
  async *postSSE(endpoint, body) {
327
- const res = await this._fetch(`${this.apiUrl}${endpoint}`, {
361
+ const res = await this.send(`${this.apiUrl}${endpoint}`, {
328
362
  method: 'POST',
329
363
  headers: {
330
364
  ...this.authHeaders(),
@@ -332,13 +366,8 @@ export class TacitClient {
332
366
  },
333
367
  body: JSON.stringify(body),
334
368
  });
335
- if (!res.ok) {
336
- const text = await res.text().catch(() => '');
337
- if (res.status === 401) {
338
- throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
339
- }
340
- throw new TacitApiError(res.status, text, endpoint);
341
- }
369
+ if (!res.ok)
370
+ await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
342
371
  if (!res.body) {
343
372
  throw new Error('SSE response has no body');
344
373
  }
@@ -376,23 +405,17 @@ export class TacitClient {
376
405
  }
377
406
  /** POST multipart form data (for file ingest). */
378
407
  async postFormData(endpoint, formData) {
379
- // Build headers without Content-Type (let fetch set multipart boundary).
380
- const headers = {};
381
- if (this.token) {
382
- headers['Authorization'] = `Bearer ${this.token}`;
383
- }
384
- const res = await this._fetch(`${this.apiUrl}${endpoint}`, {
408
+ // Use authHeaders() for correct HMAC/Bearer routing (BUG-403),
409
+ // then drop Content-Type so fetch sets the multipart boundary.
410
+ const headers = this.authHeaders();
411
+ delete headers['Content-Type'];
412
+ const res = await this.send(`${this.apiUrl}${endpoint}`, {
385
413
  method: 'POST',
386
414
  headers,
387
415
  body: formData,
388
416
  });
389
- if (!res.ok) {
390
- const text = await res.text().catch(() => '');
391
- if (res.status === 401) {
392
- throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
393
- }
394
- throw new TacitApiError(res.status, text, endpoint);
395
- }
417
+ if (!res.ok)
418
+ await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
396
419
  return res.json();
397
420
  }
398
421
  }
@@ -400,29 +423,41 @@ export class TacitApiError extends Error {
400
423
  statusCode;
401
424
  body;
402
425
  endpoint;
403
- constructor(statusCode, body, endpoint) {
404
- super(`Tacit API error ${statusCode} on ${endpoint}`);
426
+ workspace;
427
+ constructor(statusCode, body, endpoint,
428
+ /** Workspace name when the client knew it, for the <workspace> slot of api-errors.ts messages. */
429
+ workspace = null,
430
+ /** The api-errors.ts message for this status + code, when the table has one. */
431
+ message) {
432
+ super(message ?? `Tacit API error ${statusCode} on ${endpoint}`);
405
433
  this.statusCode = statusCode;
406
434
  this.body = body;
407
435
  this.endpoint = endpoint;
436
+ this.workspace = workspace;
408
437
  this.name = 'TacitApiError';
409
438
  }
410
439
  }
411
440
  /**
412
- * Thrown when the API returns 401 — indicates the developer token has expired
413
- * or been revoked. Tools catch this and surface a user-actionable message.
441
+ * Thrown when the API returns 401 — the credential has expired or been revoked.
442
+ * Tools catch this and surface a user-actionable message.
414
443
  *
415
- * FEAT-193: The server grants a 7-day grace window after expiry — during that
416
- * window, `POST /api/v1/developer-tokens/refresh` still works (no browser
417
- * re-auth needed). After 7 days, full device-auth is required.
444
+ * `code` is the server's named error code when the 401 body carried one
445
+ * (e.g. MEMBERSHIP_NOT_FOUND, CREDENTIAL_BINDING_MISMATCH); null for an old server.
418
446
  *
419
447
  * Security invariant: token plaintext is NEVER included in this error.
420
448
  */
421
449
  export class TokenExpiredError extends Error {
422
450
  renewalUrl;
423
451
  setupCommand;
424
- constructor(renewalUrl, setupCommand) {
425
- const msg = [
452
+ code;
453
+ workspace;
454
+ statusCode = 401;
455
+ constructor(renewalUrl, setupCommand, code = null,
456
+ /** The api-errors.ts message for this 401. When absent, the generic renewal text is used. */
457
+ message,
458
+ /** Workspace name when the client knew it. */
459
+ workspace = null) {
460
+ const msg = message ?? [
426
461
  'Developer token expired or revoked.',
427
462
  'Re-authenticate within 7 days for easy refresh (no browser flow needed).',
428
463
  `Renew at: ${renewalUrl}`,
@@ -431,101 +466,49 @@ export class TokenExpiredError extends Error {
431
466
  super(msg);
432
467
  this.renewalUrl = renewalUrl;
433
468
  this.setupCommand = setupCommand;
469
+ this.code = code;
470
+ this.workspace = workspace;
434
471
  this.name = 'TokenExpiredError';
435
472
  }
436
473
  }
437
- function isNonEmpty(val) {
438
- return typeof val === 'string' && val.trim().length > 0;
439
- }
440
- const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
441
- export function loadProfile(name) {
442
- if (!PROFILE_NAME_RE.test(name)) {
443
- throw new Error(`Invalid profile name '${name}'. Names must match: ${PROFILE_NAME_RE}`);
444
- }
445
- const profilePath = path.join(os.homedir(), '.tacit', 'profiles', `${name}.json`);
446
- if (!fs.existsSync(profilePath)) {
447
- throw new Error(`Profile '${name}' not found at ${profilePath}`);
474
+ /** `tacit_switch_workspace` with a credential that is not a session JWT (D-45). */
475
+ export class SwitchNotSupportedError extends Error {
476
+ constructor() {
477
+ super(SWITCH_NOT_SUPPORTED);
478
+ this.name = 'SwitchNotSupportedError';
448
479
  }
449
- let data;
480
+ }
481
+ /** Named error code from a JSON error body: {"error":{"code":"X"}}, {"code":"X"} or {"error":"X"}. */
482
+ function errorCodeOf(body) {
450
483
  try {
451
- data = JSON.parse(fs.readFileSync(profilePath, 'utf-8'));
452
- }
453
- catch (err) {
454
- throw new Error(`Profile '${name}' is corrupted: ${err instanceof Error ? err.message : String(err)}. Re-run: tacit login`);
455
- }
456
- if (data.version !== 2) {
457
- throw new Error(`Profile '${name}' was created by setup and lacks credentials. Re-run: npx -p @tacitai/mcp-server tacit login`);
458
- }
459
- if (typeof data.workspace_id !== 'string' || !data.workspace_id ||
460
- typeof data.token !== 'string' || !data.token ||
461
- typeof data.api_url !== 'string' || !data.api_url) {
462
- throw new Error(`Profile '${name}' is missing required fields (workspace_id, token, api_url). Re-run: tacit login`);
463
- }
464
- if (typeof data.expires_at === 'string') {
465
- const expiresMs = Date.parse(data.expires_at);
466
- if (!Number.isNaN(expiresMs) && Date.now() > expiresMs) {
467
- process.stderr.write(`[TACIT] Warning: profile '${name}' token expired ${data.expires_at}. Re-run: tacit login\n`);
484
+ const parsed = JSON.parse(body);
485
+ const nested = parsed.error;
486
+ if (nested && typeof nested === 'object' && typeof nested.code === 'string') {
487
+ return nested.code;
468
488
  }
489
+ if (typeof parsed.code === 'string')
490
+ return parsed.code;
491
+ if (typeof nested === 'string')
492
+ return nested;
493
+ }
494
+ catch {
495
+ // Not JSON.
469
496
  }
470
- return data;
497
+ return null;
471
498
  }
472
499
  /**
473
- * 5-level resolution chain (FEAT-255 §2.1). Empty-string-as-unset rule applies.
474
- * Returns TacitClientOptions from the first matching level.
475
- * Throws on set-but-invalid states (profile missing, WORKSPACE_ID without TOKEN).
500
+ * The one place a non-2xx response becomes an error: 401 -> TokenExpiredError, anything else -> TacitApiError.
501
+ * The 401 message comes from api-errors.ts (named code first, then the no-code row).
476
502
  */
477
- export function resolveProfileOptions() {
478
- // Level 1: TACIT_PROFILE env → load profile (profile values take precedence over stray env vars)
479
- const profileName = process.env['TACIT_PROFILE'];
480
- if (isNonEmpty(profileName)) {
481
- const profile = loadProfile(profileName);
482
- return {
483
- apiUrl: profile.api_url,
484
- appUrl: profile.app_url,
485
- token: profile.token,
486
- workspaceId: profile.workspace_id,
487
- };
488
- }
489
- // Level 2: explicit env vars (backward compat)
490
- if (isNonEmpty(process.env['TACIT_WORKSPACE_ID'])) {
491
- if (!isNonEmpty(process.env['TACIT_TOKEN'])) {
492
- throw new Error('TACIT_WORKSPACE_ID set but TACIT_TOKEN missing');
493
- }
494
- return {
495
- apiUrl: process.env['TACIT_API_URL']?.trim() || undefined,
496
- token: process.env['TACIT_TOKEN'].trim(),
497
- workspaceId: process.env['TACIT_WORKSPACE_ID'].trim(),
498
- };
499
- }
500
- if (isNonEmpty(process.env['TACIT_TOKEN'])) {
501
- return {
502
- apiUrl: process.env['TACIT_API_URL']?.trim() || undefined,
503
- token: process.env['TACIT_TOKEN'].trim(),
504
- };
505
- }
506
- // Level 3: sync.json workspace_id + default profile credentials
507
- // (constructor handles sync.json as fallback when no profile opts are set)
508
- // Level 4: ~/.tacit/default → profile name
509
- const defaultPath = path.join(os.homedir(), '.tacit', 'default');
510
- try {
511
- if (fs.existsSync(defaultPath)) {
512
- const defaultName = fs.readFileSync(defaultPath, 'utf-8').trim();
513
- if (defaultName) {
514
- const profile = loadProfile(defaultName);
515
- return {
516
- apiUrl: isNonEmpty(process.env['TACIT_API_URL']) ? process.env['TACIT_API_URL'].trim() : profile.api_url,
517
- appUrl: isNonEmpty(process.env['TACIT_APP_URL']) ? process.env['TACIT_APP_URL'].trim() : profile.app_url,
518
- token: profile.token,
519
- workspaceId: profile.workspace_id,
520
- };
521
- }
522
- }
523
- }
524
- catch (err) {
525
- process.stderr.write(`[TACIT] Default profile load failed: ${err instanceof Error ? err.message : String(err)}\n`);
526
- }
527
- // Level 5: no profile config — return empty (backward compat with env-only setup)
528
- return {};
503
+ async function throwForStatus(res, endpoint, apiUrl, ctx = {}) {
504
+ const text = await res.text().catch(() => '');
505
+ const code = errorCodeOf(text);
506
+ const workspace = ctx.workspace ?? null;
507
+ if (res.status === 401) {
508
+ const message = messageForResponse(401, code, ctx) ?? messageForResponse(401, null, ctx) ?? undefined;
509
+ throw new TokenExpiredError(`${apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${apiUrl}`, code, message, workspace);
510
+ }
511
+ throw new TacitApiError(res.status, text, endpoint, workspace, messageForResponse(res.status, code, ctx) ?? undefined);
529
512
  }
530
513
  const requestStore = new AsyncLocalStorage();
531
514
  /** HTTPS mode: bind the caller's token/apiUrl/principal to everything run inside fn. */
@@ -535,92 +518,11 @@ export function runWithRequestContext(token, apiUrl, fn, principal) {
535
518
  export function getRequestPrincipal() {
536
519
  return requestStore.getStore()?.principal ?? null;
537
520
  }
538
- const AUTONOMY_ORDINAL = { GUEST: 0, SCRIBE: 1, MENTAT: 2, TWIN: 3 };
539
- export function parseAutonomyLevel(raw) {
540
- if (typeof raw !== 'string' || !raw)
541
- return 'SCRIBE';
542
- const upper = raw.toUpperCase();
543
- if (upper === 'OWNER')
544
- return 'TWIN';
545
- if (upper === 'GUEST' || upper === 'SCRIBE' || upper === 'MENTAT' || upper === 'TWIN')
546
- return upper;
547
- return 'SCRIBE';
548
- }
549
- export function autonomyAtLeast(current, required) {
550
- return AUTONOMY_ORDINAL[current] >= AUTONOMY_ORDINAL[required];
551
- }
552
- const autonomyCache = new Map();
553
- function envFallbackAutonomy() {
554
- return parseAutonomyLevel(process.env['TACIT_AUTONOMY_LEVEL']);
555
- }
556
- export async function getRequestAutonomy(principal) {
557
- const cached = autonomyCache.get(principal);
558
- if (cached)
559
- return cached;
560
- const token = process.env['TACIT_TOKEN'] ?? '';
561
- if (!token) {
562
- const level = envFallbackAutonomy();
563
- autonomyCache.set(principal, level);
564
- return level;
565
- }
566
- // HMAC session tokens carry autonomy_level in their payload — no API call needed
567
- if (isHmacSessionToken(token)) {
568
- try {
569
- const payloadB64 = token.split('.')[0];
570
- const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString('utf-8'));
571
- const level = parseAutonomyLevel(payload.autonomy_level);
572
- autonomyCache.set(principal, level);
573
- return level;
574
- }
575
- catch {
576
- return envFallbackAutonomy();
577
- }
578
- }
579
- const apiUrl = (process.env['TACIT_API_URL'] ?? 'http://localhost:7473').replace(/\/$/, '');
580
- try {
581
- const resp = await globalThis.fetch(`${apiUrl}/api/v1/people/myself`, {
582
- headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
583
- signal: AbortSignal.timeout(5000),
584
- });
585
- if (resp.status === 401) {
586
- return { error: 'token_expired' };
587
- }
588
- if (resp.status === 403) {
589
- const body = await resp.text().catch(() => '');
590
- if (body.includes('people.read')) {
591
- autonomyCache.set(principal, 'GUEST');
592
- return 'GUEST';
593
- }
594
- const level = envFallbackAutonomy();
595
- autonomyCache.set(principal, level);
596
- return level;
597
- }
598
- if (resp.status === 404) {
599
- const level = envFallbackAutonomy();
600
- autonomyCache.set(principal, level);
601
- return level;
602
- }
603
- if (!resp.ok) {
604
- const level = envFallbackAutonomy();
605
- return level; // don't cache non-2xx
606
- }
607
- const data = (await resp.json());
608
- const level = parseAutonomyLevel(data['autonomy_level']);
609
- autonomyCache.set(principal, level);
610
- return level;
611
- }
612
- catch {
613
- return envFallbackAutonomy(); // network error — don't cache
614
- }
615
- }
616
- export async function ensureAutonomy(principal) {
617
- return getRequestAutonomy(principal);
618
- }
619
- export function getCachedAutonomy(principal) {
620
- return autonomyCache.get(principal) ?? null;
621
- }
622
- /** Shared singleton client (initialized lazily on first use). */
521
+ /** Shared client for the module-level getClient() (stdio: installed once at startup by index.ts). */
623
522
  let _defaultClient = null;
523
+ export function setDefaultClient(client) {
524
+ _defaultClient = client;
525
+ }
624
526
  export function getClient() {
625
527
  const ctx = requestStore.getStore();
626
528
  if (ctx) {