@draht/mom 2026.3.2-2
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/CHANGELOG.md +448 -0
- package/README.md +490 -0
- package/dist/agent.d.ts +24 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +758 -0
- package/dist/agent.js.map +1 -0
- package/dist/context.d.ts +70 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +221 -0
- package/dist/context.js.map +1 -0
- package/dist/download.d.ts +2 -0
- package/dist/download.d.ts.map +1 -0
- package/dist/download.js +89 -0
- package/dist/download.js.map +1 -0
- package/dist/events.d.ts +57 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +310 -0
- package/dist/events.js.map +1 -0
- package/dist/log.d.ts +39 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +222 -0
- package/dist/log.js.map +1 -0
- package/dist/main.d.ts +3 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +271 -0
- package/dist/main.js.map +1 -0
- package/dist/sandbox.d.ts +34 -0
- package/dist/sandbox.d.ts.map +1 -0
- package/dist/sandbox.js +183 -0
- package/dist/sandbox.js.map +1 -0
- package/dist/slack.d.ts +128 -0
- package/dist/slack.d.ts.map +1 -0
- package/dist/slack.js +455 -0
- package/dist/slack.js.map +1 -0
- package/dist/store.d.ts +60 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +180 -0
- package/dist/store.js.map +1 -0
- package/dist/tools/attach.d.ts +10 -0
- package/dist/tools/attach.d.ts.map +1 -0
- package/dist/tools/attach.js +34 -0
- package/dist/tools/attach.js.map +1 -0
- package/dist/tools/bash.d.ts +10 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/bash.js +78 -0
- package/dist/tools/bash.js.map +1 -0
- package/dist/tools/edit.d.ts +11 -0
- package/dist/tools/edit.d.ts.map +1 -0
- package/dist/tools/edit.js +131 -0
- package/dist/tools/edit.js.map +1 -0
- package/dist/tools/index.d.ts +5 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +16 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/read.d.ts +11 -0
- package/dist/tools/read.d.ts.map +1 -0
- package/dist/tools/read.js +134 -0
- package/dist/tools/read.js.map +1 -0
- package/dist/tools/truncate.d.ts +57 -0
- package/dist/tools/truncate.d.ts.map +1 -0
- package/dist/tools/truncate.js +184 -0
- package/dist/tools/truncate.js.map +1 -0
- package/dist/tools/write.d.ts +10 -0
- package/dist/tools/write.d.ts.map +1 -0
- package/dist/tools/write.js +33 -0
- package/dist/tools/write.js.map +1 -0
- package/package.json +54 -0
package/dist/store.js
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync } from "fs";
|
|
2
|
+
import { appendFile, writeFile } from "fs/promises";
|
|
3
|
+
import { join } from "path";
|
|
4
|
+
import * as log from "./log.js";
|
|
5
|
+
export class ChannelStore {
|
|
6
|
+
workingDir;
|
|
7
|
+
botToken;
|
|
8
|
+
pendingDownloads = [];
|
|
9
|
+
isDownloading = false;
|
|
10
|
+
// Track recently logged message timestamps to prevent duplicates
|
|
11
|
+
// Key: "channelId:ts", automatically cleaned up after 60 seconds
|
|
12
|
+
recentlyLogged = new Map();
|
|
13
|
+
constructor(config) {
|
|
14
|
+
this.workingDir = config.workingDir;
|
|
15
|
+
this.botToken = config.botToken;
|
|
16
|
+
// Ensure working directory exists
|
|
17
|
+
if (!existsSync(this.workingDir)) {
|
|
18
|
+
mkdirSync(this.workingDir, { recursive: true });
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Get or create the directory for a channel/DM
|
|
23
|
+
*/
|
|
24
|
+
getChannelDir(channelId) {
|
|
25
|
+
const dir = join(this.workingDir, channelId);
|
|
26
|
+
if (!existsSync(dir)) {
|
|
27
|
+
mkdirSync(dir, { recursive: true });
|
|
28
|
+
}
|
|
29
|
+
return dir;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Generate a unique local filename for an attachment
|
|
33
|
+
*/
|
|
34
|
+
generateLocalFilename(originalName, timestamp) {
|
|
35
|
+
// Convert slack timestamp (1234567890.123456) to milliseconds
|
|
36
|
+
const ts = Math.floor(parseFloat(timestamp) * 1000);
|
|
37
|
+
// Sanitize original name (remove problematic characters)
|
|
38
|
+
const sanitized = originalName.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
39
|
+
return `${ts}_${sanitized}`;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Process attachments from a Slack message event
|
|
43
|
+
* Returns attachment metadata and queues downloads
|
|
44
|
+
*/
|
|
45
|
+
processAttachments(channelId, files, timestamp) {
|
|
46
|
+
const attachments = [];
|
|
47
|
+
for (const file of files) {
|
|
48
|
+
const url = file.url_private_download || file.url_private;
|
|
49
|
+
if (!url)
|
|
50
|
+
continue;
|
|
51
|
+
if (!file.name) {
|
|
52
|
+
log.logWarning("Attachment missing name, skipping", url);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
const filename = this.generateLocalFilename(file.name, timestamp);
|
|
56
|
+
const localPath = `${channelId}/attachments/${filename}`;
|
|
57
|
+
attachments.push({
|
|
58
|
+
original: file.name,
|
|
59
|
+
local: localPath,
|
|
60
|
+
});
|
|
61
|
+
// Queue for background download
|
|
62
|
+
this.pendingDownloads.push({ channelId, localPath, url });
|
|
63
|
+
}
|
|
64
|
+
// Trigger background download
|
|
65
|
+
this.processDownloadQueue();
|
|
66
|
+
return attachments;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Log a message to the channel's log.jsonl
|
|
70
|
+
* Returns false if message was already logged (duplicate)
|
|
71
|
+
*/
|
|
72
|
+
async logMessage(channelId, message) {
|
|
73
|
+
// Check for duplicate (same channel + timestamp)
|
|
74
|
+
const dedupeKey = `${channelId}:${message.ts}`;
|
|
75
|
+
if (this.recentlyLogged.has(dedupeKey)) {
|
|
76
|
+
return false; // Already logged
|
|
77
|
+
}
|
|
78
|
+
// Mark as logged and schedule cleanup after 60 seconds
|
|
79
|
+
this.recentlyLogged.set(dedupeKey, Date.now());
|
|
80
|
+
setTimeout(() => this.recentlyLogged.delete(dedupeKey), 60000);
|
|
81
|
+
const logPath = join(this.getChannelDir(channelId), "log.jsonl");
|
|
82
|
+
// Ensure message has a date field
|
|
83
|
+
if (!message.date) {
|
|
84
|
+
// Parse timestamp to get date
|
|
85
|
+
let date;
|
|
86
|
+
if (message.ts.includes(".")) {
|
|
87
|
+
// Slack timestamp format (1234567890.123456)
|
|
88
|
+
date = new Date(parseFloat(message.ts) * 1000);
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
// Epoch milliseconds
|
|
92
|
+
date = new Date(parseInt(message.ts, 10));
|
|
93
|
+
}
|
|
94
|
+
message.date = date.toISOString();
|
|
95
|
+
}
|
|
96
|
+
const line = `${JSON.stringify(message)}\n`;
|
|
97
|
+
await appendFile(logPath, line, "utf-8");
|
|
98
|
+
return true;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Log a bot response
|
|
102
|
+
*/
|
|
103
|
+
async logBotResponse(channelId, text, ts) {
|
|
104
|
+
await this.logMessage(channelId, {
|
|
105
|
+
date: new Date().toISOString(),
|
|
106
|
+
ts,
|
|
107
|
+
user: "bot",
|
|
108
|
+
text,
|
|
109
|
+
attachments: [],
|
|
110
|
+
isBot: true,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Get the timestamp of the last logged message for a channel
|
|
115
|
+
* Returns null if no log exists
|
|
116
|
+
*/
|
|
117
|
+
getLastTimestamp(channelId) {
|
|
118
|
+
const logPath = join(this.workingDir, channelId, "log.jsonl");
|
|
119
|
+
if (!existsSync(logPath)) {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
const content = readFileSync(logPath, "utf-8");
|
|
124
|
+
const lines = content.trim().split("\n");
|
|
125
|
+
if (lines.length === 0 || lines[0] === "") {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
const lastLine = lines[lines.length - 1];
|
|
129
|
+
const message = JSON.parse(lastLine);
|
|
130
|
+
return message.ts;
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Process the download queue in the background
|
|
138
|
+
*/
|
|
139
|
+
async processDownloadQueue() {
|
|
140
|
+
if (this.isDownloading || this.pendingDownloads.length === 0)
|
|
141
|
+
return;
|
|
142
|
+
this.isDownloading = true;
|
|
143
|
+
while (this.pendingDownloads.length > 0) {
|
|
144
|
+
const item = this.pendingDownloads.shift();
|
|
145
|
+
if (!item)
|
|
146
|
+
break;
|
|
147
|
+
try {
|
|
148
|
+
await this.downloadAttachment(item.localPath, item.url);
|
|
149
|
+
// Success - could add success logging here if we have context
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
153
|
+
log.logWarning(`Failed to download attachment`, `${item.localPath}: ${errorMsg}`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
this.isDownloading = false;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Download a single attachment
|
|
160
|
+
*/
|
|
161
|
+
async downloadAttachment(localPath, url) {
|
|
162
|
+
const filePath = join(this.workingDir, localPath);
|
|
163
|
+
// Ensure directory exists
|
|
164
|
+
const dir = join(this.workingDir, localPath.substring(0, localPath.lastIndexOf("/")));
|
|
165
|
+
if (!existsSync(dir)) {
|
|
166
|
+
mkdirSync(dir, { recursive: true });
|
|
167
|
+
}
|
|
168
|
+
const response = await fetch(url, {
|
|
169
|
+
headers: {
|
|
170
|
+
Authorization: `Bearer ${this.botToken}`,
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
if (!response.ok) {
|
|
174
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
175
|
+
}
|
|
176
|
+
const buffer = await response.arrayBuffer();
|
|
177
|
+
await writeFile(filePath, Buffer.from(buffer));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AA6BhC,MAAM,OAAO,YAAY;IAChB,UAAU,CAAS;IACnB,QAAQ,CAAS;IACjB,gBAAgB,GAAsB,EAAE,CAAC;IACzC,aAAa,GAAG,KAAK,CAAC;IAC9B,iEAAiE;IACjE,iEAAiE;IACzD,cAAc,GAAG,IAAI,GAAG,EAAkB,CAAC;IAEnD,YAAY,MAA0B,EAAE;QACvC,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;QACpC,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;QAEhC,kCAAkC;QAClC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;YAClC,SAAS,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACjD,CAAC;IAAA,CACD;IAED;;OAEG;IACH,aAAa,CAAC,SAAiB,EAAU;QACxC,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;QAC7C,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACtB,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS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AI,EAAE,CAAC,CAAC;QACrC,CAAC;QAED,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;YACjC,OAAO,EAAE;gBACR,aAAa,EAAE,UAAU,IAAI,CAAC,QAAQ,EAAE;aACxC;SACD,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YAClB,MAAM,IAAI,KAAK,CAAC,QAAQ,QAAQ,CAAC,MAAM,KAAK,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;QACpE,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC;QAC5C,MAAM,SAAS,CAAC,QAAQ,EAAE,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAAA,CAC/C;CACD","sourcesContent":["import { existsSync, mkdirSync, readFileSync } from \"fs\";\nimport { appendFile, writeFile } from \"fs/promises\";\nimport { join } from \"path\";\nimport * as log from \"./log.js\";\n\nexport interface Attachment {\n\toriginal: string; // original filename from uploader\n\tlocal: string; // path relative to working dir (e.g., \"C12345/attachments/1732531234567_file.png\")\n}\n\nexport interface LoggedMessage {\n\tdate: string; // ISO 8601 date (e.g., \"2025-11-26T10:44:00.000Z\") for easy grepping\n\tts: string; // slack timestamp or epoch ms\n\tuser: string; // user ID (or \"bot\" for bot responses)\n\tuserName?: string; // handle (e.g., \"mario\")\n\tdisplayName?: string; // display name (e.g., \"Mario Zechner\")\n\ttext: string;\n\tattachments: Attachment[];\n\tisBot: boolean;\n}\n\nexport interface ChannelStoreConfig {\n\tworkingDir: string;\n\tbotToken: string; // needed for authenticated file downloads\n}\n\ninterface PendingDownload {\n\tchannelId: string;\n\tlocalPath: string; // relative path\n\turl: string;\n}\n\nexport class ChannelStore {\n\tprivate workingDir: string;\n\tprivate botToken: string;\n\tprivate pendingDownloads: PendingDownload[] = [];\n\tprivate isDownloading = false;\n\t// Track recently logged message timestamps to prevent duplicates\n\t// Key: \"channelId:ts\", automatically cleaned up after 60 seconds\n\tprivate recentlyLogged = new Map<string, number>();\n\n\tconstructor(config: ChannelStoreConfig) {\n\t\tthis.workingDir = config.workingDir;\n\t\tthis.botToken = config.botToken;\n\n\t\t// Ensure working directory exists\n\t\tif (!existsSync(this.workingDir)) {\n\t\t\tmkdirSync(this.workingDir, { recursive: true });\n\t\t}\n\t}\n\n\t/**\n\t * Get or create the directory for a channel/DM\n\t */\n\tgetChannelDir(channelId: string): string {\n\t\tconst dir = join(this.workingDir, channelId);\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\t\treturn dir;\n\t}\n\n\t/**\n\t * Generate a unique local filename for an attachment\n\t */\n\tgenerateLocalFilename(originalName: string, timestamp: string): string {\n\t\t// Convert slack timestamp (1234567890.123456) to milliseconds\n\t\tconst ts = Math.floor(parseFloat(timestamp) * 1000);\n\t\t// Sanitize original name (remove problematic characters)\n\t\tconst sanitized = originalName.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n\t\treturn `${ts}_${sanitized}`;\n\t}\n\n\t/**\n\t * Process attachments from a Slack message event\n\t * Returns attachment metadata and queues downloads\n\t */\n\tprocessAttachments(\n\t\tchannelId: string,\n\t\tfiles: Array<{ name?: string; url_private_download?: string; url_private?: string }>,\n\t\ttimestamp: string,\n\t): Attachment[] {\n\t\tconst attachments: Attachment[] = [];\n\n\t\tfor (const file of files) {\n\t\t\tconst url = file.url_private_download || file.url_private;\n\t\t\tif (!url) continue;\n\t\t\tif (!file.name) {\n\t\t\t\tlog.logWarning(\"Attachment missing name, skipping\", url);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst filename = this.generateLocalFilename(file.name, timestamp);\n\t\t\tconst localPath = `${channelId}/attachments/${filename}`;\n\n\t\t\tattachments.push({\n\t\t\t\toriginal: file.name,\n\t\t\t\tlocal: localPath,\n\t\t\t});\n\n\t\t\t// Queue for background download\n\t\t\tthis.pendingDownloads.push({ channelId, localPath, url });\n\t\t}\n\n\t\t// Trigger background download\n\t\tthis.processDownloadQueue();\n\n\t\treturn attachments;\n\t}\n\n\t/**\n\t * Log a message to the channel's log.jsonl\n\t * Returns false if message was already logged (duplicate)\n\t */\n\tasync logMessage(channelId: string, message: LoggedMessage): Promise<boolean> {\n\t\t// Check for duplicate (same channel + timestamp)\n\t\tconst dedupeKey = `${channelId}:${message.ts}`;\n\t\tif (this.recentlyLogged.has(dedupeKey)) {\n\t\t\treturn false; // Already logged\n\t\t}\n\n\t\t// Mark as logged and schedule cleanup after 60 seconds\n\t\tthis.recentlyLogged.set(dedupeKey, Date.now());\n\t\tsetTimeout(() => this.recentlyLogged.delete(dedupeKey), 60000);\n\n\t\tconst logPath = join(this.getChannelDir(channelId), \"log.jsonl\");\n\n\t\t// Ensure message has a date field\n\t\tif (!message.date) {\n\t\t\t// Parse timestamp to get date\n\t\t\tlet date: Date;\n\t\t\tif (message.ts.includes(\".\")) {\n\t\t\t\t// Slack timestamp format (1234567890.123456)\n\t\t\t\tdate = new Date(parseFloat(message.ts) * 1000);\n\t\t\t} else {\n\t\t\t\t// Epoch milliseconds\n\t\t\t\tdate = new Date(parseInt(message.ts, 10));\n\t\t\t}\n\t\t\tmessage.date = date.toISOString();\n\t\t}\n\n\t\tconst line = `${JSON.stringify(message)}\\n`;\n\t\tawait appendFile(logPath, line, \"utf-8\");\n\t\treturn true;\n\t}\n\n\t/**\n\t * Log a bot response\n\t */\n\tasync logBotResponse(channelId: string, text: string, ts: string): Promise<void> {\n\t\tawait this.logMessage(channelId, {\n\t\t\tdate: new Date().toISOString(),\n\t\t\tts,\n\t\t\tuser: \"bot\",\n\t\t\ttext,\n\t\t\tattachments: [],\n\t\t\tisBot: true,\n\t\t});\n\t}\n\n\t/**\n\t * Get the timestamp of the last logged message for a channel\n\t * Returns null if no log exists\n\t */\n\tgetLastTimestamp(channelId: string): string | null {\n\t\tconst logPath = join(this.workingDir, channelId, \"log.jsonl\");\n\t\tif (!existsSync(logPath)) {\n\t\t\treturn null;\n\t\t}\n\n\t\ttry {\n\t\t\tconst content = readFileSync(logPath, \"utf-8\");\n\t\t\tconst lines = content.trim().split(\"\\n\");\n\t\t\tif (lines.length === 0 || lines[0] === \"\") {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst lastLine = lines[lines.length - 1];\n\t\t\tconst message = JSON.parse(lastLine) as LoggedMessage;\n\t\t\treturn message.ts;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Process the download queue in the background\n\t */\n\tprivate async processDownloadQueue(): Promise<void> {\n\t\tif (this.isDownloading || this.pendingDownloads.length === 0) return;\n\n\t\tthis.isDownloading = true;\n\n\t\twhile (this.pendingDownloads.length > 0) {\n\t\t\tconst item = this.pendingDownloads.shift();\n\t\t\tif (!item) break;\n\n\t\t\ttry {\n\t\t\t\tawait this.downloadAttachment(item.localPath, item.url);\n\t\t\t\t// Success - could add success logging here if we have context\n\t\t\t} catch (error) {\n\t\t\t\tconst errorMsg = error instanceof Error ? error.message : String(error);\n\t\t\t\tlog.logWarning(`Failed to download attachment`, `${item.localPath}: ${errorMsg}`);\n\t\t\t}\n\t\t}\n\n\t\tthis.isDownloading = false;\n\t}\n\n\t/**\n\t * Download a single attachment\n\t */\n\tprivate async downloadAttachment(localPath: string, url: string): Promise<void> {\n\t\tconst filePath = join(this.workingDir, localPath);\n\n\t\t// Ensure directory exists\n\t\tconst dir = join(this.workingDir, localPath.substring(0, localPath.lastIndexOf(\"/\")));\n\t\tif (!existsSync(dir)) {\n\t\t\tmkdirSync(dir, { recursive: true });\n\t\t}\n\n\t\tconst response = await fetch(url, {\n\t\t\theaders: {\n\t\t\t\tAuthorization: `Bearer ${this.botToken}`,\n\t\t\t},\n\t\t});\n\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(`HTTP ${response.status}: ${response.statusText}`);\n\t\t}\n\n\t\tconst buffer = await response.arrayBuffer();\n\t\tawait writeFile(filePath, Buffer.from(buffer));\n\t}\n}\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AgentTool } from "@draht/agent-core";
|
|
2
|
+
export declare function setUploadFunction(fn: (filePath: string, title?: string) => Promise<void>): void;
|
|
3
|
+
declare const attachSchema: import("@sinclair/typebox").TObject<{
|
|
4
|
+
label: import("@sinclair/typebox").TString;
|
|
5
|
+
path: import("@sinclair/typebox").TString;
|
|
6
|
+
title: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
7
|
+
}>;
|
|
8
|
+
export declare const attachTool: AgentTool<typeof attachSchema>;
|
|
9
|
+
export {};
|
|
10
|
+
//# sourceMappingURL=attach.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach.d.ts","sourceRoot":"","sources":["../../src/tools/attach.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAOnD,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAE/F;AAED,QAAA,MAAM,YAAY;;;;EAIhB,CAAC;AAEH,eAAO,MAAM,UAAU,EAAE,SAAS,CAAC,OAAO,YAAY,CA6BrD,CAAC","sourcesContent":["import type { AgentTool } from \"@draht/agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport { basename, resolve as resolvePath } from \"path\";\n\n// This will be set by the agent before running\nlet uploadFn: ((filePath: string, title?: string) => Promise<void>) | null = null;\n\nexport function setUploadFunction(fn: (filePath: string, title?: string) => Promise<void>): void {\n\tuploadFn = fn;\n}\n\nconst attachSchema = Type.Object({\n\tlabel: Type.String({ description: \"Brief description of what you're sharing (shown to user)\" }),\n\tpath: Type.String({ description: \"Path to the file to attach\" }),\n\ttitle: Type.Optional(Type.String({ description: \"Title for the file (defaults to filename)\" })),\n});\n\nexport const attachTool: AgentTool<typeof attachSchema> = {\n\tname: \"attach\",\n\tlabel: \"attach\",\n\tdescription:\n\t\t\"Attach a file to your response. Use this to share files, images, or documents with the user. Only files from /workspace/ can be attached.\",\n\tparameters: attachSchema,\n\texecute: async (\n\t\t_toolCallId: string,\n\t\t{ path, title }: { label: string; path: string; title?: string },\n\t\tsignal?: AbortSignal,\n\t) => {\n\t\tif (!uploadFn) {\n\t\t\tthrow new Error(\"Upload function not configured\");\n\t\t}\n\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Operation aborted\");\n\t\t}\n\n\t\tconst absolutePath = resolvePath(path);\n\t\tconst fileName = title || basename(absolutePath);\n\n\t\tawait uploadFn(absolutePath, fileName);\n\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\" as const, text: `Attached file: ${fileName}` }],\n\t\t\tdetails: undefined,\n\t\t};\n\t},\n};\n"]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
import { basename, resolve as resolvePath } from "path";
|
|
3
|
+
// This will be set by the agent before running
|
|
4
|
+
let uploadFn = null;
|
|
5
|
+
export function setUploadFunction(fn) {
|
|
6
|
+
uploadFn = fn;
|
|
7
|
+
}
|
|
8
|
+
const attachSchema = Type.Object({
|
|
9
|
+
label: Type.String({ description: "Brief description of what you're sharing (shown to user)" }),
|
|
10
|
+
path: Type.String({ description: "Path to the file to attach" }),
|
|
11
|
+
title: Type.Optional(Type.String({ description: "Title for the file (defaults to filename)" })),
|
|
12
|
+
});
|
|
13
|
+
export const attachTool = {
|
|
14
|
+
name: "attach",
|
|
15
|
+
label: "attach",
|
|
16
|
+
description: "Attach a file to your response. Use this to share files, images, or documents with the user. Only files from /workspace/ can be attached.",
|
|
17
|
+
parameters: attachSchema,
|
|
18
|
+
execute: async (_toolCallId, { path, title }, signal) => {
|
|
19
|
+
if (!uploadFn) {
|
|
20
|
+
throw new Error("Upload function not configured");
|
|
21
|
+
}
|
|
22
|
+
if (signal?.aborted) {
|
|
23
|
+
throw new Error("Operation aborted");
|
|
24
|
+
}
|
|
25
|
+
const absolutePath = resolvePath(path);
|
|
26
|
+
const fileName = title || basename(absolutePath);
|
|
27
|
+
await uploadFn(absolutePath, fileName);
|
|
28
|
+
return {
|
|
29
|
+
content: [{ type: "text", text: `Attached file: ${fileName}` }],
|
|
30
|
+
details: undefined,
|
|
31
|
+
};
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
//# sourceMappingURL=attach.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach.js","sourceRoot":"","sources":["../../src/tools/attach.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,MAAM,CAAC;AAExD,+CAA+C;AAC/C,IAAI,QAAQ,GAAiE,IAAI,CAAC;AAElF,MAAM,UAAU,iBAAiB,CAAC,EAAuD,EAAQ;IAChG,QAAQ,GAAG,EAAE,CAAC;AAAA,CACd;AAED,MAAM,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC;IAChC,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,0DAA0D,EAAE,CAAC;IAC/F,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,4BAA4B,EAAE,CAAC;IAChE,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,2CAA2C,EAAE,CAAC,CAAC;CAC/F,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,UAAU,GAAmC;IACzD,IAAI,EAAE,QAAQ;IACd,KAAK,EAAE,QAAQ;IACf,WAAW,EACV,2IAA2I;IAC5I,UAAU,EAAE,YAAY;IACxB,OAAO,EAAE,KAAK,EACb,WAAmB,EACnB,EAAE,IAAI,EAAE,KAAK,EAAmD,EAChE,MAAoB,EACnB,EAAE,CAAC;QACJ,IAAI,CAAC,QAAQ,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;QACnD,CAAC;QAED,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;QACtC,CAAC;QAED,MAAM,YAAY,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;QACvC,MAAM,QAAQ,GAAG,KAAK,IAAI,QAAQ,CAAC,YAAY,CAAC,CAAC;QAEjD,MAAM,QAAQ,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;QAEvC,OAAO;YACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,kBAAkB,QAAQ,EAAE,EAAE,CAAC;YACxE,OAAO,EAAE,SAAS;SAClB,CAAC;IAAA,CACF;CACD,CAAC","sourcesContent":["import type { AgentTool } from \"@draht/agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport { basename, resolve as resolvePath } from \"path\";\n\n// This will be set by the agent before running\nlet uploadFn: ((filePath: string, title?: string) => Promise<void>) | null = null;\n\nexport function setUploadFunction(fn: (filePath: string, title?: string) => Promise<void>): void {\n\tuploadFn = fn;\n}\n\nconst attachSchema = Type.Object({\n\tlabel: Type.String({ description: \"Brief description of what you're sharing (shown to user)\" }),\n\tpath: Type.String({ description: \"Path to the file to attach\" }),\n\ttitle: Type.Optional(Type.String({ description: \"Title for the file (defaults to filename)\" })),\n});\n\nexport const attachTool: AgentTool<typeof attachSchema> = {\n\tname: \"attach\",\n\tlabel: \"attach\",\n\tdescription:\n\t\t\"Attach a file to your response. Use this to share files, images, or documents with the user. Only files from /workspace/ can be attached.\",\n\tparameters: attachSchema,\n\texecute: async (\n\t\t_toolCallId: string,\n\t\t{ path, title }: { label: string; path: string; title?: string },\n\t\tsignal?: AbortSignal,\n\t) => {\n\t\tif (!uploadFn) {\n\t\t\tthrow new Error(\"Upload function not configured\");\n\t\t}\n\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Operation aborted\");\n\t\t}\n\n\t\tconst absolutePath = resolvePath(path);\n\t\tconst fileName = title || basename(absolutePath);\n\n\t\tawait uploadFn(absolutePath, fileName);\n\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\" as const, text: `Attached file: ${fileName}` }],\n\t\t\tdetails: undefined,\n\t\t};\n\t},\n};\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AgentTool } from "@draht/agent-core";
|
|
2
|
+
import type { Executor } from "../sandbox.js";
|
|
3
|
+
declare const bashSchema: import("@sinclair/typebox").TObject<{
|
|
4
|
+
label: import("@sinclair/typebox").TString;
|
|
5
|
+
command: import("@sinclair/typebox").TString;
|
|
6
|
+
timeout: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
|
|
7
|
+
}>;
|
|
8
|
+
export declare function createBashTool(executor: Executor): AgentTool<typeof bashSchema>;
|
|
9
|
+
export {};
|
|
10
|
+
//# sourceMappingURL=bash.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../src/tools/bash.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAEnD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAW9C,QAAA,MAAM,UAAU;;;;EAId,CAAC;AAOH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAoE/E","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { createWriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@draht/agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport type { Executor } from \"../sandbox.js\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateTail } from \"./truncate.js\";\n\n/**\n * Generate a unique temp file path for bash output\n */\nfunction getTempFilePath(): string {\n\tconst id = randomBytes(8).toString(\"hex\");\n\treturn join(tmpdir(), `mom-bash-${id}.log`);\n}\n\nconst bashSchema = Type.Object({\n\tlabel: Type.String({ description: \"Brief description of what this command does (shown to user)\" }),\n\tcommand: Type.String({ description: \"Bash command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\ninterface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\nexport function createBashTool(executor: Executor): AgentTool<typeof bashSchema> {\n\treturn {\n\t\tname: \"bash\",\n\t\tlabel: \"bash\",\n\t\tdescription: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tparameters: bashSchema,\n\t\texecute: async (\n\t\t\t_toolCallId: string,\n\t\t\t{ command, timeout }: { label: string; command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t) => {\n\t\t\t// Track output for potential temp file writing\n\t\t\tlet tempFilePath: string | undefined;\n\t\t\tlet tempFileStream: ReturnType<typeof createWriteStream> | undefined;\n\n\t\t\tconst result = await executor.exec(command, { timeout, signal });\n\t\t\tlet output = \"\";\n\t\t\tif (result.stdout) output += result.stdout;\n\t\t\tif (result.stderr) {\n\t\t\t\tif (output) output += \"\\n\";\n\t\t\t\toutput += result.stderr;\n\t\t\t}\n\n\t\t\tconst totalBytes = Buffer.byteLength(output, \"utf-8\");\n\n\t\t\t// Write to temp file if output exceeds limit\n\t\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\t\ttempFilePath = getTempFilePath();\n\t\t\t\ttempFileStream = createWriteStream(tempFilePath);\n\t\t\t\ttempFileStream.write(output);\n\t\t\t\ttempFileStream.end();\n\t\t\t}\n\n\t\t\t// Apply tail truncation\n\t\t\tconst truncation = truncateTail(output);\n\t\t\tlet outputText = truncation.content || \"(no output)\";\n\n\t\t\t// Build details with truncation info\n\t\t\tlet details: BashToolDetails | undefined;\n\n\t\t\tif (truncation.truncated) {\n\t\t\t\tdetails = {\n\t\t\t\t\ttruncation,\n\t\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t\t};\n\n\t\t\t\t// Build actionable notice\n\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\tconst endLine = truncation.totalLines;\n\n\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t// Edge case: last line alone > 50KB\n\t\t\t\t\tconst lastLineSize = formatSize(Buffer.byteLength(output.split(\"\\n\").pop() || \"\", \"utf-8\"));\n\t\t\t\t\toutputText += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${tempFilePath}]`;\n\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${tempFilePath}]`;\n\t\t\t\t} else {\n\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${tempFilePath}]`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (result.code !== 0) {\n\t\t\t\tthrow new Error(`${outputText}\\n\\nCommand exited with code ${result.code}`.trim());\n\t\t\t}\n\n\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { createWriteStream } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { Type } from "@sinclair/typebox";
|
|
6
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
|
|
7
|
+
/**
|
|
8
|
+
* Generate a unique temp file path for bash output
|
|
9
|
+
*/
|
|
10
|
+
function getTempFilePath() {
|
|
11
|
+
const id = randomBytes(8).toString("hex");
|
|
12
|
+
return join(tmpdir(), `mom-bash-${id}.log`);
|
|
13
|
+
}
|
|
14
|
+
const bashSchema = Type.Object({
|
|
15
|
+
label: Type.String({ description: "Brief description of what this command does (shown to user)" }),
|
|
16
|
+
command: Type.String({ description: "Bash command to execute" }),
|
|
17
|
+
timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })),
|
|
18
|
+
});
|
|
19
|
+
export function createBashTool(executor) {
|
|
20
|
+
return {
|
|
21
|
+
name: "bash",
|
|
22
|
+
label: "bash",
|
|
23
|
+
description: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,
|
|
24
|
+
parameters: bashSchema,
|
|
25
|
+
execute: async (_toolCallId, { command, timeout }, signal) => {
|
|
26
|
+
// Track output for potential temp file writing
|
|
27
|
+
let tempFilePath;
|
|
28
|
+
let tempFileStream;
|
|
29
|
+
const result = await executor.exec(command, { timeout, signal });
|
|
30
|
+
let output = "";
|
|
31
|
+
if (result.stdout)
|
|
32
|
+
output += result.stdout;
|
|
33
|
+
if (result.stderr) {
|
|
34
|
+
if (output)
|
|
35
|
+
output += "\n";
|
|
36
|
+
output += result.stderr;
|
|
37
|
+
}
|
|
38
|
+
const totalBytes = Buffer.byteLength(output, "utf-8");
|
|
39
|
+
// Write to temp file if output exceeds limit
|
|
40
|
+
if (totalBytes > DEFAULT_MAX_BYTES) {
|
|
41
|
+
tempFilePath = getTempFilePath();
|
|
42
|
+
tempFileStream = createWriteStream(tempFilePath);
|
|
43
|
+
tempFileStream.write(output);
|
|
44
|
+
tempFileStream.end();
|
|
45
|
+
}
|
|
46
|
+
// Apply tail truncation
|
|
47
|
+
const truncation = truncateTail(output);
|
|
48
|
+
let outputText = truncation.content || "(no output)";
|
|
49
|
+
// Build details with truncation info
|
|
50
|
+
let details;
|
|
51
|
+
if (truncation.truncated) {
|
|
52
|
+
details = {
|
|
53
|
+
truncation,
|
|
54
|
+
fullOutputPath: tempFilePath,
|
|
55
|
+
};
|
|
56
|
+
// Build actionable notice
|
|
57
|
+
const startLine = truncation.totalLines - truncation.outputLines + 1;
|
|
58
|
+
const endLine = truncation.totalLines;
|
|
59
|
+
if (truncation.lastLinePartial) {
|
|
60
|
+
// Edge case: last line alone > 50KB
|
|
61
|
+
const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
|
|
62
|
+
outputText += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${tempFilePath}]`;
|
|
63
|
+
}
|
|
64
|
+
else if (truncation.truncatedBy === "lines") {
|
|
65
|
+
outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${tempFilePath}]`;
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${tempFilePath}]`;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (result.code !== 0) {
|
|
72
|
+
throw new Error(`${outputText}\n\nCommand exited with code ${result.code}`.trim());
|
|
73
|
+
}
|
|
74
|
+
return { content: [{ type: "text", text: outputText }], details };
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=bash.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bash.js","sourceRoot":"","sources":["../../src/tools/bash.ts"],"names":[],"mappings":"AAAA,OAAO,EA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CAAC,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;oBAC5F,UAAU,IAAI,qBAAqB,UAAU,CAAC,UAAU,CAAC,WAAW,CAAC,YAAY,OAAO,aAAa,YAAY,mBAAmB,YAAY,GAAG,CAAC;gBACrJ,CAAC;qBAAM,IAAI,UAAU,CAAC,WAAW,KAAK,OAAO,EAAE,CAAC;oBAC/C,UAAU,IAAI,sBAAsB,SAAS,IAAI,OAAO,OAAO,UAAU,CAAC,UAAU,kBAAkB,YAAY,GAAG,CAAC;gBACvH,CAAC;qBAAM,CAAC;oBACP,UAAU,IAAI,sBAAsB,SAAS,IAAI,OAAO,OAAO,UAAU,CAAC,UAAU,KAAK,UAAU,CAAC,iBAAiB,CAAC,yBAAyB,YAAY,GAAG,CAAC;gBAChK,CAAC;YACF,CAAC;YAED,IAAI,MAAM,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;gBACvB,MAAM,IAAI,KAAK,CAAC,GAAG,UAAU,gCAAgC,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;YACpF,CAAC;YAED,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC;QAAA,CAClE;KACD,CAAC;AAAA,CACF","sourcesContent":["import { randomBytes } from \"node:crypto\";\nimport { createWriteStream } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentTool } from \"@draht/agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport type { Executor } from \"../sandbox.js\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult, truncateTail } from \"./truncate.js\";\n\n/**\n * Generate a unique temp file path for bash output\n */\nfunction getTempFilePath(): string {\n\tconst id = randomBytes(8).toString(\"hex\");\n\treturn join(tmpdir(), `mom-bash-${id}.log`);\n}\n\nconst bashSchema = Type.Object({\n\tlabel: Type.String({ description: \"Brief description of what this command does (shown to user)\" }),\n\tcommand: Type.String({ description: \"Bash command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n});\n\ninterface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n}\n\nexport function createBashTool(executor: Executor): AgentTool<typeof bashSchema> {\n\treturn {\n\t\tname: \"bash\",\n\t\tlabel: \"bash\",\n\t\tdescription: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tparameters: bashSchema,\n\t\texecute: async (\n\t\t\t_toolCallId: string,\n\t\t\t{ command, timeout }: { label: string; command: string; timeout?: number },\n\t\t\tsignal?: AbortSignal,\n\t\t) => {\n\t\t\t// Track output for potential temp file writing\n\t\t\tlet tempFilePath: string | undefined;\n\t\t\tlet tempFileStream: ReturnType<typeof createWriteStream> | undefined;\n\n\t\t\tconst result = await executor.exec(command, { timeout, signal });\n\t\t\tlet output = \"\";\n\t\t\tif (result.stdout) output += result.stdout;\n\t\t\tif (result.stderr) {\n\t\t\t\tif (output) output += \"\\n\";\n\t\t\t\toutput += result.stderr;\n\t\t\t}\n\n\t\t\tconst totalBytes = Buffer.byteLength(output, \"utf-8\");\n\n\t\t\t// Write to temp file if output exceeds limit\n\t\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\t\ttempFilePath = getTempFilePath();\n\t\t\t\ttempFileStream = createWriteStream(tempFilePath);\n\t\t\t\ttempFileStream.write(output);\n\t\t\t\ttempFileStream.end();\n\t\t\t}\n\n\t\t\t// Apply tail truncation\n\t\t\tconst truncation = truncateTail(output);\n\t\t\tlet outputText = truncation.content || \"(no output)\";\n\n\t\t\t// Build details with truncation info\n\t\t\tlet details: BashToolDetails | undefined;\n\n\t\t\tif (truncation.truncated) {\n\t\t\t\tdetails = {\n\t\t\t\t\ttruncation,\n\t\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t\t};\n\n\t\t\t\t// Build actionable notice\n\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\tconst endLine = truncation.totalLines;\n\n\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t// Edge case: last line alone > 50KB\n\t\t\t\t\tconst lastLineSize = formatSize(Buffer.byteLength(output.split(\"\\n\").pop() || \"\", \"utf-8\"));\n\t\t\t\t\toutputText += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${tempFilePath}]`;\n\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${tempFilePath}]`;\n\t\t\t\t} else {\n\t\t\t\t\toutputText += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${tempFilePath}]`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (result.code !== 0) {\n\t\t\t\tthrow new Error(`${outputText}\\n\\nCommand exited with code ${result.code}`.trim());\n\t\t\t}\n\n\t\t\treturn { content: [{ type: \"text\", text: outputText }], details };\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { AgentTool } from "@draht/agent-core";
|
|
2
|
+
import type { Executor } from "../sandbox.js";
|
|
3
|
+
declare const editSchema: import("@sinclair/typebox").TObject<{
|
|
4
|
+
label: import("@sinclair/typebox").TString;
|
|
5
|
+
path: import("@sinclair/typebox").TString;
|
|
6
|
+
oldText: import("@sinclair/typebox").TString;
|
|
7
|
+
newText: import("@sinclair/typebox").TString;
|
|
8
|
+
}>;
|
|
9
|
+
export declare function createEditTool(executor: Executor): AgentTool<typeof editSchema>;
|
|
10
|
+
export {};
|
|
11
|
+
//# sourceMappingURL=edit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"edit.d.ts","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAGnD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAqF9C,QAAA,MAAM,UAAU;;;;;EAKd,CAAC;AAEH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAAC,OAAO,UAAU,CAAC,CAiE/E","sourcesContent":["import type { AgentTool } from \"@draht/agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport * as Diff from \"diff\";\nimport type { Executor } from \"../sandbox.js\";\n\n/**\n * Generate a unified diff string with line numbers and context\n */\nfunction generateDiffString(oldContent: string, newContent: string, contextLines = 4): string {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\n\t\t\tif (lastWasChange || nextPartIsChange) {\n\t\t\t\tlet linesToShow = raw;\n\t\t\t\tlet skipStart = 0;\n\t\t\t\tlet skipEnd = 0;\n\n\t\t\t\tif (!lastWasChange) {\n\t\t\t\t\tskipStart = Math.max(0, raw.length - contextLines);\n\t\t\t\t\tlinesToShow = raw.slice(skipStart);\n\t\t\t\t}\n\n\t\t\t\tif (!nextPartIsChange && linesToShow.length > contextLines) {\n\t\t\t\t\tskipEnd = linesToShow.length - contextLines;\n\t\t\t\t\tlinesToShow = linesToShow.slice(0, contextLines);\n\t\t\t\t}\n\n\t\t\t\tif (skipStart > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t}\n\n\t\t\t\tfor (const line of linesToShow) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skipEnd > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t}\n\n\t\t\t\toldLineNum += skipStart + skipEnd;\n\t\t\t\tnewLineNum += skipStart + skipEnd;\n\t\t\t} else {\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn output.join(\"\\n\");\n}\n\nconst editSchema = Type.Object({\n\tlabel: Type.String({ description: \"Brief description of the edit you're making (shown to user)\" }),\n\tpath: Type.String({ description: \"Path to the file to edit (relative or absolute)\" }),\n\toldText: Type.String({ description: \"Exact text to find and replace (must match exactly)\" }),\n\tnewText: Type.String({ description: \"New text to replace the old text with\" }),\n});\n\nexport function createEditTool(executor: Executor): AgentTool<typeof editSchema> {\n\treturn {\n\t\tname: \"edit\",\n\t\tlabel: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.\",\n\t\tparameters: editSchema,\n\t\texecute: async (\n\t\t\t_toolCallId: string,\n\t\t\t{ path, oldText, newText }: { label: string; path: string; oldText: string; newText: string },\n\t\t\tsignal?: AbortSignal,\n\t\t) => {\n\t\t\t// Read the file\n\t\t\tconst readResult = await executor.exec(`cat ${shellEscape(path)}`, { signal });\n\t\t\tif (readResult.code !== 0) {\n\t\t\t\tthrow new Error(readResult.stderr || `File not found: ${path}`);\n\t\t\t}\n\n\t\t\tconst content = readResult.stdout;\n\n\t\t\t// Check if old text exists\n\t\t\tif (!content.includes(oldText)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Count occurrences\n\t\t\tconst occurrences = content.split(oldText).length - 1;\n\n\t\t\tif (occurrences > 1) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Perform replacement\n\t\t\tconst index = content.indexOf(oldText);\n\t\t\tconst newContent = content.substring(0, index) + newText + content.substring(index + oldText.length);\n\n\t\t\tif (content === newContent) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Write the file back\n\t\t\tconst writeResult = await executor.exec(`printf '%s' ${shellEscape(newContent)} > ${shellEscape(path)}`, {\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tif (writeResult.code !== 0) {\n\t\t\t\tthrow new Error(writeResult.stderr || `Failed to write file: ${path}`);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Successfully replaced text in ${path}. Changed ${oldText.length} characters to ${newText.length} characters.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: { diff: generateDiffString(content, newContent) },\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction shellEscape(s: string): string {\n\treturn `'${s.replace(/'/g, \"'\\\\''\")}'`;\n}\n"]}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
|
+
import * as Diff from "diff";
|
|
3
|
+
/**
|
|
4
|
+
* Generate a unified diff string with line numbers and context
|
|
5
|
+
*/
|
|
6
|
+
function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
7
|
+
const parts = Diff.diffLines(oldContent, newContent);
|
|
8
|
+
const output = [];
|
|
9
|
+
const oldLines = oldContent.split("\n");
|
|
10
|
+
const newLines = newContent.split("\n");
|
|
11
|
+
const maxLineNum = Math.max(oldLines.length, newLines.length);
|
|
12
|
+
const lineNumWidth = String(maxLineNum).length;
|
|
13
|
+
let oldLineNum = 1;
|
|
14
|
+
let newLineNum = 1;
|
|
15
|
+
let lastWasChange = false;
|
|
16
|
+
for (let i = 0; i < parts.length; i++) {
|
|
17
|
+
const part = parts[i];
|
|
18
|
+
const raw = part.value.split("\n");
|
|
19
|
+
if (raw[raw.length - 1] === "") {
|
|
20
|
+
raw.pop();
|
|
21
|
+
}
|
|
22
|
+
if (part.added || part.removed) {
|
|
23
|
+
for (const line of raw) {
|
|
24
|
+
if (part.added) {
|
|
25
|
+
const lineNum = String(newLineNum).padStart(lineNumWidth, " ");
|
|
26
|
+
output.push(`+${lineNum} ${line}`);
|
|
27
|
+
newLineNum++;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
31
|
+
output.push(`-${lineNum} ${line}`);
|
|
32
|
+
oldLineNum++;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
lastWasChange = true;
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);
|
|
39
|
+
if (lastWasChange || nextPartIsChange) {
|
|
40
|
+
let linesToShow = raw;
|
|
41
|
+
let skipStart = 0;
|
|
42
|
+
let skipEnd = 0;
|
|
43
|
+
if (!lastWasChange) {
|
|
44
|
+
skipStart = Math.max(0, raw.length - contextLines);
|
|
45
|
+
linesToShow = raw.slice(skipStart);
|
|
46
|
+
}
|
|
47
|
+
if (!nextPartIsChange && linesToShow.length > contextLines) {
|
|
48
|
+
skipEnd = linesToShow.length - contextLines;
|
|
49
|
+
linesToShow = linesToShow.slice(0, contextLines);
|
|
50
|
+
}
|
|
51
|
+
if (skipStart > 0) {
|
|
52
|
+
output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
|
|
53
|
+
}
|
|
54
|
+
for (const line of linesToShow) {
|
|
55
|
+
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
56
|
+
output.push(` ${lineNum} ${line}`);
|
|
57
|
+
oldLineNum++;
|
|
58
|
+
newLineNum++;
|
|
59
|
+
}
|
|
60
|
+
if (skipEnd > 0) {
|
|
61
|
+
output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
|
|
62
|
+
}
|
|
63
|
+
oldLineNum += skipStart + skipEnd;
|
|
64
|
+
newLineNum += skipStart + skipEnd;
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
oldLineNum += raw.length;
|
|
68
|
+
newLineNum += raw.length;
|
|
69
|
+
}
|
|
70
|
+
lastWasChange = false;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return output.join("\n");
|
|
74
|
+
}
|
|
75
|
+
const editSchema = Type.Object({
|
|
76
|
+
label: Type.String({ description: "Brief description of the edit you're making (shown to user)" }),
|
|
77
|
+
path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
|
|
78
|
+
oldText: Type.String({ description: "Exact text to find and replace (must match exactly)" }),
|
|
79
|
+
newText: Type.String({ description: "New text to replace the old text with" }),
|
|
80
|
+
});
|
|
81
|
+
export function createEditTool(executor) {
|
|
82
|
+
return {
|
|
83
|
+
name: "edit",
|
|
84
|
+
label: "edit",
|
|
85
|
+
description: "Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.",
|
|
86
|
+
parameters: editSchema,
|
|
87
|
+
execute: async (_toolCallId, { path, oldText, newText }, signal) => {
|
|
88
|
+
// Read the file
|
|
89
|
+
const readResult = await executor.exec(`cat ${shellEscape(path)}`, { signal });
|
|
90
|
+
if (readResult.code !== 0) {
|
|
91
|
+
throw new Error(readResult.stderr || `File not found: ${path}`);
|
|
92
|
+
}
|
|
93
|
+
const content = readResult.stdout;
|
|
94
|
+
// Check if old text exists
|
|
95
|
+
if (!content.includes(oldText)) {
|
|
96
|
+
throw new Error(`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`);
|
|
97
|
+
}
|
|
98
|
+
// Count occurrences
|
|
99
|
+
const occurrences = content.split(oldText).length - 1;
|
|
100
|
+
if (occurrences > 1) {
|
|
101
|
+
throw new Error(`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`);
|
|
102
|
+
}
|
|
103
|
+
// Perform replacement
|
|
104
|
+
const index = content.indexOf(oldText);
|
|
105
|
+
const newContent = content.substring(0, index) + newText + content.substring(index + oldText.length);
|
|
106
|
+
if (content === newContent) {
|
|
107
|
+
throw new Error(`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`);
|
|
108
|
+
}
|
|
109
|
+
// Write the file back
|
|
110
|
+
const writeResult = await executor.exec(`printf '%s' ${shellEscape(newContent)} > ${shellEscape(path)}`, {
|
|
111
|
+
signal,
|
|
112
|
+
});
|
|
113
|
+
if (writeResult.code !== 0) {
|
|
114
|
+
throw new Error(writeResult.stderr || `Failed to write file: ${path}`);
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
content: [
|
|
118
|
+
{
|
|
119
|
+
type: "text",
|
|
120
|
+
text: `Successfully replaced text in ${path}. Changed ${oldText.length} characters to ${newText.length} characters.`,
|
|
121
|
+
},
|
|
122
|
+
],
|
|
123
|
+
details: { diff: generateDiffString(content, newContent) },
|
|
124
|
+
};
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function shellEscape(s) {
|
|
129
|
+
return `'${s.replace(/'/g, "'\\''")}'`;
|
|
130
|
+
}
|
|
131
|
+
//# sourceMappingURL=edit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"edit.js","sourceRoot":"","sources":["../../src/tools/edit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAG7B;;GAEG;AACH,SAAS,kBAAkB,CAAC,UAAkB,EAAE,UAAkB,EAAE,YAAY,GAAG,CAAC,EAAU;IAC7F,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;IACrD,MAAM,MAAM,GAAa,EAAE,CAAC;IAE5B,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACxC,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACxC,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC9D,MAAM,YAAY,GAAG,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I,EAAE,CAAC,CAAC;YACxE,CAAC;YAED,OAAO;gBACN,OAAO,EAAE;oBACR;wBACC,IAAI,EAAE,MAAM;wBACZ,IAAI,EAAE,iCAAiC,IAAI,aAAa,OAAO,CAAC,MAAM,kBAAkB,OAAO,CAAC,MAAM,cAAc;qBACpH;iBACD;gBACD,OAAO,EAAE,EAAE,IAAI,EAAE,kBAAkB,CAAC,OAAO,EAAE,UAAU,CAAC,EAAE;aAC1D,CAAC;QAAA,CACF;KACD,CAAC;AAAA,CACF;AAED,SAAS,WAAW,CAAC,CAAS,EAAU;IACvC,OAAO,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC;AAAA,CACvC","sourcesContent":["import type { AgentTool } from \"@draht/agent-core\";\nimport { Type } from \"@sinclair/typebox\";\nimport * as Diff from \"diff\";\nimport type { Executor } from \"../sandbox.js\";\n\n/**\n * Generate a unified diff string with line numbers and context\n */\nfunction generateDiffString(oldContent: string, newContent: string, contextLines = 4): string {\n\tconst parts = Diff.diffLines(oldContent, newContent);\n\tconst output: string[] = [];\n\n\tconst oldLines = oldContent.split(\"\\n\");\n\tconst newLines = newContent.split(\"\\n\");\n\tconst maxLineNum = Math.max(oldLines.length, newLines.length);\n\tconst lineNumWidth = String(maxLineNum).length;\n\n\tlet oldLineNum = 1;\n\tlet newLineNum = 1;\n\tlet lastWasChange = false;\n\n\tfor (let i = 0; i < parts.length; i++) {\n\t\tconst part = parts[i];\n\t\tconst raw = part.value.split(\"\\n\");\n\t\tif (raw[raw.length - 1] === \"\") {\n\t\t\traw.pop();\n\t\t}\n\n\t\tif (part.added || part.removed) {\n\t\t\tfor (const line of raw) {\n\t\t\t\tif (part.added) {\n\t\t\t\t\tconst lineNum = String(newLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`+${lineNum} ${line}`);\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t} else {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(`-${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlastWasChange = true;\n\t\t} else {\n\t\t\tconst nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);\n\n\t\t\tif (lastWasChange || nextPartIsChange) {\n\t\t\t\tlet linesToShow = raw;\n\t\t\t\tlet skipStart = 0;\n\t\t\t\tlet skipEnd = 0;\n\n\t\t\t\tif (!lastWasChange) {\n\t\t\t\t\tskipStart = Math.max(0, raw.length - contextLines);\n\t\t\t\t\tlinesToShow = raw.slice(skipStart);\n\t\t\t\t}\n\n\t\t\t\tif (!nextPartIsChange && linesToShow.length > contextLines) {\n\t\t\t\t\tskipEnd = linesToShow.length - contextLines;\n\t\t\t\t\tlinesToShow = linesToShow.slice(0, contextLines);\n\t\t\t\t}\n\n\t\t\t\tif (skipStart > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t}\n\n\t\t\t\tfor (const line of linesToShow) {\n\t\t\t\t\tconst lineNum = String(oldLineNum).padStart(lineNumWidth, \" \");\n\t\t\t\t\toutput.push(` ${lineNum} ${line}`);\n\t\t\t\t\toldLineNum++;\n\t\t\t\t\tnewLineNum++;\n\t\t\t\t}\n\n\t\t\t\tif (skipEnd > 0) {\n\t\t\t\t\toutput.push(` ${\"\".padStart(lineNumWidth, \" \")} ...`);\n\t\t\t\t}\n\n\t\t\t\toldLineNum += skipStart + skipEnd;\n\t\t\t\tnewLineNum += skipStart + skipEnd;\n\t\t\t} else {\n\t\t\t\toldLineNum += raw.length;\n\t\t\t\tnewLineNum += raw.length;\n\t\t\t}\n\n\t\t\tlastWasChange = false;\n\t\t}\n\t}\n\n\treturn output.join(\"\\n\");\n}\n\nconst editSchema = Type.Object({\n\tlabel: Type.String({ description: \"Brief description of the edit you're making (shown to user)\" }),\n\tpath: Type.String({ description: \"Path to the file to edit (relative or absolute)\" }),\n\toldText: Type.String({ description: \"Exact text to find and replace (must match exactly)\" }),\n\tnewText: Type.String({ description: \"New text to replace the old text with\" }),\n});\n\nexport function createEditTool(executor: Executor): AgentTool<typeof editSchema> {\n\treturn {\n\t\tname: \"edit\",\n\t\tlabel: \"edit\",\n\t\tdescription:\n\t\t\t\"Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.\",\n\t\tparameters: editSchema,\n\t\texecute: async (\n\t\t\t_toolCallId: string,\n\t\t\t{ path, oldText, newText }: { label: string; path: string; oldText: string; newText: string },\n\t\t\tsignal?: AbortSignal,\n\t\t) => {\n\t\t\t// Read the file\n\t\t\tconst readResult = await executor.exec(`cat ${shellEscape(path)}`, { signal });\n\t\t\tif (readResult.code !== 0) {\n\t\t\t\tthrow new Error(readResult.stderr || `File not found: ${path}`);\n\t\t\t}\n\n\t\t\tconst content = readResult.stdout;\n\n\t\t\t// Check if old text exists\n\t\t\tif (!content.includes(oldText)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Could not find the exact text in ${path}. The old text must match exactly including all whitespace and newlines.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Count occurrences\n\t\t\tconst occurrences = content.split(oldText).length - 1;\n\n\t\t\tif (occurrences > 1) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Perform replacement\n\t\t\tconst index = content.indexOf(oldText);\n\t\t\tconst newContent = content.substring(0, index) + newText + content.substring(index + oldText.length);\n\n\t\t\tif (content === newContent) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Write the file back\n\t\t\tconst writeResult = await executor.exec(`printf '%s' ${shellEscape(newContent)} > ${shellEscape(path)}`, {\n\t\t\t\tsignal,\n\t\t\t});\n\t\t\tif (writeResult.code !== 0) {\n\t\t\t\tthrow new Error(writeResult.stderr || `Failed to write file: ${path}`);\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `Successfully replaced text in ${path}. Changed ${oldText.length} characters to ${newText.length} characters.`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: { diff: generateDiffString(content, newContent) },\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction shellEscape(s: string): string {\n\treturn `'${s.replace(/'/g, \"'\\\\''\")}'`;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAO9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,wBAAgB,cAAc,CAAC,QAAQ,EAAE,QAAQ,GAAG,SAAS,CAAC,GAAG,CAAC,EAAE,CAQnE","sourcesContent":["import type { AgentTool } from \"@draht/agent-core\";\nimport type { Executor } from \"../sandbox.js\";\nimport { attachTool } from \"./attach.js\";\nimport { createBashTool } from \"./bash.js\";\nimport { createEditTool } from \"./edit.js\";\nimport { createReadTool } from \"./read.js\";\nimport { createWriteTool } from \"./write.js\";\n\nexport { setUploadFunction } from \"./attach.js\";\n\nexport function createMomTools(executor: Executor): AgentTool<any>[] {\n\treturn [\n\t\tcreateReadTool(executor),\n\t\tcreateBashTool(executor),\n\t\tcreateEditTool(executor),\n\t\tcreateWriteTool(executor),\n\t\tattachTool,\n\t];\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { attachTool } from "./attach.js";
|
|
2
|
+
import { createBashTool } from "./bash.js";
|
|
3
|
+
import { createEditTool } from "./edit.js";
|
|
4
|
+
import { createReadTool } from "./read.js";
|
|
5
|
+
import { createWriteTool } from "./write.js";
|
|
6
|
+
export { setUploadFunction } from "./attach.js";
|
|
7
|
+
export function createMomTools(executor) {
|
|
8
|
+
return [
|
|
9
|
+
createReadTool(executor),
|
|
10
|
+
createBashTool(executor),
|
|
11
|
+
createEditTool(executor),
|
|
12
|
+
createWriteTool(executor),
|
|
13
|
+
attachTool,
|
|
14
|
+
];
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/tools/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,UAAU,cAAc,CAAC,QAAkB,EAAoB;IACpE,OAAO;QACN,cAAc,CAAC,QAAQ,CAAC;QACxB,cAAc,CAAC,QAAQ,CAAC;QACxB,cAAc,CAAC,QAAQ,CAAC;QACxB,eAAe,CAAC,QAAQ,CAAC;QACzB,UAAU;KACV,CAAC;AAAA,CACF","sourcesContent":["import type { AgentTool } from \"@draht/agent-core\";\nimport type { Executor } from \"../sandbox.js\";\nimport { attachTool } from \"./attach.js\";\nimport { createBashTool } from \"./bash.js\";\nimport { createEditTool } from \"./edit.js\";\nimport { createReadTool } from \"./read.js\";\nimport { createWriteTool } from \"./write.js\";\n\nexport { setUploadFunction } from \"./attach.js\";\n\nexport function createMomTools(executor: Executor): AgentTool<any>[] {\n\treturn [\n\t\tcreateReadTool(executor),\n\t\tcreateBashTool(executor),\n\t\tcreateEditTool(executor),\n\t\tcreateWriteTool(executor),\n\t\tattachTool,\n\t];\n}\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { AgentTool } from "@draht/agent-core";
|
|
2
|
+
import type { Executor } from "../sandbox.js";
|
|
3
|
+
declare const readSchema: import("@sinclair/typebox").TObject<{
|
|
4
|
+
label: import("@sinclair/typebox").TString;
|
|
5
|
+
path: import("@sinclair/typebox").TString;
|
|
6
|
+
offset: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
|
|
7
|
+
limit: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
|
|
8
|
+
}>;
|
|
9
|
+
export declare function createReadTool(executor: Executor): AgentTool<typeof readSchema>;
|
|
10
|
+
export {};
|
|
11
|
+
//# sourceMappingURL=read.d.ts.map
|