@aprovan/stitchery 0.1.0-dev.03aaf5b

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,1308 @@
1
+ // src/server/index.ts
2
+ import { createServer } from "http";
3
+ import { createMCPClient } from "@ai-sdk/mcp";
4
+ import { Experimental_StdioMCPTransport } from "@ai-sdk/mcp/mcp-stdio";
5
+ import { createUtcpBackend } from "@aprovan/patchwork-utcp";
6
+ import { jsonSchema as jsonSchema2 } from "ai";
7
+
8
+ // src/server/routes.ts
9
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
10
+ import {
11
+ streamText,
12
+ convertToModelMessages,
13
+ stepCountIs
14
+ } from "ai";
15
+
16
+ // src/prompts.ts
17
+ var PATCHWORK_PROMPT = `
18
+ You are a friendly assistant! When responding to the user, you _must_ respond with JSX files!
19
+
20
+ Look at 'patchwork.compilers' to see what specific runtime components and libraries are supported. (e.g. '['@aprovan/patchwork-image-shadcn' supports React, Tailwind, & ShadCN components). If there are no compilers, respond as you normally would. If compilers are available, ALWAYS respond with a component following [Component Generation](#component-generation).
21
+
22
+ Look at 'patchwork.services' to see what services are available for widgets to call. If services are listed, you can generate widgets that make service calls using global namespace objects.
23
+
24
+ **IMPORTANT: If you need to discover available services or get details about a specific service, use the \`search_services\` tool.**
25
+
26
+ ## Component Generation
27
+
28
+ Respond with code blocks using tagged attributes on the fence line. The \`note\` attribute (optional but encouraged) provides a brief description visible in the UI. The \`path\` attribute specifies the virtual file path.
29
+
30
+ ### Code Block Format
31
+
32
+ \`\`\`tsx note="Main component" path="components/weather/main.tsx"
33
+ export default function WeatherWidget() {
34
+ // component code
35
+ }
36
+ \`\`\`
37
+
38
+ ### Attribute Order
39
+ Put \`note\` first so it's available soonest in streaming UI.
40
+
41
+ ### Multi-File Generation
42
+
43
+ When generating complex widgets, you can output multiple files. Use the \`@/\` prefix for virtual file system paths. ALWAYS prefer to generate visible components before metadata.
44
+
45
+ **Example multi-file widget:**
46
+
47
+ \`\`\`json note="Widget configuration" path="components/dashboard/package.json"
48
+ {
49
+ "description": "Interactive dashboard widget",
50
+ "patchwork": {
51
+ "inputs": {
52
+ "type": "object",
53
+ "properties": {
54
+ "title": { "type": "string" }
55
+ }
56
+ },
57
+ "services": {
58
+ "analytics": ["getMetrics", "getChartData"]
59
+ }
60
+ }
61
+ }
62
+ \`\`\`
63
+
64
+ \`\`\`tsx note="Main widget component" path="components/dashboard/main.tsx"
65
+ import { Card } from './Card';
66
+ import { Chart } from './Chart';
67
+
68
+ export default function Dashboard({ title = "Dashboard" }) {
69
+ return (
70
+ <div>
71
+ <h1>{title}</h1>
72
+ <Card />
73
+ <Chart />
74
+ </div>
75
+ );
76
+ }
77
+ \`\`\`
78
+
79
+ \`\`\`tsx note="Card subcomponent" path="components/dashboard/Card.tsx"
80
+ export function Card() {
81
+ return <div className="p-4 rounded border">Card content</div>;
82
+ }
83
+ \`\`\`
84
+
85
+ ### Requirements
86
+ - DO think heavily about correctness of code and syntax
87
+ - DO keep things simple and self-contained
88
+ - ALWAYS include the \`path\` attribute specifying the file location. Be generic with the name and describe the general component's use
89
+ - ALWAYS output the COMPLETE code block with opening \`\`\`tsx and closing \`\`\` markers
90
+ - Use \`note\` attribute to describe what each code block does (optional but encouraged)
91
+ - NEVER truncate or cut off code - finish the entire component before stopping
92
+ - If the component is complex, simplify it rather than leaving it incomplete
93
+ - Do NOT include: a heading/title
94
+
95
+ ### Visual Design Guidelines
96
+ Create professional, polished interfaces that present information **spatially** rather than as vertical lists:
97
+ - Use **cards, grids, and flexbox layouts** to organize related data into visual groups
98
+ - Leverage **icons** (from lucide-react) alongside text to communicate meaning at a glance
99
+ - Apply **visual hierarchy** through typography scale, weight, and color contrast
100
+ - Use **whitespace strategically** to create breathing room and separation
101
+ - Prefer **horizontal arrangements** where data fits naturally (e.g., stats in a row, badges inline)
102
+ - Group related metrics into **compact visual clusters** rather than separate line items
103
+ - Use **subtle backgrounds, borders, and shadows** to define sections without heavy dividers
104
+
105
+ ### Root Element Constraints
106
+ The component will be rendered inside a parent container that handles positioning. Your root element should:
107
+ - \u2705 Use intrinsic sizing (let content determine dimensions)
108
+ - \u2705 Handle internal padding (e.g., \`p-4\`, \`p-6\`)
109
+ - \u274C NEVER add centering utilities (\`items-center\`, \`justify-center\`) to position itself
110
+ - \u274C NEVER add viewport-relative sizing (\`min-h-screen\`, \`h-screen\`, \`w-screen\`)
111
+ - \u274C NEVER add flex/grid on root just for self-centering
112
+
113
+ ### Using Services in Widgets (CRITICAL)
114
+
115
+ **MANDATORY workflow - you must follow these steps IN ORDER:**
116
+
117
+ 1. **Use \`search_services\`** to discover the service schema
118
+ 2. **STOP. Make an actual call to the service tool itself** (e.g., \`weather_get_forecast\`, \`github_get_repo\`) with real arguments. This is NOT optional. Do NOT skip this step.
119
+ 3. **Observe the response** - verify it succeeded and note the exact data structure
120
+ 4. **Only then generate the widget** that fetches the same data at runtime
121
+
122
+ **\`search_services\` is NOT a substitute for calling the actual service.** It only returns documentation. You MUST invoke the real service tool to validate your arguments work.
123
+
124
+ **Tool naming:** Service tools use underscores, not dots. For example: \`weather_get_forecast\`, \`github_list_repos\`.
125
+
126
+ **Example workflow for a weather widget:**
127
+ \`\`\`
128
+ Step 1: search_services({ query: "weather" })
129
+ \u2192 Learn that weather_get_current_conditions exists with params: { latitude, longitude }
130
+
131
+ Step 2: weather_get_current_conditions({ latitude: 29.7604, longitude: -95.3698 }) \u2190 REQUIRED!
132
+ \u2192 Verify it returns { temp: 72, humidity: 65, ... }
133
+
134
+ Step 3: Generate widget that calls weather.get_current_conditions at runtime
135
+ \`\`\`
136
+
137
+ **If you skip Step 2, you will generate broken widgets.** Arguments that look correct in the schema may fail at runtime due to validation rules, required formats, or service-specific constraints.
138
+
139
+ **NEVER embed static data directly in the component.**
140
+
141
+ \u274C **WRONG** - Embedding data directly:
142
+ \`\`\`tsx path="components/weather/bad-example.tsx"
143
+ // DON'T DO THIS - calling tool, then embedding the response as static data
144
+ export default function WeatherWidget() {
145
+ // Static data embedded at generation time - BAD!
146
+ const weather = { temp: 72, condition: "sunny", humidity: 45 };
147
+ return <div>Temperature: {weather.temp}\xB0F</div>;
148
+ }
149
+ \`\`\`
150
+
151
+ \u2705 **CORRECT** - Fetching data at runtime:
152
+ \`\`\`tsx note="Weather widget with runtime data" path="components/weather/main.tsx"
153
+ export default function WeatherWidget() {
154
+ const [data, setData] = useState(null);
155
+ const [loading, setLoading] = useState(true);
156
+ const [error, setError] = useState(null);
157
+
158
+ useEffect(() => {
159
+ // Fetch data at runtime - GOOD!
160
+ weather.get_forecast({ latitude: 48.8566, longitude: 2.3522 })
161
+ .then(setData)
162
+ .catch(setError)
163
+ .finally(() => setLoading(false));
164
+ }, []);
165
+
166
+ if (loading) return <Skeleton className="h-32 w-full" />;
167
+ if (error) return <Alert variant="destructive">{error.message}</Alert>;
168
+
169
+ return <div>Temperature: {data.temp}\xB0F</div>;
170
+ }
171
+ \`\`\`
172
+
173
+ **Why this matters:**
174
+ - Widgets with runtime service calls show **live data** that updates when refreshed
175
+ - Static embedded data becomes **stale immediately** after generation
176
+ - The proxy pattern allows widgets to be **reusable** across different contexts
177
+ - Error handling and loading states improve **user experience**
178
+
179
+ **Service call pattern:**
180
+ \`\`\`tsx
181
+ // Services are available as global namespace objects
182
+ // Call format: namespace.procedure_name({ ...args })
183
+
184
+ const [data, setData] = useState(null);
185
+ const [loading, setLoading] = useState(true);
186
+ const [error, setError] = useState(null);
187
+
188
+ useEffect(() => {
189
+ serviceName.procedure_name({ param1: value1 })
190
+ .then(setData)
191
+ .catch(setError)
192
+ .finally(() => setLoading(false));
193
+ }, [/* dependencies */]);
194
+ \`\`\`
195
+
196
+ **Required for service-using widgets:**
197
+ - Always show loading indicators (Skeleton, Loader2 spinner, etc.)
198
+ - Always handle errors gracefully with user-friendly messages
199
+ - Use appropriate React hooks (useState, useEffect) for async data
200
+ - Services are injected as globals - NO imports needed
201
+
202
+ ### Validating Service Calls (CRITICAL - READ CAREFULLY)
203
+
204
+ **Calling \`search_services\` multiple times is NOT validation.** You must call the actual service tool.
205
+
206
+ \u274C **WRONG workflow (will produce broken widgets):**
207
+ \`\`\`
208
+ 1. search_services({ query: "weather" }) \u2190 Only gets schema
209
+ 2. search_services({ query: "location" }) \u2190 Still only schema
210
+ 3. Generate widget \u2190 BROKEN - never tested the actual service!
211
+ \`\`\`
212
+
213
+ \u2705 **CORRECT workflow:**
214
+ \`\`\`
215
+ 1. search_services({ query: "weather" }) \u2190 Get schema
216
+ 2. weather_get_forecast({ latitude: 29.76, longitude: -95.37 }) \u2190 ACTUALLY CALL IT
217
+ 3. Observe response: { temp: 72, conditions: "sunny", ... }
218
+ 4. Generate widget that calls weather.get_forecast at runtime
219
+ \`\`\`
220
+
221
+ **The service tool (e.g., \`weather_get_forecast\`, \`github_list_repos\`) is a DIFFERENT tool from \`search_services\`.** You have access to both. Use both.
222
+
223
+ **Only after a successful test call to the actual service should you generate the widget.**
224
+
225
+ ### Component Parameterization (IMPORTANT)
226
+
227
+ **Widgets should accept props for dynamic values instead of hardcoding:**
228
+
229
+ \u274C **WRONG** - Hardcoded values:
230
+ \`\`\`tsx path="components/weather/bad-example.tsx"
231
+ export default function WeatherWidget() {
232
+ // Location hardcoded - BAD!
233
+ const [lat, lon] = [48.8566, 2.3522]; // Paris
234
+ // ...
235
+ }
236
+ \`\`\`
237
+
238
+ \u2705 **CORRECT** - Parameterized with props and defaults:
239
+ \`\`\`tsx note="Parameterized weather widget" path="components/weather/main.tsx"
240
+ interface WeatherWidgetProps {
241
+ location?: string; // e.g., "Paris, France"
242
+ latitude?: number; // Direct coordinates (optional)
243
+ longitude?: number;
244
+ }
245
+
246
+ export default function WeatherWidget({
247
+ location = "Paris, France",
248
+ latitude,
249
+ longitude
250
+ }: WeatherWidgetProps) {
251
+ // Use provided coordinates or look up from location name
252
+ // ...
253
+ }
254
+ \`\`\`
255
+
256
+ **Why parameterize:**
257
+ - Components become **reusable** across different contexts
258
+ - Users can **customize behavior** without editing code
259
+ - Enables **composition** - parent components can pass different values
260
+ - Supports **testing** with various inputs
261
+
262
+ **What to parameterize:**
263
+ - Location names, coordinates, IDs
264
+ - Search queries and filters
265
+ - Display options (count, format, theme)
266
+ - API-specific identifiers (usernames, repo names, etc.)
267
+
268
+ ### Anti-patterns to Avoid
269
+ - \u274C Bulleted or numbered lists of key-value pairs
270
+ - \u274C Vertical stacks where horizontal layouts would fit
271
+ - \u274C Plain text labels without visual treatment
272
+ - \u274C Uniform styling that doesn't distinguish primary from secondary information
273
+ - \u274C Wrapping components in centering containers (parent handles this)
274
+ - \u274C **Embedding API response data directly in components instead of fetching at runtime**
275
+ - \u274C **Calling a tool, then putting the response as static JSX/JSON in the generated code**
276
+ - \u274C **Hardcoding values that should be component props**
277
+ - \u274C **Calling \`search_services\` multiple times instead of calling the actual service tool**
278
+ - \u274C **Generating a widget without first making a real call to the service with your intended arguments**
279
+ - \u274C **Treating schema documentation as proof that a service call will work**
280
+ - \u274C **Omitting the \`path\` attribute on code blocks**
281
+ `;
282
+ var EDIT_PROMPT = `
283
+ You are editing an existing JSX component. The user will provide the current code and describe the changes they want.
284
+
285
+ ## Response Format
286
+
287
+ Use code fences with tagged attributes. The \`note\` attribute (optional but encouraged) provides a brief description visible in the UI. The \`path\` attribute specifies the target file.
288
+
289
+ \`\`\`diff note="Brief description of this change" path="@/components/Button.tsx"
290
+ <<<<<<< SEARCH
291
+ exact code to find
292
+ =======
293
+ replacement code
294
+ >>>>>>> REPLACE
295
+ \`\`\`
296
+
297
+ ### Attribute Order
298
+ Put \`note\` first so it's available soonest in streaming UI.
299
+
300
+ ### Multi-File Edits
301
+ When editing multiple files, use the \`path\` attribute with virtual paths (\`@/\` prefix for generated files):
302
+
303
+ \`\`\`diff note="Update button handler" path="@/components/Button.tsx"
304
+ <<<<<<< SEARCH
305
+ onClick={() => {}}
306
+ =======
307
+ onClick={() => handleClick()}
308
+ >>>>>>> REPLACE
309
+ \`\`\`
310
+
311
+ \`\`\`diff note="Add utility function" path="@/lib/utils.ts"
312
+ <<<<<<< SEARCH
313
+ export const formatDate = ...
314
+ =======
315
+ export const formatDate = ...
316
+
317
+ export const handleClick = () => console.log('clicked');
318
+ >>>>>>> REPLACE
319
+ \`\`\`
320
+
321
+ ## Rules
322
+ - SEARCH block must match the existing code EXACTLY (whitespace, indentation, everything)
323
+ - You can include multiple diff blocks for multiple changes
324
+ - Each diff block should have its own \`note\` attribute annotation
325
+ - Keep changes minimal and targeted
326
+ - Do NOT output the full file - only the diffs
327
+ - If clarification is needed, ask briefly before any diffs
328
+
329
+ ## CRITICAL: Diff Marker Safety
330
+ - NEVER include the strings "<<<<<<< SEARCH", "=======", or ">>>>>>> REPLACE" inside your replacement code
331
+ - These are reserved markers for parsing the diff format
332
+ - If you need to show diff-like content, use alternative notation (e.g., "// old code" / "// new code")
333
+ - Malformed diff markers will cause the edit to fail
334
+
335
+ ## Summary
336
+ After all diffs, provide a brief markdown summary of the changes made. Use formatting like:
337
+ - **Bold** for emphasis on key changes
338
+ - Bullet points for listing multiple changes
339
+ - Keep it concise (2-4 lines max)
340
+ - Do NOT include: a heading/title
341
+ `;
342
+
343
+ // src/server/routes.ts
344
+ function parseBody(req) {
345
+ return new Promise((resolve2, reject) => {
346
+ let body = "";
347
+ req.on("data", (chunk) => body += chunk);
348
+ req.on("end", () => {
349
+ try {
350
+ resolve2(JSON.parse(body));
351
+ } catch (err) {
352
+ reject(err);
353
+ }
354
+ });
355
+ req.on("error", reject);
356
+ });
357
+ }
358
+ async function handleChat(req, res, ctx) {
359
+ const {
360
+ messages,
361
+ metadata
362
+ } = await parseBody(req);
363
+ const normalizedMessages = messages.map((msg) => ({
364
+ ...msg,
365
+ parts: msg.parts ?? [{ type: "text", text: "" }]
366
+ }));
367
+ const provider = createOpenAICompatible({
368
+ name: "copilot-proxy",
369
+ baseURL: ctx.copilotProxyUrl
370
+ });
371
+ const result = streamText({
372
+ model: provider("claude-sonnet-4"),
373
+ system: `---
374
+ patchwork:
375
+ compilers: ${(metadata?.patchwork?.compilers ?? []).join(",") ?? "[]"}
376
+ services: ${ctx.registry.getNamespaces().join(",")}
377
+ ---
378
+
379
+ ${PATCHWORK_PROMPT}
380
+
381
+ ${ctx.servicesPrompt}`,
382
+ messages: await convertToModelMessages(normalizedMessages),
383
+ stopWhen: stepCountIs(5),
384
+ tools: ctx.tools
385
+ });
386
+ const response = result.toUIMessageStreamResponse();
387
+ response.headers.forEach(
388
+ (value, key) => res.setHeader(key, value)
389
+ );
390
+ if (!response.body) {
391
+ res.end();
392
+ return;
393
+ }
394
+ const reader = response.body.getReader();
395
+ const pump = async () => {
396
+ const { done, value } = await reader.read();
397
+ if (done) {
398
+ res.end();
399
+ return;
400
+ }
401
+ res.write(value);
402
+ await pump();
403
+ };
404
+ await pump();
405
+ }
406
+ async function handleEdit(req, res, ctx) {
407
+ const { code, prompt } = await parseBody(
408
+ req
409
+ );
410
+ const provider = createOpenAICompatible({
411
+ name: "copilot-proxy",
412
+ baseURL: ctx.copilotProxyUrl
413
+ });
414
+ const result = streamText({
415
+ model: provider("claude-opus-4.5"),
416
+ system: `Current component code:
417
+ \`\`\`tsx
418
+ ${code}
419
+ \`\`\`
420
+
421
+ ${EDIT_PROMPT}`,
422
+ messages: [{ role: "user", content: prompt }]
423
+ });
424
+ res.setHeader("Content-Type", "text/plain");
425
+ res.setHeader("Transfer-Encoding", "chunked");
426
+ res.writeHead(200);
427
+ for await (const chunk of result.textStream) {
428
+ res.write(chunk);
429
+ }
430
+ res.end();
431
+ }
432
+
433
+ // src/server/local-packages.ts
434
+ import fs from "fs";
435
+ import path from "path";
436
+ function handleLocalPackages(req, res, ctx) {
437
+ const rawUrl = req.url || "";
438
+ if (!rawUrl.startsWith("/_local-packages")) {
439
+ return false;
440
+ }
441
+ const urlWithoutPrefix = rawUrl.replace("/_local-packages", "");
442
+ const url = urlWithoutPrefix.split("?")[0] || "";
443
+ const match = url.match(/^\/@([^/]+)\/([^/@]+)(.*)$/);
444
+ if (!match) {
445
+ return false;
446
+ }
447
+ const [, scope, name, restPath] = match;
448
+ const packageName = `@${scope}/${name}`;
449
+ const localPath = ctx.localPackages[packageName];
450
+ if (!localPath) {
451
+ res.writeHead(404);
452
+ res.end(`Package ${packageName} not found in local overrides`);
453
+ return true;
454
+ }
455
+ const rest = restPath || "";
456
+ let filePath;
457
+ try {
458
+ if (rest === "/package.json") {
459
+ filePath = path.join(localPath, "package.json");
460
+ } else if (rest === "" || rest === "/") {
461
+ const pkgJson = JSON.parse(
462
+ fs.readFileSync(path.join(localPath, "package.json"), "utf-8")
463
+ );
464
+ const mainEntry = pkgJson.main || "dist/index.js";
465
+ filePath = path.join(localPath, mainEntry);
466
+ } else {
467
+ const normalizedPath = rest.startsWith("/") ? rest.slice(1) : rest;
468
+ const distPath = path.join(localPath, "dist", normalizedPath);
469
+ const rootPath = path.join(localPath, normalizedPath);
470
+ filePath = fs.existsSync(distPath) ? distPath : rootPath;
471
+ }
472
+ } catch (err) {
473
+ ctx.log("Error resolving file path:", err);
474
+ res.writeHead(500);
475
+ res.end(`Error resolving path for ${packageName}: ${err}`);
476
+ return true;
477
+ }
478
+ try {
479
+ ctx.log(`Serving ${filePath}`);
480
+ const content = fs.readFileSync(filePath, "utf-8");
481
+ const ext = path.extname(filePath);
482
+ const contentType = ext === ".json" ? "application/json" : ext === ".js" ? "application/javascript" : ext === ".ts" ? "application/typescript" : "text/plain";
483
+ res.setHeader("Content-Type", contentType);
484
+ res.writeHead(200);
485
+ res.end(content);
486
+ } catch (err) {
487
+ ctx.log("Error serving file:", filePath, err);
488
+ res.writeHead(404);
489
+ res.end(`File not found: ${filePath}`);
490
+ }
491
+ return true;
492
+ }
493
+
494
+ // src/server/vfs-routes.ts
495
+ import {
496
+ readFile,
497
+ writeFile,
498
+ unlink,
499
+ readdir,
500
+ stat,
501
+ mkdir,
502
+ rm
503
+ } from "fs/promises";
504
+ import { watch } from "fs";
505
+ import { dirname, resolve, sep } from "path";
506
+ function normalizeRelPath(path2) {
507
+ const decoded = decodeURIComponent(path2).replace(/\\/g, "/");
508
+ return decoded.replace(/^\/+|\/+$/g, "");
509
+ }
510
+ function resolvePath(rootDir, relPath) {
511
+ const root = resolve(rootDir);
512
+ const full = resolve(root, relPath);
513
+ if (full !== root && !full.startsWith(`${root}${sep}`)) {
514
+ throw new Error("Invalid path");
515
+ }
516
+ return full;
517
+ }
518
+ function joinRelPath(base, name) {
519
+ return base ? `${base}/${name}` : name;
520
+ }
521
+ async function listAllFiles(rootDir, relPath) {
522
+ const targetPath = resolvePath(rootDir, relPath);
523
+ let entries = [];
524
+ try {
525
+ entries = await readdir(targetPath, { withFileTypes: true });
526
+ } catch {
527
+ return [];
528
+ }
529
+ const results = [];
530
+ for (const entry of entries) {
531
+ const entryRelPath = joinRelPath(relPath, entry.name);
532
+ if (entry.isDirectory()) {
533
+ results.push(...await listAllFiles(rootDir, entryRelPath));
534
+ } else {
535
+ results.push(entryRelPath);
536
+ }
537
+ }
538
+ return results.sort((a, b) => a.localeCompare(b));
539
+ }
540
+ async function ensureDir(filePath) {
541
+ await mkdir(dirname(filePath), { recursive: true });
542
+ }
543
+ function sendJson(res, status, body) {
544
+ res.setHeader("Content-Type", "application/json");
545
+ res.writeHead(status);
546
+ res.end(JSON.stringify(body));
547
+ }
548
+ function handleVFS(req, res, ctx) {
549
+ const url = req.url || "/";
550
+ const method = req.method || "GET";
551
+ if (!url.startsWith("/vfs")) return false;
552
+ if (url === "/vfs/config" && method === "GET") {
553
+ res.setHeader("Content-Type", "application/json");
554
+ res.writeHead(200);
555
+ res.end(JSON.stringify({ usePaths: ctx.usePaths }));
556
+ return true;
557
+ }
558
+ const handleRequest = async () => {
559
+ const urlObj = new URL(url, "http://localhost");
560
+ const query = urlObj.searchParams;
561
+ const rawPath = urlObj.pathname.slice(4);
562
+ const relPath = normalizeRelPath(rawPath);
563
+ if (query.has("watch")) {
564
+ if (method !== "GET") {
565
+ res.writeHead(405);
566
+ res.end("Method not allowed");
567
+ return;
568
+ }
569
+ const watchPath = normalizeRelPath(query.get("watch") || "");
570
+ const fullWatchPath = resolvePath(ctx.rootDir, watchPath);
571
+ let watchStats;
572
+ try {
573
+ watchStats = await stat(fullWatchPath);
574
+ } catch {
575
+ res.writeHead(404);
576
+ res.end("Not found");
577
+ return;
578
+ }
579
+ res.setHeader("Content-Type", "text/event-stream");
580
+ res.setHeader("Cache-Control", "no-cache");
581
+ res.setHeader("Connection", "keep-alive");
582
+ res.writeHead(200);
583
+ const watcher = watch(
584
+ fullWatchPath,
585
+ { recursive: watchStats.isDirectory() },
586
+ async (eventType, filename) => {
587
+ const eventPath = normalizeRelPath(
588
+ [watchPath, filename ? filename.toString() : ""].filter(Boolean).join("/")
589
+ );
590
+ const fullEventPath = resolvePath(ctx.rootDir, eventPath);
591
+ let type = "update";
592
+ if (eventType === "rename") {
593
+ try {
594
+ await stat(fullEventPath);
595
+ type = "create";
596
+ } catch {
597
+ type = "delete";
598
+ }
599
+ }
600
+ res.write("event: change\n");
601
+ res.write(
602
+ `data: ${JSON.stringify({
603
+ type,
604
+ path: eventPath,
605
+ mtime: (/* @__PURE__ */ new Date()).toISOString()
606
+ })}
607
+
608
+ `
609
+ );
610
+ }
611
+ );
612
+ req.on("close", () => watcher.close());
613
+ return;
614
+ }
615
+ if (method === "HEAD" && !relPath) {
616
+ res.writeHead(200);
617
+ res.end();
618
+ return;
619
+ }
620
+ if (method === "GET" && !relPath && !query.toString()) {
621
+ const files = await listAllFiles(ctx.rootDir, "");
622
+ sendJson(res, 200, files);
623
+ return;
624
+ }
625
+ if (!relPath && method !== "GET" && method !== "HEAD") {
626
+ res.writeHead(400);
627
+ res.end("Invalid path");
628
+ return;
629
+ }
630
+ const targetPath = resolvePath(ctx.rootDir, relPath);
631
+ if (method === "GET" && query.get("stat") === "true") {
632
+ try {
633
+ const stats = await stat(targetPath);
634
+ sendJson(res, 200, {
635
+ size: stats.size,
636
+ mtime: stats.mtime.toISOString(),
637
+ isFile: stats.isFile(),
638
+ isDirectory: stats.isDirectory()
639
+ });
640
+ } catch {
641
+ res.writeHead(404);
642
+ res.end("Not found");
643
+ }
644
+ return;
645
+ }
646
+ if (method === "GET" && query.get("readdir") === "true") {
647
+ try {
648
+ const entries = await readdir(targetPath, { withFileTypes: true });
649
+ const mapped = entries.map((entry) => ({
650
+ name: entry.name,
651
+ isDirectory: entry.isDirectory()
652
+ })).sort((a, b) => a.name.localeCompare(b.name));
653
+ sendJson(res, 200, mapped);
654
+ } catch (err) {
655
+ const code = err.code;
656
+ if (code === "ENOTDIR") {
657
+ res.writeHead(409);
658
+ res.end("Not a directory");
659
+ return;
660
+ }
661
+ res.writeHead(404);
662
+ res.end("Not found");
663
+ }
664
+ return;
665
+ }
666
+ if (method === "POST" && query.get("mkdir") === "true") {
667
+ const recursive = query.get("recursive") === "true";
668
+ try {
669
+ await mkdir(targetPath, { recursive });
670
+ res.writeHead(200);
671
+ res.end("ok");
672
+ } catch {
673
+ res.writeHead(500);
674
+ res.end("Mkdir failed");
675
+ }
676
+ return;
677
+ }
678
+ switch (method) {
679
+ case "GET": {
680
+ try {
681
+ const content = await readFile(targetPath, "utf-8");
682
+ res.setHeader("Content-Type", "text/plain");
683
+ res.writeHead(200);
684
+ res.end(content);
685
+ } catch {
686
+ res.writeHead(404);
687
+ res.end("Not found");
688
+ }
689
+ return;
690
+ }
691
+ case "PUT": {
692
+ let body = "";
693
+ req.on("data", (chunk) => body += chunk);
694
+ req.on("end", async () => {
695
+ try {
696
+ await ensureDir(targetPath);
697
+ await writeFile(targetPath, body, "utf-8");
698
+ res.writeHead(200);
699
+ res.end("ok");
700
+ } catch (err) {
701
+ ctx.log("VFS PUT error:", err);
702
+ res.writeHead(500);
703
+ res.end("Write failed");
704
+ }
705
+ });
706
+ return;
707
+ }
708
+ case "DELETE": {
709
+ const recursive = query.get("recursive") === "true";
710
+ let stats;
711
+ try {
712
+ stats = await stat(targetPath);
713
+ } catch {
714
+ res.writeHead(404);
715
+ res.end("Not found");
716
+ return;
717
+ }
718
+ if (stats.isDirectory()) {
719
+ if (!recursive) {
720
+ try {
721
+ const entries = await readdir(targetPath);
722
+ if (entries.length > 0) {
723
+ res.writeHead(409);
724
+ res.end("Directory not empty");
725
+ return;
726
+ }
727
+ await rm(targetPath, { recursive: false });
728
+ res.writeHead(200);
729
+ res.end("ok");
730
+ } catch {
731
+ res.writeHead(500);
732
+ res.end("Delete failed");
733
+ }
734
+ return;
735
+ }
736
+ try {
737
+ await rm(targetPath, { recursive: true });
738
+ res.writeHead(200);
739
+ res.end("ok");
740
+ } catch {
741
+ res.writeHead(500);
742
+ res.end("Delete failed");
743
+ }
744
+ return;
745
+ }
746
+ try {
747
+ await unlink(targetPath);
748
+ res.writeHead(200);
749
+ res.end("ok");
750
+ } catch {
751
+ res.writeHead(404);
752
+ res.end("Not found");
753
+ }
754
+ return;
755
+ }
756
+ case "HEAD": {
757
+ try {
758
+ await stat(targetPath);
759
+ res.writeHead(200);
760
+ res.end();
761
+ } catch {
762
+ res.writeHead(404);
763
+ res.end();
764
+ }
765
+ return;
766
+ }
767
+ default:
768
+ res.writeHead(405);
769
+ res.end("Method not allowed");
770
+ }
771
+ };
772
+ handleRequest().catch((err) => {
773
+ ctx.log("VFS error:", err);
774
+ res.writeHead(500);
775
+ res.end("Internal error");
776
+ });
777
+ return true;
778
+ }
779
+
780
+ // src/server/services.ts
781
+ import { jsonSchema } from "ai";
782
+ var ServiceRegistry = class {
783
+ tools = /* @__PURE__ */ new Map();
784
+ toolInfo = /* @__PURE__ */ new Map();
785
+ backends = [];
786
+ /**
787
+ * Register tools from MCP or other sources
788
+ * @param tools - Record of tool name to Tool
789
+ * @param namespace - Optional namespace to prefix all tools (e.g., MCP server name)
790
+ */
791
+ registerTools(tools, namespace) {
792
+ for (const [toolName, tool] of Object.entries(tools)) {
793
+ const name = namespace ? `${namespace}.${toolName}` : toolName;
794
+ this.tools.set(name, tool);
795
+ const dotIndex = name.indexOf(".");
796
+ const ns = dotIndex > 0 ? name.substring(0, dotIndex) : name;
797
+ const procedure = dotIndex > 0 ? name.substring(dotIndex + 1) : name;
798
+ this.toolInfo.set(name, {
799
+ name,
800
+ namespace: ns,
801
+ procedure,
802
+ description: tool.description,
803
+ parameters: tool.inputSchema ?? {},
804
+ typescriptInterface: this.generateTypeScriptInterface(name, tool)
805
+ });
806
+ }
807
+ }
808
+ /**
809
+ * Register a service backend (UTCP, HTTP, etc.)
810
+ * Creates callable Tool objects for each procedure so the LLM can invoke them directly.
811
+ * Backends are tried in order of registration, first success wins.
812
+ */
813
+ registerBackend(backend, toolInfos) {
814
+ this.backends.push(backend);
815
+ if (toolInfos) {
816
+ for (const info of toolInfos) {
817
+ this.toolInfo.set(info.name, info);
818
+ const tool = {
819
+ description: info.description,
820
+ inputSchema: jsonSchema(
821
+ info.parameters ?? { type: "object", properties: {} }
822
+ ),
823
+ execute: async (args) => {
824
+ return backend.call(info.namespace, info.procedure, [args]);
825
+ }
826
+ };
827
+ this.tools.set(info.name, tool);
828
+ }
829
+ }
830
+ }
831
+ /**
832
+ * Generate TypeScript interface from tool schema
833
+ */
834
+ generateTypeScriptInterface(name, tool) {
835
+ const schema = tool.inputSchema;
836
+ const props = schema?.properties ?? {};
837
+ const required = schema?.required ?? [];
838
+ const params = Object.entries(props).map(([key, val]) => {
839
+ const optional = !required.includes(key) ? "?" : "";
840
+ const type = val.type === "number" ? "number" : val.type === "boolean" ? "boolean" : val.type === "array" ? "unknown[]" : val.type === "object" ? "Record<string, unknown>" : "string";
841
+ const comment = val.description ? ` // ${val.description}` : "";
842
+ return ` ${key}${optional}: ${type};${comment}`;
843
+ }).join("\n");
844
+ return `interface ${name.replace(
845
+ /[^a-zA-Z0-9]/g,
846
+ "_"
847
+ )}Args {
848
+ ${params}
849
+ }`;
850
+ }
851
+ /**
852
+ * Convert internal tool name (namespace.procedure) to LLM-safe name (namespace_procedure)
853
+ * OpenAI-compatible APIs require tool names to match ^[a-zA-Z0-9_-]+$
854
+ */
855
+ toLLMToolName(internalName) {
856
+ return internalName.replace(/\./g, "_");
857
+ }
858
+ /**
859
+ * Convert LLM tool name (namespace_procedure) back to internal name (namespace.procedure)
860
+ * Only converts the first underscore after the namespace prefix
861
+ */
862
+ fromLLMToolName(llmName) {
863
+ for (const internalName of this.tools.keys()) {
864
+ if (this.toLLMToolName(internalName) === llmName) {
865
+ return internalName;
866
+ }
867
+ }
868
+ const underscoreIndex = llmName.indexOf("_");
869
+ if (underscoreIndex > 0) {
870
+ return llmName.substring(0, underscoreIndex) + "." + llmName.substring(underscoreIndex + 1);
871
+ }
872
+ return llmName;
873
+ }
874
+ /**
875
+ * Get all tools for LLM usage with LLM-safe names (underscores instead of dots)
876
+ */
877
+ getTools() {
878
+ const result = {};
879
+ for (const [name, tool] of this.tools) {
880
+ result[this.toLLMToolName(name)] = tool;
881
+ }
882
+ return result;
883
+ }
884
+ /**
885
+ * Get service metadata for prompt generation
886
+ */
887
+ getServiceInfo() {
888
+ return Array.from(this.toolInfo.values());
889
+ }
890
+ /**
891
+ * Get unique namespaces
892
+ */
893
+ getNamespaces() {
894
+ const namespaces = /* @__PURE__ */ new Set();
895
+ for (const info of this.toolInfo.values()) {
896
+ namespaces.add(info.namespace);
897
+ }
898
+ return Array.from(namespaces);
899
+ }
900
+ /**
901
+ * Search for services by query, namespace, or list all
902
+ */
903
+ searchServices(options = {}) {
904
+ const { query, namespace, limit = 20, includeInterfaces = false } = options;
905
+ let results = Array.from(this.toolInfo.values());
906
+ if (namespace) {
907
+ results = results.filter((info) => info.namespace === namespace);
908
+ }
909
+ if (query) {
910
+ const queryLower = query.toLowerCase();
911
+ const keywords = queryLower.split(/\s+/).filter(Boolean);
912
+ results = results.map((info) => {
913
+ const searchText = `${info.name} ${info.namespace} ${info.procedure} ${info.description ?? ""}`.toLowerCase();
914
+ const matchCount = keywords.filter(
915
+ (kw) => searchText.includes(kw)
916
+ ).length;
917
+ return { info, score: matchCount / keywords.length };
918
+ }).filter(({ score }) => score > 0).sort((a, b) => b.score - a.score).map(({ info }) => info);
919
+ }
920
+ results = results.slice(0, limit);
921
+ if (!includeInterfaces) {
922
+ results = results.map(({ typescriptInterface: _, ...rest }) => rest);
923
+ }
924
+ return results;
925
+ }
926
+ /**
927
+ * Get detailed info about a specific tool
928
+ */
929
+ getToolInfo(toolName) {
930
+ return this.toolInfo.get(toolName);
931
+ }
932
+ /**
933
+ * List all tool names
934
+ */
935
+ listToolNames() {
936
+ return Array.from(this.toolInfo.keys());
937
+ }
938
+ /**
939
+ * Call a service procedure
940
+ */
941
+ async call(namespace, procedure, args) {
942
+ for (const backend of this.backends) {
943
+ try {
944
+ return await backend.call(namespace, procedure, [args]);
945
+ } catch {
946
+ }
947
+ }
948
+ const exactKey = `${namespace}.${procedure}`;
949
+ let tool = this.tools.get(exactKey);
950
+ if (!tool) {
951
+ for (const [name, t] of this.tools) {
952
+ if (name.startsWith(`${namespace}.`) && name.endsWith(procedure)) {
953
+ tool = t;
954
+ break;
955
+ }
956
+ }
957
+ }
958
+ if (!tool) {
959
+ throw new Error(
960
+ `Service not found: ${namespace}.${procedure}. Available: ${Array.from(
961
+ this.tools.keys()
962
+ ).slice(0, 10).join(", ")}`
963
+ );
964
+ }
965
+ if (!tool.execute) {
966
+ throw new Error(`Tool ${namespace}.${procedure} has no execute function`);
967
+ }
968
+ const result = await tool.execute(args, {
969
+ toolCallId: `${Date.now()}-${Math.random().toString(36).slice(2)}`,
970
+ messages: []
971
+ });
972
+ return result;
973
+ }
974
+ /**
975
+ * Check if a service exists
976
+ */
977
+ has(namespace, procedure) {
978
+ const key = `${namespace}.${procedure}`;
979
+ return this.tools.has(key);
980
+ }
981
+ /**
982
+ * Get count of registered tools
983
+ */
984
+ get size() {
985
+ return this.toolInfo.size;
986
+ }
987
+ };
988
+ function generateServicesPrompt(registry) {
989
+ const namespaces = registry.getNamespaces();
990
+ if (namespaces.length === 0) return "";
991
+ const services = registry.getServiceInfo();
992
+ const byNamespace = /* @__PURE__ */ new Map();
993
+ for (const service of services) {
994
+ const existing = byNamespace.get(service.namespace) || [];
995
+ existing.push(service);
996
+ byNamespace.set(service.namespace, existing);
997
+ }
998
+ let prompt = `## Available Services
999
+
1000
+ The following services are available for generated widgets to call:
1001
+
1002
+ `;
1003
+ for (const [ns, tools] of byNamespace) {
1004
+ prompt += `### \`${ns}\`
1005
+ `;
1006
+ for (const tool of tools) {
1007
+ prompt += `- \`${ns}.${tool.procedure}()\``;
1008
+ if (tool.description) {
1009
+ prompt += `: ${tool.description}`;
1010
+ }
1011
+ prompt += "\n";
1012
+ }
1013
+ prompt += "\n";
1014
+ }
1015
+ prompt += `**Usage in widgets:**
1016
+ \`\`\`tsx
1017
+ // Services are available as global namespaces
1018
+ const result = await ${namespaces[0] ?? "service"}.${byNamespace.get(namespaces[0] ?? "")?.[0]?.procedure ?? "example"}({ /* args */ });
1019
+ \`\`\`
1020
+
1021
+ Make sure to handle loading states and errors when calling services.
1022
+ `;
1023
+ return prompt;
1024
+ }
1025
+
1026
+ // src/server/index.ts
1027
+ async function initMcpTools(configs, registry) {
1028
+ for (const config of configs) {
1029
+ const client = await createMCPClient({
1030
+ transport: new Experimental_StdioMCPTransport({
1031
+ command: config.command,
1032
+ args: config.args
1033
+ })
1034
+ });
1035
+ registry.registerTools(await client.tools(), config.name);
1036
+ }
1037
+ }
1038
+ var searchServicesSchema = {
1039
+ type: "object",
1040
+ properties: {
1041
+ query: {
1042
+ type: "string",
1043
+ description: 'Natural language description of what you want to do (e.g., "get weather forecast", "list github repos")'
1044
+ },
1045
+ namespace: {
1046
+ type: "string",
1047
+ description: 'Filter results to a specific service namespace (e.g., "weather", "github")'
1048
+ },
1049
+ tool_name: {
1050
+ type: "string",
1051
+ description: "Get detailed info about a specific tool by name"
1052
+ },
1053
+ limit: {
1054
+ type: "number",
1055
+ description: "Maximum number of results to return",
1056
+ default: 10
1057
+ },
1058
+ include_interfaces: {
1059
+ type: "boolean",
1060
+ description: "Include TypeScript interface definitions in results",
1061
+ default: true
1062
+ }
1063
+ }
1064
+ };
1065
+ function createSearchServicesTool(registry) {
1066
+ return {
1067
+ description: `Search for available services/tools. Use this to discover what APIs are available for widgets to call.
1068
+
1069
+ Returns matching services with their TypeScript interfaces. Use when:
1070
+ - You need to find a service to accomplish a task
1071
+ - You want to explore available APIs in a namespace
1072
+ - You need the exact interface/parameters for a service call`,
1073
+ inputSchema: jsonSchema2(searchServicesSchema),
1074
+ execute: async (args) => {
1075
+ if (args.tool_name) {
1076
+ const info = registry.getToolInfo(args.tool_name);
1077
+ if (!info) {
1078
+ return {
1079
+ success: false,
1080
+ error: `Tool '${args.tool_name}' not found`
1081
+ };
1082
+ }
1083
+ return { success: true, tool: info };
1084
+ }
1085
+ const results = registry.searchServices({
1086
+ query: args.query,
1087
+ namespace: args.namespace,
1088
+ limit: args.limit ?? 10,
1089
+ includeInterfaces: args.include_interfaces ?? true
1090
+ });
1091
+ return {
1092
+ success: true,
1093
+ count: results.length,
1094
+ tools: results,
1095
+ namespaces: registry.getNamespaces()
1096
+ };
1097
+ }
1098
+ };
1099
+ }
1100
+ function parseBody2(req) {
1101
+ return new Promise((resolve2, reject) => {
1102
+ let body = "";
1103
+ req.on("data", (chunk) => body += chunk);
1104
+ req.on("end", () => {
1105
+ try {
1106
+ resolve2(JSON.parse(body));
1107
+ } catch (err) {
1108
+ reject(err);
1109
+ }
1110
+ });
1111
+ req.on("error", reject);
1112
+ });
1113
+ }
1114
+ async function createStitcheryServer(config = {}) {
1115
+ const {
1116
+ port = 6434,
1117
+ host = "127.0.0.1",
1118
+ copilotProxyUrl = "http://127.0.0.1:6433/v1",
1119
+ localPackages = {},
1120
+ mcpServers = [],
1121
+ utcp,
1122
+ vfsDir,
1123
+ vfsUsePaths = false,
1124
+ verbose = false
1125
+ } = config;
1126
+ const log = verbose ? (...args) => console.log("[stitchery]", ...args) : () => {
1127
+ };
1128
+ const registry = new ServiceRegistry();
1129
+ log("Initializing MCP tools...");
1130
+ await initMcpTools(mcpServers, registry);
1131
+ log(`Loaded ${registry.size} tools from ${mcpServers.length} MCP servers`);
1132
+ if (utcp) {
1133
+ log("Initializing UTCP backend...");
1134
+ log("UTCP config:", JSON.stringify(utcp, null, 2));
1135
+ try {
1136
+ const { backend, toolInfos } = await createUtcpBackend(
1137
+ utcp,
1138
+ utcp.cwd
1139
+ );
1140
+ registry.registerBackend(backend, toolInfos);
1141
+ log(
1142
+ `Registered UTCP backend with ${toolInfos.length} tools:`,
1143
+ toolInfos.map((tool) => tool.name).join(", ")
1144
+ );
1145
+ } catch (err) {
1146
+ console.error("[stitchery] Failed to initialize UTCP backend:", err);
1147
+ }
1148
+ }
1149
+ log("Local packages:", localPackages);
1150
+ const internalTools = {
1151
+ search_services: createSearchServicesTool(registry)
1152
+ };
1153
+ const allTools = { ...registry.getTools(), ...internalTools };
1154
+ const routeCtx = {
1155
+ copilotProxyUrl,
1156
+ tools: allTools,
1157
+ registry,
1158
+ servicesPrompt: generateServicesPrompt(registry),
1159
+ log
1160
+ };
1161
+ const localPkgCtx = { localPackages, log };
1162
+ const vfsCtx = vfsDir ? { rootDir: vfsDir, usePaths: vfsUsePaths, log } : null;
1163
+ const server = createServer(async (req, res) => {
1164
+ res.setHeader("Access-Control-Allow-Origin", "*");
1165
+ res.setHeader(
1166
+ "Access-Control-Allow-Methods",
1167
+ "GET, POST, PUT, DELETE, HEAD, OPTIONS"
1168
+ );
1169
+ res.setHeader(
1170
+ "Access-Control-Allow-Headers",
1171
+ "Content-Type, Authorization"
1172
+ );
1173
+ if (req.method === "OPTIONS") {
1174
+ res.writeHead(204);
1175
+ res.end();
1176
+ return;
1177
+ }
1178
+ const url = req.url || "/";
1179
+ log(`${req.method} ${url}`);
1180
+ try {
1181
+ if (handleLocalPackages(req, res, localPkgCtx)) {
1182
+ return;
1183
+ }
1184
+ if (vfsCtx && handleVFS(req, res, vfsCtx)) {
1185
+ return;
1186
+ }
1187
+ if (url === "/api/chat" && req.method === "POST") {
1188
+ await handleChat(req, res, routeCtx);
1189
+ return;
1190
+ }
1191
+ if (url === "/api/edit" && req.method === "POST") {
1192
+ await handleEdit(req, res, routeCtx);
1193
+ return;
1194
+ }
1195
+ const proxyMatch = url.match(/^\/api\/proxy\/([^/]+)\/(.+)$/);
1196
+ if (proxyMatch && req.method === "POST") {
1197
+ const [, namespace, procedure] = proxyMatch;
1198
+ try {
1199
+ const body = await parseBody2(req);
1200
+ const result = await registry.call(
1201
+ namespace,
1202
+ procedure,
1203
+ body.args ?? {}
1204
+ );
1205
+ res.setHeader("Content-Type", "application/json");
1206
+ res.writeHead(200);
1207
+ res.end(JSON.stringify(result));
1208
+ } catch (err) {
1209
+ log("Proxy error:", err);
1210
+ res.setHeader("Content-Type", "application/json");
1211
+ res.writeHead(500);
1212
+ res.end(
1213
+ JSON.stringify({
1214
+ error: err instanceof Error ? err.message : "Service call failed"
1215
+ })
1216
+ );
1217
+ }
1218
+ return;
1219
+ }
1220
+ if (url === "/api/services/search" && req.method === "POST") {
1221
+ const body = await parseBody2(req);
1222
+ res.setHeader("Content-Type", "application/json");
1223
+ res.writeHead(200);
1224
+ if (body.tool_name) {
1225
+ const info = registry.getToolInfo(body.tool_name);
1226
+ if (!info) {
1227
+ res.end(
1228
+ JSON.stringify({
1229
+ success: false,
1230
+ error: `Tool '${body.tool_name}' not found`
1231
+ })
1232
+ );
1233
+ } else {
1234
+ res.end(JSON.stringify({ success: true, tool: info }));
1235
+ }
1236
+ return;
1237
+ }
1238
+ const results = registry.searchServices({
1239
+ query: body.query,
1240
+ namespace: body.namespace,
1241
+ limit: body.limit ?? 20,
1242
+ includeInterfaces: body.include_interfaces ?? false
1243
+ });
1244
+ res.end(
1245
+ JSON.stringify({
1246
+ success: true,
1247
+ count: results.length,
1248
+ tools: results,
1249
+ namespaces: registry.getNamespaces()
1250
+ })
1251
+ );
1252
+ return;
1253
+ }
1254
+ if (url === "/api/services" && req.method === "GET") {
1255
+ res.setHeader("Content-Type", "application/json");
1256
+ res.writeHead(200);
1257
+ res.end(
1258
+ JSON.stringify({
1259
+ namespaces: registry.getNamespaces(),
1260
+ services: registry.getServiceInfo()
1261
+ })
1262
+ );
1263
+ return;
1264
+ }
1265
+ if (url === "/health" || url === "/") {
1266
+ res.setHeader("Content-Type", "application/json");
1267
+ res.writeHead(200);
1268
+ res.end(JSON.stringify({ status: "ok", service: "stitchery" }));
1269
+ return;
1270
+ }
1271
+ res.writeHead(404);
1272
+ res.end(`Not found: ${url}`);
1273
+ } catch (err) {
1274
+ log("Error:", err);
1275
+ res.writeHead(500);
1276
+ res.end(err instanceof Error ? err.message : "Internal server error");
1277
+ }
1278
+ });
1279
+ return {
1280
+ server,
1281
+ registry,
1282
+ async start() {
1283
+ return new Promise((resolve2, reject) => {
1284
+ server.on("error", reject);
1285
+ server.listen(port, host, () => {
1286
+ log(`Server listening on http://${host}:${port}`);
1287
+ resolve2({ port, host });
1288
+ });
1289
+ });
1290
+ },
1291
+ async stop() {
1292
+ return new Promise((resolve2, reject) => {
1293
+ server.close((err) => {
1294
+ if (err) reject(err);
1295
+ else resolve2();
1296
+ });
1297
+ });
1298
+ }
1299
+ };
1300
+ }
1301
+ export {
1302
+ EDIT_PROMPT,
1303
+ PATCHWORK_PROMPT,
1304
+ ServiceRegistry,
1305
+ createStitcheryServer,
1306
+ generateServicesPrompt
1307
+ };
1308
+ //# sourceMappingURL=index.js.map