agentool 0.0.1 → 1.1.0

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.
Files changed (147) hide show
  1. package/README.md +738 -52
  2. package/dist/ask-user/index.cjs +8 -0
  3. package/dist/ask-user/index.d.cts +68 -0
  4. package/dist/ask-user/index.d.ts +68 -0
  5. package/dist/ask-user/index.js +8 -0
  6. package/dist/bash/index.cjs +8 -0
  7. package/dist/bash/index.d.cts +63 -0
  8. package/dist/bash/index.d.ts +63 -0
  9. package/dist/bash/index.js +8 -0
  10. package/dist/chunk-3EPGFWZV.cjs +30 -0
  11. package/dist/chunk-3VO6NETR.cjs +79 -0
  12. package/dist/chunk-44AFQ2B7.js +30 -0
  13. package/dist/chunk-4HIATLKI.js +112 -0
  14. package/dist/chunk-4HXAKPQH.cjs +36 -0
  15. package/dist/chunk-4YI2H55A.js +142 -0
  16. package/dist/chunk-56CL4JCW.cjs +53 -0
  17. package/dist/chunk-5NW4OGRI.cjs +99 -0
  18. package/dist/chunk-5O55DKOB.cjs +112 -0
  19. package/dist/chunk-5TDZF4IM.cjs +197 -0
  20. package/dist/chunk-6DJSWTWQ.cjs +40 -0
  21. package/dist/chunk-6PQLFDGT.js +117 -0
  22. package/dist/chunk-ACGW44YT.js +47 -0
  23. package/dist/chunk-CAEVLIQB.cjs +117 -0
  24. package/dist/chunk-CGTPF6IS.js +90 -0
  25. package/dist/chunk-E6NBEYZD.js +51 -0
  26. package/dist/chunk-EA3YV7ZG.js +79 -0
  27. package/dist/chunk-ECYT46FP.js +40 -0
  28. package/dist/chunk-FV2R5FFQ.cjs +102 -0
  29. package/dist/chunk-FW3UJ622.cjs +59 -0
  30. package/dist/chunk-G3ITTPGX.js +99 -0
  31. package/dist/chunk-HDKXSKMO.js +30 -0
  32. package/dist/chunk-HNP7JDQC.cjs +159 -0
  33. package/dist/chunk-HNUL2CID.cjs +34 -0
  34. package/dist/chunk-HZAQRHBT.js +99 -0
  35. package/dist/chunk-I3ONDY7P.js +46 -0
  36. package/dist/chunk-I6KFFQPV.cjs +58 -0
  37. package/dist/chunk-IEX4NOVN.cjs +48 -0
  38. package/dist/chunk-IRRNYFI5.js +48 -0
  39. package/dist/chunk-K77GC2QI.js +59 -0
  40. package/dist/chunk-L5JH4I77.cjs +51 -0
  41. package/dist/chunk-LK6SQH2G.cjs +30 -0
  42. package/dist/chunk-LPV5CN2K.js +58 -0
  43. package/dist/chunk-LTE5NG4D.js +53 -0
  44. package/dist/chunk-MF7CJVIZ.js +40 -0
  45. package/dist/chunk-MIYA7TNR.cjs +123 -0
  46. package/dist/chunk-MJCAXASI.js +123 -0
  47. package/dist/chunk-OM2UFTGS.cjs +47 -0
  48. package/dist/chunk-ONBH74ZV.cjs +90 -0
  49. package/dist/chunk-OXLQ7QVL.cjs +40 -0
  50. package/dist/chunk-P6Z5XFDS.js +73 -0
  51. package/dist/chunk-QZ5GS6HW.cjs +46 -0
  52. package/dist/chunk-S7IVHOA6.js +75 -0
  53. package/dist/chunk-SUSAPI5W.cjs +142 -0
  54. package/dist/chunk-TMW3XKKJ.js +34 -0
  55. package/dist/chunk-UDIG7332.js +159 -0
  56. package/dist/chunk-VLNDEVKS.js +102 -0
  57. package/dist/chunk-VXZ4RKJI.js +36 -0
  58. package/dist/chunk-XAQGZ374.js +197 -0
  59. package/dist/chunk-YPPPGGLA.cjs +99 -0
  60. package/dist/chunk-ZBLQV6UO.cjs +73 -0
  61. package/dist/chunk-ZFQZWXOI.cjs +75 -0
  62. package/dist/context-compaction/index.cjs +8 -0
  63. package/dist/context-compaction/index.d.cts +77 -0
  64. package/dist/context-compaction/index.d.ts +77 -0
  65. package/dist/context-compaction/index.js +8 -0
  66. package/dist/diff/index.cjs +9 -0
  67. package/dist/diff/index.d.cts +72 -0
  68. package/dist/diff/index.d.ts +72 -0
  69. package/dist/diff/index.js +9 -0
  70. package/dist/edit/index.cjs +10 -0
  71. package/dist/edit/index.d.cts +53 -0
  72. package/dist/edit/index.d.ts +53 -0
  73. package/dist/edit/index.js +10 -0
  74. package/dist/glob/index.cjs +10 -0
  75. package/dist/glob/index.d.cts +47 -0
  76. package/dist/glob/index.d.ts +47 -0
  77. package/dist/glob/index.js +10 -0
  78. package/dist/grep/index.cjs +10 -0
  79. package/dist/grep/index.d.cts +50 -0
  80. package/dist/grep/index.d.ts +50 -0
  81. package/dist/grep/index.js +10 -0
  82. package/dist/http-request/index.cjs +8 -0
  83. package/dist/http-request/index.d.cts +60 -0
  84. package/dist/http-request/index.d.ts +60 -0
  85. package/dist/http-request/index.js +8 -0
  86. package/dist/index.cjs +133 -0
  87. package/dist/index.d.cts +23 -0
  88. package/dist/index.d.ts +23 -0
  89. package/dist/index.js +133 -0
  90. package/dist/lsp/index.cjs +10 -0
  91. package/dist/lsp/index.d.cts +35 -0
  92. package/dist/lsp/index.d.ts +35 -0
  93. package/dist/lsp/index.js +10 -0
  94. package/dist/memory/index.cjs +9 -0
  95. package/dist/memory/index.d.cts +63 -0
  96. package/dist/memory/index.d.ts +63 -0
  97. package/dist/memory/index.js +9 -0
  98. package/dist/multi-edit/index.cjs +11 -0
  99. package/dist/multi-edit/index.d.cts +72 -0
  100. package/dist/multi-edit/index.d.ts +72 -0
  101. package/dist/multi-edit/index.js +11 -0
  102. package/dist/read/index.cjs +10 -0
  103. package/dist/read/index.d.cts +67 -0
  104. package/dist/read/index.d.ts +67 -0
  105. package/dist/read/index.js +10 -0
  106. package/dist/sleep/index.cjs +8 -0
  107. package/dist/sleep/index.d.cts +60 -0
  108. package/dist/sleep/index.d.ts +60 -0
  109. package/dist/sleep/index.js +8 -0
  110. package/dist/task-create/index.cjs +9 -0
  111. package/dist/task-create/index.d.cts +19 -0
  112. package/dist/task-create/index.d.ts +19 -0
  113. package/dist/task-create/index.js +9 -0
  114. package/dist/task-get/index.cjs +9 -0
  115. package/dist/task-get/index.d.cts +15 -0
  116. package/dist/task-get/index.d.ts +15 -0
  117. package/dist/task-get/index.js +9 -0
  118. package/dist/task-list/index.cjs +9 -0
  119. package/dist/task-list/index.d.cts +11 -0
  120. package/dist/task-list/index.d.ts +11 -0
  121. package/dist/task-list/index.js +9 -0
  122. package/dist/task-update/index.cjs +9 -0
  123. package/dist/task-update/index.d.cts +31 -0
  124. package/dist/task-update/index.d.ts +31 -0
  125. package/dist/task-update/index.js +9 -0
  126. package/dist/tool-search/index.cjs +8 -0
  127. package/dist/tool-search/index.d.cts +18 -0
  128. package/dist/tool-search/index.d.ts +18 -0
  129. package/dist/tool-search/index.js +8 -0
  130. package/dist/types-3QPDuCXN.d.cts +45 -0
  131. package/dist/types-3QPDuCXN.d.ts +45 -0
  132. package/dist/web-fetch/index.cjs +8 -0
  133. package/dist/web-fetch/index.d.cts +54 -0
  134. package/dist/web-fetch/index.d.ts +54 -0
  135. package/dist/web-fetch/index.js +8 -0
  136. package/dist/web-search/index.cjs +8 -0
  137. package/dist/web-search/index.d.cts +21 -0
  138. package/dist/web-search/index.d.ts +21 -0
  139. package/dist/web-search/index.js +8 -0
  140. package/dist/write/index.cjs +10 -0
  141. package/dist/write/index.d.cts +47 -0
  142. package/dist/write/index.d.ts +47 -0
  143. package/dist/write/index.js +10 -0
  144. package/package.json +170 -20
  145. package/dist/core/index.d.ts +0 -20
  146. package/dist/core/index.js +0 -1
  147. package/dist/core/index.js.map +0 -1
