@artyfacts/claude 1.3.29 → 1.3.30

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