@artyfacts/claude 1.3.27 → 1.3.28

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