@tacitai/mcp-server 0.6.55 → 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 (59) 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/career.js +25 -1
  43. package/dist/tools/errors.d.ts +12 -0
  44. package/dist/tools/errors.js +65 -0
  45. package/dist/tools/exec-route.d.ts +34 -0
  46. package/dist/tools/exec-route.js +101 -27
  47. package/dist/tools/iam.js +2 -3
  48. package/dist/tools/secretary.d.ts +1 -0
  49. package/dist/tools/secretary.js +2 -1
  50. package/dist/tools/synthesize.d.ts +37 -0
  51. package/dist/tools/synthesize.js +126 -7
  52. package/dist/tools/voice.d.ts +3 -2
  53. package/dist/tools/voice.js +70 -18
  54. package/dist/tools/workspaces.js +7 -4
  55. package/dist/version.d.ts +6 -0
  56. package/dist/version.js +18 -0
  57. package/dist/workflow-registry.d.ts +1 -0
  58. package/dist/workflow-registry.js +21 -0
  59. package/package.json +4 -1
package/dist/prompts.js CHANGED
@@ -59,7 +59,7 @@ export function buildAssistantSystemPrompt(state) {
59
59
  lines.push('');
60
60
  lines.push('When the user asks for anything "in my voice" or you need voice-matched composition:');
61
61
  lines.push('1. Call tacit_voice_list_profiles to find their voice profile.');
62
- lines.push('2. Call tacit_compose_in_voice with the request. This uses TACIT Voice Resonance — a real system that analyzes writing samples to capture cadence, vocabulary, and patterns.');
62
+ lines.push('2. Assemble the grounded text (facts, draft) yourself, then call tacit_compose_in_voice with that text in `content` and the instruction in `query`. If it returns an error or voice_match_degraded is true, tell the user — do not fall back to your own draft. This uses TACIT Voice Resonance — a real system that analyzes writing samples to capture cadence, vocabulary, and patterns.');
63
63
  lines.push('3. NEVER draft text yourself and claim it matches the user\'s voice. That is LLM approximation, not voice matching.');
64
64
  lines.push('4. NEVER offer to "paste a sample email" or "upload writing samples" during onboarding — voice profiles are pre-loaded during workspace setup.');
65
65
  lines.push('5. If no voice profile exists, say so honestly and move on — do not fake it.');
@@ -269,8 +269,8 @@ export const EXPERIENCES = [
269
269
  { id: 'build_your_map', num: 5, name: 'Build Your Map', tier: 1, tierName: 'Orient & Equip', action: 'This experience adapts to the workspace state. First, detect what exists:\n\n1. Call tacit_pyramid_list_portfolios to get all portfolios.\n2. For each portfolio, call tacit_pyramid_list_programs(portfolio_id) to aggregate programs.\n3. Call tacit_pyramid_list_value_streams to get all value streams.\n4. Exclude onboarding scaffolding when counting: ignore programs matching "*Onboarding Journey" and value streams named "Onboarding". Never exclude a portfolio — even if its only VS is "Onboarding", it represents a real investment segment.\n5. Count the remaining "real" programs and value streams.\n\nBRANCH A — EMPTY WORKSPACE (zero real programs AND zero real value streams after excluding onboarding scaffolding):\nRun the setup interview to build the user\'s actual pyramid. First, check existing portfolios by pillar — if Experience 4 or a prior session already created portfolios (e.g. an INTERNAL "Employee Experience"), adopt them per pillar. Do not duplicate. Ask whether each existing name fits or should be renamed. Then ask these questions one at a time:\n\n(1) "What do customers pay you for today?" → Distinct offerings become Value Streams inside a PRODUCT portfolio.\n(2) "What company-wide strategic decisions govern how you invest across everything?" → A BUSINESS portfolio covering governance, brand, capital allocation.\n(3) "What experience qualities do your employees receive that enable them to deliver?" → An INTERNAL portfolio covering employee experience excellence.\n(4) "What must stay true no matter what you are currently working on?" → The Knowledge Base: stream categories for offering truth, domain categories for cross-stream truth.\n(5) "Which 2-3 numbers define success this year?" → Strategic Objectives and Key Results at portfolio level, then VS Objectives that ladder up.\n(6) "What are you driving to done in the next 12 months?" → These become Programs.\n\nCreate real entities across all three pillars (BUSINESS, PRODUCT, INTERNAL). Validate every name against the four naming tests: board-slide (portfolio), customer-receipt (value stream), end-date (program), matrix/function-detection (should it be a domain category instead?). Functions like Engineering, Marketing, HR, Finance are NEVER portfolios or value streams — they describe how work gets done, not investment segments or offerings.\n\nBRANCH B — POPULATED WORKSPACE (any real programs OR real value streams exist after excluding onboarding scaffolding — i.e. NOT Branch A):\nShow what is already there — list all portfolios, value streams, programs, and dossiers. Explain each entity using the same definitions taught in Experience 4. Then run an audit/review against the setup interview questions, reframed as review questions:\n\n- "Does your portfolio structure cover all three pillars (BUSINESS, PRODUCT, INTERNAL)?"\n- "Do your value streams pass the customer-receipt test? Are any named after functions instead of what people receive?"\n- "Do your programs pass the end-date test? Are any immortal (never-ending)?"\n- "Are there functions masquerading as portfolios or value streams?" (the org-chart anti-pattern)\n- Identify gaps: missing pillars, orphan programs not linked to a value stream, function-named entities, flat pyramid (everything in one program).\n\nPresent findings as suggestions, not directives. Offer to help fix any issues found.', signal: 'User has either built their real pyramid structure (Branch A) or reviewed and validated their existing structure (Branch B)', tip: 'Three pillars: BUSINESS (where to invest), PRODUCT (what customers receive), INTERNAL (what employees receive). Every name has a test — if it fails, it belongs on a different tier.' },
270
270
  { id: 'connect_your_tools', num: 6, name: 'Connect Your Tools', tier: 1, tierName: 'Orient & Equip', action: 'First, CHECK what is already connected before telling the user anything: (1) Call tacit_github_list_connections to see GitHub repo connections. (2) Check your available MCP tool list — if you have Gmail tools (mcp__claude_ai_Gmail__*), Gmail IS connected. If you have Slack tools (mcp__plugin_*_slack__*), Slack IS connected. If you have Google Calendar tools, Calendar IS connected. If you have Google Drive tools, Drive IS connected. Present a CONNECTION STATUS showing what is already active and what is not. For anything already connected, say "Already connected — ready to use." For anything not connected, explain how to connect it via claude.ai Settings → Integrations. Also show GitHub workspace connections from step 1. Do NOT say a tool is disconnected if you can see its MCP tools in your available tool list. WAIT for the user to either connect something new or confirm they want to move on.', signal: 'User knows their connection status and has either connected new tools or confirmed they are ready to proceed', tip: 'GitHub connections sync your repos into the workspace. Gmail and Slack power the Morning Brief. Google Drive lets you pull in documents directly.' },
271
271
  { id: 'research_publish', num: 7, name: 'Research & Publish', tier: 2, tierName: 'The Operating System', action: 'Research a topic and publish a report. Ask the user what they want to research, or suggest a topic relevant to their business. Then: (1) Call tacit_research_prepare with the topic as the query. This runs two research lanes in parallel: a workspace lane (KB, pyramid, lake) and an academic lane (arXiv, OpenAlex, Semantic Scholar). The response includes research_lanes[] — each lane has a status and results array with source attribution. Use ALL results from both lanes. If the academic lane status is "partial", some providers returned results while others hit rate limits — use what came back. If "failed", note it and continue with workspace results. (2) Search the web for current information to complement the workspace and academic findings. (3) Combine ALL findings — workspace knowledge, academic papers, and web results — into a STYLED HTML REPORT using /artifact-design — invoke the artifact-design skill to get the design system, then build a proper HTML artifact with title, date, executive summary, sections with findings, citations, and a professional layout. Academic sources should be cited with author, title, and link. Publish it as a Claude artifact so the user sees it in their browser. Save the HTML file to disk. (4) After the artifact is saved, ingest the HTML FILE into TACIT via tacit_gm_ingest — pass the file path, not the content. The GM classifies and proposes placement. The user approves before anything moves. IMPORTANT: Do NOT copy-paste the report content into tacit_artifact_create. The correct flow is: create the HTML file → publish as Claude artifact → ingest the file via GM. This preserves provenance and goes through the lake-first pipeline.\n\nFILE SAVE PATH: Save the HTML file to ~/tacit-reports/ (inside the user home directory), NOT to the scratchpad. TACIT can only read files under the user home directory. After saving, pass the ~/tacit-reports/ path to tacit_gm_ingest.\n\nONBOARDING PLACEMENT DEFAULT: If the user reached this experience through onboarding (the completed set includes your_first_structure), default to placing the output in their onboarding program. Look up the program: call tacit_pyramid_list_value_streams, find the "Onboarding" VS, then call tacit_pyramid_list_programs filtered by that VS id to find their "{Name}\'s Onboarding Journey" program. When the GM proposes placement, suggest this program as the target — e.g. "I\'ll file this under your onboarding program ({Name}\'s Onboarding Journey). Approve?" The user can override to a different location, but the onboarding program is the default during onboarding.', signal: 'First research artifact published as a Claude artifact in the browser with workspace, academic, and web sources, then the HTML file ingested and placed via GM workflow', tip: 'After publishing, your General Manager will propose where to place the report in your knowledge structure — you approve the placement.' },
272
- { id: 'run_sales', num: 8, name: 'Run Sales', tier: 2, tierName: 'The Operating System', action: 'Part 1 — Discovery Brief: Say "Prepare a discovery brief for a potential client." TACIT uses workspace knowledge to build a discovery framework. The brief should be a STYLED HTML REPORT using /artifact-design — same flow as Experience 7: invoke artifact-design, build the HTML, publish as a Claude artifact, save the file to disk, then ingest the HTML file via tacit_gm_ingest for placement. ONBOARDING PLACEMENT DEFAULT: If the user reached this experience through onboarding (the completed set includes your_first_structure), default to placing the output in their onboarding program — look up the "Onboarding" VS via tacit_pyramid_list_value_streams, then find their "{Name}\'s Onboarding Journey" program via tacit_pyramid_list_programs filtered by that VS. Propose this program as the target; the user can override. Part 2 — Voice Composition: After the brief, draft an intro email using the TACIT Voice Resonance system. MANDATORY TWO-STEP FLOW: (1) GROUND FIRST — assemble the key facts from the discovery brief (prospect name, pain points, value proposition, relevant capabilities) into a structured plain-text brief. This is the content the voice system will work with. (2) COMPOSE IN VOICE — call tacit_voice_list_profiles to find the user\'s voice profile (it MUST exist — voice samples were pre-loaded). Then call tacit_compose_in_voice, passing the grounded-facts brief as the content to voice-ify. This ensures the voice system has concrete facts instead of re-retrieving from workspace docs. This uses TACIT\'s actual voice fingerprinting system, NOT LLM approximation. NEVER draft the email yourself and claim it matches the user\'s voice. NEVER offer to "paste a sample email" or "upload writing samples" — voice profiles are already loaded. If tacit_voice_list_profiles returns no profiles, say "I expected to find your voice profile but it is not set up yet — let me check with the team" and move on.\n\nGROUNDING ENFORCEMENT: NEVER fabricate people names, meeting dates, verbatim quotes, financial figures, or technical specifications. Every claim in the discovery brief and email must be grounded in workspace data returned by TACIT tools. If the workspace has thin data on the prospect, produce an honest thin brief — state what is known, flag what is missing, and suggest how to fill the gaps. A short, honest brief is always better than a fabricated detailed one.', signal: 'First sales deliverable as HTML report, then first voice-matched composition using TACIT Voice Resonance (not LLM approximation)', tip: 'Voice Resonance is a real system — it analyzes your writing samples to capture your cadence, vocabulary, and patterns. Every "in my voice" request routes through this system.' },
273
- { id: 'morning_brief', num: 9, name: 'Morning Brief', tier: 2, tierName: 'The Operating System', action: 'IMPORTANT — CONNECTOR DETECTION: Before running the brief, CHECK your available MCP tool list to determine what is connected. Gmail IS connected if you have mcp__claude_ai_Gmail__* tools available. Slack IS connected if you have mcp__plugin_*_slack__* tools. Calendar IS connected if you have mcp__claude_ai_Google_Calendar__* tools. Do NOT say "Gmail not connected" if you can see Gmail MCP tools — that is a false negative.\n\nSCOPE CHECK: After detecting connected tools, verify each connector belongs to the same organization as the workspace. If Slack channels or Gmail accounts reference a different company than the workspace name, exclude that connector data and explain why — say "Your connected [tool] appears to belong to a different organization than [workspace name]. That data has been excluded to maintain workspace isolation." Only include connector data from the workspace-matched organization.\n\nRun the COS daily brief: gather workspace state (programs, deadlines, proposals, KB freshness), and for each connected tool, pull real data — Gmail threads, Slack channels, Calendar events. Present the full operating picture. If a connector genuinely has no MCP tools available, say "not yet connected" and explain how to connect via claude.ai Integrations. After the brief, offer to draft a team message in the user\'s voice. TWO-STEP VOICE FLOW (mandatory): (1) GROUND FIRST — assemble a structured brief of the key facts, numbers, and updates you gathered from the morning brief (programs, deadlines, email highlights, meeting items). Write this as plain text with concrete data points. (2) COMPOSE IN VOICE — call tacit_compose_in_voice, passing the grounded-facts brief as the content to voice-ify. This ensures the voice system has verified facts to work with instead of re-retrieving from workspace documents (which cannot see the live MCP query results you just gathered). NEVER skip step 1 and call tacit_compose_in_voice with just "draft a team update" — the voice system cannot access the live data you collected.', signal: 'First daily operating picture with accurate connector status and real data from connected tools', tip: 'Meet your executive team. COS (Chief of Staff — daily ops, email, meetings), COO (Chief Operating Officer — business ops, sales, audits), GM (General Manager — content ingestion, classification, pyramid placement). Address them by name to route through their workflow.' },
272
+ { id: 'run_sales', num: 8, name: 'Run Sales', tier: 2, tierName: 'The Operating System', action: 'Part 1 — Discovery Brief: Say "Prepare a discovery brief for a potential client." TACIT uses workspace knowledge to build a discovery framework. The brief should be a STYLED HTML REPORT using /artifact-design — same flow as Experience 7: invoke artifact-design, build the HTML, publish as a Claude artifact, save the file to disk, then ingest the HTML file via tacit_gm_ingest for placement. ONBOARDING PLACEMENT DEFAULT: If the user reached this experience through onboarding (the completed set includes your_first_structure), default to placing the output in their onboarding program — look up the "Onboarding" VS via tacit_pyramid_list_value_streams, then find their "{Name}\'s Onboarding Journey" program via tacit_pyramid_list_programs filtered by that VS. Propose this program as the target; the user can override. Part 2 — Voice Composition: After the brief, draft an intro email using the TACIT Voice Resonance system. MANDATORY TWO-STEP FLOW: (1) GROUND FIRST — assemble the key facts from the discovery brief (prospect name, pain points, value proposition, relevant capabilities) into a structured plain-text brief. This is the content the voice system will work with. (2) COMPOSE IN VOICE — call tacit_voice_list_profiles to find the user\'s voice profile (it MUST exist — voice samples were pre-loaded). Then call tacit_compose_in_voice, passing the grounded-facts brief as the `content` argument (the instruction goes in `query`). This ensures the voice system has concrete facts instead of re-retrieving from workspace docs. This uses TACIT\'s actual voice fingerprinting system, NOT LLM approximation. NEVER draft the email yourself and claim it matches the user\'s voice. NEVER offer to "paste a sample email" or "upload writing samples" — voice profiles are already loaded. If tacit_voice_list_profiles returns no profiles, say "I expected to find your voice profile but it is not set up yet — let me check with the team" and move on.\n\nGROUNDING ENFORCEMENT: NEVER fabricate people names, meeting dates, verbatim quotes, financial figures, or technical specifications. Every claim in the discovery brief and email must be grounded in workspace data returned by TACIT tools. If the workspace has thin data on the prospect, produce an honest thin brief — state what is known, flag what is missing, and suggest how to fill the gaps. A short, honest brief is always better than a fabricated detailed one.', signal: 'First sales deliverable as HTML report, then first voice-matched composition using TACIT Voice Resonance (not LLM approximation)', tip: 'Voice Resonance is a real system — it analyzes your writing samples to capture your cadence, vocabulary, and patterns. Every "in my voice" request routes through this system.' },
273
+ { id: 'morning_brief', num: 9, name: 'Morning Brief', tier: 2, tierName: 'The Operating System', action: 'IMPORTANT — CONNECTOR DETECTION: Before running the brief, CHECK your available MCP tool list to determine what is connected. Gmail IS connected if you have mcp__claude_ai_Gmail__* tools available. Slack IS connected if you have mcp__plugin_*_slack__* tools. Calendar IS connected if you have mcp__claude_ai_Google_Calendar__* tools. Do NOT say "Gmail not connected" if you can see Gmail MCP tools — that is a false negative.\n\nSCOPE CHECK: After detecting connected tools, verify each connector belongs to the same organization as the workspace. If Slack channels or Gmail accounts reference a different company than the workspace name, exclude that connector data and explain why — say "Your connected [tool] appears to belong to a different organization than [workspace name]. That data has been excluded to maintain workspace isolation." Only include connector data from the workspace-matched organization.\n\nRun the COS daily brief: gather workspace state (programs, deadlines, proposals, KB freshness), and for each connected tool, pull real data — Gmail threads, Slack channels, Calendar events. Present the full operating picture. If a connector genuinely has no MCP tools available, say "not yet connected" and explain how to connect via claude.ai Integrations. After the brief, offer to draft a team message in the user\'s voice. TWO-STEP VOICE FLOW (mandatory): (1) GROUND FIRST — assemble a structured brief of the key facts, numbers, and updates you gathered from the morning brief (programs, deadlines, email highlights, meeting items). Write this as plain text with concrete data points. (2) COMPOSE IN VOICE — call tacit_compose_in_voice, passing the grounded-facts brief as the `content` argument (the instruction goes in `query`). This ensures the voice system has verified facts to work with instead of re-retrieving from workspace documents (which cannot see the live MCP query results you just gathered). NEVER skip step 1 and call tacit_compose_in_voice with just "draft a team update" — the voice system cannot access the live data you collected.', signal: 'First daily operating picture with accurate connector status and real data from connected tools', tip: 'Meet your executive team. COS (Chief of Staff — daily ops, email, meetings), COO (Chief Operating Officer — business ops, sales, audits), GM (General Manager — content ingestion, classification, pyramid placement). Address them by name to route through their workflow.' },
274
274
  { id: 'business_pulse', num: 10, name: 'Your Business Pulse', tier: 2, tierName: 'The Operating System', action: 'Show the user what TACIT can see about their business right now. Ask "Want to see your business pulse?" Then: (1) Gather workspace data — call tacit_pyramid_list_portfolios, tacit_pyramid_list_programs, tacit_pyramid_list_value_streams to assess structure completeness. Call tacit_kb_freshness to check knowledge currency. Call tacit_lake_browse_catalog to gauge content volume. Check connector status from the MCP tool list (Gmail, Slack, Calendar, Drive, GitHub). Call tacit_voice_list_profiles to check voice readiness. (2) Score each dimension (structure completeness, knowledge freshness, content depth, tool connectivity, voice readiness) and produce a STYLED HTML REPORT using /artifact-design — same flow as Experience 7: invoke artifact-design, build the HTML, publish as a Claude artifact, save the file to disk. The report should include dimension scores, a summary health grade, and concrete recommendations for what to build next. Frame it as a health snapshot, not a formal audit. (3) After the artifact is saved, ingest the HTML file via tacit_gm_ingest for placement. ONBOARDING PLACEMENT DEFAULT: If the user reached this experience through onboarding (the completed set includes your_first_structure), default to placing the output in their onboarding program — look up the "Onboarding" VS via tacit_pyramid_list_value_streams, then find their "{Name}\'s Onboarding Journey" program via tacit_pyramid_list_programs filtered by that VS. Propose this program as the target; the user can override.', signal: 'First business pulse report published as a Claude artifact showing workspace health scores, then filed via GM workflow', tip: 'This is your quick health snapshot. When you want the deep version, say "Have COO audit our business" — COO runs the formal operational review with remediation tracking.' },
275
275
  { id: 'operating_rhythm', num: 11, name: 'Your Operating Rhythm', tier: 3, tierName: 'Agentic Mastery', action: 'Summarize what the user has accomplished across the onboarding and suggest their operating rhythm. CONNECTOR STATUS: Check your available MCP tool list — if you have Gmail/Slack/Calendar/Drive MCP tools, those ARE connected. Do NOT say they are disconnected. CONNECTOR SCOPE: If any connector belongs to a different organization than the workspace (e.g., Slack is from "GoodOps" but the workspace is "Redwood Inference"), note this in the operating rhythm summary and advise that connector data from a different organization will be excluded from briefs to maintain workspace isolation. VOICE: Call tacit_voice_list_profiles — if profiles exist, voice is ready. Do NOT ask the user to upload samples if profiles already exist. Focus on: (1) Daily rhythm — morning brief via COS, email triage, meeting prep. (2) Weekly rhythm — COO business review, GM content organization. (3) Delegation — crew dispatch for complex deliverables. (4) What to explore next based on what they have connected and used.', signal: 'User has a clear picture of their operating rhythm and next steps', tip: 'By now you know the team: COS for daily ops, COO for business operations, GM for content. Address them directly anytime.' },
276
276
  ];
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Server startup resolution and the status-only modes (MV-1542c step 1.4, D-49, D-52).
3
+ *
4
+ * Startup: resolve credentials (levels 0/1/2/4/5) -> URL lock -> whoami -> one of
5
+ * normal full tool set
6
+ * error a credential problem; only `tacit_status`, which returns the exact failure and fix
7
+ * signed_out no credential anywhere; only `tacit_status`; never contacts a default server
8
+ *
9
+ * `error` and `signed_out` load no other tool, make no other API call, and the same text
10
+ * goes to stderr. Tokens never appear in any of it.
11
+ */
12
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
13
+ import { TacitClient } from './client.js';
14
+ import { type CredentialSource, type IdentityCheck } from './credentials.js';
15
+ export type ServerMode = {
16
+ mode: 'normal';
17
+ } | {
18
+ mode: 'error';
19
+ message: string;
20
+ } | {
21
+ mode: 'signed_out';
22
+ message: string;
23
+ };
24
+ export declare const SIGNED_OUT_MESSAGE = "Not signed in. Run: npx @tacitai/mcp-server setup";
25
+ export type StatusOnlyMode = Exclude<ServerMode, {
26
+ mode: 'normal';
27
+ }>;
28
+ export type StartupResult = {
29
+ mode: {
30
+ mode: 'normal';
31
+ };
32
+ client: TacitClient;
33
+ source: CredentialSource;
34
+ profile?: string;
35
+ identity: IdentityCheck;
36
+ warnings: string[];
37
+ } | {
38
+ mode: StatusOnlyMode;
39
+ source: CredentialSource;
40
+ profile?: string;
41
+ warnings: string[];
42
+ };
43
+ export interface StartupOptions {
44
+ env?: NodeJS.ProcessEnv;
45
+ /** Replaces global fetch (tests). */
46
+ fetchFn?: typeof globalThis.fetch;
47
+ now?: number;
48
+ }
49
+ export declare function resolveStartup(opts?: StartupOptions): Promise<StartupResult>;
50
+ /** The `tacit_status` result body for an error / signed_out server. */
51
+ export declare function statusPayload(mode: StatusOnlyMode, source: CredentialSource, profile?: string): {
52
+ profile?: string | undefined;
53
+ mode: "error" | "signed_out";
54
+ message: string;
55
+ source: CredentialSource;
56
+ };
57
+ /**
58
+ * The one tool an error / signed_out server exposes. It exists only in these stdio modes and is
59
+ * never part of the normal tool set, so it is registered through this constant rather than a
60
+ * literal `server.tool('tacit_…')` (tools/registry.test.ts classifies every literal registration
61
+ * for the HTTPS gate; this tool is never reachable over HTTPS).
62
+ */
63
+ export declare const STATUS_TOOL_NAME = "tacit_status";
64
+ /** Register the one tool an error / signed_out server exposes. */
65
+ export declare function registerStatusTool(server: McpServer, mode: StatusOnlyMode, source: CredentialSource, profile?: string): void;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Server startup resolution and the status-only modes (MV-1542c step 1.4, D-49, D-52).
3
+ *
4
+ * Startup: resolve credentials (levels 0/1/2/4/5) -> URL lock -> whoami -> one of
5
+ * normal full tool set
6
+ * error a credential problem; only `tacit_status`, which returns the exact failure and fix
7
+ * signed_out no credential anywhere; only `tacit_status`; never contacts a default server
8
+ *
9
+ * `error` and `signed_out` load no other tool, make no other API call, and the same text
10
+ * goes to stderr. Tokens never appear in any of it.
11
+ */
12
+ import { TacitClient } from './client.js';
13
+ import { rememberAutonomy, parseAutonomyLevel } from './autonomy.js';
14
+ import { networkError } from './api-errors.js';
15
+ import { CredentialError, StartupFault, resolveCredentials, verifyIdentity, } from './credentials.js';
16
+ export const SIGNED_OUT_MESSAGE = 'Not signed in. Run: npx @tacitai/mcp-server setup';
17
+ function profileNameOf(source) {
18
+ return source.level === 1 || source.level === 4 ? source.profile : undefined;
19
+ }
20
+ function hostLabel(url) {
21
+ if (!url)
22
+ return 'the server';
23
+ try {
24
+ return new URL(url).host;
25
+ }
26
+ catch {
27
+ return url;
28
+ }
29
+ }
30
+ function causeText(identity) {
31
+ if (identity.status === 'unreachable')
32
+ return `Couldn't confirm your login (${identity.cause}); continuing.`;
33
+ if (identity.status === 'unsupported')
34
+ return "This TACIT server can't confirm logins (older server); continuing.";
35
+ return null;
36
+ }
37
+ export async function resolveStartup(opts = {}) {
38
+ const env = opts.env ?? process.env;
39
+ let resolved;
40
+ try {
41
+ resolved = resolveCredentials(env, opts.now);
42
+ }
43
+ catch (err) {
44
+ if (err instanceof CredentialError) {
45
+ return { mode: { mode: 'error', message: err.message }, source: err.source, profile: profileNameOf(err.source), warnings: [] };
46
+ }
47
+ throw err;
48
+ }
49
+ const { source, warnings } = resolved;
50
+ const profile = profileNameOf(source);
51
+ if (source.level === 5) {
52
+ return { mode: { mode: 'signed_out', message: SIGNED_OUT_MESSAGE }, source, warnings };
53
+ }
54
+ const client = opts.fetchFn ? new TacitClient(opts.fetchFn, resolved.options) : new TacitClient(resolved.options);
55
+ let identity;
56
+ try {
57
+ identity = await verifyIdentity(client, resolved);
58
+ }
59
+ catch (err) {
60
+ if (err instanceof StartupFault) {
61
+ return { mode: { mode: 'error', message: err.message }, source, profile, warnings };
62
+ }
63
+ throw err;
64
+ }
65
+ // S3 / M-1: a saved profile is never trusted unverified. Without a whoami answer the profile's
66
+ // workspace label can't be checked against the token, so start in error mode (tacit_status only).
67
+ if (resolved.profile && identity.status !== 'verified') {
68
+ const message = identity.status === 'unreachable'
69
+ ? networkError(hostLabel(resolved.options.apiUrl), identity.cause)
70
+ : 'This TACIT server is older than this version of tacit and can\'t confirm CLI logins. Ask your admin to update it.';
71
+ return { mode: { mode: 'error', message }, source, profile, warnings };
72
+ }
73
+ const note = causeText(identity);
74
+ const allWarnings = note ? [...warnings, note] : warnings;
75
+ if (identity.status === 'verified') {
76
+ client.applyIdentity(identity.who);
77
+ if (typeof identity.who.autonomy_level === 'string' && identity.who.autonomy_level) {
78
+ rememberAutonomy('__stdio__', parseAutonomyLevel(identity.who.autonomy_level), 'whoami');
79
+ }
80
+ }
81
+ return { mode: { mode: 'normal' }, client, source, profile, identity, warnings: allWarnings };
82
+ }
83
+ /** The `tacit_status` result body for an error / signed_out server. */
84
+ export function statusPayload(mode, source, profile) {
85
+ return { mode: mode.mode, message: mode.message, source, ...(profile ? { profile } : {}) };
86
+ }
87
+ /**
88
+ * The one tool an error / signed_out server exposes. It exists only in these stdio modes and is
89
+ * never part of the normal tool set, so it is registered through this constant rather than a
90
+ * literal `server.tool('tacit_…')` (tools/registry.test.ts classifies every literal registration
91
+ * for the HTTPS gate; this tool is never reachable over HTTPS).
92
+ */
93
+ export const STATUS_TOOL_NAME = 'tacit_status';
94
+ /** Register the one tool an error / signed_out server exposes. */
95
+ export function registerStatusTool(server, mode, source, profile) {
96
+ server.tool(STATUS_TOOL_NAME, 'Show whether TACIT is signed in and, if not, the exact problem and how to fix it.', {}, async () => ({
97
+ content: [{ type: 'text', text: JSON.stringify(statusPayload(mode, source, profile)) }],
98
+ }));
99
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Old-entry migration for `setup` (MV-1542c step 1.3, P3.5, D-46/D-48).
3
+ *
4
+ * Finds Claude Code entries that still carry a literal `TACIT_TOKEN`, reports each one (shape and host,
5
+ * never the value), asks per entry, rewrites accepted entries without the token and with
6
+ * `TACIT_PROFILE=<slug>` (names and scope kept), then signs the old token out on the server with
7
+ * `if_bound_to_person_id` so only the signing-in member's own token can be revoked.
8
+ *
9
+ * Tracked `.mcp.json` files and the legacy `~/.claude/mcp.json` are reported only, never edited.
10
+ * The old token is never sent anywhere except as the Bearer of its own revoke call.
11
+ */
12
+ import { type LegacyEntry } from './claude-config.js';
13
+ import type { SignInIo } from './signin.js';
14
+ export interface MigrateContext {
15
+ io: SignInIo;
16
+ out(line: string): void;
17
+ env: NodeJS.ProcessEnv;
18
+ fetchFn: typeof fetch;
19
+ /** The sign-in that just succeeded. `personId` null = could not be confirmed (no revoke is sent). */
20
+ apiUrl: string;
21
+ workspaceId: string;
22
+ profile: string;
23
+ personId: string | null;
24
+ }
25
+ export interface MigrateResult {
26
+ found: number;
27
+ rewritten: number;
28
+ failed: number;
29
+ leftAlone: number;
30
+ }
31
+ export declare const REVOKE_QUESTION = "Revoke the old login stored there? (Y/n) ";
32
+ export declare const CONSENT_QUESTION = "Replace with a sign-in and remove the token? (y/N) ";
33
+ /** Token-free replacement for a named per-workspace entry: same command, args and non-credential env. */
34
+ export declare function rewrittenNamedEntry(e: LegacyEntry, profile: string): Record<string, unknown> | null;
35
+ export declare function migrateLegacyEntries(entries: LegacyEntry[], ctx: MigrateContext): Promise<MigrateResult>;
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Old-entry migration for `setup` (MV-1542c step 1.3, P3.5, D-46/D-48).
3
+ *
4
+ * Finds Claude Code entries that still carry a literal `TACIT_TOKEN`, reports each one (shape and host,
5
+ * never the value), asks per entry, rewrites accepted entries without the token and with
6
+ * `TACIT_PROFILE=<slug>` (names and scope kept), then signs the old token out on the server with
7
+ * `if_bound_to_person_id` so only the signing-in member's own token can be revoked.
8
+ *
9
+ * Tracked `.mcp.json` files and the legacy `~/.claude/mcp.json` are reported only, never edited.
10
+ * The old token is never sent anywhere except as the Bearer of its own revoke call.
11
+ */
12
+ import * as fs from 'node:fs';
13
+ import { PACKAGE_NAME, countBackupsWithToken, registerUserEntry, replaceEntry, } from './claude-config.js';
14
+ const CREDENTIAL_KEYS = ['TACIT_TOKEN', 'TACIT_WORKSPACE_ID', 'TACIT_API_URL', 'TACIT_APP_URL', 'TACIT_SESSION_TOKEN', 'TACIT_PROFILE'];
15
+ export const REVOKE_QUESTION = 'Revoke the old login stored there? (Y/n) ';
16
+ export const CONSENT_QUESTION = 'Replace with a sign-in and remove the token? (y/N) ';
17
+ const SESSION_LINE = (n) => `Old login for ${n} is a browser session token. It can't be revoked from here and stays valid until it expires ` +
18
+ '(about 100 years). Change nothing else, but tell your workspace admin.';
19
+ function hostOf(url) {
20
+ try {
21
+ return url ? new URL(url).host : null;
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ function describe(e) {
28
+ const where = e.scope === 'local' ? `local ${e.projectPath ?? ''}`.trim() : e.scope === 'legacy-file' ? 'legacy file' : e.scope;
29
+ const host = hostOf(e.apiUrl);
30
+ return ` ${e.name} [${where}] in ${e.file}: ${e.shape} token${host ? `, server ${host}` : ''}${e.gitTracked ? ', git-tracked' : ''}`;
31
+ }
32
+ function stillOverrides(e) {
33
+ return `Warning: ${e.name} in ${e.file} still holds a login token and will override your saved logins for that workspace.`;
34
+ }
35
+ /** Token-free replacement for a named per-workspace entry: same command, args and non-credential env. */
36
+ export function rewrittenNamedEntry(e, profile) {
37
+ const env = (e.entry['env'] ?? {});
38
+ const kept = {};
39
+ for (const [k, v] of Object.entries(env)) {
40
+ if (CREDENTIAL_KEYS.includes(k) || typeof v !== 'string' || v.includes(e.token))
41
+ continue;
42
+ kept[k] = v;
43
+ }
44
+ const { env: _env, ...rest } = e.entry;
45
+ void _env;
46
+ if (JSON.stringify(rest).includes(e.token))
47
+ return null;
48
+ return { ...rest, type: rest['type'] ?? 'stdio', env: { ...kept, TACIT_PROFILE: profile } };
49
+ }
50
+ async function revoke(name, token, entryApiUrl, ctx) {
51
+ const entryHost = hostOf(entryApiUrl);
52
+ if (!entryApiUrl || !entryHost)
53
+ return `Could not revoke the old token for ${name} (its server is unknown). It remains valid.`;
54
+ if (entryHost !== hostOf(ctx.apiUrl))
55
+ return `Could not revoke the old token for ${name} (it belongs to ${entryHost}, not this sign-in). It remains valid.`;
56
+ if (!ctx.personId)
57
+ return `Could not revoke the old token for ${name} (your identity could not be confirmed). It remains valid.`;
58
+ try {
59
+ const res = await ctx.fetchFn(`${entryApiUrl.replace(/\/+$/, '')}/api/v1/iam/tokens/self/revoke`, {
60
+ method: 'POST',
61
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
62
+ body: JSON.stringify({ if_bound_to_person_id: ctx.personId }),
63
+ signal: AbortSignal.timeout(15_000),
64
+ });
65
+ if (res.ok)
66
+ return `Old token for ${name} revoked.`;
67
+ let code = '';
68
+ try {
69
+ const b = (await res.json());
70
+ code = b.error?.code ?? b.code ?? '';
71
+ }
72
+ catch { /* no body */ }
73
+ if (res.status === 401)
74
+ return `Old token for ${name} was already expired or revoked.`;
75
+ if (res.status === 400 && code === 'NOT_A_DEVELOPER_TOKEN')
76
+ return SESSION_LINE(name);
77
+ if (res.status === 400 && code === 'INVALID_REQUEST_BODY') {
78
+ return `Could not sign out ${name} on the server (the request was malformed). It remains valid; update ${PACKAGE_NAME}.`;
79
+ }
80
+ if (res.status === 409 && code === 'UNBOUND_TOKEN_SHARED')
81
+ return `Old token for ${name} is a shared workspace token. It was left active; ask the workspace owner.`;
82
+ if (res.status === 409 && code === 'BINDING_MISMATCH')
83
+ return `Old token for ${name} belongs to a different member. It was left unchanged.`;
84
+ return `Could not revoke the old token for ${name} (HTTP ${res.status}). It remains valid.`;
85
+ }
86
+ catch (err) {
87
+ return `Could not revoke the old token for ${name} (${err instanceof Error ? err.name : 'network error'}). It remains valid.`;
88
+ }
89
+ }
90
+ async function rewrite(e, ctx) {
91
+ if (e.scope === 'local' && (!e.projectPath || !fs.existsSync(e.projectPath)))
92
+ return { ok: false, detail: 'its project folder no longer exists (stale entry)' };
93
+ if (e.name === 'tacit' && e.scope === 'user' && !e.workspaceId) {
94
+ const r = await registerUserEntry(e.folder, { replaceForeign: true, env: ctx.env });
95
+ return r.status === 'added' || r.status === 'already' ? { ok: true } : { ok: false, detail: r.detail ?? r.status };
96
+ }
97
+ const entry = rewrittenNamedEntry(e, ctx.profile);
98
+ if (!entry)
99
+ return { ok: false, detail: 'the token is stored outside the env block' };
100
+ const r = await replaceEntry(e.folder, e.name, e.scope === 'local' ? 'local' : 'user', entry, { cwd: e.projectPath, env: ctx.env });
101
+ return r.status === 'added' ? { ok: true } : { ok: false, detail: r.detail ?? r.status };
102
+ }
103
+ /** Why an entry cannot be rewritten for THIS sign-in, or null when it can. */
104
+ function mismatch(e, ctx) {
105
+ const generic = e.name === 'tacit' && e.scope === 'user' && !e.workspaceId;
106
+ if (generic)
107
+ return null;
108
+ if (!e.workspaceId)
109
+ return 'it does not say which workspace it is for';
110
+ if (e.workspaceId !== ctx.workspaceId)
111
+ return `it is for workspace ${e.workspaceId}, not the one you signed in to`;
112
+ const h = hostOf(e.apiUrl);
113
+ if (h && h !== hostOf(ctx.apiUrl))
114
+ return `it points at ${h}, not the server you signed in to`;
115
+ return null;
116
+ }
117
+ export async function migrateLegacyEntries(entries, ctx) {
118
+ const res = { found: entries.length, rewritten: 0, failed: 0, leftAlone: 0 };
119
+ if (entries.length === 0)
120
+ return res;
121
+ ctx.out(`Found ${entries.length} TACIT ${entries.length === 1 ? 'entry' : 'entries'} in Claude Code config that still hold a login token:`);
122
+ const done = new Set();
123
+ const revokeOk = new Set();
124
+ for (const e of entries) {
125
+ ctx.out(describe(e));
126
+ if (e.scope === 'project' || e.scope === 'legacy-file') {
127
+ res.leftAlone++;
128
+ ctx.out(e.scope === 'legacy-file'
129
+ ? ` Claude Code does not read this file. Delete the ${e.name} entry yourself.`
130
+ : ` Not changed: project files are never edited.${e.gitTracked ? ' This file is tracked by git; the old token stays in history.' : ''}`);
131
+ ctx.out(e.scope === 'project' ? stillOverrides(e) : `Warning: ${e.name} in ${e.file} still holds a login token.`);
132
+ if (e.shape === 'legacy' || e.shape === 'iam') {
133
+ if (ctx.io.isTTY && (await ctx.io.confirm(` ${REVOKE_QUESTION}`, true)))
134
+ revokeOk.add(e);
135
+ else
136
+ ctx.out(` The login stored in ${e.file} stays valid.`);
137
+ }
138
+ else if (e.shape === 'jwt' || e.shape === 'hmac')
139
+ ctx.out(SESSION_LINE(e.name));
140
+ ctx.out(` Delete the ${e.name} entry from ${e.file} yourself; setup never edits this file.`);
141
+ continue;
142
+ }
143
+ const why = mismatch(e, ctx);
144
+ if (why) {
145
+ res.leftAlone++;
146
+ ctx.out(` Not rewritten: ${why}.`);
147
+ ctx.out(stillOverrides(e));
148
+ continue;
149
+ }
150
+ const yes = ctx.io.isTTY ? await ctx.io.confirm(` ${CONSENT_QUESTION}`, false) : false;
151
+ if (!yes) {
152
+ res.leftAlone++;
153
+ ctx.out(stillOverrides(e));
154
+ continue;
155
+ }
156
+ const r = await rewrite(e, ctx);
157
+ if (!r.ok) {
158
+ res.failed++;
159
+ ctx.out(` Could not rewrite ${e.name} (${r.detail ?? 'failed'}). It was left as it was.`);
160
+ continue;
161
+ }
162
+ res.rewritten++;
163
+ done.add(e);
164
+ ctx.out(` Rewrote ${e.name} without the token (TACIT_PROFILE=${e.name === 'tacit' && !e.workspaceId ? '${TACIT_PROFILE:-}' : ctx.profile}).`);
165
+ }
166
+ await signOutOldTokens(entries, done, revokeOk, ctx);
167
+ const folders = new Map();
168
+ for (const e of done)
169
+ folders.set(e.folder.configFile, e.folder);
170
+ for (const f of folders.values()) {
171
+ const b = countBackupsWithToken(f);
172
+ if (b.withToken > 0) {
173
+ ctx.out(`Claude Code keeps copies of its config in ${f.backupsDir}/ (${b.withToken} files contain the old token). ` +
174
+ 'Revoking the token on the server is what makes those copies harmless.');
175
+ }
176
+ }
177
+ return res;
178
+ }
179
+ async function signOutOldTokens(all, rewritten, revokeOk, ctx) {
180
+ const byToken = new Map();
181
+ for (const e of all)
182
+ byToken.set(e.token, [...(byToken.get(e.token) ?? []), e]);
183
+ for (const [token, holders] of byToken) {
184
+ const consented = holders.find((h) => revokeOk.has(h));
185
+ if (consented) {
186
+ ctx.out(await revoke(consented.name, token, consented.apiUrl, ctx));
187
+ continue;
188
+ }
189
+ const first = holders.find((h) => rewritten.has(h));
190
+ if (!first)
191
+ continue;
192
+ const still = holders.filter((h) => !rewritten.has(h));
193
+ if (still.length > 0) {
194
+ ctx.out(`Old token for ${first.name} was left active: ${still[0].name} in ${still[0].file} still uses it.`);
195
+ continue;
196
+ }
197
+ if (first.shape === 'jwt' || first.shape === 'hmac')
198
+ ctx.out(SESSION_LINE(first.name));
199
+ else if (first.shape === 'legacy' || first.shape === 'iam')
200
+ ctx.out(await revoke(first.name, token, first.apiUrl, ctx));
201
+ else
202
+ ctx.out(`Old token for ${first.name} was removed from the entry but could not be revoked from here. Revoke it in TACIT if it is no longer needed.`);
203
+ }
204
+ }
package/dist/setup.d.ts CHANGED
@@ -1,75 +1,50 @@
1
1
  /**
2
- * setup — wizard subcommand for @tacit/mcp-server
2
+ * `setup` for @tacitai/mcp-server (MV-1542c step 1.3, P3.1 / P3.2).
3
3
  *
4
- * Usage:
5
- * node dist/index.js setup [--dry-run] [--api-url <url>] [--token <token>] [--profile <name>] [--smoke]
4
+ * npx @tacitai/mcp-server setup [--api-url <url>] [--app-url <url>] [--name <profile>] [--no-browser]
5
+ * [--mode always|on-demand] [--install-cli | --no-install-cli] [--device-label <label>]
6
+ * [--all-configs] [--smoke] [--dry-run]
6
7
  *
7
- * Contract (§2.1 of sparc_specification.md, Phase-2 QE resolutions + W5 device-auth):
8
- * F1 smoke — calls tacit_synthesize via getClient()/postSSE; exits non-zero on empty/error.
9
- * F2 token — when token is obtained (device-auth or --token), writes it directly to mcp.json
10
- * (file is 0600). Falls back to env-var placeholder "${TACIT_TOKEN_*}" when token
11
- * came from the environment.
12
- * Merge — deep-merges ONLY mcpServers[profile]; all other keys preserved.
13
- * Idempotent — same --api-url + --profile → byte-identical mcp.json.
14
- * Secrets — token written to mcp.json (0600) when obtained via device-auth or --token;
15
- * NEVER printed to stdout/stderr (dry-run output is redacted).
8
+ * Steps (each failing step stops; nothing later runs on a partial sign-in):
9
+ * 1 targets 2 exported-credential warning 3 signIn 4 profile 5 load mode 6 install `tacit`
10
+ * 7 old-entry migration 8 registration (+ --all-configs) 9 summary (then --smoke)
16
11
  *
17
- * W5 additions:
18
- * --profile <name> — profile name (default: 'tacit'); drives env-var name + mcp.json key.
19
- * Device-auth flow — when --token is NOT provided and token env var is absent, opens browser
20
- * to ${apiUrl}/auth/device, waits for localhost:9123 callback, exchanges
21
- * code for token, derives profile from workspace_name (unless --profile set).
22
- * Metadata file — writes ~/.tacit/profiles/<profile>.json with { expires_at, api_url }.
23
- *
24
- * Security invariants:
25
- * - Token is NEVER logged or written to disk.
26
- * - Authorization header value excluded from all logging paths.
27
- * - State nonce generated from crypto.randomBytes (never user-provided).
28
- * - Tampered state in device-auth callback → exit 1 (S-10/AC-13).
29
- */
30
- /**
31
- * Derive the environment variable name for a given profile name.
32
- *
33
- * AC-3, AC-4, AC-10:
34
- * 'tacit' → 'TACIT_TOKEN'
35
- * 'tacit-acme' → 'TACIT_TOKEN_ACME'
36
- * 'my-workspace' → 'TACIT_TOKEN_MY_WORKSPACE'
37
- */
38
- export declare function profileToEnvVar(profile: string): string;
39
- /**
40
- * Derive a profile name from a workspace_name returned by device-auth exchange.
41
- * AC-12: lowercased, spaces→hyphens, non-alphanumeric-hyphen stripped.
12
+ * The only place a token is stored is the 0600 profile. The Claude Code entry names the profile and
13
+ * holds no credential; no token reaches argv, env, stdout or a log line. `~/.claude/mcp.json` is never
14
+ * written. Exit codes: 0 done, 1 failed, 2 state / PKCE check or denial, 3 signed in and profile saved
15
+ * but Claude Code registration or a needed `tacit` install did not complete.
42
16
  */
17
+ import { type IssuedCredential, type SignInIo, type SignInOptions } from './signin.js';
18
+ export declare const TOKEN_REMOVED_MESSAGE = "--token was removed: a token on the command line is visible to other users. Sign in with setup, or put TACIT_TOKEN in the environment for --smoke.";
19
+ /** workspace_name to profile slug (AC-12). */
43
20
  export declare function workspaceNameToProfile(name: string): string;
44
- /**
45
- * Web app URL for shareable links: api.* → app.*, localhost API → localhost:5174.
46
- */
21
+ /** Web app URL for shareable links: api.* to app.*, localhost API to localhost:5174. */
47
22
  export declare function deriveAppUrl(apiUrl: string): string;
48
- /**
49
- * Write ~/.tacit/profiles/<profile>.json with { expires_at, api_url }.
50
- * Token plaintext is NEVER written here — metadata only.
51
- */
52
- export declare function writeProfileMetadata(profile: string, expiresAt: string, apiUrl: string): void;
53
- interface DeviceAuthResult {
54
- token: string;
55
- expiresAt: string;
56
- workspaceName: string;
23
+ export interface SetupOptions {
24
+ apiUrl?: string;
25
+ appUrl?: string;
26
+ name?: string;
27
+ noBrowser: boolean;
28
+ mode?: 'always' | 'on-demand';
29
+ install: 'ask' | 'yes' | 'no';
30
+ deviceLabel?: string;
31
+ allConfigs: boolean;
32
+ smoke: boolean;
33
+ dryRun: boolean;
57
34
  }
58
- /**
59
- * Opens a browser to the device-auth URL and waits for the OAuth callback.
60
- * Returns the token, expiry, and workspace name from the exchange response.
61
- *
62
- * Security:
63
- * - State nonce is generated via crypto.randomBytes (never user-provided).
64
- * - Tampered state → exit 1 (S-10 / AC-13).
65
- * - Token plaintext is NEVER logged.
66
- *
67
- * Error paths:
68
- * - /auth/device returns 404 → reject immediately (pre-flight probe).
69
- * - Port 9123 occupied → reject (caller falls back to loginFlow).
70
- * - 120s timeout → reject (caller falls back to loginFlow).
71
- * - Browser open fails → print URL to stdout for manual copy-paste (AC-16 fallback).
72
- */
73
- export declare function deviceAuthFlow(apiUrl: string): Promise<DeviceAuthResult>;
35
+ export declare class UsageError extends Error {
36
+ }
37
+ export declare function parseArgs(argv: string[]): SetupOptions;
38
+ export declare function defaultIo(): SignInIo;
39
+ export interface SetupDeps {
40
+ io?: SignInIo;
41
+ signInFn?: (opts: SignInOptions) => Promise<IssuedCredential>;
42
+ fetchFn?: typeof fetch;
43
+ env?: NodeJS.ProcessEnv;
44
+ cwd?: string;
45
+ out?: (line: string) => void;
46
+ err?: (line: string) => void;
47
+ }
48
+ /** Runs setup and returns the exit code (0, 1, 2 or 3). */
49
+ export declare function runSetup(argv: string[], deps?: SetupDeps): Promise<number>;
74
50
  export declare function setup(argv: string[]): Promise<void>;
75
- export {};