@perstack/base 0.0.1 → 0.0.3

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.1",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);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.3",
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,118 @@ 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 validatedPath;
355
+ }
356
+ async function appendTextFileStudioMode(path2, text) {
357
+ const validatedPath = await validatePath(path2);
358
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
359
+ const existingItem = await findWorkspaceItem(relativePath);
360
+ if (!existingItem) {
361
+ throw new Error(`File ${relativePath} does not exist.`);
362
+ }
363
+ if (existingItem.type === "workspaceItemDirectory") {
364
+ throw new Error(`Path ${relativePath} is a directory.`);
365
+ }
366
+ await appendTextFileLocalMode(path2, text);
367
+ await deleteWorkspaceItem(existingItem.id);
368
+ const content = await readFile(validatedPath, "utf-8");
369
+ await createWorkspaceItem(
370
+ {
371
+ type: "workspaceItemFile",
372
+ path: relativePath,
373
+ owner: "expert",
374
+ lifecycle: "expertJob",
375
+ permission: "readWrite"
376
+ },
377
+ content
378
+ );
379
+ return relativePath;
380
+ }
381
+
382
+ // src/tools/attempt-completion.ts
383
+ import { dedent as dedent2 } from "ts-dedent";
384
+ var addAttemptCompletionTool = (server) => {
385
+ server.tool(
386
+ "attemptCompletion",
387
+ dedent2`
28
388
  Task completion signal that triggers immediate final report generation.
29
389
  Use cases:
30
390
  - Signaling task completion to Perstack runtime
@@ -39,7 +399,30 @@ Mode: Studio (Workspace API)`,L,async({path:e,text:r})=>{try{return {content:[{t
39
399
  - Triggers immediate transition to final report
40
400
  - Should only be used when task is fully complete
41
401
  - 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`
402
+ `,
403
+ {},
404
+ attemptCompletion
405
+ );
406
+ };
407
+ async function attemptCompletion() {
408
+ return {
409
+ content: [
410
+ {
411
+ type: "text",
412
+ text: "End the agent loop and provide a final report"
413
+ }
414
+ ]
415
+ };
416
+ }
417
+
418
+ // src/tools/create-directory.ts
419
+ import { existsSync as existsSync2, statSync as statSync2 } from "fs";
420
+ import { mkdir } from "fs/promises";
421
+ import { dirname } from "path";
422
+ import { dedent as dedent3 } from "ts-dedent";
423
+ import { z as z2 } from "zod";
424
+ var toolName2 = "createDirectory";
425
+ var toolDescription2 = dedent3`
43
426
  Directory creator for establishing folder structures in the workspace.
44
427
 
45
428
  Use cases:
@@ -56,11 +439,122 @@ Mode: Studio (Workspace API)`,L,async({path:e,text:r})=>{try{return {content:[{t
56
439
 
57
440
  Parameters:
58
441
  - path: Directory path to create
59
- `,H={path:z$1.string()};function J(t){switch(m()){case "local":{t.tool(z,`${j}
442
+ `;
443
+ var toolInputSchema2 = {
444
+ path: z2.string()
445
+ };
446
+ function addCreateDirectoryTool(server) {
447
+ const mode = getWorkspaceMode();
448
+ switch (mode) {
449
+ case "local" /* LOCAL */: {
450
+ server.tool(
451
+ toolName2,
452
+ `${toolDescription2}
453
+
454
+ Mode: Local (Local filesystem)`,
455
+ toolInputSchema2,
456
+ async ({ path: path2 }) => {
457
+ try {
458
+ return {
459
+ content: [
460
+ {
461
+ type: "text",
462
+ text: JSON.stringify(await createDirectoryLocalMode(path2))
463
+ }
464
+ ]
465
+ };
466
+ } catch (e) {
467
+ if (e instanceof Error) {
468
+ return {
469
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
470
+ };
471
+ }
472
+ throw e;
473
+ }
474
+ }
475
+ );
476
+ break;
477
+ }
478
+ case "studio" /* STUDIO */: {
479
+ server.tool(
480
+ toolName2,
481
+ `${toolDescription2}
60
482
 
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}
483
+ Mode: Studio (Workspace API)`,
484
+ toolInputSchema2,
485
+ async ({ path: path2 }) => {
486
+ try {
487
+ return {
488
+ content: [
489
+ {
490
+ type: "text",
491
+ text: JSON.stringify(await createDirectoryStudioMode(path2))
492
+ }
493
+ ]
494
+ };
495
+ } catch (e) {
496
+ if (e instanceof Error) {
497
+ return {
498
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
499
+ };
500
+ }
501
+ throw e;
502
+ }
503
+ }
504
+ );
505
+ break;
506
+ }
507
+ }
508
+ }
509
+ async function createDirectoryLocalMode(path2) {
510
+ const validatedPath = await validatePath(path2);
511
+ const exists = existsSync2(validatedPath);
512
+ if (exists) {
513
+ throw new Error(`Directory ${path2} already exists`);
514
+ }
515
+ const parentDir = dirname(validatedPath);
516
+ if (existsSync2(parentDir)) {
517
+ const parentStats = statSync2(parentDir);
518
+ if (!(parentStats.mode & 128)) {
519
+ throw new Error(`Parent directory ${parentDir} is not writable`);
520
+ }
521
+ }
522
+ await mkdir(validatedPath, { recursive: true });
523
+ return validatedPath;
524
+ }
525
+ async function createDirectoryStudioMode(path2) {
526
+ const validatedPath = await validatePath(path2);
527
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
528
+ const existingItem = await findWorkspaceItem(relativePath);
529
+ if (existingItem) {
530
+ throw new Error(`Directory ${relativePath} already exists`);
531
+ }
532
+ const pathParts = relativePath.split("/").filter((part) => part !== "");
533
+ for (let i = 1; i <= pathParts.length; i++) {
534
+ const currentPath = pathParts.slice(0, i).join("/");
535
+ if (currentPath === "") continue;
536
+ const existingParent = await findWorkspaceItem(currentPath);
537
+ if (!existingParent) {
538
+ await createWorkspaceItem({
539
+ type: "workspaceItemDirectory",
540
+ path: currentPath,
541
+ owner: "expert",
542
+ lifecycle: "expertJob",
543
+ permission: "readWrite"
544
+ });
545
+ }
546
+ }
547
+ await createDirectoryLocalMode(path2);
548
+ return relativePath;
549
+ }
62
550
 
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`
551
+ // src/tools/delete-file.ts
552
+ import { existsSync as existsSync3, statSync as statSync3 } from "fs";
553
+ import { unlink } from "fs/promises";
554
+ import { dedent as dedent4 } from "ts-dedent";
555
+ import { z as z3 } from "zod";
556
+ var toolName3 = "deleteFile";
557
+ var toolDescription3 = dedent4`
64
558
  File deleter for removing files from the workspace.
65
559
 
66
560
  Use cases:
@@ -77,11 +571,110 @@ Mode: Studio (Workspace API)`,H,async({path:e})=>{try{return {content:[{type:"te
77
571
 
78
572
  Parameters:
79
573
  - path: File path to delete
80
- `,V={path:z$1.string()};function _(t){switch(m()){case "local":{t.tool(G,`${K}
574
+ `;
575
+ var toolInputSchema3 = {
576
+ path: z3.string()
577
+ };
578
+ function addDeleteFileTool(server) {
579
+ const mode = getWorkspaceMode();
580
+ switch (mode) {
581
+ case "local" /* LOCAL */: {
582
+ server.tool(
583
+ toolName3,
584
+ `${toolDescription3}
81
585
 
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}
586
+ Mode: Local (Local filesystem)`,
587
+ toolInputSchema3,
588
+ async ({ path: path2 }) => {
589
+ try {
590
+ return {
591
+ content: [
592
+ {
593
+ type: "text",
594
+ text: JSON.stringify(await deleteFileLocalMode(path2))
595
+ }
596
+ ]
597
+ };
598
+ } catch (e) {
599
+ if (e instanceof Error) {
600
+ return {
601
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
602
+ };
603
+ }
604
+ throw e;
605
+ }
606
+ }
607
+ );
608
+ break;
609
+ }
610
+ case "studio" /* STUDIO */: {
611
+ server.tool(
612
+ toolName3,
613
+ `${toolDescription3}
83
614
 
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`
615
+ Mode: Studio (Workspace API)`,
616
+ toolInputSchema3,
617
+ async ({ path: path2 }) => {
618
+ try {
619
+ return {
620
+ content: [
621
+ {
622
+ type: "text",
623
+ text: JSON.stringify(await deleteFileStudioMode(path2))
624
+ }
625
+ ]
626
+ };
627
+ } catch (e) {
628
+ if (e instanceof Error) {
629
+ return {
630
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
631
+ };
632
+ }
633
+ throw e;
634
+ }
635
+ }
636
+ );
637
+ break;
638
+ }
639
+ }
640
+ }
641
+ async function deleteFileLocalMode(path2) {
642
+ const validatedPath = await validatePath(path2);
643
+ if (!existsSync3(validatedPath)) {
644
+ throw new Error(`File ${path2} does not exist.`);
645
+ }
646
+ const stats = statSync3(validatedPath);
647
+ if (stats.isDirectory()) {
648
+ throw new Error(`Path ${path2} is a directory. Use delete directory tool instead.`);
649
+ }
650
+ if (!(stats.mode & 128)) {
651
+ throw new Error(`File ${path2} is not writable`);
652
+ }
653
+ await unlink(validatedPath);
654
+ return validatedPath;
655
+ }
656
+ async function deleteFileStudioMode(path2) {
657
+ const validatedPath = await validatePath(path2);
658
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
659
+ const existingItem = await findWorkspaceItem(relativePath);
660
+ if (!existingItem) {
661
+ throw new Error(`File ${relativePath} does not exist.`);
662
+ }
663
+ if (existingItem.type === "workspaceItemDirectory") {
664
+ throw new Error(`Path ${relativePath} is a directory. Use delete directory tool instead.`);
665
+ }
666
+ await deleteFileLocalMode(path2);
667
+ await deleteWorkspaceItem(existingItem.id);
668
+ return relativePath;
669
+ }
670
+
671
+ // src/tools/edit-text-file.ts
672
+ import { existsSync as existsSync4, statSync as statSync4 } from "fs";
673
+ import { readFile as readFile2, writeFile } from "fs/promises";
674
+ import { dedent as dedent5 } from "ts-dedent";
675
+ import { z as z4 } from "zod";
676
+ var toolName4 = "editTextFile";
677
+ var toolDescription4 = dedent5`
85
678
  Text file editor for modifying existing files with precise text replacement.
86
679
 
87
680
  Use cases:
@@ -102,12 +695,134 @@ Mode: Studio (Workspace API)`,V,async({path:e})=>{try{return {content:[{type:"te
102
695
  - 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
696
  - IF YOU WANT TO EDIT MORE THAN 2000 CHARACTERS, USE THIS TOOL MULTIPLE TIMES
104
697
  - 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}
698
+ `;
699
+ var toolInputSchema4 = {
700
+ path: z4.string().describe("Target file path to edit."),
701
+ newText: z4.string().min(1).max(2e3).describe("Text to append to the file. Max 2000 characters."),
702
+ oldText: z4.string().min(1).max(2e3).describe("Exact text to find and replace. Max 2000 characters.")
703
+ };
704
+ function addEditTextFileTool(server) {
705
+ const mode = getWorkspaceMode();
706
+ switch (mode) {
707
+ case "local" /* LOCAL */: {
708
+ server.tool(
709
+ toolName4,
710
+ `${toolDescription4}
711
+
712
+ Mode: Local (Local filesystem)`,
713
+ toolInputSchema4,
714
+ async ({ path: path2, newText, oldText }) => {
715
+ try {
716
+ return {
717
+ content: [
718
+ {
719
+ type: "text",
720
+ text: JSON.stringify(await editTextFileLocalMode(path2, newText, oldText))
721
+ }
722
+ ]
723
+ };
724
+ } catch (e) {
725
+ if (e instanceof Error) {
726
+ return {
727
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
728
+ };
729
+ }
730
+ throw e;
731
+ }
732
+ }
733
+ );
734
+ break;
735
+ }
736
+ case "studio" /* STUDIO */: {
737
+ server.tool(
738
+ toolName4,
739
+ `${toolDescription4}
106
740
 
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}
741
+ Mode: Studio (Workspace API)`,
742
+ toolInputSchema4,
743
+ async ({ path: path2, oldText, newText }) => {
744
+ try {
745
+ return {
746
+ content: [
747
+ {
748
+ type: "text",
749
+ text: JSON.stringify(await editTextFileStudioMode(path2, newText, oldText))
750
+ }
751
+ ]
752
+ };
753
+ } catch (e) {
754
+ if (e instanceof Error) {
755
+ return {
756
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
757
+ };
758
+ }
759
+ throw e;
760
+ }
761
+ }
762
+ );
763
+ break;
764
+ }
765
+ }
766
+ }
767
+ async function editTextFileLocalMode(path2, newText, oldText) {
768
+ const validatedPath = await validatePath(path2);
769
+ if (!existsSync4(validatedPath)) {
770
+ throw new Error(`File ${path2} does not exist.`);
771
+ }
772
+ const stats = statSync4(validatedPath);
773
+ if (!(stats.mode & 128)) {
774
+ throw new Error(`File ${path2} is not writable`);
775
+ }
776
+ await applyFileEdit(validatedPath, newText, oldText);
777
+ return validatedPath;
778
+ }
779
+ async function editTextFileStudioMode(path2, newText, oldText) {
780
+ const validatedPath = await validatePath(path2);
781
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
782
+ const existingItem = await findWorkspaceItem(relativePath);
783
+ if (!existingItem) {
784
+ throw new Error(`File ${relativePath} does not exist.`);
785
+ }
786
+ if (existingItem.type === "workspaceItemDirectory") {
787
+ throw new Error(`Path ${relativePath} is a directory.`);
788
+ }
789
+ await editTextFileLocalMode(path2, newText, oldText);
790
+ await deleteWorkspaceItem(existingItem.id);
791
+ const content = await readFile2(validatedPath, "utf-8");
792
+ await createWorkspaceItem(
793
+ {
794
+ type: "workspaceItemFile",
795
+ path: relativePath,
796
+ owner: "expert",
797
+ lifecycle: "expertJob",
798
+ permission: "readWrite"
799
+ },
800
+ content
801
+ );
802
+ return relativePath;
803
+ }
804
+ function normalizeLineEndings(text) {
805
+ return text.replace(/\r\n/g, "\n");
806
+ }
807
+ async function applyFileEdit(filePath, newText, oldText) {
808
+ const content = normalizeLineEndings(await readFile2(filePath, "utf-8"));
809
+ const normalizedOld = normalizeLineEndings(oldText);
810
+ const normalizedNew = normalizeLineEndings(newText);
811
+ if (!content.includes(normalizedOld)) {
812
+ throw new Error(`Could not find exact match for oldText in file ${filePath}`);
813
+ }
814
+ const modifiedContent = content.replace(normalizedOld, normalizedNew);
815
+ await writeFile(filePath, modifiedContent, "utf-8");
816
+ }
108
817
 
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`
818
+ // src/tools/get-file-info.ts
819
+ import { existsSync as existsSync5, statSync as statSync5 } from "fs";
820
+ import { basename, dirname as dirname2, extname, resolve } from "path";
821
+ import mime2 from "mime-types";
822
+ import { dedent as dedent6 } from "ts-dedent";
823
+ import { z as z5 } from "zod";
824
+ var toolName5 = "getFileInfo";
825
+ var toolDescription5 = dedent6`
111
826
  File information retriever for detailed metadata about files and directories.
112
827
 
113
828
  Use cases:
@@ -124,11 +839,141 @@ Mode: Studio (Workspace API)`,Z,async({path:e,oldText:r,newText:i})=>{try{return
124
839
 
125
840
  Parameters:
126
841
  - path: File or directory path to inspect
127
- `,ie={path:z$1.string()};function se(t){switch(m()){case "local":{t.tool(oe,`${re}
842
+ `;
843
+ var toolInputSchema5 = {
844
+ path: z5.string()
845
+ };
846
+ function addGetFileInfoTool(server) {
847
+ const mode = getWorkspaceMode();
848
+ switch (mode) {
849
+ case "local" /* LOCAL */: {
850
+ server.tool(
851
+ toolName5,
852
+ `${toolDescription5}
128
853
 
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}
854
+ Mode: Local (Local filesystem)`,
855
+ toolInputSchema5,
856
+ async ({ path: path2 }) => {
857
+ try {
858
+ return {
859
+ content: [
860
+ {
861
+ type: "text",
862
+ text: JSON.stringify(await getFileInfoLocalMode(path2))
863
+ }
864
+ ]
865
+ };
866
+ } catch (e) {
867
+ if (e instanceof Error) {
868
+ return {
869
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
870
+ };
871
+ }
872
+ throw e;
873
+ }
874
+ }
875
+ );
876
+ break;
877
+ }
878
+ case "studio" /* STUDIO */: {
879
+ server.tool(
880
+ toolName5,
881
+ `${toolDescription5}
130
882
 
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`
883
+ Mode: Studio (Workspace API + Local filesystem)`,
884
+ toolInputSchema5,
885
+ async ({ path: path2 }) => {
886
+ try {
887
+ return {
888
+ content: [
889
+ {
890
+ type: "text",
891
+ text: JSON.stringify(await getFileInfoStudioMode(path2))
892
+ }
893
+ ]
894
+ };
895
+ } catch (e) {
896
+ if (e instanceof Error) {
897
+ return {
898
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
899
+ };
900
+ }
901
+ throw e;
902
+ }
903
+ }
904
+ );
905
+ break;
906
+ }
907
+ }
908
+ }
909
+ async function getFileInfoLocalMode(path2) {
910
+ const validatedPath = await validatePath(path2);
911
+ if (!existsSync5(validatedPath)) {
912
+ throw new Error(`File or directory ${path2} does not exist`);
913
+ }
914
+ const stats = statSync5(validatedPath);
915
+ const isDirectory = stats.isDirectory();
916
+ const mimeType = isDirectory ? null : mime2.lookup(validatedPath) || "application/octet-stream";
917
+ const formatSize = (bytes) => {
918
+ if (bytes === 0) return "0 B";
919
+ const units = ["B", "KB", "MB", "GB", "TB"];
920
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
921
+ return `${(bytes / 1024 ** i).toFixed(2)} ${units[i]}`;
922
+ };
923
+ return {
924
+ exists: true,
925
+ path: validatedPath,
926
+ absolutePath: resolve(validatedPath),
927
+ name: basename(validatedPath),
928
+ directory: dirname2(validatedPath),
929
+ extension: isDirectory ? null : extname(validatedPath),
930
+ type: isDirectory ? "directory" : "file",
931
+ mimeType,
932
+ size: stats.size,
933
+ sizeFormatted: formatSize(stats.size),
934
+ created: stats.birthtime.toISOString(),
935
+ modified: stats.mtime.toISOString(),
936
+ accessed: stats.atime.toISOString(),
937
+ permissions: {
938
+ readable: true,
939
+ writable: Boolean(stats.mode & 128),
940
+ executable: Boolean(stats.mode & 64)
941
+ }
942
+ };
943
+ }
944
+ async function getFileInfoStudioMode(path2) {
945
+ const validatedPath = await validatePath(path2);
946
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
947
+ const localInfo = await getFileInfoLocalMode(path2);
948
+ const workspaceItem = await findWorkspaceItem(relativePath);
949
+ return {
950
+ ...localInfo,
951
+ workspaceItem: workspaceItem ? {
952
+ id: workspaceItem.id,
953
+ type: workspaceItem.type,
954
+ path: workspaceItem.path,
955
+ owner: workspaceItem.owner,
956
+ lifecycle: workspaceItem.lifecycle,
957
+ permission: workspaceItem.permission,
958
+ createdAt: workspaceItem.createdAt,
959
+ updatedAt: workspaceItem.updatedAt,
960
+ ...workspaceItem.type === "workspaceItemFile" ? {
961
+ key: workspaceItem.key,
962
+ mimeType: workspaceItem.mimeType,
963
+ size: workspaceItem.size
964
+ } : {}
965
+ } : null
966
+ };
967
+ }
968
+
969
+ // src/tools/list-directory.ts
970
+ import { existsSync as existsSync6, statSync as statSync6 } from "fs";
971
+ import { readdir } from "fs/promises";
972
+ import { join } from "path";
973
+ import { dedent as dedent7 } from "ts-dedent";
974
+ import { z as z6 } from "zod";
975
+ var toolName6 = "listDirectory";
976
+ var toolDescription6 = dedent7`
132
977
  Directory content lister with detailed file information.
133
978
 
134
979
  Use cases:
@@ -145,11 +990,133 @@ Mode: Studio (Workspace API + Local filesystem)`,ie,async({path:e})=>{try{return
145
990
 
146
991
  Parameters:
147
992
  - 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}
993
+ `;
994
+ var toolInputSchema6 = {
995
+ path: z6.string().optional()
996
+ };
997
+ function addListDirectoryTool(server) {
998
+ const mode = getWorkspaceMode();
999
+ switch (mode) {
1000
+ case "local" /* LOCAL */: {
1001
+ server.tool(
1002
+ toolName6,
1003
+ `${toolDescription6}
1004
+
1005
+ Mode: Local (Local filesystem)`,
1006
+ toolInputSchema6,
1007
+ async ({ path: path2 = "." }) => {
1008
+ try {
1009
+ return {
1010
+ content: [
1011
+ {
1012
+ type: "text",
1013
+ text: JSON.stringify(await listDirectoryLocalMode(path2))
1014
+ }
1015
+ ]
1016
+ };
1017
+ } catch (e) {
1018
+ if (e instanceof Error) {
1019
+ return {
1020
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1021
+ };
1022
+ }
1023
+ throw e;
1024
+ }
1025
+ }
1026
+ );
1027
+ break;
1028
+ }
1029
+ case "studio" /* STUDIO */: {
1030
+ server.tool(
1031
+ toolName6,
1032
+ `${toolDescription6}
149
1033
 
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}
1034
+ Mode: Studio (Workspace API)`,
1035
+ toolInputSchema6,
1036
+ async ({ path: path2 = "." }) => {
1037
+ try {
1038
+ return {
1039
+ content: [
1040
+ {
1041
+ type: "text",
1042
+ text: JSON.stringify(await listDirectoryStudioMode(path2))
1043
+ }
1044
+ ]
1045
+ };
1046
+ } catch (e) {
1047
+ if (e instanceof Error) {
1048
+ return {
1049
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1050
+ };
1051
+ }
1052
+ throw e;
1053
+ }
1054
+ }
1055
+ );
1056
+ break;
1057
+ }
1058
+ }
1059
+ }
1060
+ async function listDirectoryLocalMode(path2) {
1061
+ const validatedPath = await validatePath(path2);
1062
+ if (!existsSync6(validatedPath)) {
1063
+ throw new Error(`Directory ${path2} does not exist.`);
1064
+ }
1065
+ const stats = statSync6(validatedPath);
1066
+ if (!stats.isDirectory()) {
1067
+ throw new Error(`Path ${path2} is not a directory.`);
1068
+ }
1069
+ const entries = await readdir(validatedPath);
1070
+ const items = [];
1071
+ for (const entry of entries.sort()) {
1072
+ try {
1073
+ const fullPath = await validatePath(join(validatedPath, entry));
1074
+ const entryStats = statSync6(fullPath);
1075
+ const item = {
1076
+ name: entry,
1077
+ path: entry,
1078
+ type: entryStats.isDirectory() ? "directory" : "file",
1079
+ size: entryStats.size,
1080
+ modified: entryStats.mtime.toISOString()
1081
+ };
1082
+ items.push(item);
1083
+ } catch (e) {
1084
+ if (e instanceof Error && e.message.includes("perstack directory is not allowed")) {
1085
+ continue;
1086
+ }
1087
+ throw e;
1088
+ }
1089
+ }
1090
+ return items;
1091
+ }
1092
+ async function listDirectoryStudioMode(path2) {
1093
+ const validatedPath = await validatePath(path2);
1094
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
1095
+ const workspaceItems = await getWorkspaceItems();
1096
+ const filteredItems = workspaceItems.filter((item) => {
1097
+ if (relativePath === "" || relativePath === ".") {
1098
+ return !item.path.includes("/");
1099
+ }
1100
+ const pathPrefix = relativePath.endsWith("/") ? relativePath : `${relativePath}/`;
1101
+ return item.path.startsWith(pathPrefix) && !item.path.substring(pathPrefix.length).includes("/");
1102
+ });
1103
+ return filteredItems.map((item) => ({
1104
+ name: item.path.split("/").pop() || item.path,
1105
+ path: item.path,
1106
+ type: item.type === "workspaceItemDirectory" ? "directory" : "file",
1107
+ size: item.type === "workspaceItemFile" ? item.size : 0,
1108
+ modified: item.updatedAt
1109
+ }));
1110
+ }
151
1111
 
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()){let n=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);}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`
1112
+ // src/tools/move-file.ts
1113
+ import { existsSync as existsSync7, statSync as statSync7 } from "fs";
1114
+ import { mkdir as mkdir2, rename } from "fs/promises";
1115
+ import { dirname as dirname3 } from "path";
1116
+ import { dedent as dedent8 } from "ts-dedent";
1117
+ import { z as z7 } from "zod";
1118
+ var toolName7 = "moveFile";
1119
+ var toolDescription7 = dedent8`
153
1120
  File mover for relocating or renaming files within the workspace.
154
1121
 
155
1122
  Use cases:
@@ -167,11 +1134,134 @@ Mode: Studio (Workspace API)`,de,async({path:e="."})=>{try{return {content:[{typ
167
1134
  Parameters:
168
1135
  - source: Current file path
169
1136
  - 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}
1137
+ `;
1138
+ var toolInputSchema7 = {
1139
+ source: z7.string(),
1140
+ destination: z7.string()
1141
+ };
1142
+ function addMoveFileTool(server) {
1143
+ const mode = getWorkspaceMode();
1144
+ switch (mode) {
1145
+ case "local" /* LOCAL */: {
1146
+ server.tool(
1147
+ toolName7,
1148
+ `${toolDescription7}
1149
+
1150
+ Mode: Local (Local filesystem)`,
1151
+ toolInputSchema7,
1152
+ async ({ source, destination }) => {
1153
+ try {
1154
+ return {
1155
+ content: [
1156
+ {
1157
+ type: "text",
1158
+ text: JSON.stringify(await moveFileLocalMode(source, destination))
1159
+ }
1160
+ ]
1161
+ };
1162
+ } catch (e) {
1163
+ if (e instanceof Error) {
1164
+ return {
1165
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1166
+ };
1167
+ }
1168
+ throw e;
1169
+ }
1170
+ }
1171
+ );
1172
+ break;
1173
+ }
1174
+ case "studio" /* STUDIO */: {
1175
+ server.tool(
1176
+ toolName7,
1177
+ `${toolDescription7}
171
1178
 
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}
1179
+ Mode: Studio (Workspace API)`,
1180
+ toolInputSchema7,
1181
+ async ({ source, destination }) => {
1182
+ try {
1183
+ return {
1184
+ content: [
1185
+ {
1186
+ type: "text",
1187
+ text: JSON.stringify(await moveFileStudioMode(source, destination))
1188
+ }
1189
+ ]
1190
+ };
1191
+ } catch (e) {
1192
+ if (e instanceof Error) {
1193
+ return {
1194
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1195
+ };
1196
+ }
1197
+ throw e;
1198
+ }
1199
+ }
1200
+ );
1201
+ break;
1202
+ }
1203
+ }
1204
+ }
1205
+ async function moveFileLocalMode(source, destination) {
1206
+ const validatedSource = await validatePath(source);
1207
+ const validatedDestination = await validatePath(destination);
1208
+ if (!existsSync7(validatedSource)) {
1209
+ throw new Error(`Source file ${source} does not exist.`);
1210
+ }
1211
+ const sourceStats = statSync7(validatedSource);
1212
+ if (!(sourceStats.mode & 128)) {
1213
+ throw new Error(`Source file ${source} is not writable`);
1214
+ }
1215
+ if (existsSync7(validatedDestination)) {
1216
+ throw new Error(`Destination ${destination} already exists.`);
1217
+ }
1218
+ const destDir = dirname3(validatedDestination);
1219
+ await mkdir2(destDir, { recursive: true });
1220
+ await rename(validatedSource, validatedDestination);
1221
+ return validatedDestination;
1222
+ }
1223
+ async function moveFileStudioMode(source, destination) {
1224
+ const validatedSource = await validatePath(source);
1225
+ const validatedDestination = await validatePath(destination);
1226
+ const relativeSource = validatedSource.startsWith(workspacePath) ? validatedSource.slice(workspacePath.length + 1) : validatedSource;
1227
+ const relativeDestination = validatedDestination.startsWith(workspacePath) ? validatedDestination.slice(workspacePath.length + 1) : validatedDestination;
1228
+ const sourceItem = await findWorkspaceItem(relativeSource);
1229
+ if (!sourceItem) {
1230
+ throw new Error(`Source file ${relativeSource} does not exist.`);
1231
+ }
1232
+ const destItem = await findWorkspaceItem(relativeDestination);
1233
+ if (destItem) {
1234
+ throw new Error(`Destination ${relativeDestination} already exists.`);
1235
+ }
1236
+ const destDir = dirname3(relativeDestination);
1237
+ if (destDir !== "." && destDir !== "/") {
1238
+ const destDirItem = await findWorkspaceItem(destDir);
1239
+ if (!destDirItem) {
1240
+ await createWorkspaceItem({
1241
+ type: "workspaceItemDirectory",
1242
+ path: destDir,
1243
+ owner: "expert",
1244
+ lifecycle: "expertJob",
1245
+ permission: "readWrite"
1246
+ });
1247
+ }
1248
+ }
1249
+ await updateWorkspaceItem(sourceItem.id, {
1250
+ path: relativeDestination
1251
+ });
1252
+ await moveFileLocalMode(source, destination);
1253
+ return relativeDestination;
1254
+ }
173
1255
 
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`
1256
+ // src/tools/read-image-file.ts
1257
+ import { existsSync as existsSync8 } from "fs";
1258
+ import { stat } from "fs/promises";
1259
+ import mime3 from "mime-types";
1260
+ import { dedent as dedent9 } from "ts-dedent";
1261
+ import { z as z8 } from "zod";
1262
+ var MAX_IMAGE_SIZE = 15 * 1024 * 1024;
1263
+ var toolName8 = "readImageFile";
1264
+ var toolDescription8 = dedent9`
175
1265
  Image file reader that converts images to base64 encoded strings with MIME type validation.
176
1266
 
177
1267
  Use cases:
@@ -193,7 +1283,64 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
193
1283
 
194
1284
  Notes:
195
1285
  - 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`
1286
+ `;
1287
+ var toolInputSchema8 = {
1288
+ path: z8.string()
1289
+ };
1290
+ function addReadImageFileTool(server) {
1291
+ server.tool(toolName8, toolDescription8, toolInputSchema8, async ({ path: path2 }) => {
1292
+ try {
1293
+ return {
1294
+ content: [
1295
+ {
1296
+ type: "text",
1297
+ text: JSON.stringify(await readImageFile(path2))
1298
+ }
1299
+ ]
1300
+ };
1301
+ } catch (e) {
1302
+ if (e instanceof Error) {
1303
+ return {
1304
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1305
+ };
1306
+ }
1307
+ throw e;
1308
+ }
1309
+ });
1310
+ }
1311
+ async function readImageFile(path2) {
1312
+ const validatedPath = await validatePath(path2);
1313
+ const isFile = existsSync8(validatedPath);
1314
+ if (!isFile) {
1315
+ throw new Error(`File ${path2} does not exist.`);
1316
+ }
1317
+ const mimeType = mime3.lookup(validatedPath);
1318
+ if (!mimeType || !["image/png", "image/jpeg", "image/gif", "image/webp"].includes(mimeType)) {
1319
+ throw new Error(`File ${path2} is not supported.`);
1320
+ }
1321
+ const fileStats = await stat(validatedPath);
1322
+ const fileSizeMB = fileStats.size / (1024 * 1024);
1323
+ if (fileStats.size > MAX_IMAGE_SIZE) {
1324
+ throw new Error(
1325
+ `Image file too large (${fileSizeMB.toFixed(1)}MB). Maximum supported size is ${MAX_IMAGE_SIZE / (1024 * 1024)}MB. Please use a smaller image file.`
1326
+ );
1327
+ }
1328
+ return {
1329
+ path: validatedPath,
1330
+ mimeType,
1331
+ size: fileStats.size
1332
+ };
1333
+ }
1334
+
1335
+ // src/tools/read-pdf-file.ts
1336
+ import { existsSync as existsSync9 } from "fs";
1337
+ import { stat as stat2 } from "fs/promises";
1338
+ import mime4 from "mime-types";
1339
+ import { dedent as dedent10 } from "ts-dedent";
1340
+ import { z as z9 } from "zod";
1341
+ var MAX_PDF_SIZE = 30 * 1024 * 1024;
1342
+ var toolName9 = "readPdfFile";
1343
+ var toolDescription9 = dedent10`
197
1344
  PDF file reader that converts documents to base64 encoded resources.
198
1345
 
199
1346
  Use cases:
@@ -211,7 +1358,62 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
211
1358
  - Returns entire PDF content, no page range support
212
1359
  - Maximum file size: 10MB (larger files will be rejected)
213
1360
  - 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`
1361
+ `;
1362
+ var toolInputSchema9 = {
1363
+ path: z9.string()
1364
+ };
1365
+ function addReadPdfFileTool(server) {
1366
+ server.tool(toolName9, toolDescription9, toolInputSchema9, async ({ path: path2 }) => {
1367
+ try {
1368
+ return {
1369
+ content: [
1370
+ {
1371
+ type: "text",
1372
+ text: JSON.stringify(await readPdfFile(path2))
1373
+ }
1374
+ ]
1375
+ };
1376
+ } catch (e) {
1377
+ if (e instanceof Error) {
1378
+ return {
1379
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1380
+ };
1381
+ }
1382
+ throw e;
1383
+ }
1384
+ });
1385
+ }
1386
+ async function readPdfFile(path2) {
1387
+ const validatedPath = await validatePath(path2);
1388
+ const isFile = existsSync9(validatedPath);
1389
+ if (!isFile) {
1390
+ throw new Error(`File ${path2} does not exist.`);
1391
+ }
1392
+ const mimeType = mime4.lookup(validatedPath);
1393
+ if (mimeType !== "application/pdf") {
1394
+ throw new Error(`File ${path2} is not a PDF file.`);
1395
+ }
1396
+ const fileStats = await stat2(validatedPath);
1397
+ const fileSizeMB = fileStats.size / (1024 * 1024);
1398
+ if (fileStats.size > MAX_PDF_SIZE) {
1399
+ throw new Error(
1400
+ `PDF file too large (${fileSizeMB.toFixed(1)}MB). Maximum supported size is ${MAX_PDF_SIZE / (1024 * 1024)}MB. Please use a smaller PDF file.`
1401
+ );
1402
+ }
1403
+ return {
1404
+ path: validatedPath,
1405
+ mimeType,
1406
+ size: fileStats.size
1407
+ };
1408
+ }
1409
+
1410
+ // src/tools/read-text-file.ts
1411
+ import { existsSync as existsSync10 } from "fs";
1412
+ import { readFile as readFile4 } from "fs/promises";
1413
+ import { dedent as dedent11 } from "ts-dedent";
1414
+ import { z as z10 } from "zod";
1415
+ var toolName10 = "readTextFile";
1416
+ var toolDescription10 = dedent11`
215
1417
  Text file reader with line range support for UTF-8 encoded files.
216
1418
 
217
1419
  Use cases:
@@ -231,9 +1433,58 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
231
1433
  - Documentation: .md, .txt, .rst
232
1434
  - Configuration: .json, .yaml, .toml, .ini
233
1435
  - 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`
1436
+ `;
1437
+ var toolInputSchema10 = {
1438
+ path: z10.string(),
1439
+ from: z10.number().optional().describe("The line number to start reading from."),
1440
+ to: z10.number().optional().describe("The line number to stop reading at.")
1441
+ };
1442
+ function addReadTextFileTool(server) {
1443
+ server.tool(toolName10, toolDescription10, toolInputSchema10, async ({ path: path2, from, to }) => {
1444
+ try {
1445
+ return {
1446
+ content: [
1447
+ {
1448
+ type: "text",
1449
+ text: JSON.stringify(await readTextFile(path2, from, to))
1450
+ }
1451
+ ]
1452
+ };
1453
+ } catch (e) {
1454
+ if (e instanceof Error) {
1455
+ return {
1456
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1457
+ };
1458
+ }
1459
+ throw e;
1460
+ }
1461
+ });
1462
+ }
1463
+ async function readTextFile(path2, from, to) {
1464
+ const validatedPath = await validatePath(path2);
1465
+ const isFile = existsSync10(validatedPath);
1466
+ if (!isFile) {
1467
+ throw new Error(`File ${path2} does not exist.`);
1468
+ }
1469
+ const fileContent = await readFile4(validatedPath, "utf-8");
1470
+ const lines = fileContent.split("\n");
1471
+ const fromLine = from ?? 0;
1472
+ const toLine = to ?? lines.length;
1473
+ const selectedLines = lines.slice(fromLine, toLine);
1474
+ const content = selectedLines.join("\n");
1475
+ return {
1476
+ path: path2,
1477
+ content,
1478
+ from: fromLine,
1479
+ to: toLine
1480
+ };
1481
+ }
1482
+
1483
+ // src/tools/test-url.ts
1484
+ import { dedent as dedent12 } from "ts-dedent";
1485
+ import { z as z11 } from "zod";
1486
+ var toolName11 = "testUrl";
1487
+ var toolDescription11 = dedent12`
237
1488
  URL tester that validates multiple URLs and extracts metadata.
238
1489
 
239
1490
  Use cases:
@@ -253,7 +1504,135 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
253
1504
  - Maximum 10 URLs per request to prevent abuse
254
1505
  - 10 second timeout per URL request
255
1506
  - 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`
1507
+ `;
1508
+ var toolInputSchema11 = {
1509
+ urls: z11.array(z11.string()).min(1).max(10).describe("Array of URLs to test (max 10 URLs).")
1510
+ };
1511
+ function addTestUrlTool(server) {
1512
+ server.tool(toolName11, toolDescription11, toolInputSchema11, async ({ urls }) => {
1513
+ try {
1514
+ const results = await testUrls(urls);
1515
+ return {
1516
+ content: [
1517
+ {
1518
+ type: "text",
1519
+ text: JSON.stringify(results, null, 2)
1520
+ }
1521
+ ]
1522
+ };
1523
+ } catch (e) {
1524
+ if (e instanceof Error) {
1525
+ return {
1526
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1527
+ };
1528
+ }
1529
+ throw e;
1530
+ }
1531
+ });
1532
+ }
1533
+ async function testUrls(urls) {
1534
+ const results = await Promise.allSettled(
1535
+ urls.map(async (url) => {
1536
+ try {
1537
+ const controller = new AbortController();
1538
+ const timeoutId = setTimeout(() => controller.abort(), 1e4);
1539
+ const response = await fetch(url, {
1540
+ method: "GET",
1541
+ signal: controller.signal,
1542
+ headers: {
1543
+ "User-Agent": "Perstack URL Tester/1.0"
1544
+ }
1545
+ });
1546
+ clearTimeout(timeoutId);
1547
+ let title = "";
1548
+ let description = "";
1549
+ if (response.ok && response.headers.get("content-type")?.includes("text/html")) {
1550
+ try {
1551
+ const html = await response.text();
1552
+ title = extractTitle(html);
1553
+ description = extractDescription(html);
1554
+ } catch {
1555
+ }
1556
+ }
1557
+ return {
1558
+ url,
1559
+ status: response.status,
1560
+ title,
1561
+ description
1562
+ };
1563
+ } catch (error) {
1564
+ return {
1565
+ url,
1566
+ status: 0,
1567
+ title: "",
1568
+ description: error instanceof Error ? error.message : "Unknown error"
1569
+ };
1570
+ }
1571
+ })
1572
+ );
1573
+ return results.map((result) => {
1574
+ if (result.status === "fulfilled") {
1575
+ return result.value;
1576
+ }
1577
+ return {
1578
+ url: "unknown",
1579
+ status: 0,
1580
+ title: "",
1581
+ description: "Promise rejected"
1582
+ };
1583
+ });
1584
+ }
1585
+ function extractTitle(html) {
1586
+ const titleMatch = html.match(/<title[^>]*>([^<]*)/i);
1587
+ return titleMatch ? titleMatch[1].trim() : "";
1588
+ }
1589
+ function extractDescription(html) {
1590
+ const metaDescMatch = html.match(
1591
+ /<meta[^>]*name=["']description["'][^>]*content=["']([^"']*)["']/i
1592
+ );
1593
+ if (metaDescMatch) {
1594
+ return metaDescMatch[1].trim();
1595
+ }
1596
+ const ogDescMatch = html.match(
1597
+ /<meta[^>]*property=["']og:description["'][^>]*content=["']([^"']*)["']/i
1598
+ );
1599
+ if (ogDescMatch) {
1600
+ return ogDescMatch[1].trim();
1601
+ }
1602
+ return "";
1603
+ }
1604
+
1605
+ // src/tools/think.ts
1606
+ import { dedent as dedent13 } from "ts-dedent";
1607
+ import { z as z12 } from "zod";
1608
+ var ThoughtInputSchema = z12.object({
1609
+ thought: z12.string().describe("Your current thinking step"),
1610
+ nextThoughtNeeded: z12.boolean().optional().describe("true if you need more thinking, even if at what seemed like the end")
1611
+ });
1612
+ var Thought = class {
1613
+ thoughtHistory = [];
1614
+ branches = {};
1615
+ processThought(input) {
1616
+ const { nextThoughtNeeded } = input;
1617
+ this.thoughtHistory.push(input);
1618
+ return {
1619
+ content: [
1620
+ {
1621
+ type: "text",
1622
+ text: JSON.stringify({
1623
+ nextThoughtNeeded,
1624
+ thoughtHistoryLength: this.thoughtHistory.length
1625
+ })
1626
+ }
1627
+ ]
1628
+ };
1629
+ }
1630
+ };
1631
+ function addThinkTool(server) {
1632
+ const thought = new Thought();
1633
+ server.tool(
1634
+ "think",
1635
+ dedent13`
257
1636
  Sequential thinking tool for step-by-step problem analysis and solution development.
258
1637
 
259
1638
  Use cases:
@@ -278,7 +1657,54 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
278
1657
  - Capture insights and eureka moments as they emerge
279
1658
  - Engage in reflective introspection and constructive self-critique
280
1659
  - 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`
1660
+ `,
1661
+ ThoughtInputSchema.shape,
1662
+ async (input) => {
1663
+ return thought.processThought(input);
1664
+ }
1665
+ );
1666
+ }
1667
+
1668
+ // src/tools/todo.ts
1669
+ import { dedent as dedent14 } from "ts-dedent";
1670
+ import { z as z13 } from "zod";
1671
+ var TodoInputSchema = z13.object({
1672
+ newTodos: z13.array(z13.string()).describe("New todos to add").optional(),
1673
+ completedTodos: z13.array(z13.number()).describe("Todo ids that are completed").optional()
1674
+ });
1675
+ var Todo = class {
1676
+ currentTodoId = 0;
1677
+ todos = [];
1678
+ processTodo(input) {
1679
+ const { newTodos, completedTodos } = input;
1680
+ if (newTodos) {
1681
+ this.todos.push(
1682
+ ...newTodos.map((title) => ({ id: this.currentTodoId++, title, completed: false }))
1683
+ );
1684
+ }
1685
+ if (completedTodos) {
1686
+ this.todos = this.todos.map((todo) => ({
1687
+ ...todo,
1688
+ completed: todo.completed || completedTodos.includes(todo.id)
1689
+ }));
1690
+ }
1691
+ return {
1692
+ content: [
1693
+ {
1694
+ type: "text",
1695
+ text: JSON.stringify({
1696
+ todos: this.todos
1697
+ })
1698
+ }
1699
+ ]
1700
+ };
1701
+ }
1702
+ };
1703
+ function addTodoTool(server) {
1704
+ const todo = new Todo();
1705
+ server.tool(
1706
+ "todo",
1707
+ dedent14`
282
1708
  Todo list manager that tracks tasks and their completion status.
283
1709
 
284
1710
  Use cases:
@@ -294,7 +1720,23 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
294
1720
  Parameters:
295
1721
  - newTodos: Array of task descriptions to add
296
1722
  - completedTodos: Array of todo IDs to mark as completed
297
- `,ho.shape,async e=>o.processTodo(e));}var Ae="writeTextFile",We=dedent`
1723
+ `,
1724
+ TodoInputSchema.shape,
1725
+ async (input) => {
1726
+ return todo.processTodo(input);
1727
+ }
1728
+ );
1729
+ }
1730
+
1731
+ // src/tools/write-text-file.ts
1732
+ import { existsSync as existsSync11, statSync as statSync8 } from "fs";
1733
+ import { writeFile as writeFile2 } from "fs/promises";
1734
+ import { mkdir as mkdir3 } from "fs/promises";
1735
+ import { dirname as dirname4 } from "path";
1736
+ import { dedent as dedent15 } from "ts-dedent";
1737
+ import { z as z14 } from "zod";
1738
+ var toolName12 = "writeTextFile";
1739
+ var toolDescription12 = dedent15`
298
1740
  Text file writer that creates or overwrites files with UTF-8 content.
299
1741
 
300
1742
  Use cases:
@@ -312,9 +1754,164 @@ Mode: Studio (Workspace API)`,we,async({source:e,destination:r})=>{try{return {c
312
1754
  - YOU MUST PROVIDE A VALID UTF-8 STRING FOR THE TEXT
313
1755
  - 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
1756
  - 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}
1757
+ `;
1758
+ var toolInputSchema12 = {
1759
+ path: z14.string().describe("Target file path (relative or absolute)."),
1760
+ text: z14.string().min(1).max(2e3).describe("Text to write to the file. Max 2000 characters.")
1761
+ };
1762
+ function addWriteTextFileTool(server) {
1763
+ const mode = getWorkspaceMode();
1764
+ switch (mode) {
1765
+ case "local" /* LOCAL */: {
1766
+ server.tool(
1767
+ toolName12,
1768
+ `${toolDescription12}
1769
+
1770
+ Mode: Local (Local filesystem)`,
1771
+ toolInputSchema12,
1772
+ async ({ path: path2, text }) => {
1773
+ try {
1774
+ return {
1775
+ content: [
1776
+ {
1777
+ type: "text",
1778
+ text: JSON.stringify(await writeTextFileLocalMode(path2, text))
1779
+ }
1780
+ ]
1781
+ };
1782
+ } catch (e) {
1783
+ if (e instanceof Error) {
1784
+ return {
1785
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1786
+ };
1787
+ }
1788
+ throw e;
1789
+ }
1790
+ }
1791
+ );
1792
+ break;
1793
+ }
1794
+ case "studio" /* STUDIO */: {
1795
+ server.tool(
1796
+ toolName12,
1797
+ `${toolDescription12}
316
1798
 
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}
1799
+ Mode: Studio (Workspace API)`,
1800
+ toolInputSchema12,
1801
+ async ({ path: path2, text }) => {
1802
+ try {
1803
+ return {
1804
+ content: [
1805
+ {
1806
+ type: "text",
1807
+ text: JSON.stringify(await writeTextFileStudioMode(path2, text))
1808
+ }
1809
+ ]
1810
+ };
1811
+ } catch (e) {
1812
+ if (e instanceof Error) {
1813
+ return {
1814
+ content: [{ type: "text", text: JSON.stringify({ error: e.message }) }]
1815
+ };
1816
+ }
1817
+ throw e;
1818
+ }
1819
+ }
1820
+ );
1821
+ break;
1822
+ }
1823
+ }
1824
+ }
1825
+ async function writeTextFileLocalMode(path2, text) {
1826
+ const validatedPath = await validatePath(path2);
1827
+ if (existsSync11(validatedPath)) {
1828
+ const stats = statSync8(validatedPath);
1829
+ if (!(stats.mode & 128)) {
1830
+ throw new Error(`File ${path2} is not writable`);
1831
+ }
1832
+ }
1833
+ const dir = dirname4(validatedPath);
1834
+ await mkdir3(dir, { recursive: true });
1835
+ await writeFile2(validatedPath, text, "utf-8");
1836
+ return {
1837
+ path: validatedPath
1838
+ };
1839
+ }
1840
+ async function writeTextFileStudioMode(path2, text) {
1841
+ const validatedPath = await validatePath(path2);
1842
+ const relativePath = validatedPath.startsWith(workspacePath) ? validatedPath.slice(workspacePath.length + 1) : validatedPath;
1843
+ const existingItem = await findWorkspaceItem(relativePath);
1844
+ if (existingItem) {
1845
+ if (existingItem.type === "workspaceItemDirectory") {
1846
+ throw new Error(`Path ${relativePath} is a directory`);
1847
+ }
1848
+ throw new Error("Updating existing file content is not supported yet");
1849
+ }
1850
+ const pathParts = relativePath.split("/").filter((part) => part !== "");
1851
+ for (let i = 1; i < pathParts.length; i++) {
1852
+ const currentPath = pathParts.slice(0, i).join("/");
1853
+ if (currentPath === "") continue;
1854
+ const existingParent = await findWorkspaceItem(currentPath);
1855
+ if (!existingParent) {
1856
+ await createWorkspaceItem({
1857
+ type: "workspaceItemDirectory",
1858
+ path: currentPath,
1859
+ owner: "expert",
1860
+ lifecycle: "expertJob",
1861
+ permission: "readWrite"
1862
+ });
1863
+ }
1864
+ }
1865
+ await createWorkspaceItem(
1866
+ {
1867
+ type: "workspaceItemFile",
1868
+ path: relativePath,
1869
+ owner: "expert",
1870
+ lifecycle: "expertJob",
1871
+ permission: "readWrite"
1872
+ },
1873
+ text
1874
+ );
1875
+ await writeTextFileLocalMode(path2, text);
1876
+ return {
1877
+ path: relativePath
1878
+ };
1879
+ }
318
1880
 
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
1881
+ // src/index.ts
1882
+ async function main() {
1883
+ const program = new Command();
1884
+ program.name(package_default.name).description(package_default.description).version(package_default.version, "-v, --version", "display the version number").action(async () => {
1885
+ const server = new McpServer(
1886
+ {
1887
+ name: package_default.name,
1888
+ version: package_default.version
1889
+ },
1890
+ {
1891
+ capabilities: {
1892
+ tools: {}
1893
+ }
1894
+ }
1895
+ );
1896
+ addAttemptCompletionTool(server);
1897
+ addThinkTool(server);
1898
+ addTodoTool(server);
1899
+ addReadImageFileTool(server);
1900
+ addReadPdfFileTool(server);
1901
+ addReadTextFileTool(server);
1902
+ addEditTextFileTool(server);
1903
+ addAppendTextFileTool(server);
1904
+ addDeleteFileTool(server);
1905
+ addMoveFileTool(server);
1906
+ addGetFileInfoTool(server);
1907
+ addWriteTextFileTool(server);
1908
+ addCreateDirectoryTool(server);
1909
+ addListDirectoryTool(server);
1910
+ addTestUrlTool(server);
1911
+ const transport = new StdioServerTransport();
1912
+ await server.connect(transport);
1913
+ });
1914
+ program.parse();
1915
+ }
1916
+ main();
320
1917
  //# sourceMappingURL=index.js.map