@artyfacts/claude 1.3.24 → 1.3.25

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.
@@ -0,0 +1,1085 @@
1
+ // src/auth.ts
2
+ import * as fs from "fs";
3
+ import * as path from "path";
4
+ import * as os from "os";
5
+ import * as readline from "readline";
6
+ var CREDENTIALS_DIR = path.join(os.homedir(), ".artyfacts");
7
+ var CREDENTIALS_FILE = path.join(CREDENTIALS_DIR, "credentials.json");
8
+ var DEFAULT_BASE_URL = "https://artyfacts.dev/api/v1";
9
+ function loadCredentials() {
10
+ try {
11
+ if (!fs.existsSync(CREDENTIALS_FILE)) {
12
+ return null;
13
+ }
14
+ const data = fs.readFileSync(CREDENTIALS_FILE, "utf-8");
15
+ const credentials = JSON.parse(data);
16
+ if (credentials.expiresAt) {
17
+ const expiresAt = new Date(credentials.expiresAt);
18
+ if (expiresAt < /* @__PURE__ */ new Date()) {
19
+ console.log("\u26A0\uFE0F Credentials have expired");
20
+ return null;
21
+ }
22
+ }
23
+ return credentials;
24
+ } catch (error) {
25
+ console.error("Failed to load credentials:", error);
26
+ return null;
27
+ }
28
+ }
29
+ function saveCredentials(credentials) {
30
+ try {
31
+ if (!fs.existsSync(CREDENTIALS_DIR)) {
32
+ fs.mkdirSync(CREDENTIALS_DIR, { mode: 448, recursive: true });
33
+ }
34
+ fs.writeFileSync(
35
+ CREDENTIALS_FILE,
36
+ JSON.stringify(credentials, null, 2),
37
+ { mode: 384 }
38
+ );
39
+ } catch (error) {
40
+ throw new Error(`Failed to save credentials: ${error}`);
41
+ }
42
+ }
43
+ function clearCredentials() {
44
+ try {
45
+ if (fs.existsSync(CREDENTIALS_FILE)) {
46
+ fs.unlinkSync(CREDENTIALS_FILE);
47
+ }
48
+ } catch (error) {
49
+ console.error("Failed to clear credentials:", error);
50
+ }
51
+ }
52
+ async function runDeviceAuth(baseUrl = DEFAULT_BASE_URL) {
53
+ console.log("\u{1F510} Starting device authentication...\n");
54
+ const deviceAuth = await requestDeviceCode(baseUrl);
55
+ console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
56
+ console.log("\u{1F4CB} To authenticate, visit:");
57
+ console.log(` ${deviceAuth.verificationUri}`);
58
+ console.log("");
59
+ console.log("\u{1F511} Enter this code:");
60
+ console.log(` ${deviceAuth.userCode}`);
61
+ console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n");
62
+ console.log("\u23F3 Waiting for authentication...\n");
63
+ const credentials = await pollForToken(
64
+ baseUrl,
65
+ deviceAuth.deviceCode,
66
+ deviceAuth.interval,
67
+ deviceAuth.expiresIn
68
+ );
69
+ saveCredentials(credentials);
70
+ console.log("\u2705 Authentication successful!");
71
+ console.log(` Agent ID: ${credentials.agentId}`);
72
+ if (credentials.agentName) {
73
+ console.log(` Agent Name: ${credentials.agentName}`);
74
+ }
75
+ console.log("");
76
+ return credentials;
77
+ }
78
+ async function requestDeviceCode(baseUrl) {
79
+ const response = await fetch(`${baseUrl}/auth/device`, {
80
+ method: "POST",
81
+ headers: {
82
+ "Content-Type": "application/json"
83
+ },
84
+ body: JSON.stringify({
85
+ client_id: "artyfacts-claude",
86
+ scope: "agent:execute"
87
+ })
88
+ });
89
+ if (!response.ok) {
90
+ const error = await response.text();
91
+ throw new Error(`Failed to start device auth: ${error}`);
92
+ }
93
+ const data = await response.json();
94
+ return {
95
+ deviceCode: data.deviceCode || data.device_code || "",
96
+ userCode: data.userCode || data.user_code || "",
97
+ verificationUri: data.verificationUri || data.verification_uri || `https://artyfacts.dev/auth/device`,
98
+ expiresIn: data.expiresIn || data.expires_in || 600,
99
+ interval: data.interval || 5
100
+ };
101
+ }
102
+ async function pollForToken(baseUrl, deviceCode, interval, expiresIn) {
103
+ const startTime = Date.now();
104
+ const timeoutMs = expiresIn * 1e3;
105
+ while (true) {
106
+ if (Date.now() - startTime > timeoutMs) {
107
+ throw new Error("Device authentication timed out");
108
+ }
109
+ await sleep(interval * 1e3);
110
+ const response = await fetch(`${baseUrl}/auth/device/token`, {
111
+ method: "POST",
112
+ headers: {
113
+ "Content-Type": "application/json"
114
+ },
115
+ body: JSON.stringify({
116
+ device_code: deviceCode,
117
+ client_id: "artyfacts-claude"
118
+ })
119
+ });
120
+ if (response.ok) {
121
+ const data = await response.json();
122
+ return {
123
+ apiKey: data.apiKey,
124
+ agentId: data.agentId,
125
+ agentName: data.agentName,
126
+ expiresAt: data.expiresAt
127
+ };
128
+ }
129
+ const errorData = await response.json().catch(() => ({}));
130
+ const errorCode = errorData.error || errorData.code;
131
+ if (errorCode === "authorization_pending") {
132
+ process.stdout.write(".");
133
+ continue;
134
+ }
135
+ if (errorCode === "slow_down") {
136
+ interval = Math.min(interval * 2, 30);
137
+ continue;
138
+ }
139
+ if (errorCode === "expired_token") {
140
+ throw new Error("Device code expired. Please try again.");
141
+ }
142
+ if (errorCode === "access_denied") {
143
+ throw new Error("Authorization was denied.");
144
+ }
145
+ throw new Error(`Authentication failed: ${errorData.message || errorCode || response.statusText}`);
146
+ }
147
+ }
148
+ async function promptForApiKey() {
149
+ const rl = readline.createInterface({
150
+ input: process.stdin,
151
+ output: process.stdout
152
+ });
153
+ const question = (prompt) => {
154
+ return new Promise((resolve) => {
155
+ rl.question(prompt, resolve);
156
+ });
157
+ };
158
+ console.log("\u{1F511} Manual Configuration\n");
159
+ console.log("Enter your Artyfacts credentials:\n");
160
+ const apiKey = await question("API Key: ");
161
+ const agentId = await question("Agent ID: ");
162
+ const agentName = await question("Agent Name (optional): ");
163
+ rl.close();
164
+ if (!apiKey || !agentId) {
165
+ throw new Error("API Key and Agent ID are required");
166
+ }
167
+ const credentials = {
168
+ apiKey: apiKey.trim(),
169
+ agentId: agentId.trim(),
170
+ agentName: agentName.trim() || void 0
171
+ };
172
+ saveCredentials(credentials);
173
+ console.log("\n\u2705 Credentials saved!");
174
+ return credentials;
175
+ }
176
+ function sleep(ms) {
177
+ return new Promise((resolve) => setTimeout(resolve, ms));
178
+ }
179
+ async function getCredentials(options) {
180
+ if (!options?.forceAuth) {
181
+ const existing = loadCredentials();
182
+ if (existing) {
183
+ return existing;
184
+ }
185
+ }
186
+ return runDeviceAuth(options?.baseUrl);
187
+ }
188
+
189
+ // src/context.ts
190
+ var ContextFetcher = class {
191
+ config;
192
+ constructor(config) {
193
+ this.config = config;
194
+ }
195
+ /**
196
+ * Fetch full context for a task
197
+ */
198
+ async fetchTaskContext(taskId) {
199
+ const response = await fetch(
200
+ `${this.config.baseUrl}/tasks/${taskId}/context`,
201
+ {
202
+ headers: {
203
+ "Authorization": `Bearer ${this.config.apiKey}`,
204
+ "Accept": "application/json"
205
+ }
206
+ }
207
+ );
208
+ if (!response.ok) {
209
+ const errorText = await response.text().catch(() => "Unknown error");
210
+ throw new Error(`Failed to fetch task context: ${response.status} - ${errorText}`);
211
+ }
212
+ const data = await response.json();
213
+ return data;
214
+ }
215
+ };
216
+ function buildPromptWithContext(context) {
217
+ const parts = [];
218
+ parts.push(`You are an AI agent working within the Artyfacts task management system.
219
+
220
+ Your job is to complete the assigned task. You have full context about the organization, project, and related work.
221
+
222
+ ## Available Tools
223
+
224
+ You have access to Artyfacts MCP tools. USE THEM to complete your task:
225
+
226
+ - **create_artifact** - Create new artifacts (documents, specs, reports)
227
+ - **create_section** - Add sections to artifacts (content, tasks, decisions)
228
+ - **update_section** - Update existing sections
229
+ - **create_task** - Create new tasks under a goal
230
+ - **claim_task** - Claim a task for execution
231
+ - **complete_task** - Mark a task as complete (returns unblocked tasks)
232
+ - **block_task** - Block a task with a reason
233
+ - **list_tasks** - Query tasks from the queue
234
+ - **list_inbox** - Check pending decisions/approvals
235
+ - **resolve_inbox** - Resolve an inbox item
236
+
237
+ IMPORTANT: When asked to create agents or update artifacts, USE THE TOOLS. Don't just describe what you would do - actually do it with the tools.
238
+
239
+ ## Guidelines
240
+
241
+ - Be thorough but concise
242
+ - USE THE TOOLS to take action, don't just analyze
243
+ - If the task requires creating something, use create_artifact or create_section
244
+ - If you complete a task, check the response for unblocked_tasks to see follow-up work
245
+ - If you cannot complete the task, explain why
246
+
247
+ Format your response as follows:
248
+ 1. First, use the tools to complete the task
249
+ 2. Then summarize what you did
250
+ 3. End with a brief summary line starting with "SUMMARY:"`);
251
+ parts.push("");
252
+ parts.push("---");
253
+ parts.push("");
254
+ parts.push("## Organization Context");
255
+ parts.push(`**${context.organization.name}**`);
256
+ if (context.organization.context) {
257
+ parts.push("");
258
+ parts.push(formatOrgContext(context.organization.context));
259
+ }
260
+ parts.push("");
261
+ if (context.project) {
262
+ parts.push(`## Project: ${context.project.name}`);
263
+ if (context.project.description) {
264
+ parts.push(context.project.description);
265
+ }
266
+ parts.push("");
267
+ }
268
+ const goal = context.goal || context.artifact;
269
+ if (goal) {
270
+ parts.push(`## Goal: ${goal.title}`);
271
+ if (goal.objective) {
272
+ parts.push(`**Objective:** ${goal.objective}`);
273
+ }
274
+ if (goal.summary) {
275
+ parts.push(goal.summary);
276
+ }
277
+ if (goal.description) {
278
+ parts.push("");
279
+ parts.push(goal.description);
280
+ }
281
+ parts.push("");
282
+ if (goal.tasks && goal.tasks.length > 0) {
283
+ const relatedTasks = goal.tasks.filter((t) => t.id !== context.task.id);
284
+ if (relatedTasks.length > 0) {
285
+ parts.push("### Related Tasks:");
286
+ for (const task of relatedTasks) {
287
+ const statusEmoji = {
288
+ pending: "\u23F3",
289
+ in_progress: "\u{1F504}",
290
+ blocked: "\u{1F6AB}",
291
+ done: "\u2705"
292
+ }[task.status] || "\u2753";
293
+ const priorityBadge = task.priority ? ` [${task.priority}]` : "";
294
+ parts.push(`- ${statusEmoji} **${task.title}**${priorityBadge}`);
295
+ }
296
+ parts.push("");
297
+ }
298
+ }
299
+ if (goal.sections && goal.sections.length > 0) {
300
+ const relatedSections = goal.sections.filter((s) => s.id !== context.task.id);
301
+ if (relatedSections.length > 0) {
302
+ parts.push("### Related Sections:");
303
+ for (const section of relatedSections) {
304
+ const preview = section.content ? section.content.substring(0, 200) + (section.content.length > 200 ? "..." : "") : "No content";
305
+ const statusBadge = section.task_status ? ` [${section.task_status}]` : "";
306
+ parts.push(`- **${section.heading}**${statusBadge}: ${preview}`);
307
+ }
308
+ parts.push("");
309
+ }
310
+ }
311
+ }
312
+ parts.push("---");
313
+ parts.push("");
314
+ const taskTitle = context.task.title || context.task.heading;
315
+ parts.push(`## Your Task: ${taskTitle}`);
316
+ if (context.task.priority) {
317
+ const priorityEmoji = {
318
+ high: "\u{1F534} High",
319
+ medium: "\u{1F7E1} Medium",
320
+ low: "\u{1F7E2} Low"
321
+ }[context.task.priority] || "\u{1F7E1} Medium";
322
+ parts.push(`**Priority:** ${priorityEmoji}`);
323
+ }
324
+ if (context.task.depends_on && context.task.depends_on.length > 0) {
325
+ parts.push(`**Dependencies:** ${context.task.depends_on.length} task(s)`);
326
+ }
327
+ parts.push("");
328
+ parts.push("### Description");
329
+ const taskDescription = context.task.description || context.task.content;
330
+ parts.push(taskDescription || "No additional description provided.");
331
+ parts.push("");
332
+ if (context.task.expected_output) {
333
+ parts.push("### Expected Output");
334
+ if (context.task.expected_output.format) {
335
+ parts.push(`**Format:** ${context.task.expected_output.format}`);
336
+ }
337
+ if (context.task.expected_output.requirements && context.task.expected_output.requirements.length > 0) {
338
+ parts.push("**Requirements:**");
339
+ for (const req of context.task.expected_output.requirements) {
340
+ parts.push(`- ${req}`);
341
+ }
342
+ }
343
+ parts.push("");
344
+ }
345
+ parts.push("---");
346
+ parts.push("");
347
+ parts.push("Complete this task and provide your output below.");
348
+ return parts.join("\n");
349
+ }
350
+ function formatOrgContext(context) {
351
+ const trimmed = context.trim();
352
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
353
+ try {
354
+ const parsed = JSON.parse(trimmed);
355
+ return formatContextObject(parsed);
356
+ } catch {
357
+ return context;
358
+ }
359
+ }
360
+ return context;
361
+ }
362
+ function formatContextObject(obj, indent = "") {
363
+ if (typeof obj !== "object" || obj === null) {
364
+ return String(obj);
365
+ }
366
+ if (Array.isArray(obj)) {
367
+ return obj.map((item) => `${indent}- ${formatContextObject(item, indent + " ")}`).join("\n");
368
+ }
369
+ const lines = [];
370
+ for (const [key, value] of Object.entries(obj)) {
371
+ const label = key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
372
+ if (typeof value === "object" && value !== null) {
373
+ lines.push(`${indent}**${label}:**`);
374
+ lines.push(formatContextObject(value, indent + " "));
375
+ } else {
376
+ lines.push(`${indent}- **${label}:** ${value}`);
377
+ }
378
+ }
379
+ return lines.join("\n");
380
+ }
381
+ function createContextFetcher(config) {
382
+ return new ContextFetcher(config);
383
+ }
384
+
385
+ // src/executor.ts
386
+ import { spawn } from "child_process";
387
+ var DEFAULT_TIMEOUT = 5 * 60 * 1e3;
388
+ var DEFAULT_SYSTEM_PROMPT = `You are an AI agent working within the Artyfacts task management system.
389
+
390
+ Your job is to complete tasks assigned to you using the available tools.
391
+
392
+ ## Available Tools
393
+
394
+ You have access to Artyfacts MCP tools. USE THEM to complete your task:
395
+
396
+ - **create_artifact** - Create new artifacts (documents, specs, reports)
397
+ - **create_section** - Add sections to artifacts (content, tasks, decisions)
398
+ - **update_section** - Update existing sections
399
+ - **create_agent** - Create new AI agents with specific roles
400
+ - **list_artifacts** - Query existing artifacts
401
+ - **list_sections** - Query sections within an artifact
402
+ - **complete_task** - Mark a task as complete
403
+ - **block_task** - Block a task with a reason
404
+ - **create_blocker** - Create a decision blocker
405
+
406
+ IMPORTANT: When asked to create agents or update artifacts, USE THE TOOLS. Don't just describe what you would do - actually do it.
407
+
408
+ ## Guidelines
409
+
410
+ - USE THE TOOLS to take action
411
+ - If creating something, use create_artifact or create_section
412
+ - If creating agents, use create_agent
413
+ - If you cannot complete the task, explain why
414
+
415
+ Format your response as follows:
416
+ 1. First, use the tools to complete the task
417
+ 2. Summarize what you accomplished
418
+ 3. End with a brief summary line starting with "SUMMARY:"`;
419
+ var ClaudeExecutor = class {
420
+ config;
421
+ contextFetcher = null;
422
+ constructor(config = {}) {
423
+ this.config = {
424
+ ...config,
425
+ timeout: config.timeout || DEFAULT_TIMEOUT,
426
+ claudePath: config.claudePath || "claude"
427
+ };
428
+ if (config.baseUrl && config.apiKey) {
429
+ this.contextFetcher = createContextFetcher({
430
+ baseUrl: config.baseUrl,
431
+ apiKey: config.apiKey
432
+ });
433
+ }
434
+ }
435
+ /**
436
+ * Execute a task using Claude Code CLI
437
+ *
438
+ * If full context is available (baseUrl + apiKey configured), fetches
439
+ * organization, project, artifact, and related sections for a rich prompt.
440
+ */
441
+ async execute(task) {
442
+ try {
443
+ let prompt;
444
+ let fullContext = null;
445
+ const useFullContext = this.config.useFullContext !== false && this.contextFetcher;
446
+ if (useFullContext) {
447
+ try {
448
+ const taskId = task.id || task.taskId;
449
+ if (!taskId) {
450
+ throw new Error("Task ID required for context fetch");
451
+ }
452
+ fullContext = await this.contextFetcher.fetchTaskContext(taskId);
453
+ prompt = buildPromptWithContext(fullContext);
454
+ console.log(" \u{1F4DA} Using full context (org, project, goal, related tasks)");
455
+ } catch (contextError) {
456
+ console.warn(" \u26A0\uFE0F Could not fetch full context, using minimal prompt");
457
+ console.warn(` ${contextError instanceof Error ? contextError.message : contextError}`);
458
+ prompt = this.buildTaskPrompt(task);
459
+ }
460
+ } else {
461
+ prompt = this.buildTaskPrompt(task);
462
+ }
463
+ const output = await this.runClaude(prompt);
464
+ const taskTitle = task.title || task.heading || "Task";
465
+ const { content, summary } = this.parseResponse(output, taskTitle);
466
+ return {
467
+ success: true,
468
+ output: content,
469
+ summary,
470
+ promptUsed: prompt
471
+ };
472
+ } catch (error) {
473
+ const errorMessage = error instanceof Error ? error.message : String(error);
474
+ return {
475
+ success: false,
476
+ output: "",
477
+ summary: `Failed: ${errorMessage}`,
478
+ error: errorMessage
479
+ };
480
+ }
481
+ }
482
+ /**
483
+ * Run Claude Code CLI with the given prompt
484
+ */
485
+ runClaude(prompt) {
486
+ return new Promise((resolve, reject) => {
487
+ const claudePath = this.config.claudePath || "claude";
488
+ const mcpConfig = {
489
+ mcpServers: {
490
+ artyfacts: {
491
+ command: "npx",
492
+ args: ["-y", "@artyfacts/mcp-server"],
493
+ env: {
494
+ ARTYFACTS_API_KEY: this.config.apiKey || process.env.ARTYFACTS_API_KEY || "",
495
+ ARTYFACTS_BASE_URL: this.config.baseUrl || "https://artyfacts.dev/api/v1"
496
+ }
497
+ }
498
+ }
499
+ };
500
+ const args = [
501
+ "--print",
502
+ "--mcp-config",
503
+ JSON.stringify(mcpConfig),
504
+ "--permission-mode",
505
+ "bypassPermissions"
506
+ ];
507
+ const proc = spawn(claudePath, args, {
508
+ stdio: ["pipe", "pipe", "pipe"],
509
+ timeout: this.config.timeout
510
+ });
511
+ let stdout = "";
512
+ let stderr = "";
513
+ proc.stdout.on("data", (data) => {
514
+ stdout += data.toString();
515
+ });
516
+ proc.stderr.on("data", (data) => {
517
+ stderr += data.toString();
518
+ });
519
+ proc.on("close", (code) => {
520
+ if (code === 0) {
521
+ resolve(stdout.trim());
522
+ } else {
523
+ reject(new Error(stderr || `Claude exited with code ${code}`));
524
+ }
525
+ });
526
+ proc.on("error", (err) => {
527
+ if (err.code === "ENOENT") {
528
+ reject(new Error(
529
+ "Claude Code CLI not found. Please install it:\n npm install -g @anthropic-ai/claude-code"
530
+ ));
531
+ } else {
532
+ reject(err);
533
+ }
534
+ });
535
+ proc.stdin.write(prompt);
536
+ proc.stdin.end();
537
+ });
538
+ }
539
+ /**
540
+ * Build the task prompt (v2)
541
+ */
542
+ buildTaskPrompt(task) {
543
+ const parts = [];
544
+ const systemPrompt = this.config.systemPromptPrefix ? `${this.config.systemPromptPrefix}
545
+
546
+ ${DEFAULT_SYSTEM_PROMPT}` : DEFAULT_SYSTEM_PROMPT;
547
+ parts.push(systemPrompt);
548
+ parts.push("");
549
+ parts.push("---");
550
+ parts.push("");
551
+ const taskTitle = task.title || task.heading;
552
+ parts.push(`# Task: ${taskTitle}`);
553
+ parts.push("");
554
+ const goalTitle = task.goalTitle || task.artifactTitle;
555
+ if (goalTitle) {
556
+ parts.push(`**Goal:** ${goalTitle}`);
557
+ }
558
+ if (task.priority) {
559
+ const priorityEmoji = {
560
+ high: "\u{1F534} High",
561
+ medium: "\u{1F7E1} Medium",
562
+ low: "\u{1F7E2} Low"
563
+ }[task.priority] || "\u{1F7E1} Medium";
564
+ parts.push(`**Priority:** ${priorityEmoji}`);
565
+ }
566
+ parts.push("");
567
+ parts.push("## Description");
568
+ const taskDescription = task.description || task.content;
569
+ parts.push(taskDescription || "No additional description provided.");
570
+ parts.push("");
571
+ if (task.context && Object.keys(task.context).length > 0) {
572
+ parts.push("## Additional Context");
573
+ parts.push("```json");
574
+ parts.push(JSON.stringify(task.context, null, 2));
575
+ parts.push("```");
576
+ parts.push("");
577
+ }
578
+ parts.push("## Instructions");
579
+ parts.push("Complete this task and provide your output below.");
580
+ return parts.join("\n");
581
+ }
582
+ /**
583
+ * Parse the response to extract output and summary
584
+ */
585
+ parseResponse(fullOutput, taskHeading) {
586
+ const summaryMatch = fullOutput.match(/SUMMARY:\s*(.+?)(?:\n|$)/i);
587
+ if (summaryMatch) {
588
+ const summary2 = summaryMatch[1].trim();
589
+ const content = fullOutput.replace(/SUMMARY:\s*.+?(?:\n|$)/i, "").trim();
590
+ return { content, summary: summary2 };
591
+ }
592
+ const lines = fullOutput.split("\n").filter((l) => l.trim());
593
+ const firstLine = lines[0] || "";
594
+ const summary = firstLine.length > 100 ? `${firstLine.substring(0, 97)}...` : firstLine || `Completed: ${taskHeading}`;
595
+ return { content: fullOutput, summary };
596
+ }
597
+ /**
598
+ * Test that Claude Code CLI is available and working
599
+ */
600
+ async testConnection() {
601
+ try {
602
+ const output = await this.runClaude('Say "connected" and nothing else.');
603
+ return output.toLowerCase().includes("connected");
604
+ } catch {
605
+ return false;
606
+ }
607
+ }
608
+ /**
609
+ * Check if Claude Code CLI is installed
610
+ */
611
+ async isInstalled() {
612
+ return new Promise((resolve) => {
613
+ const proc = spawn(this.config.claudePath || "claude", ["--version"], {
614
+ stdio: ["ignore", "pipe", "pipe"]
615
+ });
616
+ proc.on("close", (code) => {
617
+ resolve(code === 0);
618
+ });
619
+ proc.on("error", () => {
620
+ resolve(false);
621
+ });
622
+ });
623
+ }
624
+ };
625
+ function createExecutor(config) {
626
+ return new ClaudeExecutor(config);
627
+ }
628
+
629
+ // src/listener.ts
630
+ import EventSource from "eventsource";
631
+ var DEFAULT_BASE_URL2 = "https://artyfacts.dev/api/v1";
632
+ var EVENT_TYPES = [
633
+ "connected",
634
+ "heartbeat",
635
+ "task_assigned",
636
+ "task_unblocked",
637
+ "blocker_resolved",
638
+ "notification",
639
+ "mcp_connect_request",
640
+ "connection_status"
641
+ ];
642
+ var ArtyfactsListener = class {
643
+ config;
644
+ eventSource = null;
645
+ callbacks = /* @__PURE__ */ new Map();
646
+ allCallbacks = /* @__PURE__ */ new Set();
647
+ state = "disconnected";
648
+ reconnectAttempts = 0;
649
+ maxReconnectAttempts = 10;
650
+ reconnectDelay = 1e3;
651
+ constructor(config) {
652
+ if (!config.apiKey) {
653
+ throw new Error("API key is required");
654
+ }
655
+ if (!config.agentId) {
656
+ throw new Error("Agent ID is required");
657
+ }
658
+ this.config = {
659
+ ...config,
660
+ baseUrl: config.baseUrl || DEFAULT_BASE_URL2
661
+ };
662
+ }
663
+ /**
664
+ * Get current connection state
665
+ */
666
+ get connectionState() {
667
+ return this.state;
668
+ }
669
+ /**
670
+ * Check if connected
671
+ */
672
+ get isConnected() {
673
+ return this.state === "connected";
674
+ }
675
+ /**
676
+ * Subscribe to all events
677
+ */
678
+ subscribe(callback) {
679
+ this.allCallbacks.add(callback);
680
+ return () => {
681
+ this.allCallbacks.delete(callback);
682
+ };
683
+ }
684
+ /**
685
+ * Subscribe to a specific event type
686
+ */
687
+ on(type, callback) {
688
+ if (!this.callbacks.has(type)) {
689
+ this.callbacks.set(type, /* @__PURE__ */ new Set());
690
+ }
691
+ this.callbacks.get(type).add(callback);
692
+ return () => {
693
+ const typeCallbacks = this.callbacks.get(type);
694
+ if (typeCallbacks) {
695
+ typeCallbacks.delete(callback);
696
+ if (typeCallbacks.size === 0) {
697
+ this.callbacks.delete(type);
698
+ }
699
+ }
700
+ };
701
+ }
702
+ /**
703
+ * Connect to the SSE stream
704
+ */
705
+ connect() {
706
+ if (this.eventSource) {
707
+ return;
708
+ }
709
+ this.setState("connecting");
710
+ const url = new URL(`${this.config.baseUrl}/events/stream`);
711
+ url.searchParams.set("apiKey", this.config.apiKey);
712
+ url.searchParams.set("agentId", this.config.agentId);
713
+ this.eventSource = new EventSource(url.toString(), {
714
+ headers: {
715
+ "Authorization": `Bearer ${this.config.apiKey}`
716
+ }
717
+ });
718
+ this.eventSource.onopen = () => {
719
+ this.reconnectAttempts = 0;
720
+ this.reconnectDelay = 1e3;
721
+ this.setState("connected");
722
+ };
723
+ this.eventSource.onmessage = (event) => {
724
+ this.handleMessage(event);
725
+ };
726
+ this.eventSource.onerror = (event) => {
727
+ this.handleError(event);
728
+ };
729
+ for (const eventType of EVENT_TYPES) {
730
+ this.eventSource.addEventListener(eventType, (event) => {
731
+ this.handleMessage(event, eventType);
732
+ });
733
+ }
734
+ }
735
+ /**
736
+ * Disconnect from the SSE stream
737
+ */
738
+ disconnect() {
739
+ if (this.eventSource) {
740
+ this.eventSource.close();
741
+ this.eventSource = null;
742
+ }
743
+ this.setState("disconnected");
744
+ }
745
+ /**
746
+ * Reconnect to the SSE stream
747
+ */
748
+ reconnect() {
749
+ this.disconnect();
750
+ this.connect();
751
+ }
752
+ /**
753
+ * Handle incoming SSE message
754
+ */
755
+ handleMessage(event, eventType) {
756
+ try {
757
+ const data = JSON.parse(event.data);
758
+ const rawData = data.data || data;
759
+ const normalizedData = rawData.id || rawData.task_id ? {
760
+ // v2 fields (primary)
761
+ id: rawData.id || rawData.task_id,
762
+ goalId: rawData.goal_id || rawData.artifact_id,
763
+ goalTitle: rawData.goal_title || rawData.artifact_title,
764
+ title: rawData.title || rawData.heading,
765
+ description: rawData.description || rawData.content,
766
+ priority: rawData.priority,
767
+ assignedTo: rawData.assigned_to,
768
+ assignedAt: rawData.assigned_at,
769
+ // Deprecated fields for backwards compatibility
770
+ taskId: rawData.id || rawData.task_id,
771
+ artifactId: rawData.goal_id || rawData.artifact_id,
772
+ artifactTitle: rawData.goal_title || rawData.artifact_title,
773
+ heading: rawData.title || rawData.heading,
774
+ content: rawData.description || rawData.content,
775
+ ...rawData
776
+ // Keep original fields too
777
+ } : rawData;
778
+ const artyfactsEvent = {
779
+ type: eventType || data.type || "unknown",
780
+ timestamp: data.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
781
+ data: normalizedData
782
+ };
783
+ const typeCallbacks = this.callbacks.get(artyfactsEvent.type);
784
+ if (typeCallbacks) {
785
+ for (const callback of typeCallbacks) {
786
+ this.safeCallCallback(callback, artyfactsEvent);
787
+ }
788
+ }
789
+ for (const callback of this.allCallbacks) {
790
+ this.safeCallCallback(callback, artyfactsEvent);
791
+ }
792
+ } catch (err) {
793
+ console.error("[Listener] Failed to parse SSE message:", event.data, err);
794
+ }
795
+ }
796
+ /**
797
+ * Safely call a callback, handling async and errors
798
+ */
799
+ async safeCallCallback(callback, event) {
800
+ try {
801
+ await callback(event);
802
+ } catch (err) {
803
+ console.error(`[Listener] Error in event callback for '${event.type}':`, err);
804
+ }
805
+ }
806
+ /**
807
+ * Handle SSE error
808
+ */
809
+ handleError(event) {
810
+ if (this.eventSource?.readyState === EventSource.CONNECTING) {
811
+ this.setState("reconnecting");
812
+ } else if (this.eventSource?.readyState === EventSource.CLOSED) {
813
+ this.setState("disconnected");
814
+ if (this.reconnectAttempts < this.maxReconnectAttempts) {
815
+ this.reconnectAttempts++;
816
+ this.reconnectDelay = Math.min(this.reconnectDelay * 2, 3e4);
817
+ console.log(
818
+ `[Listener] Connection lost, reconnecting in ${this.reconnectDelay / 1e3}s (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`
819
+ );
820
+ setTimeout(() => {
821
+ if (this.state === "disconnected") {
822
+ this.connect();
823
+ }
824
+ }, this.reconnectDelay);
825
+ } else {
826
+ const error = new Error("Max reconnection attempts reached");
827
+ this.config.onError?.(error);
828
+ }
829
+ }
830
+ }
831
+ /**
832
+ * Update connection state
833
+ */
834
+ setState(state) {
835
+ if (this.state !== state) {
836
+ this.state = state;
837
+ this.config.onStateChange?.(state);
838
+ }
839
+ }
840
+ };
841
+ function createListener(config) {
842
+ return new ArtyfactsListener(config);
843
+ }
844
+
845
+ // src/mcp.ts
846
+ import { spawnSync } from "child_process";
847
+ var DEFAULT_BASE_URL3 = "https://artyfacts.dev/api/v1";
848
+ var OAUTH_MCP_SERVERS = {
849
+ supabase: {
850
+ url: "https://mcp.supabase.com/mcp",
851
+ name: "supabase"
852
+ },
853
+ figma: {
854
+ url: "https://mcp.figma.com/mcp",
855
+ name: "figma"
856
+ }
857
+ };
858
+ var CREDENTIAL_MCP_CONFIGS = {
859
+ postgres: (config) => ({
860
+ command: "npx",
861
+ args: ["-y", "@modelcontextprotocol/server-postgres", config.connection_string]
862
+ }),
863
+ github: (config) => ({
864
+ command: "npx",
865
+ args: ["-y", "@modelcontextprotocol/server-github"],
866
+ env: {
867
+ GITHUB_PERSONAL_ACCESS_TOKEN: config.api_key
868
+ }
869
+ }),
870
+ filesystem: (config) => ({
871
+ command: "npx",
872
+ args: ["-y", "@modelcontextprotocol/server-filesystem", ...config.paths || []]
873
+ })
874
+ };
875
+ function addMcpServer(options) {
876
+ const { name, transport, url, command, args = [], env = {}, scope = "user" } = options;
877
+ const cliArgs = ["mcp", "add", "-s", scope, "-t", transport];
878
+ for (const [key, value] of Object.entries(env)) {
879
+ cliArgs.push("-e", `${key}=${value}`);
880
+ }
881
+ cliArgs.push(name);
882
+ if (transport === "http" && url) {
883
+ cliArgs.push(url);
884
+ } else if (transport === "stdio" && command) {
885
+ cliArgs.push("--", command, ...args);
886
+ } else {
887
+ return { success: false, error: "Invalid configuration: missing url or command" };
888
+ }
889
+ console.log(`[MCP] Running: claude ${cliArgs.join(" ")}`);
890
+ const result = spawnSync("claude", cliArgs, {
891
+ encoding: "utf-8",
892
+ stdio: ["pipe", "pipe", "pipe"]
893
+ });
894
+ if (result.status === 0) {
895
+ return { success: true };
896
+ } else {
897
+ const error = result.stderr || result.stdout || `Exit code ${result.status}`;
898
+ if (error.includes("already exists")) {
899
+ console.log(`[MCP] Server ${name} exists - removing old config...`);
900
+ spawnSync("claude", ["mcp", "remove", name], { encoding: "utf-8" });
901
+ const retryResult = spawnSync("claude", cliArgs, {
902
+ encoding: "utf-8",
903
+ stdio: ["pipe", "pipe", "pipe"]
904
+ });
905
+ if (retryResult.status === 0) {
906
+ return { success: true, replaced: true };
907
+ } else {
908
+ return { success: false, error: retryResult.stderr || retryResult.stdout || "Failed after removing old config" };
909
+ }
910
+ }
911
+ return { success: false, error };
912
+ }
913
+ }
914
+ var McpHandler = class {
915
+ config;
916
+ constructor(config) {
917
+ this.config = {
918
+ ...config,
919
+ baseUrl: config.baseUrl || DEFAULT_BASE_URL3
920
+ };
921
+ }
922
+ /**
923
+ * Handle an MCP connect request event
924
+ * Uses `claude mcp add` to configure the server dynamically
925
+ */
926
+ async handleConnectRequest(event) {
927
+ const { connection_id, platform, config: mcpConfig } = event.data;
928
+ try {
929
+ const serverName = mcpConfig?.server_name || platform;
930
+ const oauthServer = OAUTH_MCP_SERVERS[platform];
931
+ if (oauthServer) {
932
+ const result = addMcpServer({
933
+ name: serverName,
934
+ transport: "http",
935
+ url: oauthServer.url
936
+ });
937
+ if (!result.success) {
938
+ throw new Error(`Failed to add ${platform} MCP: ${result.error}`);
939
+ }
940
+ console.log(`[MCP] Added ${serverName} \u2192 ${oauthServer.url}`);
941
+ console.log(`[MCP] Starting ${platform} OAuth...`);
942
+ console.log(`[MCP] Claude will open - authenticate in browser, then type "done" to continue`);
943
+ console.log("");
944
+ const oauthProcess = spawnSync("claude", [
945
+ "--allowedTools",
946
+ `mcp__${serverName}__*`,
947
+ "--permission-mode",
948
+ "bypassPermissions",
949
+ `Authenticate with ${serverName} MCP now. Call the authenticate tool immediately.`
950
+ ], {
951
+ encoding: "utf-8",
952
+ stdio: "inherit",
953
+ // Interactive - user can see and respond
954
+ timeout: 3e5
955
+ // 5 minute timeout for OAuth
956
+ });
957
+ if (oauthProcess.status === 0) {
958
+ console.log(`[MCP] ${platform} OAuth completed!`);
959
+ } else {
960
+ console.log(`[MCP] OAuth session ended`);
961
+ }
962
+ } else {
963
+ const configBuilder = CREDENTIAL_MCP_CONFIGS[platform];
964
+ if (!configBuilder) {
965
+ throw new Error(`Unsupported MCP platform: ${platform}. Supported: ${[...Object.keys(OAUTH_MCP_SERVERS), ...Object.keys(CREDENTIAL_MCP_CONFIGS)].join(", ")}`);
966
+ }
967
+ if (!mcpConfig) {
968
+ throw new Error(`Platform ${platform} requires configuration (connection_string or api_key)`);
969
+ }
970
+ const serverConfig = configBuilder(mcpConfig);
971
+ const result = addMcpServer({
972
+ name: serverName,
973
+ transport: "stdio",
974
+ command: serverConfig.command,
975
+ args: serverConfig.args,
976
+ env: serverConfig.env
977
+ });
978
+ if (!result.success) {
979
+ throw new Error(`Failed to add ${platform} MCP: ${result.error}`);
980
+ }
981
+ console.log(`[MCP] Added ${serverName} for ${platform}`);
982
+ }
983
+ await this.updateConnectionStatus(connection_id, {
984
+ status: "active",
985
+ mcp_configured: true
986
+ });
987
+ this.config.onConfigured?.(connection_id, platform);
988
+ } catch (err) {
989
+ console.error(`[MCP] Failed to configure ${platform}:`, err);
990
+ await this.updateConnectionStatus(connection_id, {
991
+ status: "error",
992
+ mcp_configured: false,
993
+ error_message: err.message
994
+ });
995
+ this.config.onError?.(err, connection_id);
996
+ }
997
+ }
998
+ /**
999
+ * Check if a platform supports OAuth (no credentials needed)
1000
+ */
1001
+ static supportsOAuth(platform) {
1002
+ return platform in OAUTH_MCP_SERVERS;
1003
+ }
1004
+ /**
1005
+ * Get list of platforms with OAuth support
1006
+ */
1007
+ static getOAuthPlatforms() {
1008
+ return Object.keys(OAUTH_MCP_SERVERS);
1009
+ }
1010
+ /**
1011
+ * Update connection status in Artyfacts
1012
+ */
1013
+ async updateConnectionStatus(connectionId, update) {
1014
+ const url = `${this.config.baseUrl}/connections/${connectionId}`;
1015
+ console.log(`[MCP] Updating connection ${connectionId} to status: ${update.status}`);
1016
+ try {
1017
+ const response = await fetch(url, {
1018
+ method: "PATCH",
1019
+ headers: {
1020
+ "Authorization": `Bearer ${this.config.apiKey}`,
1021
+ "Content-Type": "application/json"
1022
+ },
1023
+ body: JSON.stringify(update)
1024
+ });
1025
+ if (!response.ok) {
1026
+ const body = await response.text();
1027
+ console.error(`[MCP] Failed to update connection status: ${response.status} - ${body}`);
1028
+ } else {
1029
+ console.log(`[MCP] Connection ${connectionId} updated to ${update.status}`);
1030
+ }
1031
+ } catch (err) {
1032
+ console.error("[MCP] Failed to update connection status:", err);
1033
+ }
1034
+ }
1035
+ /**
1036
+ * List configured MCP servers using `claude mcp list`
1037
+ */
1038
+ listServers() {
1039
+ const result = spawnSync("claude", ["mcp", "list"], {
1040
+ encoding: "utf-8",
1041
+ stdio: ["pipe", "pipe", "pipe"]
1042
+ });
1043
+ if (result.status === 0 && result.stdout) {
1044
+ return result.stdout.trim().split("\n").filter(Boolean);
1045
+ }
1046
+ return [];
1047
+ }
1048
+ /**
1049
+ * Remove an MCP server using `claude mcp remove`
1050
+ */
1051
+ removeServer(serverName) {
1052
+ const result = spawnSync("claude", ["mcp", "remove", serverName], {
1053
+ encoding: "utf-8",
1054
+ stdio: ["pipe", "pipe", "pipe"]
1055
+ });
1056
+ if (result.status === 0) {
1057
+ console.log(`[MCP] Removed server: ${serverName}`);
1058
+ return true;
1059
+ } else {
1060
+ console.error(`[MCP] Failed to remove ${serverName}: ${result.stderr || result.stdout}`);
1061
+ return false;
1062
+ }
1063
+ }
1064
+ };
1065
+ function createMcpHandler(config) {
1066
+ return new McpHandler(config);
1067
+ }
1068
+
1069
+ export {
1070
+ loadCredentials,
1071
+ saveCredentials,
1072
+ clearCredentials,
1073
+ runDeviceAuth,
1074
+ promptForApiKey,
1075
+ getCredentials,
1076
+ ContextFetcher,
1077
+ buildPromptWithContext,
1078
+ createContextFetcher,
1079
+ ClaudeExecutor,
1080
+ createExecutor,
1081
+ ArtyfactsListener,
1082
+ createListener,
1083
+ McpHandler,
1084
+ createMcpHandler
1085
+ };