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