@artyfacts/claude 1.3.25 → 1.3.27

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