@perstack/base 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,258 @@
1
1
  #!/usr/bin/env node
2
- import {McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {Command}from'commander';import {realpathSync,existsSync,statSync}from'fs';import M,{stat,readFile,appendFile,unlink,mkdir,rename,writeFile,readdir}from'fs/promises';import {dedent}from'ts-dedent';import {z as z$1}from'zod';import Ue from'os';import y,{dirname,extname,basename,resolve,join}from'path';import $e from'mime-types';var h={name:"@perstack/base",version:"0.0.2",description:"Perstack base skills for agents."};var c=realpathSync(F(process.cwd()));function F(t){return t.startsWith("~/")||t==="~"?y.join(Ue.homedir(),t.slice(1)):t}async function a(t){let o=F(t),e=y.isAbsolute(o)?y.resolve(o):y.resolve(process.cwd(),o);if(e===`${c}/perstack`)throw new Error("Access denied - perstack directory is not allowed");try{let r=await M.realpath(e);if(!r.startsWith(c))throw new Error("Access denied - symlink target outside allowed directories");return r}catch{let i=y.dirname(e);try{if(!(await M.realpath(i)).startsWith(c))throw new Error("Access denied - parent directory outside allowed directories");return e}catch{throw e.startsWith(c)?new Error(`Parent directory does not exist: ${i}`):new Error(`Access denied - path outside allowed directories: ${e} not in ${c}`)}}}var w=()=>{let t=process.env.PERSTACK_API_BASE_URL,o=process.env.PERSTACK_API_KEY,e=process.env.PERSTACK_EXPERT_JOB_ID;if(!(!t||!o||!e||t===""||o===""||e===""))return {baseUrl:t,apiKey:o,expertJobId:e}},m=()=>w()!==void 0?"studio":"local",l=async t=>{let o=w();if(!o)throw new Error("Workspace API not configured");try{let e=new URL("/api/studio/v1/workspace/items/find",o.baseUrl);e.searchParams.set("path",t);let r=await fetch(e,{headers:{Authorization:`Bearer ${o.apiKey}`,"x-studio-expert-job-id":o.expertJobId}});if(!r.ok){if(r.status===404)return null;let s=await r.text();throw new Error(`Failed to find workspace item: ${r.status} ${s}`)}return (await r.json()).data.workspaceItem}catch(e){if(e instanceof Error&&e.message.includes("404"))return null;throw e}},f=async(t,o)=>{let e=w();if(!e)throw new Error("Workspace API not configured");let r=new URL("/api/studio/v1/workspace/items",e.baseUrl);if(t.type==="workspaceItemFile"&&o){let n=new FormData;n.append("type","workspaceItemFile"),n.append("path",t.path),n.append("permission",t.permission);let d=new Blob([o],{type:$e.lookup(t.path)||"text/plain"});n.append("file",d);let p=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"x-studio-expert-job-id":e.expertJobId},body:n});if(!p.ok){let T=await p.text();throw new Error(`Failed to create workspace item: ${p.status} ${T}`)}return (await p.json()).data.workspaceItem}let i=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","x-studio-expert-job-id":e.expertJobId},body:JSON.stringify({type:t.type,path:t.path,permission:t.permission})});if(!i.ok){let n=await i.text();throw new Error(`Failed to create workspace item: ${i.status} ${n}`)}return (await i.json()).data.workspaceItem},A=async(t,o)=>{let e=w();if(!e)throw new Error("Workspace API not configured");let r={Authorization:`Bearer ${e.apiKey}`,"Content-Type":"application/json","x-studio-expert-job-id":e.expertJobId},i=new URL(`/api/studio/v1/workspace/items/${t}`,e.baseUrl),s=await fetch(i,{method:"POST",headers:r,body:JSON.stringify(o)});if(!s.ok)throw new Error(`Failed to update workspace item: ${s.status}`);return (await s.json()).data.workspaceItem},W=async(t=100,o=0)=>{let e=w();if(!e)throw new Error("Workspace API not configured");let r=new URL("/api/studio/v1/workspace/items",e.baseUrl);r.searchParams.set("take",t.toString()),r.searchParams.set("skip",o.toString());let i=await fetch(r,{headers:{Authorization:`Bearer ${e.apiKey}`,"x-studio-expert-job-id":e.expertJobId}});if(!i.ok){let n=await i.text();throw new Error(`Failed to get workspace items: ${i.status} ${n}`)}return (await i.json()).data.workspaceItems},g=async t=>{let o=w();if(!o)throw new Error("Workspace API not configured");let e=new URL(`/api/studio/v1/workspace/items/${t}`,o.baseUrl),r=await fetch(e,{method:"DELETE",headers:{Authorization:`Bearer ${o.apiKey}`,"x-studio-expert-job-id":o.expertJobId}});if(!r.ok){let i=await r.text();throw new Error(`Failed to delete workspace item: ${r.status} ${i}`)}};var D="appendTextFile",R=dedent`
2
+
3
+ // src/index.ts
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import { Command } from "commander";
7
+
8
+ // package.json
9
+ var package_default = {
10
+ name: "@perstack/base",
11
+ version: "0.0.4",
12
+ description: "Perstack base skills for agents.",
13
+ author: "Wintermute Technologies, Inc.",
14
+ type: "module",
15
+ bin: {
16
+ base: "dist/index.js"
17
+ },
18
+ exports: {
19
+ ".": "./dist/index.js"
20
+ },
21
+ files: [
22
+ "dist"
23
+ ],
24
+ scripts: {
25
+ clean: "rm -rf dist",
26
+ dev: "tsup --watch --config ../../tsup.config.ts",
27
+ build: "npm run clean && tsup --config ../../tsup.config.ts",
28
+ prepublishOnly: "npm run clean && npm run build"
29
+ },
30
+ dependencies: {
31
+ "@modelcontextprotocol/sdk": "^1.10.2",
32
+ commander: "^13.1.0",
33
+ "mime-types": "^3.0.1",
34
+ "ts-dedent": "^2.2.0",
35
+ zod: "^3.24.3"
36
+ },
37
+ devDependencies: {
38
+ "@tsconfig/node22": "^22.0.1",
39
+ "@types/mime-types": "^3.0.1",
40
+ "@types/node": "^22.15.3",
41
+ tsup: "^8.4.0",
42
+ typescript: "^5.8.3"
43
+ },
44
+ engines: {
45
+ node: ">=22.0.0"
46
+ }
47
+ };
48
+
49
+ // src/tools/append-text-file.ts
50
+ import { existsSync, statSync } from "fs";
51
+ import { appendFile } from "fs/promises";
52
+ import { readFile } from "fs/promises";
53
+ import { dedent } from "ts-dedent";
54
+ import { z } from "zod";
55
+
56
+ // src/lib/path.ts
57
+ import { realpathSync } from "fs";
58
+ import fs from "fs/promises";
59
+ import os from "os";
60
+ import path from "path";
61
+ var workspacePath = realpathSync(expandHome(process.cwd()));
62
+ function expandHome(filepath) {
63
+ if (filepath.startsWith("~/") || filepath === "~") {
64
+ return path.join(os.homedir(), filepath.slice(1));
65
+ }
66
+ return filepath;
67
+ }
68
+ async function validatePath(requestedPath) {
69
+ const expandedPath = expandHome(requestedPath);
70
+ const absolute = path.isAbsolute(expandedPath) ? path.resolve(expandedPath) : path.resolve(process.cwd(), expandedPath);
71
+ if (absolute === `${workspacePath}/perstack`) {
72
+ throw new Error("Access denied - perstack directory is not allowed");
73
+ }
74
+ try {
75
+ const realAbsolute = await fs.realpath(absolute);
76
+ if (!realAbsolute.startsWith(workspacePath)) {
77
+ throw new Error("Access denied - symlink target outside allowed directories");
78
+ }
79
+ return realAbsolute;
80
+ } catch (error) {
81
+ const parentDir = path.dirname(absolute);
82
+ try {
83
+ const realParentPath = await fs.realpath(parentDir);
84
+ if (!realParentPath.startsWith(workspacePath)) {
85
+ throw new Error("Access denied - parent directory outside allowed directories");
86
+ }
87
+ return absolute;
88
+ } catch {
89
+ if (!absolute.startsWith(workspacePath)) {
90
+ throw new Error(
91
+ `Access denied - path outside allowed directories: ${absolute} not in ${workspacePath}`
92
+ );
93
+ }
94
+ throw new Error(`Parent directory does not exist: ${parentDir}`);
95
+ }
96
+ }
97
+ }
98
+
99
+ // src/lib/workspace-api.ts
100
+ import mime from "mime-types";
101
+ var getWorkspaceApiConfig = () => {
102
+ const baseUrl = process.env.PERSTACK_API_BASE_URL;
103
+ const apiKey = process.env.PERSTACK_API_KEY;
104
+ const expertJobId = process.env.PERSTACK_EXPERT_JOB_ID;
105
+ if (!baseUrl || !apiKey || !expertJobId || baseUrl === "" || apiKey === "" || expertJobId === "") {
106
+ return void 0;
107
+ }
108
+ return { baseUrl, apiKey, expertJobId };
109
+ };
110
+ var getWorkspaceMode = () => {
111
+ return getWorkspaceApiConfig() !== void 0 ? "studio" /* STUDIO */ : "local" /* LOCAL */;
112
+ };
113
+ var findWorkspaceItem = async (path2) => {
114
+ const config = getWorkspaceApiConfig();
115
+ if (!config) {
116
+ throw new Error("Workspace API not configured");
117
+ }
118
+ try {
119
+ const url = new URL("/api/studio/v1/workspace/items/find", config.baseUrl);
120
+ url.searchParams.set("path", path2);
121
+ const response = await fetch(url, {
122
+ headers: {
123
+ Authorization: `Bearer ${config.apiKey}`,
124
+ "x-studio-expert-job-id": config.expertJobId
125
+ }
126
+ });
127
+ if (!response.ok) {
128
+ if (response.status === 404) {
129
+ return null;
130
+ }
131
+ const errorText = await response.text();
132
+ throw new Error(`Failed to find workspace item: ${response.status} ${errorText}`);
133
+ }
134
+ const result = await response.json();
135
+ return result.data.workspaceItem;
136
+ } catch (error) {
137
+ if (error instanceof Error && error.message.includes("404")) {
138
+ return null;
139
+ }
140
+ throw error;
141
+ }
142
+ };
143
+ var createWorkspaceItem = async (item, fileContent) => {
144
+ const config = getWorkspaceApiConfig();
145
+ if (!config) {
146
+ throw new Error("Workspace API not configured");
147
+ }
148
+ const url = new URL("/api/studio/v1/workspace/items", config.baseUrl);
149
+ if (item.type === "workspaceItemFile" && fileContent) {
150
+ const formData = new FormData();
151
+ formData.append("type", "workspaceItemFile");
152
+ formData.append("path", item.path);
153
+ formData.append("permission", item.permission);
154
+ const blob = new Blob([fileContent], { type: mime.lookup(item.path) || "text/plain" });
155
+ formData.append("file", blob);
156
+ const response2 = await fetch(url, {
157
+ method: "POST",
158
+ headers: {
159
+ Authorization: `Bearer ${config.apiKey}`,
160
+ "x-studio-expert-job-id": config.expertJobId
161
+ },
162
+ body: formData
163
+ });
164
+ if (!response2.ok) {
165
+ const errorText = await response2.text();
166
+ throw new Error(`Failed to create workspace item: ${response2.status} ${errorText}`);
167
+ }
168
+ const result2 = await response2.json();
169
+ return result2.data.workspaceItem;
170
+ }
171
+ const response = await fetch(url, {
172
+ method: "POST",
173
+ headers: {
174
+ Authorization: `Bearer ${config.apiKey}`,
175
+ "Content-Type": "application/json",
176
+ "x-studio-expert-job-id": config.expertJobId
177
+ },
178
+ body: JSON.stringify({
179
+ type: item.type,
180
+ path: item.path,
181
+ permission: item.permission
182
+ })
183
+ });
184
+ if (!response.ok) {
185
+ const errorText = await response.text();
186
+ throw new Error(`Failed to create workspace item: ${response.status} ${errorText}`);
187
+ }
188
+ const result = await response.json();
189
+ return result.data.workspaceItem;
190
+ };
191
+ var updateWorkspaceItem = async (id, updates) => {
192
+ const config = getWorkspaceApiConfig();
193
+ if (!config) {
194
+ throw new Error("Workspace API not configured");
195
+ }
196
+ const headers = {
197
+ Authorization: `Bearer ${config.apiKey}`,
198
+ "Content-Type": "application/json",
199
+ "x-studio-expert-job-id": config.expertJobId
200
+ };
201
+ const url = new URL(`/api/studio/v1/workspace/items/${id}`, config.baseUrl);
202
+ const response = await fetch(url, {
203
+ method: "POST",
204
+ headers,
205
+ body: JSON.stringify(updates)
206
+ });
207
+ if (!response.ok) {
208
+ throw new Error(`Failed to update workspace item: ${response.status}`);
209
+ }
210
+ const result = await response.json();
211
+ return result.data.workspaceItem;
212
+ };
213
+ var getWorkspaceItems = async (take = 100, skip = 0) => {
214
+ const config = getWorkspaceApiConfig();
215
+ if (!config) {
216
+ throw new Error("Workspace API not configured");
217
+ }
218
+ const url = new URL("/api/studio/v1/workspace/items", config.baseUrl);
219
+ url.searchParams.set("take", take.toString());
220
+ url.searchParams.set("skip", skip.toString());
221
+ const response = await fetch(url, {
222
+ headers: {
223
+ Authorization: `Bearer ${config.apiKey}`,
224
+ "x-studio-expert-job-id": config.expertJobId
225
+ }
226
+ });
227
+ if (!response.ok) {
228
+ const errorText = await response.text();
229
+ throw new Error(`Failed to get workspace items: ${response.status} ${errorText}`);
230
+ }
231
+ const result = await response.json();
232
+ return result.data.workspaceItems;
233
+ };
234
+ var deleteWorkspaceItem = async (workspaceItemId) => {
235
+ const config = getWorkspaceApiConfig();
236
+ if (!config) {
237
+ throw new Error("Workspace API not configured");
238
+ }
239
+ const url = new URL(`/api/studio/v1/workspace/items/${workspaceItemId}`, config.baseUrl);
240
+ const response = await fetch(url, {
241
+ method: "DELETE",
242
+ headers: {
243
+ Authorization: `Bearer ${config.apiKey}`,
244
+ "x-studio-expert-job-id": config.expertJobId
245
+ }
246
+ });
247
+ if (!response.ok) {
248
+ const errorText = await response.text();
249
+ throw new Error(`Failed to delete workspace item: ${response.status} ${errorText}`);
250
+ }
251
+ };
252
+
253
+ // src/tools/append-text-file.ts
254
+ var toolName = "appendTextFile";
255
+ var toolDescription = dedent`
3
256
  Text file appender for adding content to the end of existing files.
4
257
 
5
258
  Use cases:
@@ -20,11 +273,124 @@ import {McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import {StdioSer
20
273
  - YOU MUST PROVIDE A VALID UTF-8 STRING FOR THE TEXT
21
274
  - THERE IS A LIMIT ON THE NUMBER OF TOKENS THAT CAN BE GENERATED, SO DO NOT APPEND ALL THE CONTENT AT ONCE
22
275
  - IF YOU WANT TO APPEND MORE THAN 2000 CHARACTERS, USE THIS TOOL MULTIPLE TIMES
23
- `,L={path:z$1.string().describe("Target file path to append to."),text:z$1.string().min(1).max(2e3).describe("Text to append to the file. Max 2000 characters.")};function N(t){switch(m()){case "local":{t.tool(D,`${R}
276
+ `;
277
+ var toolInputSchema = {
278
+ path: z.string().describe("Target file path to append to."),
279
+ text: z.string().min(1).max(2e3).describe("Text to append to the file. Max 2000 characters.")
280
+ };
281
+ function addAppendTextFileTool(server) {
282
+ const mode = getWorkspaceMode();
283
+ switch (mode) {
284
+ case "local" /* LOCAL */: {
285
+ server.tool(
286
+ toolName,
287
+ `${toolDescription}
24
288
 
25
- Mode: Local (Local filesystem)`,L,async({path:e,text:r})=>{try{return {content:[{type:"text",text:JSON.stringify(await U(e,r))}]}}catch(i){if(i instanceof Error)return {content:[{type:"text",text:i.message}]};throw i}});break}case "studio":{t.tool(D,`${R}
289
+ Mode: Local (Local filesystem)`,
290
+ toolInputSchema,
291
+ async ({ path: path2, text }) => {
292
+ try {
293
+ return {
294
+ content: [
295
+ {
296
+ type: "text",
297
+ text: JSON.stringify(await appendTextFileLocalMode(path2, text))
298
+ }
299
+ ]
300
+ };
301
+ } catch (e) {
302
+ if (e instanceof Error) {
303
+ return {
304
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
305
+ };
306
+ }
307
+ throw e;
308
+ }
309
+ }
310
+ );
311
+ break;
312
+ }
313
+ case "studio" /* STUDIO */: {
314
+ server.tool(
315
+ toolName,
316
+ `${toolDescription}
26
317
 
27
- Mode: Studio (Workspace API)`,L,async({path:e,text:r})=>{try{return {content:[{type:"text",text:JSON.stringify(await Be(e,r))}]}}catch(i){if(i instanceof Error)return {content:[{type:"text",text:i.message}]};throw i}});break}}}async function U(t,o){let e=await a(t);if(!existsSync(e))throw new Error(`File ${t} does not exist.`);if(!(statSync(e).mode&128))throw new Error(`File ${t} is not writable`);return await appendFile(e,o),e}async function Be(t,o){let e=await a(t),r=e.startsWith(c)?e.slice(c.length+1):e,i=await l(r);if(!i)throw new Error(`File ${r} does not exist.`);if(i.type==="workspaceItemDirectory")throw new Error(`Path ${r} is a directory.`);await U(t,o),await g(i.id);let s=await readFile(e,"utf-8");return await f({type:"workspaceItemFile",path:r,permission:"readWrite"},s),r}var $=t=>{t.tool("attemptCompletion",dedent`
318
+ Mode: Studio (Workspace API)`,
319
+ toolInputSchema,
320
+ async ({ path: path2, text }) => {
321
+ try {
322
+ return {
323
+ content: [
324
+ {
325
+ type: "text",
326
+ text: JSON.stringify(await appendTextFileStudioMode(path2, text))
327
+ }
328
+ ]
329
+ };
330
+ } catch (e) {
331
+ if (e instanceof Error) {
332
+ return {
333
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
334
+ };
335
+ }
336
+ throw e;
337
+ }
338
+ }
339
+ );
340
+ break;
341
+ }
342
+ }
343
+ }
344
+ async function appendTextFileLocalMode(path2, text) {
345
+ const validatedPath = await validatePath(path2);
346
+ if (!existsSync(validatedPath)) {
347
+ throw new Error(`File ${path2} does not exist.`);
348
+ }
349
+ const stats = statSync(validatedPath);
350
+ if (!(stats.mode & 128)) {
351
+ throw new Error(`File ${path2} is not writable`);
352
+ }
353
+ await appendFile(validatedPath, text);
354
+ return {
355
+ path: validatedPath,
356
+ text
357
+ };
358
+ }
359
+ async function appendTextFileStudioMode(path2, text) {
360
+ const validatedPath = await validatePath(path2);
361
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
362
+ const existingItem = await findWorkspaceItem(relativePath);
363
+ if (!existingItem) {
364
+ throw new Error(`File ${relativePath} does not exist.`);
365
+ }
366
+ if (existingItem.type === "workspaceItemDirectory") {
367
+ throw new Error(`Path ${relativePath} is a directory.`);
368
+ }
369
+ await appendTextFileLocalMode(path2, text);
370
+ await deleteWorkspaceItem(existingItem.id);
371
+ const content = await readFile(validatedPath, "utf-8");
372
+ await createWorkspaceItem(
373
+ {
374
+ type: "workspaceItemFile",
375
+ path: relativePath,
376
+ owner: "expert",
377
+ lifecycle: "expertJob",
378
+ permission: "readWrite"
379
+ },
380
+ content
381
+ );
382
+ return {
383
+ path: relativePath,
384
+ text
385
+ };
386
+ }
387
+
388
+ // src/tools/attempt-completion.ts
389
+ import { dedent as dedent2 } from "ts-dedent";
390
+ var addAttemptCompletionTool = (server) => {
391
+ server.tool(
392
+ "attemptCompletion",
393
+ dedent2`
28
394
  Task completion signal that triggers immediate final report generation.
29
395
  Use cases:
30
396
  - Signaling task completion to Perstack runtime
@@ -39,7 +405,30 @@ Mode: Studio (Workspace API)`,L,async({path:e,text:r})=>{try{return {content:[{t
39
405
  - Triggers immediate transition to final report
40
406
  - Should only be used when task is fully complete
41
407
  - Cannot be reverted once called
42
- `,{},Ke);};async function Ke(){return {content:[{type:"text",text:"End the agent loop and provide a final report"}]}}var z="createDirectory",j=dedent`
408
+ `,
409
+ {},
410
+ attemptCompletion
411
+ );
412
+ };
413
+ async function attemptCompletion() {
414
+ return {
415
+ content: [
416
+ {
417
+ type: "text",
418
+ text: "End the agent loop and provide a final report"
419
+ }
420
+ ]
421
+ };
422
+ }
423
+
424
+ // src/tools/create-directory.ts
425
+ import { existsSync as existsSync2, statSync as statSync2 } from "fs";
426
+ import { mkdir } from "fs/promises";
427
+ import { dirname } from "path";
428
+ import { dedent as dedent3 } from "ts-dedent";
429
+ import { z as z2 } from "zod";
430
+ var toolName2 = "createDirectory";
431
+ var toolDescription2 = dedent3`
43
432
  Directory creator for establishing folder structures in the workspace.
44
433
 
45
434
  Use cases:
@@ -56,11 +445,126 @@ Mode: Studio (Workspace API)`,L,async({path:e,text:r})=>{try{return {content:[{t
56
445
 
57
446
  Parameters:
58
447
  - path: Directory path to create
59
- `,H={path:z$1.string()};function J(t){switch(m()){case "local":{t.tool(z,`${j}
448
+ `;
449
+ var toolInputSchema2 = {
450
+ path: z2.string()
451
+ };
452
+ function addCreateDirectoryTool(server) {
453
+ const mode = getWorkspaceMode();
454
+ switch (mode) {
455
+ case "local" /* LOCAL */: {
456
+ server.tool(
457
+ toolName2,
458
+ `${toolDescription2}
459
+
460
+ Mode: Local (Local filesystem)`,
461
+ toolInputSchema2,
462
+ async ({ path: path2 }) => {
463
+ try {
464
+ return {
465
+ content: [
466
+ {
467
+ type: "text",
468
+ text: JSON.stringify(await createDirectoryLocalMode(path2))
469
+ }
470
+ ]
471
+ };
472
+ } catch (e) {
473
+ if (e instanceof Error) {
474
+ return {
475
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
476
+ };
477
+ }
478
+ throw e;
479
+ }
480
+ }
481
+ );
482
+ break;
483
+ }
484
+ case "studio" /* STUDIO */: {
485
+ server.tool(
486
+ toolName2,
487
+ `${toolDescription2}
60
488
 
61
- Mode: Local (Local filesystem)`,H,async({path:e})=>{try{return {content:[{type:"text",text:JSON.stringify(await B(e))}]}}catch(r){if(r instanceof Error)return {content:[{type:"text",text:r.message}]};throw r}});break}case "studio":{t.tool(z,`${j}
489
+ Mode: Studio (Workspace API)`,
490
+ toolInputSchema2,
491
+ async ({ path: path2 }) => {
492
+ try {
493
+ return {
494
+ content: [
495
+ {
496
+ type: "text",
497
+ text: JSON.stringify(await createDirectoryStudioMode(path2))
498
+ }
499
+ ]
500
+ };
501
+ } catch (e) {
502
+ if (e instanceof Error) {
503
+ return {
504
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
505
+ };
506
+ }
507
+ throw e;
508
+ }
509
+ }
510
+ );
511
+ break;
512
+ }
513
+ }
514
+ }
515
+ async function createDirectoryLocalMode(path2) {
516
+ const validatedPath = await validatePath(path2);
517
+ const exists = existsSync2(validatedPath);
518
+ if (exists) {
519
+ throw new Error(`Directory ${path2} already exists`);
520
+ }
521
+ const parentDir = dirname(validatedPath);
522
+ if (existsSync2(parentDir)) {
523
+ const parentStats = statSync2(parentDir);
524
+ if (!(parentStats.mode & 128)) {
525
+ throw new Error(`Parent directory ${parentDir} is not writable`);
526
+ }
527
+ }
528
+ await mkdir(validatedPath, { recursive: true });
529
+ return {
530
+ path: validatedPath
531
+ };
532
+ }
533
+ async function createDirectoryStudioMode(path2) {
534
+ const validatedPath = await validatePath(path2);
535
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
536
+ const existingItem = await findWorkspaceItem(relativePath);
537
+ if (existingItem) {
538
+ throw new Error(`Directory ${relativePath} already exists`);
539
+ }
540
+ const pathParts = relativePath.split("/").filter((part) => part !== "");
541
+ for (let i = 1; i <= pathParts.length; i++) {
542
+ const currentPath = pathParts.slice(0, i).join("/");
543
+ if (currentPath === "") continue;
544
+ const existingParent = await findWorkspaceItem(currentPath);
545
+ if (!existingParent) {
546
+ await createWorkspaceItem({
547
+ type: "workspaceItemDirectory",
548
+ path: currentPath,
549
+ owner: "expert",
550
+ lifecycle: "expertJob",
551
+ permission: "readWrite"
552
+ });
553
+ }
554
+ }
555
+ await createDirectoryLocalMode(path2);
556
+ return {
557
+ path: relativePath
558
+ };
559
+ }
62
560
 
63
- Mode: Studio (Workspace API)`,H,async({path:e})=>{try{return {content:[{type:"text",text:JSON.stringify(await Ze(e))}]}}catch(r){if(r instanceof Error)return {content:[{type:"text",text:r.message}]};throw r}});break}}}async function B(t){let o=await a(t);if(existsSync(o))throw new Error(`Directory ${t} already exists`);let r=dirname(o);if(existsSync(r)&&!(statSync(r).mode&128))throw new Error(`Parent directory ${r} is not writable`);return await mkdir(o,{recursive:true}),o}async function Ze(t){let o=await a(t),e=o.startsWith(c)?o.slice(c.length+1):o;if(await l(e))throw new Error(`Directory ${e} already exists`);let i=e.split("/").filter(s=>s!=="");for(let s=1;s<=i.length;s++){let n=i.slice(0,s).join("/");if(n==="")continue;await l(n)||await f({type:"workspaceItemDirectory",path:n,permission:"readWrite"});}return await B(t),e}var G="deleteFile",K=dedent`
561
+ // src/tools/delete-file.ts
562
+ import { existsSync as existsSync3, statSync as statSync3 } from "fs";
563
+ import { unlink } from "fs/promises";
564
+ import { dedent as dedent4 } from "ts-dedent";
565
+ import { z as z3 } from "zod";
566
+ var toolName3 = "deleteFile";
567
+ var toolDescription3 = dedent4`
64
568
  File deleter for removing files from the workspace.
65
569
 
66
570
  Use cases:
@@ -77,11 +581,114 @@ Mode: Studio (Workspace API)`,H,async({path:e})=>{try{return {content:[{type:"te
77
581
 
78
582
  Parameters:
79
583
  - path: File path to delete
80
- `,V={path:z$1.string()};function _(t){switch(m()){case "local":{t.tool(G,`${K}
584
+ `;
585
+ var toolInputSchema3 = {
586
+ path: z3.string()
587
+ };
588
+ function addDeleteFileTool(server) {
589
+ const mode = getWorkspaceMode();
590
+ switch (mode) {
591
+ case "local" /* LOCAL */: {
592
+ server.tool(
593
+ toolName3,
594
+ `${toolDescription3}
81
595
 
82
- Mode: Local (Local filesystem)`,V,async({path:e})=>{try{return {content:[{type:"text",text:JSON.stringify(await q(e))}]}}catch(r){if(r instanceof Error)return {content:[{type:"text",text:r.message}]};throw r}});break}case "studio":{t.tool(G,`${K}
596
+ Mode: Local (Local filesystem)`,
597
+ toolInputSchema3,
598
+ async ({ path: path2 }) => {
599
+ try {
600
+ return {
601
+ content: [
602
+ {
603
+ type: "text",
604
+ text: JSON.stringify(await deleteFileLocalMode(path2))
605
+ }
606
+ ]
607
+ };
608
+ } catch (e) {
609
+ if (e instanceof Error) {
610
+ return {
611
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
612
+ };
613
+ }
614
+ throw e;
615
+ }
616
+ }
617
+ );
618
+ break;
619
+ }
620
+ case "studio" /* STUDIO */: {
621
+ server.tool(
622
+ toolName3,
623
+ `${toolDescription3}
83
624
 
84
- Mode: Studio (Workspace API)`,V,async({path:e})=>{try{return {content:[{type:"text",text:JSON.stringify(await it(e))}]}}catch(r){if(r instanceof Error)return {content:[{type:"text",text:r.message}]};throw r}});break}}}async function q(t){let o=await a(t);if(!existsSync(o))throw new Error(`File ${t} does not exist.`);let e=statSync(o);if(e.isDirectory())throw new Error(`Path ${t} is a directory. Use delete directory tool instead.`);if(!(e.mode&128))throw new Error(`File ${t} is not writable`);return await unlink(o),o}async function it(t){let o=await a(t),e=o.startsWith(c)?o.slice(c.length+1):o,r=await l(e);if(!r)throw new Error(`File ${e} does not exist.`);if(r.type==="workspaceItemDirectory")throw new Error(`Path ${e} is a directory. Use delete directory tool instead.`);return await q(t),await g(r.id),e}var X="editTextFile",Y=dedent`
625
+ Mode: Studio (Workspace API)`,
626
+ toolInputSchema3,
627
+ async ({ path: path2 }) => {
628
+ try {
629
+ return {
630
+ content: [
631
+ {
632
+ type: "text",
633
+ text: JSON.stringify(await deleteFileStudioMode(path2))
634
+ }
635
+ ]
636
+ };
637
+ } catch (e) {
638
+ if (e instanceof Error) {
639
+ return {
640
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
641
+ };
642
+ }
643
+ throw e;
644
+ }
645
+ }
646
+ );
647
+ break;
648
+ }
649
+ }
650
+ }
651
+ async function deleteFileLocalMode(path2) {
652
+ const validatedPath = await validatePath(path2);
653
+ if (!existsSync3(validatedPath)) {
654
+ throw new Error(`File ${path2} does not exist.`);
655
+ }
656
+ const stats = statSync3(validatedPath);
657
+ if (stats.isDirectory()) {
658
+ throw new Error(`Path ${path2} is a directory. Use delete directory tool instead.`);
659
+ }
660
+ if (!(stats.mode & 128)) {
661
+ throw new Error(`File ${path2} is not writable`);
662
+ }
663
+ await unlink(validatedPath);
664
+ return {
665
+ path: validatedPath
666
+ };
667
+ }
668
+ async function deleteFileStudioMode(path2) {
669
+ const validatedPath = await validatePath(path2);
670
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
671
+ const existingItem = await findWorkspaceItem(relativePath);
672
+ if (!existingItem) {
673
+ throw new Error(`File ${relativePath} does not exist.`);
674
+ }
675
+ if (existingItem.type === "workspaceItemDirectory") {
676
+ throw new Error(`Path ${relativePath} is a directory. Use delete directory tool instead.`);
677
+ }
678
+ await deleteFileLocalMode(path2);
679
+ await deleteWorkspaceItem(existingItem.id);
680
+ return {
681
+ path: relativePath
682
+ };
683
+ }
684
+
685
+ // src/tools/edit-text-file.ts
686
+ import { existsSync as existsSync4, statSync as statSync4 } from "fs";
687
+ import { readFile as readFile2, writeFile } from "fs/promises";
688
+ import { dedent as dedent5 } from "ts-dedent";
689
+ import { z as z4 } from "zod";
690
+ var toolName4 = "editTextFile";
691
+ var toolDescription4 = dedent5`
85
692
  Text file editor for modifying existing files with precise text replacement.
86
693
 
87
694
  Use cases:
@@ -102,12 +709,142 @@ Mode: Studio (Workspace API)`,V,async({path:e})=>{try{return {content:[{type:"te
102
709
  - THERE IS A LIMIT ON THE NUMBER OF TOKENS THAT CAN BE GENERATED, SO DO NOT WRITE ALL THE CONTENT AT ONCE (IT WILL CAUSE AN ERROR)
103
710
  - IF YOU WANT TO EDIT MORE THAN 2000 CHARACTERS, USE THIS TOOL MULTIPLE TIMES
104
711
  - DO NOT USE THIS TOOL FOR APPENDING TEXT TO FILES - USE appendTextFile TOOL INSTEAD
105
- `,Z={path:z$1.string().describe("Target file path to edit."),newText:z$1.string().min(1).max(2e3).describe("Text to append to the file. Max 2000 characters."),oldText:z$1.string().min(1).max(2e3).describe("Exact text to find and replace. Max 2000 characters.")};function ee(t){switch(m()){case "local":{t.tool(X,`${Y}
712
+ `;
713
+ var toolInputSchema4 = {
714
+ path: z4.string().describe("Target file path to edit."),
715
+ newText: z4.string().min(1).max(2e3).describe("Text to append to the file. Max 2000 characters."),
716
+ oldText: z4.string().min(1).max(2e3).describe("Exact text to find and replace. Max 2000 characters.")
717
+ };
718
+ function addEditTextFileTool(server) {
719
+ const mode = getWorkspaceMode();
720
+ switch (mode) {
721
+ case "local" /* LOCAL */: {
722
+ server.tool(
723
+ toolName4,
724
+ `${toolDescription4}
725
+
726
+ Mode: Local (Local filesystem)`,
727
+ toolInputSchema4,
728
+ async ({ path: path2, newText, oldText }) => {
729
+ try {
730
+ return {
731
+ content: [
732
+ {
733
+ type: "text",
734
+ text: JSON.stringify(await editTextFileLocalMode(path2, newText, oldText))
735
+ }
736
+ ]
737
+ };
738
+ } catch (e) {
739
+ if (e instanceof Error) {
740
+ return {
741
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
742
+ };
743
+ }
744
+ throw e;
745
+ }
746
+ }
747
+ );
748
+ break;
749
+ }
750
+ case "studio" /* STUDIO */: {
751
+ server.tool(
752
+ toolName4,
753
+ `${toolDescription4}
106
754
 
107
- Mode: Local (Local filesystem)`,Z,async({path:e,newText:r,oldText:i})=>{try{return {content:[{type:"text",text:JSON.stringify(await te(e,r,i))}]}}catch(s){if(s instanceof Error)return {content:[{type:"text",text:s.message}]};throw s}});break}case "studio":{t.tool(X,`${Y}
755
+ Mode: Studio (Workspace API)`,
756
+ toolInputSchema4,
757
+ async ({ path: path2, oldText, newText }) => {
758
+ try {
759
+ return {
760
+ content: [
761
+ {
762
+ type: "text",
763
+ text: JSON.stringify(await editTextFileStudioMode(path2, newText, oldText))
764
+ }
765
+ ]
766
+ };
767
+ } catch (e) {
768
+ if (e instanceof Error) {
769
+ return {
770
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
771
+ };
772
+ }
773
+ throw e;
774
+ }
775
+ }
776
+ );
777
+ break;
778
+ }
779
+ }
780
+ }
781
+ async function editTextFileLocalMode(path2, newText, oldText) {
782
+ const validatedPath = await validatePath(path2);
783
+ if (!existsSync4(validatedPath)) {
784
+ throw new Error(`File ${path2} does not exist.`);
785
+ }
786
+ const stats = statSync4(validatedPath);
787
+ if (!(stats.mode & 128)) {
788
+ throw new Error(`File ${path2} is not writable`);
789
+ }
790
+ await applyFileEdit(validatedPath, newText, oldText);
791
+ return {
792
+ path: validatedPath,
793
+ newText,
794
+ oldText
795
+ };
796
+ }
797
+ async function editTextFileStudioMode(path2, newText, oldText) {
798
+ const validatedPath = await validatePath(path2);
799
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
800
+ const existingItem = await findWorkspaceItem(relativePath);
801
+ if (!existingItem) {
802
+ throw new Error(`File ${relativePath} does not exist.`);
803
+ }
804
+ if (existingItem.type === "workspaceItemDirectory") {
805
+ throw new Error(`Path ${relativePath} is a directory.`);
806
+ }
807
+ await editTextFileLocalMode(path2, newText, oldText);
808
+ await deleteWorkspaceItem(existingItem.id);
809
+ const content = await readFile2(validatedPath, "utf-8");
810
+ await createWorkspaceItem(
811
+ {
812
+ type: "workspaceItemFile",
813
+ path: relativePath,
814
+ owner: "expert",
815
+ lifecycle: "expertJob",
816
+ permission: "readWrite"
817
+ },
818
+ content
819
+ );
820
+ return {
821
+ path: relativePath,
822
+ newText,
823
+ oldText
824
+ };
825
+ }
826
+ function normalizeLineEndings(text) {
827
+ return text.replace(/\r\n/g, "\n");
828
+ }
829
+ async function applyFileEdit(filePath, newText, oldText) {
830
+ const content = normalizeLineEndings(await readFile2(filePath, "utf-8"));
831
+ const normalizedOld = normalizeLineEndings(oldText);
832
+ const normalizedNew = normalizeLineEndings(newText);
833
+ if (!content.includes(normalizedOld)) {
834
+ throw new Error(`Could not find exact match for oldText in file ${filePath}`);
835
+ }
836
+ const modifiedContent = content.replace(normalizedOld, normalizedNew);
837
+ await writeFile(filePath, modifiedContent, "utf-8");
838
+ }
108
839
 
109
- Mode: Studio (Workspace API)`,Z,async({path:e,oldText:r,newText:i})=>{try{return {content:[{type:"text",text:JSON.stringify(await pt(e,i,r))}]}}catch(s){if(s instanceof Error)return {content:[{type:"text",text:s.message}]};throw s}});break}}}async function te(t,o,e){let r=await a(t);if(!existsSync(r))throw new Error(`File ${t} does not exist.`);if(!(statSync(r).mode&128))throw new Error(`File ${t} is not writable`);return await dt(r,o,e),r}async function pt(t,o,e){let r=await a(t),i=r.startsWith(c)?r.slice(c.length+1):r,s=await l(i);if(!s)throw new Error(`File ${i} does not exist.`);if(s.type==="workspaceItemDirectory")throw new Error(`Path ${i} is a directory.`);await te(t,o,e),await g(s.id);let n=await readFile(r,"utf-8");return await f({type:"workspaceItemFile",path:i,permission:"readWrite"},n),i}function I(t){return t.replace(/\r\n/g,`
110
- `)}async function dt(t,o,e){let r=I(await readFile(t,"utf-8")),i=I(e),s=I(o);if(!r.includes(i))throw new Error(`Could not find exact match for oldText in file ${t}`);let n=r.replace(i,s);await writeFile(t,n,"utf-8");}var oe="getFileInfo",re=dedent`
840
+ // src/tools/get-file-info.ts
841
+ import { existsSync as existsSync5, statSync as statSync5 } from "fs";
842
+ import { basename, dirname as dirname2, extname, resolve } from "path";
843
+ import mime2 from "mime-types";
844
+ import { dedent as dedent6 } from "ts-dedent";
845
+ import { z as z5 } from "zod";
846
+ var toolName5 = "getFileInfo";
847
+ var toolDescription5 = dedent6`
111
848
  File information retriever for detailed metadata about files and directories.
112
849
 
113
850
  Use cases:
@@ -124,11 +861,141 @@ Mode: Studio (Workspace API)`,Z,async({path:e,oldText:r,newText:i})=>{try{return
124
861
 
125
862
  Parameters:
126
863
  - path: File or directory path to inspect
127
- `,ie={path:z$1.string()};function se(t){switch(m()){case "local":{t.tool(oe,`${re}
864
+ `;
865
+ var toolInputSchema5 = {
866
+ path: z5.string()
867
+ };
868
+ function addGetFileInfoTool(server) {
869
+ const mode = getWorkspaceMode();
870
+ switch (mode) {
871
+ case "local" /* LOCAL */: {
872
+ server.tool(
873
+ toolName5,
874
+ `${toolDescription5}
128
875
 
129
- Mode: Local (Local filesystem)`,ie,async({path:e})=>{try{return {content:[{type:"text",text:JSON.stringify(await ne(e))}]}}catch(r){if(r instanceof Error)return {content:[{type:"text",text:r.message}]};throw r}});break}case "studio":{t.tool(oe,`${re}
876
+ Mode: Local (Local filesystem)`,
877
+ toolInputSchema5,
878
+ async ({ path: path2 }) => {
879
+ try {
880
+ return {
881
+ content: [
882
+ {
883
+ type: "text",
884
+ text: JSON.stringify(await getFileInfoLocalMode(path2))
885
+ }
886
+ ]
887
+ };
888
+ } catch (e) {
889
+ if (e instanceof Error) {
890
+ return {
891
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
892
+ };
893
+ }
894
+ throw e;
895
+ }
896
+ }
897
+ );
898
+ break;
899
+ }
900
+ case "studio" /* STUDIO */: {
901
+ server.tool(
902
+ toolName5,
903
+ `${toolDescription5}
130
904
 
131
- Mode: Studio (Workspace API + Local filesystem)`,ie,async({path:e})=>{try{return {content:[{type:"text",text:JSON.stringify(await Tt(e))}]}}catch(r){if(r instanceof Error)return {content:[{type:"text",text:r.message}]};throw r}});break}}}async function ne(t){let o=await a(t);if(!existsSync(o))throw new Error(`File or directory ${t} does not exist`);let e=statSync(o),r=e.isDirectory(),i=r?null:$e.lookup(o)||"application/octet-stream",s=n=>{if(n===0)return "0 B";let d=["B","KB","MB","GB","TB"],p=Math.floor(Math.log(n)/Math.log(1024));return `${(n/1024**p).toFixed(2)} ${d[p]}`};return {exists:true,path:o,absolutePath:resolve(o),name:basename(o),directory:dirname(o),extension:r?null:extname(o),type:r?"directory":"file",mimeType:i,size:e.size,sizeFormatted:s(e.size),created:e.birthtime.toISOString(),modified:e.mtime.toISOString(),accessed:e.atime.toISOString(),permissions:{readable:true,writable:!!(e.mode&128),executable:!!(e.mode&64)}}}async function Tt(t){let o=await a(t),e=o.startsWith(c)?o.slice(c.length+1):o,r=await ne(t),i=await l(e);return {...r,workspaceItem:i?{id:i.id,type:i.type,path:i.path,owner:i.owner,lifecycle:i.lifecycle,permission:i.permission,createdAt:i.createdAt,updatedAt:i.updatedAt,...i.type==="workspaceItemFile"?{key:i.key,mimeType:i.mimeType,size:i.size}:{}}:null}}var ce="listDirectory",pe=dedent`
905
+ Mode: Studio (Workspace API + Local filesystem)`,
906
+ toolInputSchema5,
907
+ async ({ path: path2 }) => {
908
+ try {
909
+ return {
910
+ content: [
911
+ {
912
+ type: "text",
913
+ text: JSON.stringify(await getFileInfoStudioMode(path2))
914
+ }
915
+ ]
916
+ };
917
+ } catch (e) {
918
+ if (e instanceof Error) {
919
+ return {
920
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
921
+ };
922
+ }
923
+ throw e;
924
+ }
925
+ }
926
+ );
927
+ break;
928
+ }
929
+ }
930
+ }
931
+ async function getFileInfoLocalMode(path2) {
932
+ const validatedPath = await validatePath(path2);
933
+ if (!existsSync5(validatedPath)) {
934
+ throw new Error(`File or directory ${path2} does not exist`);
935
+ }
936
+ const stats = statSync5(validatedPath);
937
+ const isDirectory = stats.isDirectory();
938
+ const mimeType = isDirectory ? null : mime2.lookup(validatedPath) || "application/octet-stream";
939
+ const formatSize = (bytes) => {
940
+ if (bytes === 0) return "0 B";
941
+ const units = ["B", "KB", "MB", "GB", "TB"];
942
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
943
+ return `${(bytes / 1024 ** i).toFixed(2)} ${units[i]}`;
944
+ };
945
+ return {
946
+ exists: true,
947
+ path: validatedPath,
948
+ absolutePath: resolve(validatedPath),
949
+ name: basename(validatedPath),
950
+ directory: dirname2(validatedPath),
951
+ extension: isDirectory ? null : extname(validatedPath),
952
+ type: isDirectory ? "directory" : "file",
953
+ mimeType,
954
+ size: stats.size,
955
+ sizeFormatted: formatSize(stats.size),
956
+ created: stats.birthtime.toISOString(),
957
+ modified: stats.mtime.toISOString(),
958
+ accessed: stats.atime.toISOString(),
959
+ permissions: {
960
+ readable: true,
961
+ writable: Boolean(stats.mode & 128),
962
+ executable: Boolean(stats.mode & 64)
963
+ }
964
+ };
965
+ }
966
+ async function getFileInfoStudioMode(path2) {
967
+ const validatedPath = await validatePath(path2);
968
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
969
+ const localInfo = await getFileInfoLocalMode(path2);
970
+ const workspaceItem = await findWorkspaceItem(relativePath);
971
+ return {
972
+ ...localInfo,
973
+ workspaceItem: workspaceItem ? {
974
+ id: workspaceItem.id,
975
+ type: workspaceItem.type,
976
+ path: workspaceItem.path,
977
+ owner: workspaceItem.owner,
978
+ lifecycle: workspaceItem.lifecycle,
979
+ permission: workspaceItem.permission,
980
+ createdAt: workspaceItem.createdAt,
981
+ updatedAt: workspaceItem.updatedAt,
982
+ ...workspaceItem.type === "workspaceItemFile" ? {
983
+ key: workspaceItem.key,
984
+ mimeType: workspaceItem.mimeType,
985
+ size: workspaceItem.size
986
+ } : {}
987
+ } : null
988
+ };
989
+ }
990
+
991
+ // src/tools/list-directory.ts
992
+ import { existsSync as existsSync6, statSync as statSync6 } from "fs";
993
+ import { readdir } from "fs/promises";
994
+ import { join } from "path";
995
+ import { dedent as dedent7 } from "ts-dedent";
996
+ import { z as z6 } from "zod";
997
+ var toolName6 = "listDirectory";
998
+ var toolDescription6 = dedent7`
132
999
  Directory content lister with detailed file information.
133
1000
 
134
1001
  Use cases:
@@ -145,11 +1012,139 @@ Mode: Studio (Workspace API + Local filesystem)`,ie,async({path:e})=>{try{return
145
1012
 
146
1013
  Parameters:
147
1014
  - path: Directory path to list (optional, defaults to workspace root)
148
- `,de={path:z$1.string().optional()};function le(t){switch(m()){case "local":{t.tool(ce,`${pe}
1015
+ `;
1016
+ var toolInputSchema6 = {
1017
+ path: z6.string().optional()
1018
+ };
1019
+ function addListDirectoryTool(server) {
1020
+ const mode = getWorkspaceMode();
1021
+ switch (mode) {
1022
+ case "local" /* LOCAL */: {
1023
+ server.tool(
1024
+ toolName6,
1025
+ `${toolDescription6}
1026
+
1027
+ Mode: Local (Local filesystem)`,
1028
+ toolInputSchema6,
1029
+ async ({ path: path2 = "." }) => {
1030
+ try {
1031
+ return {
1032
+ content: [
1033
+ {
1034
+ type: "text",
1035
+ text: JSON.stringify(await listDirectoryLocalMode(path2))
1036
+ }
1037
+ ]
1038
+ };
1039
+ } catch (e) {
1040
+ if (e instanceof Error) {
1041
+ return {
1042
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1043
+ };
1044
+ }
1045
+ throw e;
1046
+ }
1047
+ }
1048
+ );
1049
+ break;
1050
+ }
1051
+ case "studio" /* STUDIO */: {
1052
+ server.tool(
1053
+ toolName6,
1054
+ `${toolDescription6}
149
1055
 
150
- Mode: Local (Local filesystem)`,de,async({path:e="."})=>{try{return {content:[{type:"text",text:JSON.stringify(await Pt(e))}]}}catch(r){if(r instanceof Error)return {content:[{type:"text",text:r.message}]};throw r}});break}case "studio":{t.tool(ce,`${pe}
1056
+ Mode: Studio (Workspace API)`,
1057
+ toolInputSchema6,
1058
+ async ({ path: path2 = "." }) => {
1059
+ try {
1060
+ return {
1061
+ content: [
1062
+ {
1063
+ type: "text",
1064
+ text: JSON.stringify(await listDirectoryStudioMode(path2))
1065
+ }
1066
+ ]
1067
+ };
1068
+ } catch (e) {
1069
+ if (e instanceof Error) {
1070
+ return {
1071
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1072
+ };
1073
+ }
1074
+ throw e;
1075
+ }
1076
+ }
1077
+ );
1078
+ break;
1079
+ }
1080
+ }
1081
+ }
1082
+ async function listDirectoryLocalMode(path2) {
1083
+ const validatedPath = await validatePath(path2);
1084
+ if (!existsSync6(validatedPath)) {
1085
+ throw new Error(`Directory ${path2} does not exist.`);
1086
+ }
1087
+ const stats = statSync6(validatedPath);
1088
+ if (!stats.isDirectory()) {
1089
+ throw new Error(`Path ${path2} is not a directory.`);
1090
+ }
1091
+ const entries = await readdir(validatedPath);
1092
+ const items = [];
1093
+ for (const entry of entries.sort()) {
1094
+ try {
1095
+ const fullPath = await validatePath(join(validatedPath, entry));
1096
+ const entryStats = statSync6(fullPath);
1097
+ const item = {
1098
+ name: entry,
1099
+ path: entry,
1100
+ type: entryStats.isDirectory() ? "directory" : "file",
1101
+ size: entryStats.size,
1102
+ modified: entryStats.mtime.toISOString()
1103
+ };
1104
+ items.push(item);
1105
+ } catch (e) {
1106
+ if (e instanceof Error && e.message.includes("perstack directory is not allowed")) {
1107
+ continue;
1108
+ }
1109
+ throw e;
1110
+ }
1111
+ }
1112
+ return {
1113
+ path: validatedPath,
1114
+ items
1115
+ };
1116
+ }
1117
+ async function listDirectoryStudioMode(path2) {
1118
+ const validatedPath = await validatePath(path2);
1119
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
1120
+ const workspaceItems = await getWorkspaceItems();
1121
+ const filteredItems = workspaceItems.filter((item) => {
1122
+ if (relativePath === "" || relativePath === ".") {
1123
+ return !item.path.includes("/");
1124
+ }
1125
+ const pathPrefix = relativePath.endsWith("/") ? relativePath : `${relativePath}/`;
1126
+ return item.path.startsWith(pathPrefix) && !item.path.substring(pathPrefix.length).includes("/");
1127
+ });
1128
+ return {
1129
+ path: relativePath,
1130
+ items: filteredItems.map((item) => ({
1131
+ name: item.path.split("/").pop() || item.path,
1132
+ path: item.path,
1133
+ type: item.type === "workspaceItemDirectory" ? "directory" : "file",
1134
+ size: item.type === "workspaceItemFile" ? item.size : 0,
1135
+ modified: item.updatedAt
1136
+ }))
1137
+ };
1138
+ }
151
1139
 
152
- Mode: Studio (Workspace API)`,de,async({path:e="."})=>{try{return {content:[{type:"text",text:JSON.stringify(await bt(e))}]}}catch(r){if(r instanceof Error)return {content:[{type:"text",text:r.message}]};throw r}});break}}}async function Pt(t){let o=await a(t);if(!existsSync(o))throw new Error(`Directory ${t} does not exist.`);if(!statSync(o).isDirectory())throw new Error(`Path ${t} is not a directory.`);let r=await readdir(o),i=[];for(let s of r.sort())try{let n=await a(join(o,s)),d=statSync(n),p={name:s,path:s,type:d.isDirectory()?"directory":"file",size:d.size,modified:d.mtime.toISOString()};i.push(p);}catch(n){if(n instanceof Error&&n.message.includes("perstack directory is not allowed"))continue;throw n}return i}async function bt(t){let o=await a(t),e=o.startsWith(c)?o.slice(c.length+1):o;return (await W()).filter(s=>{if(e===""||e===".")return !s.path.includes("/");let n=e.endsWith("/")?e:`${e}/`;return s.path.startsWith(n)&&!s.path.substring(n.length).includes("/")}).map(s=>({name:s.path.split("/").pop()||s.path,path:s.path,type:s.type==="workspaceItemDirectory"?"directory":"file",size:s.type==="workspaceItemFile"?s.size:0,modified:s.updatedAt}))}var ue="moveFile",he=dedent`
1140
+ // src/tools/move-file.ts
1141
+ import { existsSync as existsSync7, statSync as statSync7 } from "fs";
1142
+ import { mkdir as mkdir2, rename } from "fs/promises";
1143
+ import { dirname as dirname3 } from "path";
1144
+ import { dedent as dedent8 } from "ts-dedent";
1145
+ import { z as z7 } from "zod";
1146
+ var toolName7 = "moveFile";
1147
+ var toolDescription7 = dedent8`
153
1148
  File mover for relocating or renaming files within the workspace.
154
1149
 
155
1150
  Use cases:
@@ -167,11 +1162,140 @@ Mode: Studio (Workspace API)`,de,async({path:e="."})=>{try{return {content:[{typ
167
1162
  Parameters:
168
1163
  - source: Current file path
169
1164
  - destination: Target file path
170
- `,we={source:z$1.string(),destination:z$1.string()};function ye(t){switch(m()){case "local":{t.tool(ue,`${he}
1165
+ `;
1166
+ var toolInputSchema7 = {
1167
+ source: z7.string(),
1168
+ destination: z7.string()
1169
+ };
1170
+ function addMoveFileTool(server) {
1171
+ const mode = getWorkspaceMode();
1172
+ switch (mode) {
1173
+ case "local" /* LOCAL */: {
1174
+ server.tool(
1175
+ toolName7,
1176
+ `${toolDescription7}
1177
+
1178
+ Mode: Local (Local filesystem)`,
1179
+ toolInputSchema7,
1180
+ async ({ source, destination }) => {
1181
+ try {
1182
+ return {
1183
+ content: [
1184
+ {
1185
+ type: "text",
1186
+ text: JSON.stringify(await moveFileLocalMode(source, destination))
1187
+ }
1188
+ ]
1189
+ };
1190
+ } catch (e) {
1191
+ if (e instanceof Error) {
1192
+ return {
1193
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1194
+ };
1195
+ }
1196
+ throw e;
1197
+ }
1198
+ }
1199
+ );
1200
+ break;
1201
+ }
1202
+ case "studio" /* STUDIO */: {
1203
+ server.tool(
1204
+ toolName7,
1205
+ `${toolDescription7}
171
1206
 
172
- Mode: Local (Local filesystem)`,we,async({source:e,destination:r})=>{try{return {content:[{type:"text",text:JSON.stringify(await xe(e,r))}]}}catch(i){if(i instanceof Error)return {content:[{type:"text",text:i.message}]};throw i}});break}case "studio":{t.tool(ue,`${he}
1207
+ Mode: Studio (Workspace API)`,
1208
+ toolInputSchema7,
1209
+ async ({ source, destination }) => {
1210
+ try {
1211
+ return {
1212
+ content: [
1213
+ {
1214
+ type: "text",
1215
+ text: JSON.stringify(await moveFileStudioMode(source, destination))
1216
+ }
1217
+ ]
1218
+ };
1219
+ } catch (e) {
1220
+ if (e instanceof Error) {
1221
+ return {
1222
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1223
+ };
1224
+ }
1225
+ throw e;
1226
+ }
1227
+ }
1228
+ );
1229
+ break;
1230
+ }
1231
+ }
1232
+ }
1233
+ async function moveFileLocalMode(source, destination) {
1234
+ const validatedSource = await validatePath(source);
1235
+ const validatedDestination = await validatePath(destination);
1236
+ if (!existsSync7(validatedSource)) {
1237
+ throw new Error(`Source file ${source} does not exist.`);
1238
+ }
1239
+ const sourceStats = statSync7(validatedSource);
1240
+ if (!(sourceStats.mode & 128)) {
1241
+ throw new Error(`Source file ${source} is not writable`);
1242
+ }
1243
+ if (existsSync7(validatedDestination)) {
1244
+ throw new Error(`Destination ${destination} already exists.`);
1245
+ }
1246
+ const destDir = dirname3(validatedDestination);
1247
+ await mkdir2(destDir, { recursive: true });
1248
+ await rename(validatedSource, validatedDestination);
1249
+ return {
1250
+ source: validatedSource,
1251
+ destination: validatedDestination
1252
+ };
1253
+ }
1254
+ async function moveFileStudioMode(source, destination) {
1255
+ const validatedSource = await validatePath(source);
1256
+ const validatedDestination = await validatePath(destination);
1257
+ const relativeSource = validatedSource.startsWith(workspacePath) ? validatedSource.slice(workspacePath.length + 1) : validatedSource;
1258
+ const relativeDestination = validatedDestination.startsWith(workspacePath) ? validatedDestination.slice(workspacePath.length + 1) : validatedDestination;
1259
+ const sourceItem = await findWorkspaceItem(relativeSource);
1260
+ if (!sourceItem) {
1261
+ throw new Error(`Source file ${relativeSource} does not exist.`);
1262
+ }
1263
+ const destItem = await findWorkspaceItem(relativeDestination);
1264
+ if (destItem) {
1265
+ throw new Error(`Destination ${relativeDestination} already exists.`);
1266
+ }
1267
+ const destDir = dirname3(relativeDestination);
1268
+ if (destDir !== "." && destDir !== "/") {
1269
+ const destDirItem = await findWorkspaceItem(destDir);
1270
+ if (!destDirItem) {
1271
+ await createWorkspaceItem({
1272
+ type: "workspaceItemDirectory",
1273
+ path: destDir,
1274
+ owner: "expert",
1275
+ lifecycle: "expertJob",
1276
+ permission: "readWrite"
1277
+ });
1278
+ }
1279
+ }
1280
+ await updateWorkspaceItem(sourceItem.id, {
1281
+ path: relativeDestination
1282
+ });
1283
+ await moveFileLocalMode(source, destination);
1284
+ return {
1285
+ source: relativeSource,
1286
+ destination: relativeDestination
1287
+ };
1288
+ }
173
1289
 
174
- Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {content:[{type:"text",text:JSON.stringify(await Ot(e,r))}]}}catch(i){if(i instanceof Error)return {content:[{type:"text",text:i.message}]};throw i}});break}}}async function xe(t,o){let e=await a(t),r=await a(o);if(!existsSync(e))throw new Error(`Source file ${t} does not exist.`);if(!(statSync(e).mode&128))throw new Error(`Source file ${t} is not writable`);if(existsSync(r))throw new Error(`Destination ${o} already exists.`);let s=dirname(r);return await mkdir(s,{recursive:true}),await rename(e,r),r}async function Ot(t,o){let e=await a(t),r=await a(o),i=e.startsWith(c)?e.slice(c.length+1):e,s=r.startsWith(c)?r.slice(c.length+1):r,n=await l(i);if(!n)throw new Error(`Source file ${i} does not exist.`);if(await l(s))throw new Error(`Destination ${s} already exists.`);let p=dirname(s);return p!=="."&&p!=="/"&&(await l(p)||await f({type:"workspaceItemDirectory",path:p,permission:"readWrite"})),await A(n.id,{path:s}),await xe(t,o),s}var Te=15*1024*1024,$t="readImageFile",Ct=dedent`
1290
+ // src/tools/read-image-file.ts
1291
+ import { existsSync as existsSync8 } from "fs";
1292
+ import { stat } from "fs/promises";
1293
+ import mime3 from "mime-types";
1294
+ import { dedent as dedent9 } from "ts-dedent";
1295
+ import { z as z8 } from "zod";
1296
+ var MAX_IMAGE_SIZE = 15 * 1024 * 1024;
1297
+ var toolName8 = "readImageFile";
1298
+ var toolDescription8 = dedent9`
175
1299
  Image file reader that converts images to base64 encoded strings with MIME type validation.
176
1300
 
177
1301
  Use cases:
@@ -193,7 +1317,64 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
193
1317
 
194
1318
  Notes:
195
1319
  - Maximum file size: 15MB (larger files will be rejected)
196
- `,zt={path:z$1.string()};function ke(t){t.tool($t,Ct,zt,async({path:o})=>{try{return {content:[{type:"text",text:JSON.stringify(await jt(o))}]}}catch(e){if(e instanceof Error)return {content:[{type:"text",text:e.message}]};throw e}});}async function jt(t){let o=await a(t);if(!existsSync(o))throw new Error(`File ${t} does not exist.`);let r=$e.lookup(o);if(!r||!["image/png","image/jpeg","image/gif","image/webp"].includes(r))throw new Error(`File ${t} is not supported.`);let i=await stat(o),s=i.size/(1024*1024);if(i.size>Te)throw new Error(`Image file too large (${s.toFixed(1)}MB). Maximum supported size is ${Te/(1024*1024)}MB. Please use a smaller image file.`);return {path:o,mimeType:r,size:i.size}}var Ie=30*1024*1024,Vt="readPdfFile",_t=dedent`
1320
+ `;
1321
+ var toolInputSchema8 = {
1322
+ path: z8.string()
1323
+ };
1324
+ function addReadImageFileTool(server) {
1325
+ server.tool(toolName8, toolDescription8, toolInputSchema8, async ({ path: path2 }) => {
1326
+ try {
1327
+ return {
1328
+ content: [
1329
+ {
1330
+ type: "text",
1331
+ text: JSON.stringify(await readImageFile(path2))
1332
+ }
1333
+ ]
1334
+ };
1335
+ } catch (e) {
1336
+ if (e instanceof Error) {
1337
+ return {
1338
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1339
+ };
1340
+ }
1341
+ throw e;
1342
+ }
1343
+ });
1344
+ }
1345
+ async function readImageFile(path2) {
1346
+ const validatedPath = await validatePath(path2);
1347
+ const isFile = existsSync8(validatedPath);
1348
+ if (!isFile) {
1349
+ throw new Error(`File ${path2} does not exist.`);
1350
+ }
1351
+ const mimeType = mime3.lookup(validatedPath);
1352
+ if (!mimeType || !["image/png", "image/jpeg", "image/gif", "image/webp"].includes(mimeType)) {
1353
+ throw new Error(`File ${path2} is not supported.`);
1354
+ }
1355
+ const fileStats = await stat(validatedPath);
1356
+ const fileSizeMB = fileStats.size / (1024 * 1024);
1357
+ if (fileStats.size > MAX_IMAGE_SIZE) {
1358
+ throw new Error(
1359
+ `Image file too large (${fileSizeMB.toFixed(1)}MB). Maximum supported size is ${MAX_IMAGE_SIZE / (1024 * 1024)}MB. Please use a smaller image file.`
1360
+ );
1361
+ }
1362
+ return {
1363
+ path: validatedPath,
1364
+ mimeType,
1365
+ size: fileStats.size
1366
+ };
1367
+ }
1368
+
1369
+ // src/tools/read-pdf-file.ts
1370
+ import { existsSync as existsSync9 } from "fs";
1371
+ import { stat as stat2 } from "fs/promises";
1372
+ import mime4 from "mime-types";
1373
+ import { dedent as dedent10 } from "ts-dedent";
1374
+ import { z as z9 } from "zod";
1375
+ var MAX_PDF_SIZE = 30 * 1024 * 1024;
1376
+ var toolName9 = "readPdfFile";
1377
+ var toolDescription9 = dedent10`
197
1378
  PDF file reader that converts documents to base64 encoded resources.
198
1379
 
199
1380
  Use cases:
@@ -211,7 +1392,62 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
211
1392
  - Returns entire PDF content, no page range support
212
1393
  - Maximum file size: 10MB (larger files will be rejected)
213
1394
  - Text extraction not performed, returns raw PDF data
214
- `,qt={path:z$1.string()};function Se(t){t.tool(Vt,_t,qt,async({path:o})=>{try{return {content:[{type:"text",text:JSON.stringify(await Xt(o))}]}}catch(e){if(e instanceof Error)return {content:[{type:"text",text:e.message}]};throw e}});}async function Xt(t){let o=await a(t);if(!existsSync(o))throw new Error(`File ${t} does not exist.`);let r=$e.lookup(o);if(r!=="application/pdf")throw new Error(`File ${t} is not a PDF file.`);let i=await stat(o),s=i.size/(1024*1024);if(i.size>Ie)throw new Error(`PDF file too large (${s.toFixed(1)}MB). Maximum supported size is ${Ie/(1024*1024)}MB. Please use a smaller PDF file.`);return {path:o,mimeType:r,size:i.size}}var eo="readTextFile",to=dedent`
1395
+ `;
1396
+ var toolInputSchema9 = {
1397
+ path: z9.string()
1398
+ };
1399
+ function addReadPdfFileTool(server) {
1400
+ server.tool(toolName9, toolDescription9, toolInputSchema9, async ({ path: path2 }) => {
1401
+ try {
1402
+ return {
1403
+ content: [
1404
+ {
1405
+ type: "text",
1406
+ text: JSON.stringify(await readPdfFile(path2))
1407
+ }
1408
+ ]
1409
+ };
1410
+ } catch (e) {
1411
+ if (e instanceof Error) {
1412
+ return {
1413
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1414
+ };
1415
+ }
1416
+ throw e;
1417
+ }
1418
+ });
1419
+ }
1420
+ async function readPdfFile(path2) {
1421
+ const validatedPath = await validatePath(path2);
1422
+ const isFile = existsSync9(validatedPath);
1423
+ if (!isFile) {
1424
+ throw new Error(`File ${path2} does not exist.`);
1425
+ }
1426
+ const mimeType = mime4.lookup(validatedPath);
1427
+ if (mimeType !== "application/pdf") {
1428
+ throw new Error(`File ${path2} is not a PDF file.`);
1429
+ }
1430
+ const fileStats = await stat2(validatedPath);
1431
+ const fileSizeMB = fileStats.size / (1024 * 1024);
1432
+ if (fileStats.size > MAX_PDF_SIZE) {
1433
+ throw new Error(
1434
+ `PDF file too large (${fileSizeMB.toFixed(1)}MB). Maximum supported size is ${MAX_PDF_SIZE / (1024 * 1024)}MB. Please use a smaller PDF file.`
1435
+ );
1436
+ }
1437
+ return {
1438
+ path: validatedPath,
1439
+ mimeType,
1440
+ size: fileStats.size
1441
+ };
1442
+ }
1443
+
1444
+ // src/tools/read-text-file.ts
1445
+ import { existsSync as existsSync10 } from "fs";
1446
+ import { readFile as readFile4 } from "fs/promises";
1447
+ import { dedent as dedent11 } from "ts-dedent";
1448
+ import { z as z10 } from "zod";
1449
+ var toolName10 = "readTextFile";
1450
+ var toolDescription10 = dedent11`
215
1451
  Text file reader with line range support for UTF-8 encoded files.
216
1452
 
217
1453
  Use cases:
@@ -231,9 +1467,58 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
231
1467
  - Documentation: .md, .txt, .rst
232
1468
  - Configuration: .json, .yaml, .toml, .ini
233
1469
  - Data files: .csv, .log, .sql
234
- `,oo={path:z$1.string(),from:z$1.number().optional().describe("The line number to start reading from."),to:z$1.number().optional().describe("The line number to stop reading at.")};function Ee(t){t.tool(eo,to,oo,async({path:o,from:e,to:r})=>{try{return {content:[{type:"text",text:JSON.stringify(await ro(o,e,r))}]}}catch(i){if(i instanceof Error)return {content:[{type:"text",text:i.message}]};throw i}});}async function ro(t,o,e){let r=await a(t);if(!existsSync(r))throw new Error(`File ${t} does not exist.`);let n=(await readFile(r,"utf-8")).split(`
235
- `),d=o??0,p=e??n.length,T=n.slice(d,p).join(`
236
- `);return {path:t,content:T,from:d,to:p}}var so="testUrl",no=dedent`
1470
+ `;
1471
+ var toolInputSchema10 = {
1472
+ path: z10.string(),
1473
+ from: z10.number().optional().describe("The line number to start reading from."),
1474
+ to: z10.number().optional().describe("The line number to stop reading at.")
1475
+ };
1476
+ function addReadTextFileTool(server) {
1477
+ server.tool(toolName10, toolDescription10, toolInputSchema10, async ({ path: path2, from, to }) => {
1478
+ try {
1479
+ return {
1480
+ content: [
1481
+ {
1482
+ type: "text",
1483
+ text: JSON.stringify(await readTextFile(path2, from, to))
1484
+ }
1485
+ ]
1486
+ };
1487
+ } catch (e) {
1488
+ if (e instanceof Error) {
1489
+ return {
1490
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1491
+ };
1492
+ }
1493
+ throw e;
1494
+ }
1495
+ });
1496
+ }
1497
+ async function readTextFile(path2, from, to) {
1498
+ const validatedPath = await validatePath(path2);
1499
+ const isFile = existsSync10(validatedPath);
1500
+ if (!isFile) {
1501
+ throw new Error(`File ${path2} does not exist.`);
1502
+ }
1503
+ const fileContent = await readFile4(validatedPath, "utf-8");
1504
+ const lines = fileContent.split("\n");
1505
+ const fromLine = from ?? 0;
1506
+ const toLine = to ?? lines.length;
1507
+ const selectedLines = lines.slice(fromLine, toLine);
1508
+ const content = selectedLines.join("\n");
1509
+ return {
1510
+ path: path2,
1511
+ content,
1512
+ from: fromLine,
1513
+ to: toLine
1514
+ };
1515
+ }
1516
+
1517
+ // src/tools/test-url.ts
1518
+ import { dedent as dedent12 } from "ts-dedent";
1519
+ import { z as z11 } from "zod";
1520
+ var toolName11 = "testUrl";
1521
+ var toolDescription11 = dedent12`
237
1522
  URL tester that validates multiple URLs and extracts metadata.
238
1523
 
239
1524
  Use cases:
@@ -253,7 +1538,137 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
253
1538
  - Maximum 10 URLs per request to prevent abuse
254
1539
  - 10 second timeout per URL request
255
1540
  - Returns empty title/description if HTML parsing fails
256
- `,ao={urls:z$1.array(z$1.string()).min(1).max(10).describe("Array of URLs to test (max 10 URLs).")};function Pe(t){t.tool(so,no,ao,async({urls:o})=>{try{let e=await co(o);return {content:[{type:"text",text:JSON.stringify(e,null,2)}]}}catch(e){if(e instanceof Error)return {content:[{type:"text",text:e.message}]};throw e}});}async function co(t){return (await Promise.allSettled(t.map(async e=>{try{let r=new AbortController,i=setTimeout(()=>r.abort(),1e4),s=await fetch(e,{method:"GET",signal:r.signal,headers:{"User-Agent":"Perstack URL Tester/1.0"}});clearTimeout(i);let n="",d="";if(s.ok&&s.headers.get("content-type")?.includes("text/html"))try{let p=await s.text();n=po(p),d=lo(p);}catch{}return {url:e,status:s.status,title:n,description:d}}catch(r){return {url:e,status:0,title:"",description:r instanceof Error?r.message:"Unknown error"}}}))).map(e=>e.status==="fulfilled"?e.value:{url:"unknown",status:0,title:"",description:"Promise rejected"})}function po(t){let o=t.match(/<title[^>]*>([^<]*)/i);return o?o[1].trim():""}function lo(t){let o=t.match(/<meta[^>]*name=["']description["'][^>]*content=["']([^"']*)["']/i);if(o)return o[1].trim();let e=t.match(/<meta[^>]*property=["']og:description["'][^>]*content=["']([^"']*)["']/i);return e?e[1].trim():""}var fo=z$1.object({thought:z$1.string().describe("Your current thinking step"),nextThoughtNeeded:z$1.boolean().optional().describe("true if you need more thinking, even if at what seemed like the end")}),v=class{thoughtHistory=[];branches={};processThought(o){let{nextThoughtNeeded:e}=o;return this.thoughtHistory.push(o),{content:[{type:"text",text:JSON.stringify({nextThoughtNeeded:e,thoughtHistoryLength:this.thoughtHistory.length})}]}}};function be(t){let o=new v;t.tool("think",dedent`
1541
+ `;
1542
+ var toolInputSchema11 = {
1543
+ urls: z11.array(z11.string()).min(1).max(10).describe("Array of URLs to test (max 10 URLs).")
1544
+ };
1545
+ function addTestUrlTool(server) {
1546
+ server.tool(toolName11, toolDescription11, toolInputSchema11, async ({ urls }) => {
1547
+ try {
1548
+ const results = await testUrls(urls);
1549
+ return {
1550
+ content: [
1551
+ {
1552
+ type: "text",
1553
+ text: JSON.stringify(results, null, 2)
1554
+ }
1555
+ ]
1556
+ };
1557
+ } catch (e) {
1558
+ if (e instanceof Error) {
1559
+ return {
1560
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1561
+ };
1562
+ }
1563
+ throw e;
1564
+ }
1565
+ });
1566
+ }
1567
+ async function testUrls(urls) {
1568
+ const results = await Promise.allSettled(
1569
+ urls.map(async (url) => {
1570
+ try {
1571
+ const controller = new AbortController();
1572
+ const timeoutId = setTimeout(() => controller.abort(), 1e4);
1573
+ const response = await fetch(url, {
1574
+ method: "GET",
1575
+ signal: controller.signal,
1576
+ headers: {
1577
+ "User-Agent": "Perstack URL Tester/1.0"
1578
+ }
1579
+ });
1580
+ clearTimeout(timeoutId);
1581
+ let title = "";
1582
+ let description = "";
1583
+ if (response.ok && response.headers.get("content-type")?.includes("text/html")) {
1584
+ try {
1585
+ const html = await response.text();
1586
+ title = extractTitle(html);
1587
+ description = extractDescription(html);
1588
+ } catch {
1589
+ }
1590
+ }
1591
+ return {
1592
+ url,
1593
+ status: response.status,
1594
+ title,
1595
+ description
1596
+ };
1597
+ } catch (error) {
1598
+ return {
1599
+ url,
1600
+ status: 0,
1601
+ title: "",
1602
+ description: error instanceof Error ? error.message : "Unknown error"
1603
+ };
1604
+ }
1605
+ })
1606
+ );
1607
+ return {
1608
+ results: results.map((result) => {
1609
+ if (result.status === "fulfilled") {
1610
+ return result.value;
1611
+ }
1612
+ return {
1613
+ url: "unknown",
1614
+ status: 0,
1615
+ title: "",
1616
+ description: "Promise rejected"
1617
+ };
1618
+ })
1619
+ };
1620
+ }
1621
+ function extractTitle(html) {
1622
+ const titleMatch = html.match(/<title[^>]*>([^<]*)/i);
1623
+ return titleMatch ? titleMatch[1].trim() : "";
1624
+ }
1625
+ function extractDescription(html) {
1626
+ const metaDescMatch = html.match(
1627
+ /<meta[^>]*name=["']description["'][^>]*content=["']([^"']*)["']/i
1628
+ );
1629
+ if (metaDescMatch) {
1630
+ return metaDescMatch[1].trim();
1631
+ }
1632
+ const ogDescMatch = html.match(
1633
+ /<meta[^>]*property=["']og:description["'][^>]*content=["']([^"']*)["']/i
1634
+ );
1635
+ if (ogDescMatch) {
1636
+ return ogDescMatch[1].trim();
1637
+ }
1638
+ return "";
1639
+ }
1640
+
1641
+ // src/tools/think.ts
1642
+ import { dedent as dedent13 } from "ts-dedent";
1643
+ import { z as z12 } from "zod";
1644
+ var ThoughtInputSchema = z12.object({
1645
+ thought: z12.string().describe("Your current thinking step"),
1646
+ nextThoughtNeeded: z12.boolean().optional().describe("true if you need more thinking, even if at what seemed like the end")
1647
+ });
1648
+ var Thought = class {
1649
+ thoughtHistory = [];
1650
+ branches = {};
1651
+ processThought(input) {
1652
+ const { nextThoughtNeeded } = input;
1653
+ this.thoughtHistory.push(input);
1654
+ return {
1655
+ content: [
1656
+ {
1657
+ type: "text",
1658
+ text: JSON.stringify({
1659
+ nextThoughtNeeded,
1660
+ thoughtHistoryLength: this.thoughtHistory.length
1661
+ })
1662
+ }
1663
+ ]
1664
+ };
1665
+ }
1666
+ };
1667
+ function addThinkTool(server) {
1668
+ const thought = new Thought();
1669
+ server.tool(
1670
+ "think",
1671
+ dedent13`
257
1672
  Sequential thinking tool for step-by-step problem analysis and solution development.
258
1673
 
259
1674
  Use cases:
@@ -278,7 +1693,54 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
278
1693
  - Capture insights and eureka moments as they emerge
279
1694
  - Engage in reflective introspection and constructive self-critique
280
1695
  - Set nextThoughtNeeded to false only when fully satisfied with the solution
281
- `,fo.shape,async e=>o.processThought(e));}var ho=z$1.object({newTodos:z$1.array(z$1.string()).describe("New todos to add").optional(),completedTodos:z$1.array(z$1.number()).describe("Todo ids that are completed").optional()}),P=class{currentTodoId=0;todos=[];processTodo(o){let{newTodos:e,completedTodos:r}=o;return e&&this.todos.push(...e.map(i=>({id:this.currentTodoId++,title:i,completed:false}))),r&&(this.todos=this.todos.map(i=>({...i,completed:i.completed||r.includes(i.id)}))),{content:[{type:"text",text:JSON.stringify({todos:this.todos})}]}}};function Me(t){let o=new P;t.tool("todo",dedent`
1696
+ `,
1697
+ ThoughtInputSchema.shape,
1698
+ async (input) => {
1699
+ return thought.processThought(input);
1700
+ }
1701
+ );
1702
+ }
1703
+
1704
+ // src/tools/todo.ts
1705
+ import { dedent as dedent14 } from "ts-dedent";
1706
+ import { z as z13 } from "zod";
1707
+ var TodoInputSchema = z13.object({
1708
+ newTodos: z13.array(z13.string()).describe("New todos to add").optional(),
1709
+ completedTodos: z13.array(z13.number()).describe("Todo ids that are completed").optional()
1710
+ });
1711
+ var Todo = class {
1712
+ currentTodoId = 0;
1713
+ todos = [];
1714
+ processTodo(input) {
1715
+ const { newTodos, completedTodos } = input;
1716
+ if (newTodos) {
1717
+ this.todos.push(
1718
+ ...newTodos.map((title) => ({ id: this.currentTodoId++, title, completed: false }))
1719
+ );
1720
+ }
1721
+ if (completedTodos) {
1722
+ this.todos = this.todos.map((todo) => ({
1723
+ ...todo,
1724
+ completed: todo.completed || completedTodos.includes(todo.id)
1725
+ }));
1726
+ }
1727
+ return {
1728
+ content: [
1729
+ {
1730
+ type: "text",
1731
+ text: JSON.stringify({
1732
+ todos: this.todos
1733
+ })
1734
+ }
1735
+ ]
1736
+ };
1737
+ }
1738
+ };
1739
+ function addTodoTool(server) {
1740
+ const todo = new Todo();
1741
+ server.tool(
1742
+ "todo",
1743
+ dedent14`
282
1744
  Todo list manager that tracks tasks and their completion status.
283
1745
 
284
1746
  Use cases:
@@ -294,7 +1756,23 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
294
1756
  Parameters:
295
1757
  - newTodos: Array of task descriptions to add
296
1758
  - completedTodos: Array of todo IDs to mark as completed
297
- `,ho.shape,async e=>o.processTodo(e));}var Ae="writeTextFile",We=dedent`
1759
+ `,
1760
+ TodoInputSchema.shape,
1761
+ async (input) => {
1762
+ return todo.processTodo(input);
1763
+ }
1764
+ );
1765
+ }
1766
+
1767
+ // src/tools/write-text-file.ts
1768
+ import { existsSync as existsSync11, statSync as statSync8 } from "fs";
1769
+ import { writeFile as writeFile2 } from "fs/promises";
1770
+ import { mkdir as mkdir3 } from "fs/promises";
1771
+ import { dirname as dirname4 } from "path";
1772
+ import { dedent as dedent15 } from "ts-dedent";
1773
+ import { z as z14 } from "zod";
1774
+ var toolName12 = "writeTextFile";
1775
+ var toolDescription12 = dedent15`
298
1776
  Text file writer that creates or overwrites files with UTF-8 content.
299
1777
 
300
1778
  Use cases:
@@ -312,9 +1790,166 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
312
1790
  - YOU MUST PROVIDE A VALID UTF-8 STRING FOR THE TEXT
313
1791
  - THERE IS A LIMIT ON THE NUMBER OF TOKENS THAT CAN BE GENERATED, SO DO NOT WRITE ALL THE CONTENT AT ONCE (IT WILL CAUSE AN ERROR)
314
1792
  - IF YOU WANT TO WRITE MORE THAN 2000 CHARACTERS, USE "appendTextFile" TOOL AFTER THIS ONE
315
- `,Oe={path:z$1.string().describe("Target file path (relative or absolute)."),text:z$1.string().min(1).max(2e3).describe("Text to write to the file. Max 2000 characters.")};function De(t){switch(m()){case "local":{t.tool(Ae,`${We}
1793
+ `;
1794
+ var toolInputSchema12 = {
1795
+ path: z14.string().describe("Target file path (relative or absolute)."),
1796
+ text: z14.string().min(1).max(2e3).describe("Text to write to the file. Max 2000 characters.")
1797
+ };
1798
+ function addWriteTextFileTool(server) {
1799
+ const mode = getWorkspaceMode();
1800
+ switch (mode) {
1801
+ case "local" /* LOCAL */: {
1802
+ server.tool(
1803
+ toolName12,
1804
+ `${toolDescription12}
1805
+
1806
+ Mode: Local (Local filesystem)`,
1807
+ toolInputSchema12,
1808
+ async ({ path: path2, text }) => {
1809
+ try {
1810
+ return {
1811
+ content: [
1812
+ {
1813
+ type: "text",
1814
+ text: JSON.stringify(await writeTextFileLocalMode(path2, text))
1815
+ }
1816
+ ]
1817
+ };
1818
+ } catch (e) {
1819
+ if (e instanceof Error) {
1820
+ return {
1821
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1822
+ };
1823
+ }
1824
+ throw e;
1825
+ }
1826
+ }
1827
+ );
1828
+ break;
1829
+ }
1830
+ case "studio" /* STUDIO */: {
1831
+ server.tool(
1832
+ toolName12,
1833
+ `${toolDescription12}
316
1834
 
317
- Mode: Local (Local filesystem)`,Oe,async({path:e,text:r})=>{try{return {content:[{type:"text",text:JSON.stringify(await Re(e,r))}]}}catch(i){if(i instanceof Error)return {content:[{type:"text",text:i.message}]};throw i}});break}case "studio":{t.tool(Ae,`${We}
1835
+ Mode: Studio (Workspace API)`,
1836
+ toolInputSchema12,
1837
+ async ({ path: path2, text }) => {
1838
+ try {
1839
+ return {
1840
+ content: [
1841
+ {
1842
+ type: "text",
1843
+ text: JSON.stringify(await writeTextFileStudioMode(path2, text))
1844
+ }
1845
+ ]
1846
+ };
1847
+ } catch (e) {
1848
+ if (e instanceof Error) {
1849
+ return {
1850
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1851
+ };
1852
+ }
1853
+ throw e;
1854
+ }
1855
+ }
1856
+ );
1857
+ break;
1858
+ }
1859
+ }
1860
+ }
1861
+ async function writeTextFileLocalMode(path2, text) {
1862
+ const validatedPath = await validatePath(path2);
1863
+ if (existsSync11(validatedPath)) {
1864
+ const stats = statSync8(validatedPath);
1865
+ if (!(stats.mode & 128)) {
1866
+ throw new Error(`File ${path2} is not writable`);
1867
+ }
1868
+ }
1869
+ const dir = dirname4(validatedPath);
1870
+ await mkdir3(dir, { recursive: true });
1871
+ await writeFile2(validatedPath, text, "utf-8");
1872
+ return {
1873
+ path: validatedPath,
1874
+ text
1875
+ };
1876
+ }
1877
+ async function writeTextFileStudioMode(path2, text) {
1878
+ const validatedPath = await validatePath(path2);
1879
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
1880
+ const existingItem = await findWorkspaceItem(relativePath);
1881
+ if (existingItem) {
1882
+ if (existingItem.type === "workspaceItemDirectory") {
1883
+ throw new Error(`Path ${relativePath} is a directory`);
1884
+ }
1885
+ throw new Error("Updating existing file content is not supported yet");
1886
+ }
1887
+ const pathParts = relativePath.split("/").filter((part) => part !== "");
1888
+ for (let i = 1; i < pathParts.length; i++) {
1889
+ const currentPath = pathParts.slice(0, i).join("/");
1890
+ if (currentPath === "") continue;
1891
+ const existingParent = await findWorkspaceItem(currentPath);
1892
+ if (!existingParent) {
1893
+ await createWorkspaceItem({
1894
+ type: "workspaceItemDirectory",
1895
+ path: currentPath,
1896
+ owner: "expert",
1897
+ lifecycle: "expertJob",
1898
+ permission: "readWrite"
1899
+ });
1900
+ }
1901
+ }
1902
+ await createWorkspaceItem(
1903
+ {
1904
+ type: "workspaceItemFile",
1905
+ path: relativePath,
1906
+ owner: "expert",
1907
+ lifecycle: "expertJob",
1908
+ permission: "readWrite"
1909
+ },
1910
+ text
1911
+ );
1912
+ await writeTextFileLocalMode(path2, text);
1913
+ return {
1914
+ path: relativePath,
1915
+ text
1916
+ };
1917
+ }
318
1918
 
319
- Mode: Studio (Workspace API)`,Oe,async({path:e,text:r})=>{try{return {content:[{type:"text",text:JSON.stringify(await Io(e,r))}]}}catch(i){if(i instanceof Error)return {content:[{type:"text",text:i.message}]};throw i}});break}}}async function Re(t,o){let e=await a(t);if(existsSync(e)&&!(statSync(e).mode&128))throw new Error(`File ${t} is not writable`);let r=dirname(e);return await mkdir(r,{recursive:true}),await writeFile(e,o,"utf-8"),{path:e}}async function Io(t,o){let e=await a(t),r=e.startsWith(c)?e.slice(c.length+1):e,i=await l(r);if(i)throw i.type==="workspaceItemDirectory"?new Error(`Path ${r} is a directory`):new Error("Updating existing file content is not supported yet");let s=r.split("/").filter(n=>n!=="");for(let n=1;n<s.length;n++){let d=s.slice(0,n).join("/");if(d==="")continue;await l(d)||await f({type:"workspaceItemDirectory",path:d,permission:"readWrite"});}return await f({type:"workspaceItemFile",path:r,permission:"readWrite"},o),await Re(t,o),{path:r}}async function Po(){let t=new Command;t.name(h.name).description(h.description).version(h.version,"-v, --version","display the version number").action(async()=>{let o=new McpServer({name:h.name,version:h.version},{capabilities:{tools:{}}});$(o),be(o),Me(o),ke(o),Se(o),Ee(o),ee(o),N(o),_(o),ye(o),se(o),De(o),J(o),le(o),Pe(o);let e=new StdioServerTransport;await o.connect(e);}),t.parse();}Po();//# sourceMappingURL=index.js.map
1919
+ // src/index.ts
1920
+ async function main() {
1921
+ const program = new Command();
1922
+ program.name(package_default.name).description(package_default.description).version(package_default.version, "-v, --version", "display the version number").action(async () => {
1923
+ const server = new McpServer(
1924
+ {
1925
+ name: package_default.name,
1926
+ version: package_default.version
1927
+ },
1928
+ {
1929
+ capabilities: {
1930
+ tools: {}
1931
+ }
1932
+ }
1933
+ );
1934
+ addAttemptCompletionTool(server);
1935
+ addThinkTool(server);
1936
+ addTodoTool(server);
1937
+ addReadImageFileTool(server);
1938
+ addReadPdfFileTool(server);
1939
+ addReadTextFileTool(server);
1940
+ addEditTextFileTool(server);
1941
+ addAppendTextFileTool(server);
1942
+ addDeleteFileTool(server);
1943
+ addMoveFileTool(server);
1944
+ addGetFileInfoTool(server);
1945
+ addWriteTextFileTool(server);
1946
+ addCreateDirectoryTool(server);
1947
+ addListDirectoryTool(server);
1948
+ addTestUrlTool(server);
1949
+ const transport = new StdioServerTransport();
1950
+ await server.connect(transport);
1951
+ });
1952
+ program.parse();
1953
+ }
1954
+ main();
320
1955
  //# sourceMappingURL=index.js.map