@@ -0,0 +1,142 @@
1
+ // src/bash/index.ts
2
+ import { tool } from "ai";
3
+ import { z } from "zod";
4
+
5
+ // src/shared/shell.ts
6
+ import { spawn } from "child_process";
7
+ var MAX_BUFFER_BYTES = 10 * 1024 * 1024;
8
+ var DEFAULT_TIMEOUT_MS = 12e4;
9
+ var SIGKILL_GRACE_MS = 5e3;
10
+ async function executeShell(command, options) {
11
+ const shellBin = options?.shell ?? process.env.SHELL ?? "/bin/bash";
12
+ const timeout = options?.timeout ?? DEFAULT_TIMEOUT_MS;
13
+ return new Promise((resolve, reject) => {
14
+ const child = spawn(shellBin, ["-c", command], {
15
+ cwd: options?.cwd,
16
+ stdio: ["pipe", "pipe", "pipe"],
17
+ // Prevent visible console window on Windows (no-op elsewhere)
18
+ windowsHide: true
19
+ });
20
+ let stdout = "";
21
+ let stderr = "";
22
+ let stdoutBytes = 0;
23
+ let stderrBytes = 0;
24
+ let settled = false;
25
+ let timeoutId;
26
+ let graceId;
27
+ function cleanup() {
28
+ if (timeoutId !== void 0) {
29
+ clearTimeout(timeoutId);
30
+ timeoutId = void 0;
31
+ }
32
+ if (graceId !== void 0) {
33
+ clearTimeout(graceId);
34
+ graceId = void 0;
35
+ }
36
+ if (abortHandler && options?.signal) {
37
+ options.signal.removeEventListener("abort", abortHandler);
38
+ }
39
+ }
40
+ function settle(result) {
41
+ if (settled) return;
42
+ settled = true;
43
+ cleanup();
44
+ resolve(result);
45
+ }
46
+ child.stdout.on("data", (chunk) => {
47
+ if (stdoutBytes >= MAX_BUFFER_BYTES) return;
48
+ const str = chunk.toString();
49
+ const remaining = MAX_BUFFER_BYTES - stdoutBytes;
50
+ if (chunk.length > remaining) {
51
+ stdout += str.slice(0, remaining);
52
+ stdoutBytes = MAX_BUFFER_BYTES;
53
+ } else {
54
+ stdout += str;
55
+ stdoutBytes += chunk.length;
56
+ }
57
+ });
58
+ child.stderr.on("data", (chunk) => {
59
+ if (stderrBytes >= MAX_BUFFER_BYTES) return;
60
+ const str = chunk.toString();
61
+ const remaining = MAX_BUFFER_BYTES - stderrBytes;
62
+ if (chunk.length > remaining) {
63
+ stderr += str.slice(0, remaining);
64
+ stderrBytes = MAX_BUFFER_BYTES;
65
+ } else {
66
+ stderr += str;
67
+ stderrBytes += chunk.length;
68
+ }
69
+ });
70
+ child.on("exit", (code, signal) => {
71
+ const exitCode = code !== null ? code : signal === "SIGKILL" ? 137 : signal === "SIGTERM" ? 143 : 1;
72
+ settle({ stdout, stderr, exitCode });
73
+ });
74
+ child.on("error", (err) => {
75
+ if (settled) return;
76
+ settled = true;
77
+ cleanup();
78
+ reject(err);
79
+ });
80
+ if (timeout > 0) {
81
+ timeoutId = setTimeout(() => {
82
+ timeoutId = void 0;
83
+ if (settled) return;
84
+ child.kill("SIGTERM");
85
+ graceId = setTimeout(() => {
86
+ graceId = void 0;
87
+ if (settled) return;
88
+ child.kill("SIGKILL");
89
+ }, SIGKILL_GRACE_MS);
90
+ }, timeout);
91
+ }
92
+ const abortHandler = options?.signal ? () => {
93
+ if (settled) return;
94
+ child.kill("SIGTERM");
95
+ } : void 0;
96
+ if (abortHandler && options?.signal) {
97
+ if (options.signal.aborted) {
98
+ child.kill("SIGTERM");
99
+ } else {
100
+ options.signal.addEventListener("abort", abortHandler, { once: true });
101
+ }
102
+ }
103
+ });
104
+ }
105
+
106
+ // src/bash/index.ts
107
+ function createBash(config = {}) {
108
+ const cwd = config.cwd ?? process.cwd();
109
+ const timeout = config.timeout ?? 12e4;
110
+ return tool({
111
+ description: "Execute a shell command and return its output. Runs the command in a bash shell with the configured working directory. Returns stdout, stderr, and exit code. Use this for running build commands, git operations, system administration, and any other shell tasks.",
112
+ inputSchema: z.object({
113
+ command: z.string().describe("The shell command to execute"),
114
+ timeout: z.number().optional().describe("Timeout in milliseconds (default: 120000)"),
115
+ description: z.string().optional().describe("Human-readable description of what the command does")
116
+ }),
117
+ execute: async ({ command, timeout: cmdTimeout }) => {
118
+ try {
119
+ const result = await executeShell(command, {
120
+ cwd,
121
+ timeout: cmdTimeout ?? timeout,
122
+ shell: config.shell
123
+ });
124
+ const parts = [];
125
+ if (result.stdout) parts.push(result.stdout);
126
+ if (result.stderr) parts.push(`STDERR:
127
+ ${result.stderr}`);
128
+ if (result.exitCode !== 0) parts.push(`Exit code: ${result.exitCode}`);
129
+ return parts.length > 0 ? parts.join("\n") : `Command completed with exit code ${result.exitCode}`;
130
+ } catch (error) {
131
+ const msg = error instanceof Error ? error.message : String(error);
132
+ return `Error [bash]: Failed to execute command: ${msg}`;
133
+ }
134
+ }
135
+ });
136
+ }
137
+ var bash = createBash();
138
+
139
+ export {
140
+ createBash,
141
+ bash
142
+ };
@@ -0,0 +1,53 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
+
3
+
4
+
5
+
6
+ var _chunkL5JH4I77cjs = require('./chunk-L5JH4I77.cjs');
7
+
8
+ // src/task-create/index.ts
9
+ var _ai = require('ai');
10
+ var _zod = require('zod');
11
+ var _path = require('path');
12
+ function createTaskCreate(config = {}) {
13
+ const cwd = _nullishCoalesce(config.cwd, () => ( process.cwd()));
14
+ const tasksFile = _nullishCoalesce(config.tasksFile, () => ( _path.join.call(void 0, cwd, ".agentool", "tasks.json")));
15
+ return _ai.tool.call(void 0, {
16
+ description: 'Create a new task to track work. Each task gets a unique ID, starts with "pending" status, and can include optional metadata.',
17
+ inputSchema: _zod.z.object({
18
+ subject: _zod.z.string().describe("A brief title for the task"),
19
+ description: _zod.z.string().describe("What needs to be done"),
20
+ metadata: _zod.z.record(_zod.z.string(), _zod.z.unknown()).optional().describe("Arbitrary metadata to attach to the task")
21
+ }),
22
+ execute: async ({ subject, description, metadata }) => {
23
+ try {
24
+ const tasks = await _chunkL5JH4I77cjs.loadTasks.call(void 0, tasksFile);
25
+ const now = (/* @__PURE__ */ new Date()).toISOString();
26
+ const entry = {
27
+ id: _chunkL5JH4I77cjs.generateId.call(void 0, ),
28
+ subject,
29
+ description,
30
+ status: "pending",
31
+ blocks: [],
32
+ blockedBy: [],
33
+ metadata,
34
+ createdAt: now,
35
+ updatedAt: now
36
+ };
37
+ tasks.push(entry);
38
+ await _chunkL5JH4I77cjs.saveTasks.call(void 0, tasksFile, tasks);
39
+ return `Created task ${entry.id}.
40
+ ${_chunkL5JH4I77cjs.formatTask.call(void 0, entry)}`;
41
+ } catch (error) {
42
+ const msg = error instanceof Error ? error.message : String(error);
43
+ return `Error [task-create]: ${msg}`;
44
+ }
45
+ }
46
+ });
47
+ }
48
+ var taskCreate = createTaskCreate();
49
+
50
+
51
+
52
+
53
+ exports.createTaskCreate = createTaskCreate; exports.taskCreate = taskCreate;
@@ -0,0 +1,99 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/shared/edit-helpers.ts
2
+ var LEFT_SINGLE_CURLY_QUOTE = "\u2018";
3
+ var RIGHT_SINGLE_CURLY_QUOTE = "\u2019";
4
+ var LEFT_DOUBLE_CURLY_QUOTE = "\u201C";
5
+ var RIGHT_DOUBLE_CURLY_QUOTE = "\u201D";
6
+ function normalizeQuotes(str) {
7
+ return str.replaceAll(LEFT_SINGLE_CURLY_QUOTE, "'").replaceAll(RIGHT_SINGLE_CURLY_QUOTE, "'").replaceAll(LEFT_DOUBLE_CURLY_QUOTE, '"').replaceAll(RIGHT_DOUBLE_CURLY_QUOTE, '"');
8
+ }
9
+ function findActualString(fileContent, searchString) {
10
+ if (fileContent.includes(searchString)) {
11
+ return searchString;
12
+ }
13
+ const normalizedSearch = normalizeQuotes(searchString);
14
+ const normalizedFile = normalizeQuotes(fileContent);
15
+ const searchIndex = normalizedFile.indexOf(normalizedSearch);
16
+ if (searchIndex !== -1) {
17
+ return fileContent.substring(
18
+ searchIndex,
19
+ searchIndex + searchString.length
20
+ );
21
+ }
22
+ return null;
23
+ }
24
+ function preserveQuoteStyle(oldString, actualOldString, newString) {
25
+ if (oldString === actualOldString) {
26
+ return newString;
27
+ }
28
+ const hasDoubleQuotes = actualOldString.includes(LEFT_DOUBLE_CURLY_QUOTE) || actualOldString.includes(RIGHT_DOUBLE_CURLY_QUOTE);
29
+ const hasSingleQuotes = actualOldString.includes(LEFT_SINGLE_CURLY_QUOTE) || actualOldString.includes(RIGHT_SINGLE_CURLY_QUOTE);
30
+ if (!hasDoubleQuotes && !hasSingleQuotes) {
31
+ return newString;
32
+ }
33
+ let result = newString;
34
+ if (hasDoubleQuotes) {
35
+ result = applyCurlyDoubleQuotes(result);
36
+ }
37
+ if (hasSingleQuotes) {
38
+ result = applyCurlySingleQuotes(result);
39
+ }
40
+ return result;
41
+ }
42
+ function applyEditToFile(originalContent, oldString, newString, replaceAll = false) {
43
+ const f = replaceAll ? (content, search, replace) => content.replaceAll(search, () => replace) : (content, search, replace) => content.replace(search, () => replace);
44
+ if (newString !== "") {
45
+ return f(originalContent, oldString, newString);
46
+ }
47
+ const stripTrailingNewline = !oldString.endsWith("\n") && originalContent.includes(oldString + "\n");
48
+ return stripTrailingNewline ? f(originalContent, oldString + "\n", newString) : f(originalContent, oldString, newString);
49
+ }
50
+ function isOpeningContext(chars, index) {
51
+ if (index === 0) {
52
+ return true;
53
+ }
54
+ const prev = chars[index - 1];
55
+ return prev === " " || prev === " " || prev === "\n" || prev === "\r" || prev === "(" || prev === "[" || prev === "{" || prev === "\u2014" || // em dash
56
+ prev === "\u2013";
57
+ }
58
+ function applyCurlyDoubleQuotes(str) {
59
+ const chars = [...str];
60
+ const result = [];
61
+ for (let i = 0; i < chars.length; i++) {
62
+ if (chars[i] === '"') {
63
+ result.push(
64
+ isOpeningContext(chars, i) ? LEFT_DOUBLE_CURLY_QUOTE : RIGHT_DOUBLE_CURLY_QUOTE
65
+ );
66
+ } else {
67
+ result.push(chars[i]);
68
+ }
69
+ }
70
+ return result.join("");
71
+ }
72
+ function applyCurlySingleQuotes(str) {
73
+ const chars = [...str];
74
+ const result = [];
75
+ for (let i = 0; i < chars.length; i++) {
76
+ if (chars[i] === "'") {
77
+ const prev = i > 0 ? chars[i - 1] : void 0;
78
+ const next = i < chars.length - 1 ? chars[i + 1] : void 0;
79
+ const prevIsLetter = prev !== void 0 && new RegExp("\\p{L}", "u").test(prev);
80
+ const nextIsLetter = next !== void 0 && new RegExp("\\p{L}", "u").test(next);
81
+ if (prevIsLetter && nextIsLetter) {
82
+ result.push(RIGHT_SINGLE_CURLY_QUOTE);
83
+ } else {
84
+ result.push(
85
+ isOpeningContext(chars, i) ? LEFT_SINGLE_CURLY_QUOTE : RIGHT_SINGLE_CURLY_QUOTE
86
+ );
87
+ }
88
+ } else {
89
+ result.push(chars[i]);
90
+ }
91
+ }
92
+ return result.join("");
93
+ }
94
+
95
+
96
+
97
+
98
+
99
+ exports.findActualString = findActualString; exports.preserveQuoteStyle = preserveQuoteStyle; exports.applyEditToFile = applyEditToFile;
@@ -0,0 +1,112 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/web-fetch/index.ts
2
+ var _ai = require('ai');
3
+ var _zod = require('zod');
4
+
5
+ // src/shared/fetch.ts
6
+ var MAX_MARKDOWN_LENGTH = 1e5;
7
+ var DEFAULT_TIMEOUT_MS = 3e4;
8
+ var DEFAULT_MAX_CONTENT_LENGTH = 10 * 1024 * 1024;
9
+ var turndownPromise;
10
+ function getTurndownService() {
11
+ return turndownPromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("turndown"))).then((m) => {
12
+ const Turndown = m.default;
13
+ return new Turndown();
14
+ });
15
+ }
16
+ function composeSignal(timeoutMs, userSignal) {
17
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
18
+ if (!userSignal) {
19
+ return timeoutSignal;
20
+ }
21
+ return AbortSignal.any([timeoutSignal, userSignal]);
22
+ }
23
+ async function fetchUrl(url, options) {
24
+ const timeoutMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _ => _.timeout]), () => ( DEFAULT_TIMEOUT_MS));
25
+ const maxBytes = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.maxContentLength]), () => ( DEFAULT_MAX_CONTENT_LENGTH));
26
+ const signal = composeSignal(timeoutMs, _optionalChain([options, 'optionalAccess', _3 => _3.signal]));
27
+ const headers = {
28
+ Accept: "text/markdown, text/html, */*"
29
+ };
30
+ if (_optionalChain([options, 'optionalAccess', _4 => _4.userAgent])) {
31
+ headers["User-Agent"] = options.userAgent;
32
+ }
33
+ const response = await fetch(url, { signal, headers });
34
+ const chunks = [];
35
+ let totalBytes = 0;
36
+ if (response.body) {
37
+ const reader = response.body.getReader();
38
+ for (; ; ) {
39
+ const { done, value } = await reader.read();
40
+ if (done) break;
41
+ totalBytes += value.byteLength;
42
+ if (totalBytes > maxBytes) {
43
+ await reader.cancel();
44
+ throw new Error(
45
+ `Response body exceeds maxContentLength (${maxBytes} bytes)`
46
+ );
47
+ }
48
+ chunks.push(value);
49
+ }
50
+ }
51
+ const rawBuffer = Buffer.concat(chunks);
52
+ const byteLength = rawBuffer.length;
53
+ const contentType = _nullishCoalesce(response.headers.get("content-type"), () => ( ""));
54
+ const textContent = rawBuffer.toString("utf-8");
55
+ let content;
56
+ if (contentType.includes("text/html")) {
57
+ const td = await getTurndownService();
58
+ content = td.turndown(textContent);
59
+ } else {
60
+ content = textContent;
61
+ }
62
+ let truncated = false;
63
+ if (content.length > MAX_MARKDOWN_LENGTH) {
64
+ content = content.slice(0, MAX_MARKDOWN_LENGTH);
65
+ truncated = true;
66
+ }
67
+ return {
68
+ content,
69
+ contentType,
70
+ statusCode: response.status,
71
+ byteLength,
72
+ truncated
73
+ };
74
+ }
75
+
76
+ // src/web-fetch/index.ts
77
+ function createWebFetch(config = {}) {
78
+ return _ai.tool.call(void 0, {
79
+ description: "Fetch a URL and return its content. HTML pages are automatically converted to markdown for easier reading. JSON and other text content is returned as-is. Content is truncated at 100,000 characters to manage context size.",
80
+ inputSchema: _zod.z.object({
81
+ url: _zod.z.string().url().describe("The URL to fetch")
82
+ }),
83
+ execute: async ({ url }) => {
84
+ try {
85
+ const result = await fetchUrl(url, {
86
+ timeout: _nullishCoalesce(config.timeout, () => ( 3e4)),
87
+ maxContentLength: config.maxContentLength,
88
+ userAgent: config.userAgent
89
+ });
90
+ const parts = [];
91
+ parts.push(`URL: ${url}`);
92
+ parts.push(`Status: ${result.statusCode}`);
93
+ parts.push(`Content-Type: ${result.contentType}`);
94
+ if (result.truncated) {
95
+ parts.push("(Content truncated to 100,000 characters)");
96
+ }
97
+ parts.push("");
98
+ parts.push(result.content);
99
+ return parts.join("\n");
100
+ } catch (error) {
101
+ const msg = error instanceof Error ? error.message : String(error);
102
+ return `Error [web-fetch]: Failed to fetch ${url}: ${msg}`;
103
+ }
104
+ }
105
+ });
106
+ }
107
+ var webFetch = createWebFetch();
108
+
109
+
110
+
111
+
112
+ exports.createWebFetch = createWebFetch; exports.webFetch = webFetch;
@@ -0,0 +1,197 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/lsp/index.ts
2
+ var _ai = require('ai');
3
+ var _zod = require('zod');
4
+ var _child_process = require('child_process');
5
+ var _promises = require('fs/promises');
6
+ var _url = require('url');
7
+ var _path = require('path');
8
+ var nextId = 1;
9
+ function encodeJsonRpc(msg) {
10
+ const body = JSON.stringify(msg);
11
+ return Buffer.from(`Content-Length: ${Buffer.byteLength(body)}\r
12
+ \r
13
+ ${body}`);
14
+ }
15
+ function parseJsonRpcResponses(buffer) {
16
+ const parsed = [];
17
+ let offset = 0;
18
+ while (offset < buffer.length) {
19
+ const headerEnd = buffer.indexOf("\r\n\r\n", offset);
20
+ if (headerEnd === -1) break;
21
+ const match = /Content-Length:\s*(\d+)/i.exec(buffer.subarray(offset, headerEnd).toString());
22
+ if (!match) break;
23
+ const bodyStart = headerEnd + 4;
24
+ const contentLength = parseInt(match[1], 10);
25
+ if (bodyStart + contentLength > buffer.length) break;
26
+ try {
27
+ parsed.push(JSON.parse(buffer.subarray(bodyStart, bodyStart + contentLength).toString()));
28
+ } catch (e2) {
29
+ }
30
+ offset = bodyStart + contentLength;
31
+ }
32
+ return parsed;
33
+ }
34
+ function operationToMethod(operation) {
35
+ const map = {
36
+ goToDefinition: "textDocument/definition",
37
+ findReferences: "textDocument/references",
38
+ hover: "textDocument/hover",
39
+ documentSymbol: "textDocument/documentSymbol",
40
+ workspaceSymbol: "workspace/symbol",
41
+ goToImplementation: "textDocument/implementation",
42
+ prepareCallHierarchy: "textDocument/prepareCallHierarchy",
43
+ incomingCalls: "textDocument/prepareCallHierarchy",
44
+ outgoingCalls: "textDocument/prepareCallHierarchy"
45
+ };
46
+ return _nullishCoalesce(map[operation], () => ( operation));
47
+ }
48
+ function buildRequestParams(op, uri, line, char) {
49
+ if (op === "workspaceSymbol") return { query: "" };
50
+ const td = { uri };
51
+ if (op === "documentSymbol") return { textDocument: td };
52
+ const pos = { line, character: char };
53
+ if (op === "findReferences") return { textDocument: td, position: pos, context: { includeDeclaration: true } };
54
+ return { textDocument: td, position: pos };
55
+ }
56
+ function sendRequest(proc, method, params) {
57
+ const id = nextId++;
58
+ const msg = { jsonrpc: "2.0", id, method, params };
59
+ proc.stdin.write(encodeJsonRpc(msg));
60
+ return id;
61
+ }
62
+ function sendNotification(proc, method, params) {
63
+ const msg = { jsonrpc: "2.0", method, params };
64
+ proc.stdin.write(encodeJsonRpc(msg));
65
+ }
66
+ function waitForResponse(proc, id, timeoutMs) {
67
+ return new Promise((resolveP, reject) => {
68
+ let buf = Buffer.alloc(0);
69
+ const timer = setTimeout(() => {
70
+ cleanup();
71
+ reject(new Error(`LSP request timed out after ${timeoutMs}ms`));
72
+ }, timeoutMs);
73
+ const cleanup = () => {
74
+ clearTimeout(timer);
75
+ proc.stdout.off("data", onData);
76
+ proc.stdout.off("error", onErr);
77
+ };
78
+ function onData(chunk) {
79
+ buf = Buffer.concat([buf, chunk]);
80
+ for (const msg of parseJsonRpcResponses(buf)) {
81
+ const rpc = msg;
82
+ if (rpc.id === id) {
83
+ cleanup();
84
+ resolveP(rpc.error ? { error: rpc.error } : { result: rpc.result });
85
+ return;
86
+ }
87
+ }
88
+ }
89
+ function onErr(e) {
90
+ cleanup();
91
+ reject(e);
92
+ }
93
+ proc.stdout.on("data", onData);
94
+ proc.stdout.on("error", onErr);
95
+ });
96
+ }
97
+ async function shutdownServer(proc, ms) {
98
+ try {
99
+ const id = sendRequest(proc, "shutdown", {});
100
+ await waitForResponse(proc, id, Math.min(ms, 5e3));
101
+ sendNotification(proc, "exit", {});
102
+ } catch (e3) {
103
+ } finally {
104
+ proc.kill();
105
+ }
106
+ }
107
+ async function executeLspOperation(serverConfig, params, timeoutMs) {
108
+ const absolutePath = _path.resolve.call(void 0, params.cwd, params.filePath);
109
+ const uri = _url.pathToFileURL.call(void 0, absolutePath).href;
110
+ const proc = _child_process.spawn.call(void 0, serverConfig.command, _nullishCoalesce(serverConfig.args, () => ( [])), {
111
+ cwd: params.cwd,
112
+ stdio: ["pipe", "pipe", "pipe"]
113
+ });
114
+ const spawnError = new Promise((_, reject) => {
115
+ proc.on("error", (err) => reject(err));
116
+ });
117
+ try {
118
+ const initId = sendRequest(proc, "initialize", {
119
+ processId: process.pid,
120
+ capabilities: {},
121
+ rootUri: _url.pathToFileURL.call(void 0, params.cwd).href
122
+ });
123
+ const rpc = (id) => Promise.race([waitForResponse(proc, id, timeoutMs), spawnError]);
124
+ await rpc(initId);
125
+ sendNotification(proc, "initialized", {});
126
+ const content = await _promises.readFile.call(void 0, absolutePath, "utf-8");
127
+ const langId = _path.extname.call(void 0, absolutePath).replace(".", "") || "plaintext";
128
+ sendNotification(proc, "textDocument/didOpen", {
129
+ textDocument: { uri, languageId: langId, version: 1, text: content }
130
+ });
131
+ const method = operationToMethod(params.operation);
132
+ const reqParams = buildRequestParams(params.operation, uri, _nullishCoalesce(params.line, () => ( 0)), _nullishCoalesce(params.character, () => ( 0)));
133
+ let response = await rpc(sendRequest(proc, method, reqParams));
134
+ if (response.error) return `Error [lsp]: Server error: ${response.error.message} (code ${response.error.code})`;
135
+ if ((params.operation === "incomingCalls" || params.operation === "outgoingCalls") && Array.isArray(response.result) && response.result.length > 0) {
136
+ const cm = params.operation === "incomingCalls" ? "callHierarchy/incomingCalls" : "callHierarchy/outgoingCalls";
137
+ response = await rpc(sendRequest(proc, cm, { item: response.result[0] }));
138
+ if (response.error) return `Error [lsp]: Server error: ${response.error.message} (code ${response.error.code})`;
139
+ }
140
+ await shutdownServer(proc, timeoutMs);
141
+ return _nullishCoalesce(JSON.stringify(response.result, null, 2), () => ( "null"));
142
+ } catch (error) {
143
+ proc.kill();
144
+ throw error;
145
+ }
146
+ }
147
+ var LSP_OPERATIONS = [
148
+ "goToDefinition",
149
+ "findReferences",
150
+ "hover",
151
+ "documentSymbol",
152
+ "workspaceSymbol",
153
+ "goToImplementation",
154
+ "prepareCallHierarchy",
155
+ "incomingCalls",
156
+ "outgoingCalls"
157
+ ];
158
+ function createLsp(config = {}) {
159
+ const timeoutMs = _nullishCoalesce(config.timeout, () => ( 3e4));
160
+ return _ai.tool.call(void 0, {
161
+ description: "Perform language server operations like go-to-definition, find-references, and hover. Requires LSP server configuration. Supports 9 operations: goToDefinition, findReferences, hover, documentSymbol, workspaceSymbol, goToImplementation, prepareCallHierarchy, incomingCalls, outgoingCalls.",
162
+ inputSchema: _zod.z.object({
163
+ operation: _zod.z.enum(LSP_OPERATIONS).describe("The LSP operation to perform"),
164
+ filePath: _zod.z.string().describe("Path to the file"),
165
+ line: _zod.z.number().int().positive().describe("The line number (1-based, as shown in editors)"),
166
+ character: _zod.z.number().int().positive().describe("The character offset (1-based, as shown in editors)")
167
+ }),
168
+ execute: async ({ operation, filePath, line, character }) => {
169
+ if (!config.servers || Object.keys(config.servers).length === 0) {
170
+ return 'Error [lsp]: No LSP servers configured. Provide server configuration via createLsp({ servers: { ".ts": { command: "typescript-language-server", args: ["--stdio"] } } })';
171
+ }
172
+ const ext = _path.extname.call(void 0, filePath) || "." + filePath.split(".").pop();
173
+ const serverConfig = config.servers[ext];
174
+ if (!serverConfig) {
175
+ const available = Object.keys(config.servers).join(", ");
176
+ return `Error [lsp]: No LSP server configured for ${ext} files. Available: ${available}`;
177
+ }
178
+ try {
179
+ return await executeLspOperation(
180
+ serverConfig,
181
+ { operation, filePath, line: line - 1, character: character - 1, cwd: _nullishCoalesce(config.cwd, () => ( process.cwd())) },
182
+ timeoutMs
183
+ );
184
+ } catch (error) {
185
+ const msg = error instanceof Error ? error.message : String(error);
186
+ return `Error [lsp]: ${operation} failed for ${filePath}: ${msg}`;
187
+ }
188
+ }
189
+ });
190
+ }
191
+ var lsp = createLsp();
192
+
193
+
194
+
195
+
196
+
197
+ exports.executeLspOperation = executeLspOperation; exports.createLsp = createLsp; exports.lsp = lsp;
@@ -0,0 +1,40 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
+
3
+
4
+ var _chunkCAEVLIQBcjs = require('./chunk-CAEVLIQB.cjs');
5
+
6
+
7
+ var _chunkQZ5GS6HWcjs = require('./chunk-QZ5GS6HW.cjs');
8
+
9
+ // src/write/index.ts
10
+ var _ai = require('ai');
11
+ var _zod = require('zod');
12
+ function createWrite(config = {}) {
13
+ const cwd = _nullishCoalesce(config.cwd, () => ( process.cwd()));
14
+ return _ai.tool.call(void 0, {
15
+ description: "Write text content to a file, creating parent directories as needed. If the file exists it is overwritten. Use this to create new files or replace existing file contents.",
16
+ inputSchema: _zod.z.object({
17
+ file_path: _zod.z.string().describe("The absolute path to the file to write (must be absolute, not relative)"),
18
+ content: _zod.z.string().describe("Text content to write to the file")
19
+ }),
20
+ execute: async ({ file_path, content }) => {
21
+ try {
22
+ const absolutePath = _chunkQZ5GS6HWcjs.expandPath.call(void 0, file_path, cwd);
23
+ const existed = await _chunkCAEVLIQBcjs.pathExists.call(void 0, absolutePath);
24
+ await _chunkCAEVLIQBcjs.writeTextContent.call(void 0, absolutePath, content);
25
+ const bytes = Buffer.byteLength(content, "utf-8");
26
+ const verb = existed ? "Updated" : "Created";
27
+ return `${verb} file: ${absolutePath} (${bytes} bytes)`;
28
+ } catch (error) {
29
+ const message = error instanceof Error ? error.message : String(error);
30
+ return `Error [write]: Failed to write file: ${message}`;
31
+ }
32
+ }
33
+ });
34
+ }
35
+ var write = createWrite();
36
+
37
+
38
+
39
+
40
+ exports.createWrite = createWrite; exports.write = write;