@aprovan/stitchery 0.1.0-dev.6bd527d

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