@artyfacts/openclaw 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1172 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ ArtyfactsListener: () => ArtyfactsListener,
34
+ ContextFetcher: () => ContextFetcher,
35
+ McpHandler: () => McpHandler,
36
+ OpenClawExecutor: () => OpenClawExecutor,
37
+ buildPromptWithContext: () => buildPromptWithContext,
38
+ clearCredentials: () => clearCredentials,
39
+ createContextFetcher: () => createContextFetcher,
40
+ createExecutor: () => createExecutor,
41
+ createListener: () => createListener,
42
+ createMcpHandler: () => createMcpHandler,
43
+ getCredentials: () => getCredentials,
44
+ introspect: () => introspect,
45
+ loadCredentials: () => loadCredentials,
46
+ promptForApiKey: () => promptForApiKey,
47
+ saveCredentials: () => saveCredentials,
48
+ summarize: () => summarize
49
+ });
50
+ module.exports = __toCommonJS(index_exports);
51
+
52
+ // src/auth.ts
53
+ var fs = __toESM(require("fs"));
54
+ var path = __toESM(require("path"));
55
+ var os = __toESM(require("os"));
56
+ var readline = __toESM(require("readline"));
57
+ var CREDENTIALS_DIR = path.join(os.homedir(), ".artyfacts");
58
+ var CREDENTIALS_FILE = path.join(CREDENTIALS_DIR, "openclaw-credentials.json");
59
+ var DEFAULT_BASE_URL = "https://artyfacts.dev/api/v1";
60
+ var CLIENT_ID = "artyfacts-openclaw";
61
+ function loadCredentials() {
62
+ try {
63
+ if (!fs.existsSync(CREDENTIALS_FILE)) {
64
+ return null;
65
+ }
66
+ const data = fs.readFileSync(CREDENTIALS_FILE, "utf-8");
67
+ const credentials = JSON.parse(data);
68
+ if (credentials.expiresAt) {
69
+ const expiresAt = new Date(credentials.expiresAt);
70
+ if (expiresAt < /* @__PURE__ */ new Date()) {
71
+ console.log("\u26A0\uFE0F Credentials have expired");
72
+ return null;
73
+ }
74
+ }
75
+ return credentials;
76
+ } catch (error) {
77
+ console.error("Failed to load credentials:", error);
78
+ return null;
79
+ }
80
+ }
81
+ function saveCredentials(credentials) {
82
+ try {
83
+ if (!fs.existsSync(CREDENTIALS_DIR)) {
84
+ fs.mkdirSync(CREDENTIALS_DIR, { mode: 448, recursive: true });
85
+ }
86
+ fs.writeFileSync(
87
+ CREDENTIALS_FILE,
88
+ JSON.stringify(credentials, null, 2),
89
+ { mode: 384 }
90
+ );
91
+ } catch (error) {
92
+ throw new Error(`Failed to save credentials: ${error}`);
93
+ }
94
+ }
95
+ function clearCredentials() {
96
+ try {
97
+ if (fs.existsSync(CREDENTIALS_FILE)) {
98
+ fs.unlinkSync(CREDENTIALS_FILE);
99
+ }
100
+ } catch (error) {
101
+ console.error("Failed to clear credentials:", error);
102
+ }
103
+ }
104
+ async function runDeviceAuth(baseUrl = DEFAULT_BASE_URL) {
105
+ console.log("\u{1F510} Starting device authentication...\n");
106
+ const deviceAuth = await requestDeviceCode(baseUrl);
107
+ 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");
108
+ console.log("\u{1F4CB} To authenticate, visit:");
109
+ console.log(` ${deviceAuth.verificationUri}`);
110
+ console.log("");
111
+ console.log("\u{1F511} Enter this code:");
112
+ console.log(` ${deviceAuth.userCode}`);
113
+ 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");
114
+ console.log("\u23F3 Waiting for authentication...\n");
115
+ const credentials = await pollForToken(
116
+ baseUrl,
117
+ deviceAuth.deviceCode,
118
+ deviceAuth.interval,
119
+ deviceAuth.expiresIn
120
+ );
121
+ saveCredentials(credentials);
122
+ console.log("\u2705 Authentication successful!");
123
+ console.log(` Agent ID: ${credentials.agentId}`);
124
+ if (credentials.agentName) {
125
+ console.log(` Agent Name: ${credentials.agentName}`);
126
+ }
127
+ console.log("");
128
+ return credentials;
129
+ }
130
+ async function requestDeviceCode(baseUrl) {
131
+ const response = await fetch(`${baseUrl}/auth/device`, {
132
+ method: "POST",
133
+ headers: {
134
+ "Content-Type": "application/json"
135
+ },
136
+ body: JSON.stringify({
137
+ client_id: CLIENT_ID,
138
+ scope: "agent:execute"
139
+ })
140
+ });
141
+ if (!response.ok) {
142
+ const error = await response.text();
143
+ throw new Error(`Failed to start device auth: ${error}`);
144
+ }
145
+ const data = await response.json();
146
+ return {
147
+ deviceCode: data.deviceCode || data.device_code || "",
148
+ userCode: data.userCode || data.user_code || "",
149
+ verificationUri: data.verificationUri || data.verification_uri || `https://artyfacts.dev/auth/device`,
150
+ expiresIn: data.expiresIn || data.expires_in || 600,
151
+ interval: data.interval || 5
152
+ };
153
+ }
154
+ async function pollForToken(baseUrl, deviceCode, interval, expiresIn) {
155
+ const startTime = Date.now();
156
+ const timeoutMs = expiresIn * 1e3;
157
+ while (true) {
158
+ if (Date.now() - startTime > timeoutMs) {
159
+ throw new Error("Device authentication timed out");
160
+ }
161
+ await sleep(interval * 1e3);
162
+ const response = await fetch(`${baseUrl}/auth/device/token`, {
163
+ method: "POST",
164
+ headers: {
165
+ "Content-Type": "application/json"
166
+ },
167
+ body: JSON.stringify({
168
+ device_code: deviceCode,
169
+ client_id: CLIENT_ID
170
+ })
171
+ });
172
+ if (response.ok) {
173
+ const data = await response.json();
174
+ return {
175
+ apiKey: data.apiKey,
176
+ agentId: data.agentId,
177
+ agentName: data.agentName,
178
+ expiresAt: data.expiresAt
179
+ };
180
+ }
181
+ const errorData = await response.json().catch(() => ({}));
182
+ const errorCode = errorData.error || errorData.code;
183
+ if (errorCode === "authorization_pending") {
184
+ process.stdout.write(".");
185
+ continue;
186
+ }
187
+ if (errorCode === "slow_down") {
188
+ interval = Math.min(interval * 2, 30);
189
+ continue;
190
+ }
191
+ if (errorCode === "expired_token") {
192
+ throw new Error("Device code expired. Please try again.");
193
+ }
194
+ if (errorCode === "access_denied") {
195
+ throw new Error("Authorization was denied.");
196
+ }
197
+ throw new Error(`Authentication failed: ${errorData.message || errorCode || response.statusText}`);
198
+ }
199
+ }
200
+ async function promptForApiKey() {
201
+ const rl = readline.createInterface({
202
+ input: process.stdin,
203
+ output: process.stdout
204
+ });
205
+ const question = (prompt) => {
206
+ return new Promise((resolve) => {
207
+ rl.question(prompt, resolve);
208
+ });
209
+ };
210
+ console.log("\u{1F511} Manual Configuration\n");
211
+ console.log("Enter your Artyfacts credentials:\n");
212
+ const apiKey = await question("API Key: ");
213
+ const agentId = await question("Agent ID: ");
214
+ const agentName = await question("Agent Name (optional): ");
215
+ rl.close();
216
+ if (!apiKey || !agentId) {
217
+ throw new Error("API Key and Agent ID are required");
218
+ }
219
+ const credentials = {
220
+ apiKey: apiKey.trim(),
221
+ agentId: agentId.trim(),
222
+ agentName: agentName.trim() || void 0
223
+ };
224
+ saveCredentials(credentials);
225
+ console.log("\n\u2705 Credentials saved!");
226
+ return credentials;
227
+ }
228
+ function sleep(ms) {
229
+ return new Promise((resolve) => setTimeout(resolve, ms));
230
+ }
231
+ async function getCredentials(options) {
232
+ if (!options?.forceAuth) {
233
+ const existing = loadCredentials();
234
+ if (existing) {
235
+ return existing;
236
+ }
237
+ }
238
+ return runDeviceAuth(options?.baseUrl);
239
+ }
240
+
241
+ // src/executor.ts
242
+ var import_child_process = require("child_process");
243
+
244
+ // src/context.ts
245
+ var ContextFetcher = class {
246
+ constructor(config) {
247
+ this.config = config;
248
+ }
249
+ /**
250
+ * Fetch full context for a task
251
+ */
252
+ async fetchTaskContext(taskId) {
253
+ const response = await fetch(
254
+ `${this.config.baseUrl}/tasks/${taskId}/context`,
255
+ {
256
+ headers: {
257
+ "Authorization": `Bearer ${this.config.apiKey}`,
258
+ "Accept": "application/json"
259
+ }
260
+ }
261
+ );
262
+ if (!response.ok) {
263
+ const errorText = await response.text().catch(() => "Unknown error");
264
+ throw new Error(`Failed to fetch task context: ${response.status} - ${errorText}`);
265
+ }
266
+ const data = await response.json();
267
+ return data;
268
+ }
269
+ };
270
+ function buildPromptWithContext(context) {
271
+ const parts = [];
272
+ parts.push(`You are an AI agent working within the Artyfacts task management system.
273
+
274
+ Your job is to complete the assigned task. You have full context about the organization, project, and related work.
275
+
276
+ ## Available Tools
277
+
278
+ You have access to Artyfacts MCP tools. USE THEM to complete your task:
279
+
280
+ - **create_artifact** - Create new artifacts (documents, specs, reports)
281
+ - **create_section** - Add sections to artifacts (content, tasks, decisions)
282
+ - **update_section** - Update existing sections
283
+ - **create_agent** - Create new AI agents with specific roles
284
+ - **list_artifacts** - Query existing artifacts
285
+ - **list_sections** - Query sections within an artifact
286
+ - **complete_task** - Mark a task as complete
287
+ - **block_task** - Block a task with a reason
288
+ - **create_blocker** - Create a decision blocker
289
+
290
+ IMPORTANT: When asked to create agents or update artifacts, USE THE TOOLS. Don't just describe what you would do - actually do it with the tools.
291
+
292
+ ## Guidelines
293
+
294
+ - Be thorough but concise
295
+ - USE THE TOOLS to take action, don't just analyze
296
+ - If the task requires creating something, use create_artifact or create_section
297
+ - If the task requires creating agents, use create_agent
298
+ - If you cannot complete the task, explain why
299
+
300
+ Format your response as follows:
301
+ 1. First, use the tools to complete the task
302
+ 2. Then summarize what you did
303
+ 3. End with a brief summary line starting with "SUMMARY:"`);
304
+ parts.push("");
305
+ parts.push("---");
306
+ parts.push("");
307
+ parts.push("## Organization Context");
308
+ parts.push(`**${context.organization.name}**`);
309
+ if (context.organization.context) {
310
+ parts.push("");
311
+ parts.push(formatOrgContext(context.organization.context));
312
+ }
313
+ parts.push("");
314
+ if (context.project) {
315
+ parts.push(`## Project: ${context.project.name}`);
316
+ if (context.project.description) {
317
+ parts.push(context.project.description);
318
+ }
319
+ parts.push("");
320
+ }
321
+ parts.push(`## Artifact: ${context.artifact.title}`);
322
+ if (context.artifact.summary) {
323
+ parts.push(context.artifact.summary);
324
+ }
325
+ if (context.artifact.description) {
326
+ parts.push("");
327
+ parts.push(context.artifact.description);
328
+ }
329
+ parts.push("");
330
+ const relatedSections = context.artifact.sections.filter(
331
+ (s) => s.id !== context.task.id
332
+ );
333
+ if (relatedSections.length > 0) {
334
+ parts.push("### Related Sections:");
335
+ for (const section of relatedSections) {
336
+ const preview = section.content ? section.content.substring(0, 200) + (section.content.length > 200 ? "..." : "") : "No content";
337
+ const statusBadge = section.task_status ? ` [${section.task_status}]` : "";
338
+ parts.push(`- **${section.heading}**${statusBadge}: ${preview}`);
339
+ }
340
+ parts.push("");
341
+ }
342
+ parts.push("---");
343
+ parts.push("");
344
+ parts.push(`## Your Task: ${context.task.heading}`);
345
+ if (context.task.priority) {
346
+ const priorityLabels = ["\u{1F534} High", "\u{1F7E1} Medium", "\u{1F7E2} Low"];
347
+ parts.push(`**Priority:** ${priorityLabels[context.task.priority - 1] || "Medium"}`);
348
+ }
349
+ parts.push("");
350
+ parts.push("### Description");
351
+ parts.push(context.task.content || "No additional description provided.");
352
+ parts.push("");
353
+ if (context.task.expected_output) {
354
+ parts.push("### Expected Output");
355
+ if (context.task.expected_output.format) {
356
+ parts.push(`**Format:** ${context.task.expected_output.format}`);
357
+ }
358
+ if (context.task.expected_output.requirements && context.task.expected_output.requirements.length > 0) {
359
+ parts.push("**Requirements:**");
360
+ for (const req of context.task.expected_output.requirements) {
361
+ parts.push(`- ${req}`);
362
+ }
363
+ }
364
+ parts.push("");
365
+ }
366
+ parts.push("---");
367
+ parts.push("");
368
+ parts.push("Complete this task and provide your output below.");
369
+ return parts.join("\n");
370
+ }
371
+ function formatOrgContext(context) {
372
+ const trimmed = context.trim();
373
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
374
+ try {
375
+ const parsed = JSON.parse(trimmed);
376
+ return formatContextObject(parsed);
377
+ } catch {
378
+ return context;
379
+ }
380
+ }
381
+ return context;
382
+ }
383
+ function formatContextObject(obj, indent = "") {
384
+ if (typeof obj !== "object" || obj === null) {
385
+ return String(obj);
386
+ }
387
+ if (Array.isArray(obj)) {
388
+ return obj.map((item) => `${indent}- ${formatContextObject(item, indent + " ")}`).join("\n");
389
+ }
390
+ const lines = [];
391
+ for (const [key, value] of Object.entries(obj)) {
392
+ const label = key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
393
+ if (typeof value === "object" && value !== null) {
394
+ lines.push(`${indent}**${label}:**`);
395
+ lines.push(formatContextObject(value, indent + " "));
396
+ } else {
397
+ lines.push(`${indent}- **${label}:** ${value}`);
398
+ }
399
+ }
400
+ return lines.join("\n");
401
+ }
402
+ function createContextFetcher(config) {
403
+ return new ContextFetcher(config);
404
+ }
405
+
406
+ // src/executor.ts
407
+ var DEFAULT_TIMEOUT = 5 * 60 * 1e3;
408
+ var DEFAULT_SYSTEM_PROMPT = `You are an AI agent working within the Artyfacts task management system.
409
+
410
+ Your job is to complete tasks assigned to you using the available tools.
411
+
412
+ ## Available Tools
413
+
414
+ You have access to Artyfacts MCP tools. USE THEM to complete your task:
415
+
416
+ - **create_artifact** - Create new artifacts (documents, specs, reports)
417
+ - **create_section** - Add sections to artifacts (content, tasks, decisions)
418
+ - **update_section** - Update existing sections
419
+ - **create_agent** - Create new AI agents with specific roles
420
+ - **list_artifacts** - Query existing artifacts
421
+ - **list_sections** - Query sections within an artifact
422
+ - **complete_task** - Mark a task as complete
423
+ - **block_task** - Block a task with a reason
424
+ - **create_blocker** - Create a decision blocker
425
+
426
+ IMPORTANT: When asked to create agents or update artifacts, USE THE TOOLS. Don't just describe what you would do - actually do it.
427
+
428
+ ## Guidelines
429
+
430
+ - USE THE TOOLS to take action
431
+ - If creating something, use create_artifact or create_section
432
+ - If creating agents, use create_agent
433
+ - If you cannot complete the task, explain why
434
+
435
+ Format your response as follows:
436
+ 1. First, use the tools to complete the task
437
+ 2. Summarize what you accomplished
438
+ 3. End with a brief summary line starting with "SUMMARY:"`;
439
+ var OpenClawExecutor = class {
440
+ constructor(config = {}) {
441
+ this.contextFetcher = null;
442
+ this.config = {
443
+ ...config,
444
+ timeout: config.timeout || DEFAULT_TIMEOUT,
445
+ openclawPath: config.openclawPath || "openclaw"
446
+ };
447
+ if (config.baseUrl && config.apiKey) {
448
+ this.contextFetcher = createContextFetcher({
449
+ baseUrl: config.baseUrl,
450
+ apiKey: config.apiKey
451
+ });
452
+ }
453
+ }
454
+ /**
455
+ * Check if OpenClaw CLI is installed
456
+ */
457
+ async isInstalled() {
458
+ try {
459
+ const result = (0, import_child_process.spawnSync)(this.config.openclawPath || "openclaw", ["--version"], {
460
+ encoding: "utf-8",
461
+ stdio: ["pipe", "pipe", "pipe"]
462
+ });
463
+ return result.status === 0;
464
+ } catch {
465
+ return false;
466
+ }
467
+ }
468
+ /**
469
+ * Get OpenClaw version
470
+ */
471
+ async getVersion() {
472
+ try {
473
+ const result = (0, import_child_process.spawnSync)(this.config.openclawPath || "openclaw", ["--version"], {
474
+ encoding: "utf-8",
475
+ stdio: ["pipe", "pipe", "pipe"]
476
+ });
477
+ if (result.status === 0) {
478
+ return result.stdout.trim();
479
+ }
480
+ return null;
481
+ } catch {
482
+ return null;
483
+ }
484
+ }
485
+ /**
486
+ * Execute a task using OpenClaw CLI
487
+ */
488
+ async execute(task) {
489
+ try {
490
+ let prompt;
491
+ let fullContext = null;
492
+ const useFullContext = this.config.useFullContext !== false && this.contextFetcher;
493
+ if (useFullContext) {
494
+ try {
495
+ fullContext = await this.contextFetcher.fetchTaskContext(task.taskId);
496
+ prompt = buildPromptWithContext(fullContext);
497
+ console.log(" \u{1F4DA} Using full context (org, project, artifact, related sections)");
498
+ } catch (contextError) {
499
+ console.warn(" \u26A0\uFE0F Could not fetch full context, using minimal prompt");
500
+ console.warn(` ${contextError instanceof Error ? contextError.message : contextError}`);
501
+ prompt = this.buildTaskPrompt(task);
502
+ }
503
+ } else {
504
+ prompt = this.buildTaskPrompt(task);
505
+ }
506
+ const output = await this.runOpenClaw(prompt);
507
+ const { content, summary } = this.parseResponse(output, task.heading);
508
+ return {
509
+ success: true,
510
+ output: content,
511
+ summary,
512
+ promptUsed: prompt
513
+ };
514
+ } catch (error) {
515
+ const errorMessage = error instanceof Error ? error.message : String(error);
516
+ return {
517
+ success: false,
518
+ output: "",
519
+ summary: `Failed: ${errorMessage}`,
520
+ error: errorMessage
521
+ };
522
+ }
523
+ }
524
+ /**
525
+ * Run OpenClaw CLI with the given prompt
526
+ */
527
+ runOpenClaw(prompt) {
528
+ return new Promise((resolve, reject) => {
529
+ const openclawPath = this.config.openclawPath || "openclaw";
530
+ const args = [
531
+ "prompt",
532
+ "--output-format",
533
+ "text"
534
+ // Get plain text output
535
+ ];
536
+ if (this.config.sessionKey) {
537
+ args.push("--session", this.config.sessionKey);
538
+ }
539
+ args.push(prompt);
540
+ const proc = (0, import_child_process.spawn)(openclawPath, args, {
541
+ stdio: ["pipe", "pipe", "pipe"],
542
+ timeout: this.config.timeout,
543
+ env: {
544
+ ...process.env,
545
+ // Pass Artyfacts API key for MCP tools
546
+ ARTYFACTS_API_KEY: this.config.apiKey || process.env.ARTYFACTS_API_KEY || "",
547
+ ARTYFACTS_BASE_URL: this.config.baseUrl || "https://artyfacts.dev/api/v1"
548
+ }
549
+ });
550
+ let stdout = "";
551
+ let stderr = "";
552
+ proc.stdout.on("data", (data) => {
553
+ stdout += data.toString();
554
+ });
555
+ proc.stderr.on("data", (data) => {
556
+ stderr += data.toString();
557
+ });
558
+ proc.on("close", (code) => {
559
+ if (code === 0) {
560
+ resolve(stdout.trim());
561
+ } else {
562
+ reject(new Error(stderr || `OpenClaw exited with code ${code}`));
563
+ }
564
+ });
565
+ proc.on("error", (err) => {
566
+ if (err.code === "ENOENT") {
567
+ reject(new Error(
568
+ "OpenClaw CLI not found. Please install it:\n npm install -g openclaw"
569
+ ));
570
+ } else {
571
+ reject(err);
572
+ }
573
+ });
574
+ });
575
+ }
576
+ /**
577
+ * Build the task prompt
578
+ */
579
+ buildTaskPrompt(task) {
580
+ const parts = [];
581
+ const systemPrompt = this.config.systemPromptPrefix ? `${this.config.systemPromptPrefix}
582
+
583
+ ${DEFAULT_SYSTEM_PROMPT}` : DEFAULT_SYSTEM_PROMPT;
584
+ parts.push(systemPrompt);
585
+ parts.push("");
586
+ parts.push("---");
587
+ parts.push("");
588
+ parts.push(`# Task: ${task.heading}`);
589
+ parts.push("");
590
+ if (task.artifactTitle) {
591
+ parts.push(`**Part of:** ${task.artifactTitle}`);
592
+ parts.push(`**Artifact ID:** ${task.artifactId}`);
593
+ parts.push("");
594
+ }
595
+ if (task.priority) {
596
+ const priorityLabel = ["High", "Medium", "Low"][task.priority - 1] || "Unknown";
597
+ parts.push(`**Priority:** ${priorityLabel}`);
598
+ parts.push("");
599
+ }
600
+ parts.push("## Description");
601
+ parts.push("");
602
+ parts.push(task.content || "No description provided.");
603
+ parts.push("");
604
+ if (task.context && Object.keys(task.context).length > 0) {
605
+ parts.push("## Additional Context");
606
+ parts.push("");
607
+ parts.push("```json");
608
+ parts.push(JSON.stringify(task.context, null, 2));
609
+ parts.push("```");
610
+ parts.push("");
611
+ }
612
+ parts.push("---");
613
+ parts.push("");
614
+ parts.push("Please complete this task using the available Artyfacts tools.");
615
+ parts.push("When done, provide a summary of what you accomplished.");
616
+ return parts.join("\n");
617
+ }
618
+ /**
619
+ * Parse the response to extract content and summary
620
+ */
621
+ parseResponse(output, fallbackSummary) {
622
+ const summaryMatch = output.match(/SUMMARY:\s*(.+?)(?:\n|$)/i);
623
+ if (summaryMatch) {
624
+ const summary2 = summaryMatch[1].trim();
625
+ const content = output.replace(/SUMMARY:\s*.+?(?:\n|$)/i, "").trim();
626
+ return { content, summary: summary2 };
627
+ }
628
+ const lines = output.split("\n").filter((l) => l.trim());
629
+ const summary = lines.length > 0 ? lines[lines.length - 1].slice(0, 200) : `Completed: ${fallbackSummary}`;
630
+ return { content: output, summary };
631
+ }
632
+ };
633
+ function createExecutor(config) {
634
+ return new OpenClawExecutor(config);
635
+ }
636
+
637
+ // src/listener.ts
638
+ var import_eventsource = __toESM(require("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
+ constructor(config) {
652
+ this.eventSource = null;
653
+ this.callbacks = /* @__PURE__ */ new Map();
654
+ this.allCallbacks = /* @__PURE__ */ new Set();
655
+ this.state = "disconnected";
656
+ this.reconnectAttempts = 0;
657
+ this.maxReconnectAttempts = 10;
658
+ this.reconnectDelay = 1e3;
659
+ if (!config.apiKey) {
660
+ throw new Error("API key is required");
661
+ }
662
+ if (!config.agentId) {
663
+ throw new Error("Agent ID is required");
664
+ }
665
+ this.config = {
666
+ ...config,
667
+ baseUrl: config.baseUrl || DEFAULT_BASE_URL2
668
+ };
669
+ }
670
+ /**
671
+ * Get current connection state
672
+ */
673
+ get connectionState() {
674
+ return this.state;
675
+ }
676
+ /**
677
+ * Check if connected
678
+ */
679
+ get isConnected() {
680
+ return this.state === "connected";
681
+ }
682
+ /**
683
+ * Subscribe to all events
684
+ */
685
+ subscribe(callback) {
686
+ this.allCallbacks.add(callback);
687
+ return () => {
688
+ this.allCallbacks.delete(callback);
689
+ };
690
+ }
691
+ /**
692
+ * Subscribe to a specific event type
693
+ */
694
+ on(type, callback) {
695
+ if (!this.callbacks.has(type)) {
696
+ this.callbacks.set(type, /* @__PURE__ */ new Set());
697
+ }
698
+ this.callbacks.get(type).add(callback);
699
+ return () => {
700
+ const typeCallbacks = this.callbacks.get(type);
701
+ if (typeCallbacks) {
702
+ typeCallbacks.delete(callback);
703
+ if (typeCallbacks.size === 0) {
704
+ this.callbacks.delete(type);
705
+ }
706
+ }
707
+ };
708
+ }
709
+ /**
710
+ * Connect to the SSE stream
711
+ */
712
+ connect() {
713
+ if (this.eventSource) {
714
+ return;
715
+ }
716
+ this.setState("connecting");
717
+ const url = new URL(`${this.config.baseUrl}/events/stream`);
718
+ url.searchParams.set("apiKey", this.config.apiKey);
719
+ url.searchParams.set("agentId", this.config.agentId);
720
+ this.eventSource = new import_eventsource.default(url.toString(), {
721
+ headers: {
722
+ "Authorization": `Bearer ${this.config.apiKey}`
723
+ }
724
+ });
725
+ this.eventSource.onopen = () => {
726
+ this.reconnectAttempts = 0;
727
+ this.reconnectDelay = 1e3;
728
+ this.setState("connected");
729
+ };
730
+ this.eventSource.onmessage = (event) => {
731
+ this.handleMessage(event);
732
+ };
733
+ this.eventSource.onerror = (event) => {
734
+ this.handleError(event);
735
+ };
736
+ for (const eventType of EVENT_TYPES) {
737
+ this.eventSource.addEventListener(eventType, (event) => {
738
+ this.handleMessage(event, eventType);
739
+ });
740
+ }
741
+ }
742
+ /**
743
+ * Disconnect from the SSE stream
744
+ */
745
+ disconnect() {
746
+ if (this.eventSource) {
747
+ this.eventSource.close();
748
+ this.eventSource = null;
749
+ }
750
+ this.setState("disconnected");
751
+ }
752
+ /**
753
+ * Reconnect to the SSE stream
754
+ */
755
+ reconnect() {
756
+ this.disconnect();
757
+ this.connect();
758
+ }
759
+ /**
760
+ * Handle incoming SSE message
761
+ */
762
+ handleMessage(event, eventType) {
763
+ try {
764
+ const data = JSON.parse(event.data);
765
+ const rawData = data.data || data;
766
+ const normalizedData = rawData.task_id ? {
767
+ taskId: rawData.task_id,
768
+ sectionId: rawData.section_id,
769
+ artifactId: rawData.artifact_id,
770
+ artifactTitle: rawData.artifact_title,
771
+ heading: rawData.heading,
772
+ content: rawData.content,
773
+ assignedTo: rawData.assigned_to,
774
+ assignedAt: rawData.assigned_at,
775
+ priority: rawData.priority,
776
+ ...rawData
777
+ // Keep original fields too
778
+ } : rawData;
779
+ const artyfactsEvent = {
780
+ type: eventType || data.type || "unknown",
781
+ timestamp: data.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
782
+ data: normalizedData
783
+ };
784
+ const typeCallbacks = this.callbacks.get(artyfactsEvent.type);
785
+ if (typeCallbacks) {
786
+ for (const callback of typeCallbacks) {
787
+ this.safeCallCallback(callback, artyfactsEvent);
788
+ }
789
+ }
790
+ for (const callback of this.allCallbacks) {
791
+ this.safeCallCallback(callback, artyfactsEvent);
792
+ }
793
+ } catch (err) {
794
+ console.error("[Listener] Failed to parse SSE message:", event.data, err);
795
+ }
796
+ }
797
+ /**
798
+ * Safely call a callback, handling async and errors
799
+ */
800
+ async safeCallCallback(callback, event) {
801
+ try {
802
+ await callback(event);
803
+ } catch (err) {
804
+ console.error(`[Listener] Error in event callback for '${event.type}':`, err);
805
+ }
806
+ }
807
+ /**
808
+ * Handle SSE error
809
+ */
810
+ handleError(event) {
811
+ if (this.eventSource?.readyState === import_eventsource.default.CONNECTING) {
812
+ this.setState("reconnecting");
813
+ } else if (this.eventSource?.readyState === import_eventsource.default.CLOSED) {
814
+ this.setState("disconnected");
815
+ if (this.reconnectAttempts < this.maxReconnectAttempts) {
816
+ this.reconnectAttempts++;
817
+ this.reconnectDelay = Math.min(this.reconnectDelay * 2, 3e4);
818
+ console.log(
819
+ `[Listener] Connection lost, reconnecting in ${this.reconnectDelay / 1e3}s (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`
820
+ );
821
+ setTimeout(() => {
822
+ if (this.state === "disconnected") {
823
+ this.connect();
824
+ }
825
+ }, this.reconnectDelay);
826
+ } else {
827
+ const error = new Error("Max reconnection attempts reached");
828
+ this.config.onError?.(error);
829
+ }
830
+ }
831
+ }
832
+ /**
833
+ * Update connection state
834
+ */
835
+ setState(state) {
836
+ if (this.state !== state) {
837
+ this.state = state;
838
+ this.config.onStateChange?.(state);
839
+ }
840
+ }
841
+ };
842
+ function createListener(config) {
843
+ return new ArtyfactsListener(config);
844
+ }
845
+
846
+ // src/mcp.ts
847
+ var import_child_process2 = require("child_process");
848
+ var DEFAULT_MCP_NAME = "artyfacts";
849
+ var DEFAULT_BASE_URL3 = "https://artyfacts.dev/api/v1";
850
+ var McpHandler = class {
851
+ constructor(config) {
852
+ this.config = {
853
+ name: DEFAULT_MCP_NAME,
854
+ baseUrl: DEFAULT_BASE_URL3,
855
+ ...config
856
+ };
857
+ this.openclawPath = config.openclawPath || "openclaw";
858
+ }
859
+ /**
860
+ * Check if Artyfacts MCP server is already configured
861
+ */
862
+ isConfigured() {
863
+ try {
864
+ const result = (0, import_child_process2.spawnSync)(this.openclawPath, ["mcp", "show", this.config.name || DEFAULT_MCP_NAME], {
865
+ encoding: "utf-8",
866
+ stdio: ["pipe", "pipe", "pipe"]
867
+ });
868
+ if (result.status === 0) {
869
+ return {
870
+ configured: true,
871
+ name: this.config.name
872
+ };
873
+ }
874
+ return { configured: false };
875
+ } catch (error) {
876
+ return {
877
+ configured: false,
878
+ error: error instanceof Error ? error.message : String(error)
879
+ };
880
+ }
881
+ }
882
+ /**
883
+ * Configure Artyfacts MCP server in OpenClaw
884
+ *
885
+ * Uses: openclaw mcp set <name> --command "npx" --args "-y @artyfacts/mcp-server"
886
+ */
887
+ configure() {
888
+ console.log("\u{1F527} Configuring Artyfacts tools for OpenClaw...");
889
+ try {
890
+ const result = (0, import_child_process2.spawnSync)(this.openclawPath, [
891
+ "mcp",
892
+ "set",
893
+ this.config.name || DEFAULT_MCP_NAME,
894
+ "--command",
895
+ "npx",
896
+ "--args",
897
+ "-y",
898
+ "--args",
899
+ "@artyfacts/mcp-server",
900
+ "--env",
901
+ `ARTYFACTS_API_KEY=${this.config.apiKey}`,
902
+ "--env",
903
+ `ARTYFACTS_BASE_URL=${this.config.baseUrl || DEFAULT_BASE_URL3}`
904
+ ], {
905
+ encoding: "utf-8",
906
+ stdio: ["pipe", "pipe", "pipe"]
907
+ });
908
+ if (result.status === 0) {
909
+ console.log("\u2705 MCP tools configured! OpenClaw now has access to Artyfacts.");
910
+ return true;
911
+ } else {
912
+ return this.configureAlternative();
913
+ }
914
+ } catch (error) {
915
+ console.log("\u26A0\uFE0F Could not configure MCP:", error instanceof Error ? error.message : error);
916
+ this.printManualInstructions();
917
+ return false;
918
+ }
919
+ }
920
+ /**
921
+ * Alternative configuration approach using JSON config
922
+ */
923
+ configureAlternative() {
924
+ try {
925
+ const mcpConfig = JSON.stringify({
926
+ command: "npx",
927
+ args: ["-y", "@artyfacts/mcp-server"],
928
+ env: {
929
+ ARTYFACTS_API_KEY: this.config.apiKey,
930
+ ARTYFACTS_BASE_URL: this.config.baseUrl || DEFAULT_BASE_URL3
931
+ }
932
+ });
933
+ const result = (0, import_child_process2.spawnSync)(this.openclawPath, [
934
+ "mcp",
935
+ "set",
936
+ this.config.name || DEFAULT_MCP_NAME,
937
+ "--config",
938
+ mcpConfig
939
+ ], {
940
+ encoding: "utf-8",
941
+ stdio: ["pipe", "pipe", "pipe"]
942
+ });
943
+ if (result.status === 0) {
944
+ console.log("\u2705 MCP tools configured! OpenClaw now has access to Artyfacts.");
945
+ return true;
946
+ } else {
947
+ console.log("\u26A0\uFE0F Could not configure MCP:", result.stderr || result.stdout);
948
+ this.printManualInstructions();
949
+ return false;
950
+ }
951
+ } catch (error) {
952
+ console.log("\u26A0\uFE0F Could not configure MCP:", error instanceof Error ? error.message : error);
953
+ this.printManualInstructions();
954
+ return false;
955
+ }
956
+ }
957
+ /**
958
+ * Print manual configuration instructions
959
+ */
960
+ printManualInstructions() {
961
+ console.log("");
962
+ console.log("You can manually add the Artyfacts MCP server with:");
963
+ console.log("");
964
+ console.log(` openclaw mcp set ${this.config.name || DEFAULT_MCP_NAME} \\`);
965
+ console.log(` --command "npx" \\`);
966
+ console.log(` --args "-y" --args "@artyfacts/mcp-server" \\`);
967
+ console.log(` --env "ARTYFACTS_API_KEY=${this.config.apiKey}" \\`);
968
+ console.log(` --env "ARTYFACTS_BASE_URL=${this.config.baseUrl || DEFAULT_BASE_URL3}"`);
969
+ console.log("");
970
+ console.log("Or add to your openclaw.json:");
971
+ console.log("");
972
+ console.log(` "mcp": {`);
973
+ console.log(` "${this.config.name || DEFAULT_MCP_NAME}": {`);
974
+ console.log(` "command": "npx",`);
975
+ console.log(` "args": ["-y", "@artyfacts/mcp-server"],`);
976
+ console.log(` "env": {`);
977
+ console.log(` "ARTYFACTS_API_KEY": "<your-api-key>",`);
978
+ console.log(` "ARTYFACTS_BASE_URL": "${this.config.baseUrl || DEFAULT_BASE_URL3}"`);
979
+ console.log(` }`);
980
+ console.log(` }`);
981
+ console.log(` }`);
982
+ console.log("");
983
+ }
984
+ /**
985
+ * Remove Artyfacts MCP configuration
986
+ */
987
+ remove() {
988
+ try {
989
+ const result = (0, import_child_process2.spawnSync)(this.openclawPath, [
990
+ "mcp",
991
+ "unset",
992
+ this.config.name || DEFAULT_MCP_NAME
993
+ ], {
994
+ encoding: "utf-8",
995
+ stdio: ["pipe", "pipe", "pipe"]
996
+ });
997
+ if (result.status === 0) {
998
+ console.log("\u2705 Artyfacts MCP configuration removed.");
999
+ return true;
1000
+ } else {
1001
+ console.log("\u26A0\uFE0F Could not remove MCP config:", result.stderr || result.stdout);
1002
+ return false;
1003
+ }
1004
+ } catch (error) {
1005
+ console.log("\u26A0\uFE0F Could not remove MCP config:", error instanceof Error ? error.message : error);
1006
+ return false;
1007
+ }
1008
+ }
1009
+ /**
1010
+ * Ensure MCP is configured, configure if needed
1011
+ */
1012
+ ensureConfigured() {
1013
+ const status = this.isConfigured();
1014
+ if (status.configured) {
1015
+ console.log("\u2705 Artyfacts MCP tools already configured");
1016
+ return true;
1017
+ }
1018
+ return this.configure();
1019
+ }
1020
+ };
1021
+ function createMcpHandler(config) {
1022
+ return new McpHandler(config);
1023
+ }
1024
+
1025
+ // src/introspect.ts
1026
+ var import_promises = require("fs/promises");
1027
+ var import_path = require("path");
1028
+ var import_os = require("os");
1029
+ var import_child_process3 = require("child_process");
1030
+ var OPENCLAW_DIR = (0, import_path.join)((0, import_os.homedir)(), ".openclaw");
1031
+ var CONFIG_FILE = (0, import_path.join)(OPENCLAW_DIR, "openclaw.json");
1032
+ var CRON_FILE = (0, import_path.join)(OPENCLAW_DIR, "cron", "jobs.json");
1033
+ var SKILLS_DIR = (0, import_path.join)(OPENCLAW_DIR, "skills");
1034
+ function parseJson5(content) {
1035
+ const stripped = content.split("\n").map((line) => {
1036
+ const commentIndex = line.indexOf("//");
1037
+ if (commentIndex === -1) return line;
1038
+ const beforeComment = line.slice(0, commentIndex);
1039
+ const quotes = (beforeComment.match(/"/g) || []).length;
1040
+ if (quotes % 2 === 0) {
1041
+ return beforeComment;
1042
+ }
1043
+ return line;
1044
+ }).join("\n");
1045
+ const noTrailing = stripped.replace(/,(\s*[}\]])/g, "$1");
1046
+ return JSON.parse(noTrailing);
1047
+ }
1048
+ async function readCronJobs() {
1049
+ try {
1050
+ const content = await (0, import_promises.readFile)(CRON_FILE, "utf-8");
1051
+ const jobs = JSON.parse(content);
1052
+ return Array.isArray(jobs) ? jobs : [];
1053
+ } catch (err) {
1054
+ return [];
1055
+ }
1056
+ }
1057
+ async function readMainConfig() {
1058
+ try {
1059
+ const content = await (0, import_promises.readFile)(CONFIG_FILE, "utf-8");
1060
+ const config = parseJson5(content);
1061
+ const agentsConfig = config.agents;
1062
+ const defaults = agentsConfig?.defaults;
1063
+ const heartbeat = defaults?.heartbeat;
1064
+ const agentsList = agentsConfig?.list || [];
1065
+ const channelsConfig = config.channels;
1066
+ const channelNames = channelsConfig ? Object.keys(channelsConfig).filter((k) => k !== "defaults") : [];
1067
+ return {
1068
+ heartbeat: heartbeat || null,
1069
+ agents: agentsList,
1070
+ channels: channelNames
1071
+ };
1072
+ } catch (err) {
1073
+ return { heartbeat: null, agents: [], channels: [] };
1074
+ }
1075
+ }
1076
+ async function readMcpServers() {
1077
+ try {
1078
+ const output = (0, import_child_process3.execSync)("openclaw mcp list --json 2>/dev/null", {
1079
+ encoding: "utf-8",
1080
+ timeout: 5e3
1081
+ });
1082
+ const servers = JSON.parse(output);
1083
+ return Array.isArray(servers) ? servers : [];
1084
+ } catch (err) {
1085
+ return [];
1086
+ }
1087
+ }
1088
+ async function readSkills() {
1089
+ const skills = [];
1090
+ async function scanDir(dir, prefix = "") {
1091
+ try {
1092
+ const entries = await (0, import_promises.readdir)(dir, { withFileTypes: true });
1093
+ for (const entry of entries) {
1094
+ const fullPath = (0, import_path.join)(dir, entry.name);
1095
+ if (entry.isDirectory()) {
1096
+ await scanDir(fullPath, prefix ? `${prefix}/${entry.name}` : entry.name);
1097
+ } else if (entry.name === "SKILL.md") {
1098
+ const skillName = prefix || "root";
1099
+ const content = await (0, import_promises.readFile)(fullPath, "utf-8");
1100
+ const lines = content.split("\n");
1101
+ const descLine = lines.find((l) => l.trim() && !l.startsWith("#"));
1102
+ skills.push({
1103
+ name: skillName,
1104
+ path: fullPath,
1105
+ description: descLine?.trim().slice(0, 200),
1106
+ content
1107
+ });
1108
+ }
1109
+ }
1110
+ } catch (err) {
1111
+ }
1112
+ }
1113
+ await scanDir(SKILLS_DIR);
1114
+ return skills;
1115
+ }
1116
+ async function introspect() {
1117
+ const [crons, mainConfig, mcpServers, skills] = await Promise.all([
1118
+ readCronJobs(),
1119
+ readMainConfig(),
1120
+ readMcpServers(),
1121
+ readSkills()
1122
+ ]);
1123
+ return {
1124
+ crons,
1125
+ heartbeat: mainConfig.heartbeat,
1126
+ agents: mainConfig.agents,
1127
+ mcpServers,
1128
+ skills,
1129
+ channels: mainConfig.channels
1130
+ };
1131
+ }
1132
+ function summarize(config) {
1133
+ const parts = [];
1134
+ if (config.crons.length > 0) {
1135
+ parts.push(`${config.crons.length} cron job(s)`);
1136
+ }
1137
+ if (config.heartbeat) {
1138
+ parts.push(`heartbeat: ${config.heartbeat.every || "30m"}`);
1139
+ }
1140
+ if (config.agents.length > 0) {
1141
+ parts.push(`${config.agents.length} agent(s)`);
1142
+ }
1143
+ if (config.mcpServers.length > 0) {
1144
+ parts.push(`${config.mcpServers.length} MCP server(s)`);
1145
+ }
1146
+ if (config.skills.length > 0) {
1147
+ parts.push(`${config.skills.length} skill(s)`);
1148
+ }
1149
+ if (config.channels.length > 0) {
1150
+ parts.push(`channels: ${config.channels.join(", ")}`);
1151
+ }
1152
+ return parts.length > 0 ? parts.join(" | ") : "No configuration found";
1153
+ }
1154
+ // Annotate the CommonJS export names for ESM import in node:
1155
+ 0 && (module.exports = {
1156
+ ArtyfactsListener,
1157
+ ContextFetcher,
1158
+ McpHandler,
1159
+ OpenClawExecutor,
1160
+ buildPromptWithContext,
1161
+ clearCredentials,
1162
+ createContextFetcher,
1163
+ createExecutor,
1164
+ createListener,
1165
+ createMcpHandler,
1166
+ getCredentials,
1167
+ introspect,
1168
+ loadCredentials,
1169
+ promptForApiKey,
1170
+ saveCredentials,
1171
+ summarize
1172
+ });