zeitlich 0.1.1 → 0.2.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 (58) hide show
  1. package/README.md +165 -180
  2. package/dist/index.cjs +1314 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +128 -0
  5. package/dist/index.d.ts +51 -75
  6. package/dist/index.js +741 -1091
  7. package/dist/index.js.map +1 -1
  8. package/dist/workflow-uVNF7zoe.d.cts +941 -0
  9. package/dist/workflow-uVNF7zoe.d.ts +941 -0
  10. package/dist/workflow.cjs +914 -0
  11. package/dist/workflow.cjs.map +1 -0
  12. package/dist/workflow.d.cts +5 -0
  13. package/dist/workflow.d.ts +2 -1
  14. package/dist/workflow.js +543 -423
  15. package/dist/workflow.js.map +1 -1
  16. package/package.json +19 -17
  17. package/src/activities.ts +112 -0
  18. package/src/index.ts +49 -0
  19. package/src/lib/fs.ts +80 -0
  20. package/src/lib/model-invoker.ts +75 -0
  21. package/src/lib/session.ts +216 -0
  22. package/src/lib/state-manager.ts +268 -0
  23. package/src/lib/thread-manager.ts +169 -0
  24. package/src/lib/tool-router.ts +717 -0
  25. package/src/lib/types.ts +354 -0
  26. package/src/plugin.ts +28 -0
  27. package/src/tools/ask-user-question/handler.ts +25 -0
  28. package/src/tools/ask-user-question/tool.ts +46 -0
  29. package/src/tools/bash/bash.test.ts +104 -0
  30. package/src/tools/bash/handler.ts +36 -0
  31. package/src/tools/bash/tool.ts +20 -0
  32. package/src/tools/edit/handler.ts +156 -0
  33. package/src/tools/edit/tool.ts +39 -0
  34. package/src/tools/glob/handler.ts +62 -0
  35. package/src/tools/glob/tool.ts +27 -0
  36. package/src/tools/grep/tool.ts +45 -0
  37. package/src/tools/read/tool.ts +33 -0
  38. package/src/tools/task/handler.ts +75 -0
  39. package/src/tools/task/tool.ts +96 -0
  40. package/src/tools/task-create/handler.ts +49 -0
  41. package/src/tools/task-create/tool.ts +66 -0
  42. package/src/tools/task-get/handler.ts +38 -0
  43. package/src/tools/task-get/tool.ts +11 -0
  44. package/src/tools/task-list/handler.ts +33 -0
  45. package/src/tools/task-list/tool.ts +9 -0
  46. package/src/tools/task-update/handler.ts +79 -0
  47. package/src/tools/task-update/tool.ts +20 -0
  48. package/src/tools/write/tool.ts +26 -0
  49. package/src/workflow.ts +138 -0
  50. package/tsup.config.ts +20 -0
  51. package/dist/index.d.mts +0 -152
  52. package/dist/index.mjs +0 -1587
  53. package/dist/index.mjs.map +0 -1
  54. package/dist/workflow-7_MT-5-w.d.mts +0 -1203
  55. package/dist/workflow-7_MT-5-w.d.ts +0 -1203
  56. package/dist/workflow.d.mts +0 -4
  57. package/dist/workflow.mjs +0 -739
  58. package/dist/workflow.mjs.map +0 -1
package/dist/index.mjs DELETED
@@ -1,1587 +0,0 @@
1
- import { workflowInfo, uuid4, executeChild, proxyActivities } from '@temporalio/workflow';
2
- import z2, { z } from 'zod';
3
- import { minimatch } from 'minimatch';
4
- import { SimplePlugin } from '@temporalio/plugin';
5
- import { mapStoredMessageToChatMessage, SystemMessage, mapStoredMessagesToChatMessages, AIMessage, ToolMessage, HumanMessage } from '@langchain/core/messages';
6
- import crypto from 'crypto';
7
-
8
- // src/lib/session.ts
9
- var TASK_TOOL = "Task";
10
- function buildTaskDescription(subagents) {
11
- const subagentList = subagents.map((s) => `- **${s.name}**: ${s.description}`).join("\n");
12
- return `Launch a new agent to handle complex, multi-step tasks autonomously.
13
-
14
- The ${TASK_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
15
-
16
- Available agent types:
17
-
18
- ${subagentList}
19
-
20
- When using the ${TASK_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
21
-
22
- Usage notes:
23
-
24
- - Always include a short description (3-5 words) summarizing what the agent will do
25
- - Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
26
- - When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.
27
- - Each invocation starts fresh - provide a detailed task description with all necessary context.
28
- - Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.
29
- - The agent's outputs should generally be trusted
30
- - Clearly tell the agent what type of work you expect since it is not aware of the user's intent
31
- - If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.`;
32
- }
33
- function createTaskTool(subagents) {
34
- if (subagents.length === 0) {
35
- throw new Error("createTaskTool requires at least one subagent");
36
- }
37
- const names = subagents.map((s) => s.name);
38
- return {
39
- name: TASK_TOOL,
40
- description: buildTaskDescription(subagents),
41
- schema: z2.object({
42
- subagent: z2.enum(names).describe("The type of subagent to launch"),
43
- description: z2.string().describe("A short (3-5 word) description of the task"),
44
- prompt: z2.string().describe("The task for the agent to perform")
45
- })
46
- };
47
- }
48
- function createTaskHandler(subagents) {
49
- const { workflowId: parentWorkflowId, taskQueue: parentTaskQueue } = workflowInfo();
50
- return async (args, _toolCallId) => {
51
- const config = subagents.find((s) => s.name === args.subagent);
52
- if (!config) {
53
- throw new Error(
54
- `Unknown subagent: ${args.subagent}. Available: ${subagents.map((s) => s.name).join(", ")}`
55
- );
56
- }
57
- const childWorkflowId = `${parentWorkflowId}-${args.subagent}-${uuid4()}`;
58
- const childResult = await executeChild(config.workflowType, {
59
- workflowId: childWorkflowId,
60
- args: [{ prompt: args.prompt }],
61
- taskQueue: config.taskQueue ?? parentTaskQueue
62
- });
63
- const validated = config.resultSchema ? config.resultSchema.parse(childResult) : childResult;
64
- const content = typeof validated === "string" ? validated : JSON.stringify(validated, null, 2);
65
- return {
66
- content,
67
- result: {
68
- result: validated,
69
- childWorkflowId
70
- }
71
- };
72
- };
73
- }
74
-
75
- // src/lib/subagent-support.ts
76
- function withSubagentSupport(userTools, config) {
77
- if (config.subagents.length === 0) {
78
- throw new Error("withSubagentSupport requires at least one subagent");
79
- }
80
- const taskTool = createTaskTool(config.subagents);
81
- const taskHandler = createTaskHandler(config.subagents);
82
- return {
83
- tools: {
84
- ...userTools,
85
- Task: taskTool
86
- },
87
- taskHandler
88
- };
89
- }
90
- function hasTaskTool(tools) {
91
- return "Task" in tools;
92
- }
93
-
94
- // src/lib/session.ts
95
- var createSession = async ({ threadId, agentName, maxTurns = 50, metadata = {} }, {
96
- runAgent,
97
- promptManager,
98
- toolRouter,
99
- toolRegistry,
100
- hooks = {}
101
- }) => {
102
- const { initializeThread, appendHumanMessage, parseToolCalls } = proxyActivities({
103
- startToCloseTimeout: "30m",
104
- retry: {
105
- maximumAttempts: 6,
106
- initialInterval: "5s",
107
- maximumInterval: "15m",
108
- backoffCoefficient: 4
109
- },
110
- heartbeatTimeout: "5m"
111
- });
112
- const callSessionEnd = async (exitReason, turns) => {
113
- if (hooks.onSessionEnd) {
114
- await hooks.onSessionEnd({
115
- threadId,
116
- agentName,
117
- exitReason,
118
- turns,
119
- metadata
120
- });
121
- }
122
- };
123
- return {
124
- runSession: async (prompt, stateManager) => {
125
- if (hooks.onSessionStart) {
126
- await hooks.onSessionStart({
127
- threadId,
128
- agentName,
129
- metadata
130
- });
131
- }
132
- await initializeThread(threadId);
133
- await appendHumanMessage(
134
- threadId,
135
- await promptManager.buildContextMessage(prompt)
136
- );
137
- let exitReason = "completed";
138
- try {
139
- while (stateManager.isRunning() && !stateManager.isTerminal() && stateManager.getTurns() < maxTurns) {
140
- stateManager.incrementTurns();
141
- const currentTurn = stateManager.getTurns();
142
- const { message, stopReason } = await runAgent(
143
- {
144
- threadId,
145
- agentName,
146
- metadata
147
- },
148
- {
149
- systemPrompt: await promptManager.getSystemPrompt()
150
- }
151
- );
152
- if (stopReason === "end_turn") {
153
- stateManager.complete();
154
- exitReason = "completed";
155
- return message;
156
- }
157
- if (!toolRouter || !toolRegistry) {
158
- stateManager.complete();
159
- exitReason = "completed";
160
- return message;
161
- }
162
- const rawToolCalls = await parseToolCalls(message);
163
- const parsedToolCalls = rawToolCalls.map(
164
- (tc) => toolRegistry.parseToolCall(tc)
165
- );
166
- await toolRouter.processToolCalls(parsedToolCalls, {
167
- turn: currentTurn
168
- });
169
- if (stateManager.getStatus() === "WAITING_FOR_INPUT") {
170
- exitReason = "waiting_for_input";
171
- break;
172
- }
173
- }
174
- if (stateManager.getTurns() >= maxTurns && stateManager.isRunning()) {
175
- exitReason = "max_turns";
176
- }
177
- } catch (error) {
178
- exitReason = "failed";
179
- throw error;
180
- } finally {
181
- await callSessionEnd(exitReason, stateManager.getTurns());
182
- }
183
- return null;
184
- }
185
- };
186
- };
187
-
188
- // src/lib/types.ts
189
- function isTerminalStatus(status) {
190
- return status === "COMPLETED" || status === "FAILED" || status === "CANCELLED";
191
- }
192
-
193
- // src/lib/state-manager.ts
194
- function createAgentStateManager(config) {
195
- let status = "RUNNING";
196
- let version = 0;
197
- let turns = 0;
198
- const customState = { ...config?.initialState ?? {} };
199
- function buildState() {
200
- return {
201
- status,
202
- version,
203
- turns,
204
- ...customState
205
- };
206
- }
207
- return {
208
- getStatus() {
209
- return status;
210
- },
211
- isRunning() {
212
- return status === "RUNNING";
213
- },
214
- isTerminal() {
215
- return isTerminalStatus(status);
216
- },
217
- getTurns() {
218
- return turns;
219
- },
220
- getVersion() {
221
- return version;
222
- },
223
- run() {
224
- status = "RUNNING";
225
- version++;
226
- },
227
- waitForInput() {
228
- status = "WAITING_FOR_INPUT";
229
- version++;
230
- },
231
- complete() {
232
- status = "COMPLETED";
233
- version++;
234
- },
235
- fail() {
236
- status = "FAILED";
237
- version++;
238
- },
239
- cancel() {
240
- status = "CANCELLED";
241
- version++;
242
- },
243
- incrementVersion() {
244
- version++;
245
- },
246
- incrementTurns() {
247
- turns++;
248
- },
249
- get(key) {
250
- return customState[key];
251
- },
252
- set(key, value) {
253
- customState[key] = value;
254
- version++;
255
- },
256
- getCurrentState() {
257
- return buildState();
258
- },
259
- shouldReturnFromWait(lastKnownVersion) {
260
- return version > lastKnownVersion || isTerminalStatus(status);
261
- }
262
- };
263
- }
264
- var AGENT_HANDLER_NAMES = {
265
- getAgentState: "getAgentState",
266
- waitForStateChange: "waitForStateChange",
267
- addMessage: "addMessage"
268
- };
269
-
270
- // src/lib/prompt-manager.ts
271
- function createPromptManager(config) {
272
- const { baseSystemPrompt, instructionsPrompt, buildContextMessage } = config;
273
- async function resolvePrompt(prompt) {
274
- if (typeof prompt === "function") {
275
- return prompt();
276
- }
277
- return prompt;
278
- }
279
- return {
280
- async getSystemPrompt() {
281
- const base = await resolvePrompt(baseSystemPrompt);
282
- const instructions = await resolvePrompt(instructionsPrompt);
283
- return [base, instructions].join("\n");
284
- },
285
- async buildContextMessage(context) {
286
- return buildContextMessage(context);
287
- }
288
- };
289
- }
290
-
291
- // src/lib/tool-registry.ts
292
- function createToolRegistry(tools) {
293
- const toolMap = /* @__PURE__ */ new Map();
294
- for (const [_key, tool] of Object.entries(tools)) {
295
- toolMap.set(tool.name, tool);
296
- }
297
- return {
298
- parseToolCall(toolCall) {
299
- const tool = toolMap.get(toolCall.name);
300
- if (!tool) {
301
- throw new Error(`Tool ${toolCall.name} not found`);
302
- }
303
- const parsedArgs = tool.schema.parse(toolCall.args);
304
- return {
305
- id: toolCall.id ?? "",
306
- name: toolCall.name,
307
- args: parsedArgs
308
- };
309
- },
310
- getToolList() {
311
- return Object.values(tools);
312
- },
313
- getTool(name) {
314
- return tools[name];
315
- },
316
- hasTool(name) {
317
- return toolMap.has(name);
318
- },
319
- getToolNames() {
320
- return Array.from(toolMap.keys());
321
- }
322
- };
323
- }
324
-
325
- // src/lib/tool-router.ts
326
- function createToolRouter(options, handlers) {
327
- const { parallel = true, threadId, appendToolResult, hooks } = options;
328
- async function processToolCall(toolCall, turn) {
329
- const startTime = Date.now();
330
- let effectiveArgs = toolCall.args;
331
- if (hooks?.onPreToolUse) {
332
- const preResult = await hooks.onPreToolUse({
333
- toolCall,
334
- threadId,
335
- turn
336
- });
337
- if (preResult?.skip) {
338
- await appendToolResult({
339
- threadId,
340
- toolCallId: toolCall.id,
341
- content: JSON.stringify({
342
- skipped: true,
343
- reason: "Skipped by PreToolUse hook"
344
- })
345
- });
346
- return null;
347
- }
348
- if (preResult?.modifiedArgs !== void 0) {
349
- effectiveArgs = preResult.modifiedArgs;
350
- }
351
- }
352
- const handler = handlers[toolCall.name];
353
- let result;
354
- let content;
355
- try {
356
- if (handler) {
357
- const response = await handler(
358
- effectiveArgs,
359
- toolCall.id
360
- );
361
- result = response.result;
362
- content = response.content;
363
- } else {
364
- result = { error: `Unknown tool: ${toolCall.name}` };
365
- content = JSON.stringify(result, null, 2);
366
- }
367
- } catch (error) {
368
- if (hooks?.onPostToolUseFailure) {
369
- const failureResult = await hooks.onPostToolUseFailure({
370
- toolCall,
371
- error: error instanceof Error ? error : new Error(String(error)),
372
- threadId,
373
- turn
374
- });
375
- if (failureResult?.fallbackContent !== void 0) {
376
- content = failureResult.fallbackContent;
377
- result = { error: String(error), recovered: true };
378
- } else if (failureResult?.suppress) {
379
- content = JSON.stringify({ error: String(error), suppressed: true });
380
- result = { error: String(error), suppressed: true };
381
- } else {
382
- throw error;
383
- }
384
- } else {
385
- throw error;
386
- }
387
- }
388
- await appendToolResult({ threadId, toolCallId: toolCall.id, content });
389
- const toolResult = {
390
- toolCallId: toolCall.id,
391
- name: toolCall.name,
392
- result
393
- };
394
- if (hooks?.onPostToolUse) {
395
- const durationMs = Date.now() - startTime;
396
- await hooks.onPostToolUse({
397
- toolCall,
398
- result: toolResult,
399
- threadId,
400
- turn,
401
- durationMs
402
- });
403
- }
404
- return toolResult;
405
- }
406
- return {
407
- async processToolCalls(toolCalls, context) {
408
- if (toolCalls.length === 0) {
409
- return [];
410
- }
411
- const turn = context?.turn ?? 0;
412
- if (parallel) {
413
- const results2 = await Promise.all(
414
- toolCalls.map((tc) => processToolCall(tc, turn))
415
- );
416
- return results2.filter(
417
- (r) => r !== null
418
- );
419
- }
420
- const results = [];
421
- for (const toolCall of toolCalls) {
422
- const result = await processToolCall(toolCall, turn);
423
- if (result !== null) {
424
- results.push(result);
425
- }
426
- }
427
- return results;
428
- },
429
- async processToolCallsByName(toolCalls, toolName, handler) {
430
- const matchingCalls = toolCalls.filter((tc) => tc.name === toolName);
431
- if (matchingCalls.length === 0) {
432
- return [];
433
- }
434
- const processOne = async (toolCall) => {
435
- const response = await handler(
436
- toolCall.args,
437
- toolCall.id
438
- );
439
- await appendToolResult({
440
- threadId,
441
- toolCallId: toolCall.id,
442
- content: response.content
443
- });
444
- return {
445
- toolCallId: toolCall.id,
446
- name: toolCall.name,
447
- result: response.result
448
- };
449
- };
450
- if (parallel) {
451
- return Promise.all(matchingCalls.map(processOne));
452
- }
453
- const results = [];
454
- for (const toolCall of matchingCalls) {
455
- results.push(await processOne(toolCall));
456
- }
457
- return results;
458
- },
459
- filterByName(toolCalls, name) {
460
- return toolCalls.filter(
461
- (tc) => tc.name === name
462
- );
463
- },
464
- hasToolCall(toolCalls, name) {
465
- return toolCalls.some((tc) => tc.name === name);
466
- },
467
- getResultsByName(results, name) {
468
- return results.filter(
469
- (r) => r.name === name
470
- );
471
- }
472
- };
473
- }
474
- function hasNoOtherToolCalls(toolCalls, excludeName) {
475
- return toolCalls.filter((tc) => tc.name !== excludeName).length === 0;
476
- }
477
- var askUserQuestionTool = {
478
- name: "AskUserQuestion",
479
- description: `Use this tool when you need to ask the user questions during execution. This allows you to:
480
-
481
- 1. Gather user preferences or requirements
482
- 2. Clarify ambiguous instructions
483
- 3. Get decisions on implementation choices as you work
484
- 4. Offer choices to the user about what direction to take.
485
-
486
- Usage notes:
487
-
488
- * Users will always be able to select "Other" to provide custom text input
489
- * Use multiSelect: true to allow multiple answers to be selected for a question
490
- * If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label
491
- `,
492
- schema: z2.object({
493
- questions: z2.array(
494
- z2.object({
495
- question: z2.string().describe("The full question text to display"),
496
- header: z2.string().describe("Short label for the question (max 12 characters)"),
497
- options: z2.array(
498
- z2.object({
499
- label: z2.string(),
500
- description: z2.string()
501
- })
502
- ).min(0).max(4).describe("Array of 0-4 choices, each with label and description"),
503
- multiSelect: z2.boolean().describe("If true, users can select multiple options")
504
- })
505
- )
506
- }),
507
- strict: true
508
- };
509
- var globTool = {
510
- name: "Glob",
511
- description: `Search for files matching a glob pattern within the available file system.
512
-
513
- Usage:
514
- - Use glob patterns like "**/*.ts" to find all TypeScript files
515
- - Use "docs/**" to find all files in the docs directory
516
- - Patterns are matched against virtual paths in the file system
517
-
518
- Examples:
519
- - "*.md" - Find all markdown files in the root
520
- - "**/*.test.ts" - Find all test files recursively
521
- - "src/**/*.ts" - Find all TypeScript files in src directory
522
- `,
523
- schema: z.object({
524
- pattern: z.string().describe("Glob pattern to match files against"),
525
- root: z.string().optional().describe("Optional root directory to search from")
526
- }),
527
- strict: true
528
- };
529
- var grepTool = {
530
- name: "Grep",
531
- description: `Search file contents for a pattern within the available file system.
532
-
533
- Usage:
534
- - Searches for a regex pattern across file contents
535
- - Returns matching lines with file paths and line numbers
536
- - Can filter by file patterns and limit results
537
-
538
- Examples:
539
- - Search for "TODO" in all files
540
- - Search for function definitions with "function.*handleClick"
541
- - Search case-insensitively with ignoreCase: true
542
- `,
543
- schema: z.object({
544
- pattern: z.string().describe("Regex pattern to search for in file contents"),
545
- ignoreCase: z.boolean().optional().describe("Case-insensitive search (default: false)"),
546
- maxMatches: z.number().optional().describe("Maximum number of matches to return (default: 50)"),
547
- includePatterns: z.array(z.string()).optional().describe("Glob patterns to include (e.g., ['*.ts', '*.js'])"),
548
- excludePatterns: z.array(z.string()).optional().describe("Glob patterns to exclude (e.g., ['*.test.ts'])"),
549
- contextLines: z.number().optional().describe("Number of context lines to show around matches")
550
- }),
551
- strict: true
552
- };
553
- var readTool = {
554
- name: "FileRead",
555
- description: `Read file contents with optional pagination.
556
-
557
- Usage:
558
- - Provide the virtual path to the file you want to read
559
- - Supports text files, images, and PDFs
560
- - For large files, use offset and limit to read specific portions
561
-
562
- The tool returns the file content in an appropriate format:
563
- - Text files: Plain text content
564
- - Images: Base64-encoded image data
565
- - PDFs: Extracted text content
566
- `,
567
- schema: z.object({
568
- path: z.string().describe("Virtual path to the file to read"),
569
- offset: z.number().optional().describe(
570
- "Line number to start reading from (1-indexed, for text files)"
571
- ),
572
- limit: z.number().optional().describe("Maximum number of lines to read (for text files)")
573
- }),
574
- strict: true
575
- };
576
- var writeTool = {
577
- name: "FileWrite",
578
- description: `Create or overwrite a file with new content.
579
-
580
- Usage:
581
- - Provide the absolute virtual path to the file
582
- - The file will be created if it doesn't exist
583
- - If the file exists, it will be completely overwritten
584
-
585
- IMPORTANT:
586
- - You must read the file first (in this session) before writing to it
587
- - This is an atomic write operation - the entire file is replaced
588
- - Path must be absolute (e.g., "/docs/readme.md", not "docs/readme.md")
589
- `,
590
- schema: z.object({
591
- file_path: z.string().describe("The absolute virtual path to the file to write"),
592
- content: z.string().describe("The content to write to the file")
593
- }),
594
- strict: true
595
- };
596
- var editTool = {
597
- name: "FileEdit",
598
- description: `Edit specific sections of a file by replacing text.
599
-
600
- Usage:
601
- - Provide the exact text to find and replace
602
- - The old_string must match exactly (whitespace-sensitive)
603
- - By default, only replaces the first occurrence
604
- - Use replace_all: true to replace all occurrences
605
-
606
- IMPORTANT:
607
- - You must read the file first (in this session) before editing it
608
- - old_string must be unique in the file (unless using replace_all)
609
- - The operation fails if old_string is not found
610
- - old_string and new_string must be different
611
- `,
612
- schema: z.object({
613
- file_path: z.string().describe("The absolute virtual path to the file to modify"),
614
- old_string: z.string().describe("The exact text to replace"),
615
- new_string: z.string().describe(
616
- "The text to replace it with (must be different from old_string)"
617
- ),
618
- replace_all: z.boolean().optional().describe(
619
- "If true, replace all occurrences of old_string (default: false)"
620
- )
621
- }),
622
- strict: true
623
- };
624
-
625
- // src/lib/filesystem/types.ts
626
- function fileContentToMessageContent(content) {
627
- switch (content.type) {
628
- case "text":
629
- return [{ type: "text", text: content.content }];
630
- case "image":
631
- return [
632
- {
633
- type: "image_url",
634
- image_url: {
635
- url: `data:${content.mimeType};base64,${content.data}`
636
- }
637
- }
638
- ];
639
- case "pdf":
640
- return [{ type: "text", text: content.content }];
641
- }
642
- }
643
- var DEFAULT_HEADER = "Available files and directories:";
644
- var DEFAULT_DESCRIPTION = "You have access to the following files. Use the Read, Glob, and Grep tools to explore them.";
645
- function isExcluded(path, excludePatterns) {
646
- if (!excludePatterns || excludePatterns.length === 0) {
647
- return false;
648
- }
649
- return excludePatterns.some((pattern) => minimatch(path, pattern));
650
- }
651
- function renderNode(node, options, depth, indent) {
652
- const lines = [];
653
- if (options.maxDepth !== void 0 && depth > options.maxDepth) {
654
- return lines;
655
- }
656
- if (isExcluded(node.path, options.excludePatterns)) {
657
- return lines;
658
- }
659
- const parts = node.path.split("/");
660
- const name = parts[parts.length - 1] || node.path;
661
- let line = indent;
662
- if (node.type === "directory") {
663
- line += `${name}/`;
664
- } else {
665
- line += name;
666
- }
667
- if (options.showMimeTypes && node.mimeType) {
668
- line += ` [${node.mimeType}]`;
669
- }
670
- if (options.showDescriptions !== false && node.description) {
671
- line += ` - ${node.description}`;
672
- }
673
- lines.push(line);
674
- if (node.type === "directory" && node.children) {
675
- const childIndent = indent + " ";
676
- for (const child of node.children) {
677
- lines.push(...renderNode(child, options, depth + 1, childIndent));
678
- }
679
- }
680
- return lines;
681
- }
682
- function buildFileTreePrompt(nodes, options = {}) {
683
- const header = options.headerText ?? DEFAULT_HEADER;
684
- const description = options.descriptionText ?? DEFAULT_DESCRIPTION;
685
- const lines = [];
686
- for (const node of nodes) {
687
- lines.push(...renderNode(node, options, 0, ""));
688
- }
689
- if (lines.length === 0) {
690
- return `<file_system>
691
- ${header}
692
-
693
- ${description}
694
-
695
- (no files available)
696
- </file_system>`;
697
- }
698
- return `<file_system>
699
- ${header}
700
-
701
- ${lines.join("\n")}
702
- </file_system>`;
703
- }
704
- function flattenFileTree(nodes) {
705
- const paths = [];
706
- function traverse(node) {
707
- if (node.type === "file") {
708
- paths.push(node.path);
709
- }
710
- if (node.children) {
711
- for (const child of node.children) {
712
- traverse(child);
713
- }
714
- }
715
- }
716
- for (const node of nodes) {
717
- traverse(node);
718
- }
719
- return paths;
720
- }
721
- function isPathInScope(path, scopedNodes) {
722
- const allowedPaths = flattenFileTree(scopedNodes);
723
- return allowedPaths.includes(path);
724
- }
725
- function findNodeByPath(path, nodes) {
726
- for (const node of nodes) {
727
- if (node.path === path) {
728
- return node;
729
- }
730
- if (node.children) {
731
- const found = findNodeByPath(path, node.children);
732
- if (found) {
733
- return found;
734
- }
735
- }
736
- }
737
- return void 0;
738
- }
739
- var BaseFileSystemProvider = class {
740
- scopedNodes;
741
- allowedPaths;
742
- constructor(scopedNodes) {
743
- this.scopedNodes = scopedNodes;
744
- this.allowedPaths = new Set(flattenFileTree(scopedNodes));
745
- }
746
- /**
747
- * Validate that a path is within the allowed scope.
748
- * Throws an error if the path is not allowed.
749
- */
750
- validatePath(path) {
751
- if (!this.allowedPaths.has(path)) {
752
- throw new Error(`Path "${path}" is not within the allowed scope`);
753
- }
754
- }
755
- /**
756
- * Filter paths by glob pattern.
757
- */
758
- filterByPattern(paths, pattern, root) {
759
- const effectivePattern = root ? `${root}/${pattern}` : pattern;
760
- return paths.filter((path) => {
761
- if (root && !path.startsWith(root)) {
762
- return false;
763
- }
764
- return minimatch(path, effectivePattern, { matchBase: true });
765
- });
766
- }
767
- /**
768
- * Get all file paths in scope
769
- */
770
- getAllPaths() {
771
- return Array.from(this.allowedPaths);
772
- }
773
- /**
774
- * Find FileNode by path
775
- */
776
- findNode(path) {
777
- const findInNodes = (nodes) => {
778
- for (const node of nodes) {
779
- if (node.path === path) {
780
- return node;
781
- }
782
- if (node.children) {
783
- const found = findInNodes(node.children);
784
- if (found) return found;
785
- }
786
- }
787
- return void 0;
788
- };
789
- return findInNodes(this.scopedNodes);
790
- }
791
- /**
792
- * Read file as text for grep operations.
793
- * Default implementation uses readFile, but can be overridden for efficiency.
794
- */
795
- async readFileAsText(node) {
796
- try {
797
- const content = await this.readFile(node);
798
- if (content.type === "text") {
799
- return content.content;
800
- }
801
- if (content.type === "pdf") {
802
- return content.content;
803
- }
804
- return null;
805
- } catch {
806
- return null;
807
- }
808
- }
809
- // ============================================================================
810
- // FileSystemProvider implementation
811
- // ============================================================================
812
- async glob(pattern, root) {
813
- const allPaths = this.getAllPaths();
814
- const matchingPaths = this.filterByPattern(allPaths, pattern, root);
815
- return matchingPaths.map((path) => this.findNode(path)).filter((node) => node !== void 0);
816
- }
817
- async grep(pattern, options) {
818
- const matches = [];
819
- const maxMatches = options?.maxMatches ?? 50;
820
- const flags = options?.ignoreCase ? "gi" : "g";
821
- let regex;
822
- try {
823
- regex = new RegExp(pattern, flags);
824
- } catch {
825
- throw new Error(`Invalid regex pattern: ${pattern}`);
826
- }
827
- let paths = this.getAllPaths();
828
- if (options?.includePatterns?.length) {
829
- const includePatterns = options.includePatterns;
830
- paths = paths.filter(
831
- (path) => includePatterns.some((p) => minimatch(path, p, { matchBase: true }))
832
- );
833
- }
834
- if (options?.excludePatterns?.length) {
835
- const excludePatterns = options.excludePatterns;
836
- paths = paths.filter(
837
- (path) => !excludePatterns.some((p) => minimatch(path, p, { matchBase: true }))
838
- );
839
- }
840
- for (const path of paths) {
841
- if (matches.length >= maxMatches) break;
842
- const node = this.findNode(path);
843
- if (!node || node.type !== "file") continue;
844
- const text = await this.readFileAsText(node);
845
- if (!text) continue;
846
- const lines = text.split("\n");
847
- for (let i = 0; i < lines.length; i++) {
848
- if (matches.length >= maxMatches) break;
849
- const line = lines[i];
850
- if (line === void 0) continue;
851
- if (regex.test(line)) {
852
- regex.lastIndex = 0;
853
- const match = {
854
- path,
855
- lineNumber: i + 1,
856
- line: line.trim()
857
- };
858
- if (options?.contextLines && options.contextLines > 0) {
859
- const contextBefore = [];
860
- const contextAfter = [];
861
- for (let j = Math.max(0, i - options.contextLines); j < i; j++) {
862
- const contextLine = lines[j];
863
- if (contextLine !== void 0) {
864
- contextBefore.push(contextLine.trim());
865
- }
866
- }
867
- for (let j = i + 1; j <= Math.min(lines.length - 1, i + options.contextLines); j++) {
868
- const contextLine = lines[j];
869
- if (contextLine !== void 0) {
870
- contextAfter.push(contextLine.trim());
871
- }
872
- }
873
- match.contextBefore = contextBefore;
874
- match.contextAfter = contextAfter;
875
- }
876
- matches.push(match);
877
- }
878
- }
879
- }
880
- return matches;
881
- }
882
- async read(path) {
883
- this.validatePath(path);
884
- const node = this.findNode(path);
885
- if (!node) {
886
- throw new Error(`File not found: ${path}`);
887
- }
888
- if (node.type !== "file") {
889
- throw new Error(`Path is a directory, not a file: ${path}`);
890
- }
891
- return this.readFile(node);
892
- }
893
- async exists(path) {
894
- return this.allowedPaths.has(path);
895
- }
896
- };
897
- var InMemoryFileSystemProvider = class _InMemoryFileSystemProvider extends BaseFileSystemProvider {
898
- files;
899
- constructor(scopedNodes, files) {
900
- super(scopedNodes);
901
- this.files = files;
902
- }
903
- async readFile(node) {
904
- const content = this.files.get(node.path);
905
- if (!content) {
906
- throw new Error(`File not found in storage: ${node.path}`);
907
- }
908
- return content;
909
- }
910
- /**
911
- * Add or update a file in the in-memory storage
912
- */
913
- setFile(path, content) {
914
- this.files.set(path, content);
915
- }
916
- /**
917
- * Write text content to a file
918
- */
919
- async write(path, content) {
920
- this.validatePath(path);
921
- this.files.set(path, { type: "text", content });
922
- }
923
- /**
924
- * Create an InMemoryFileSystemProvider from a simple object map
925
- */
926
- static fromTextFiles(scopedNodes, files) {
927
- const fileMap = /* @__PURE__ */ new Map();
928
- for (const [path, content] of Object.entries(files)) {
929
- fileMap.set(path, { type: "text", content });
930
- }
931
- return new _InMemoryFileSystemProvider(scopedNodes, fileMap);
932
- }
933
- };
934
- var CompositeFileSystemProvider = class extends BaseFileSystemProvider {
935
- backends;
936
- defaultBackend;
937
- defaultResolver;
938
- constructor(scopedNodes, config) {
939
- super(scopedNodes);
940
- this.backends = new Map(Object.entries(config.backends));
941
- this.defaultBackend = config.defaultBackend;
942
- this.defaultResolver = config.defaultResolver;
943
- }
944
- /**
945
- * Get the backend name for a file node
946
- */
947
- getBackendName(node) {
948
- const backend = node.metadata?.backend;
949
- if (typeof backend === "string") {
950
- return backend;
951
- }
952
- return this.defaultBackend;
953
- }
954
- /**
955
- * Resolve content using a resolver (function or provider)
956
- */
957
- async resolveContent(resolver, node) {
958
- if (typeof resolver === "function") {
959
- return resolver(node);
960
- }
961
- return resolver.read(node.path);
962
- }
963
- async readFile(node) {
964
- const backendName = this.getBackendName(node);
965
- if (backendName) {
966
- const config = this.backends.get(backendName);
967
- if (config) {
968
- return this.resolveContent(config.resolver, node);
969
- }
970
- }
971
- if (this.defaultResolver) {
972
- return this.defaultResolver(node);
973
- }
974
- const availableBackends = Array.from(this.backends.keys()).join(", ");
975
- throw new Error(
976
- `No resolver for file "${node.path}". Backend: ${backendName ?? "(none)"}. Available backends: ${availableBackends || "(none)"}`
977
- );
978
- }
979
- /**
980
- * Add or update a backend configuration
981
- */
982
- setBackend(name, config) {
983
- this.backends.set(name, config);
984
- }
985
- /**
986
- * Remove a backend
987
- */
988
- removeBackend(name) {
989
- return this.backends.delete(name);
990
- }
991
- /**
992
- * Check if a backend exists
993
- */
994
- hasBackend(name) {
995
- return this.backends.has(name);
996
- }
997
- };
998
-
999
- // node_modules/uuid/dist/esm-node/stringify.js
1000
- var byteToHex = [];
1001
- for (let i = 0; i < 256; ++i) {
1002
- byteToHex.push((i + 256).toString(16).slice(1));
1003
- }
1004
- function unsafeStringify(arr, offset = 0) {
1005
- return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
1006
- }
1007
- var rnds8Pool = new Uint8Array(256);
1008
- var poolPtr = rnds8Pool.length;
1009
- function rng() {
1010
- if (poolPtr > rnds8Pool.length - 16) {
1011
- crypto.randomFillSync(rnds8Pool);
1012
- poolPtr = 0;
1013
- }
1014
- return rnds8Pool.slice(poolPtr, poolPtr += 16);
1015
- }
1016
- var native_default = {
1017
- randomUUID: crypto.randomUUID
1018
- };
1019
-
1020
- // node_modules/uuid/dist/esm-node/v4.js
1021
- function v4(options, buf, offset) {
1022
- if (native_default.randomUUID && !buf && !options) {
1023
- return native_default.randomUUID();
1024
- }
1025
- options = options || {};
1026
- const rnds = options.random || (options.rng || rng)();
1027
- rnds[6] = rnds[6] & 15 | 64;
1028
- rnds[8] = rnds[8] & 63 | 128;
1029
- if (buf) {
1030
- offset = offset || 0;
1031
- for (let i = 0; i < 16; ++i) {
1032
- buf[offset + i] = rnds[i];
1033
- }
1034
- return buf;
1035
- }
1036
- return unsafeStringify(rnds);
1037
- }
1038
- var v4_default = v4;
1039
-
1040
- // src/lib/thread-manager.ts
1041
- var THREAD_TTL_SECONDS = 60 * 60 * 24 * 90;
1042
- function getThreadKey(threadId, key) {
1043
- return `thread:${threadId}:${key}`;
1044
- }
1045
- function createThreadManager(config) {
1046
- const { redis, threadId, key = "messages" } = config;
1047
- const redisKey = getThreadKey(threadId, key);
1048
- return {
1049
- async initialize() {
1050
- await redis.del(redisKey);
1051
- },
1052
- async load() {
1053
- const data = await redis.lrange(redisKey, 0, -1);
1054
- return data.map((item) => JSON.parse(item));
1055
- },
1056
- async append(messages) {
1057
- if (messages.length > 0) {
1058
- await redis.rpush(redisKey, ...messages.map((m) => JSON.stringify(m)));
1059
- await redis.expire(redisKey, THREAD_TTL_SECONDS);
1060
- }
1061
- },
1062
- async delete() {
1063
- await redis.del(redisKey);
1064
- },
1065
- createHumanMessage(content) {
1066
- return new HumanMessage({
1067
- id: v4_default(),
1068
- content
1069
- }).toDict();
1070
- },
1071
- createAIMessage(content, kwargs) {
1072
- return new AIMessage({
1073
- id: v4_default(),
1074
- content,
1075
- additional_kwargs: kwargs ? {
1076
- header: kwargs.header,
1077
- options: kwargs.options,
1078
- multiSelect: kwargs.multiSelect
1079
- } : void 0
1080
- }).toDict();
1081
- },
1082
- createToolMessage(content, toolCallId) {
1083
- return new ToolMessage({
1084
- // Cast needed due to langchain type compatibility
1085
- content,
1086
- tool_call_id: toolCallId
1087
- }).toDict();
1088
- },
1089
- async appendHumanMessage(content) {
1090
- const message = this.createHumanMessage(content);
1091
- await this.append([message]);
1092
- },
1093
- async appendToolMessage(content, toolCallId) {
1094
- const message = this.createToolMessage(content, toolCallId);
1095
- await this.append([message]);
1096
- },
1097
- async appendAIMessage(content) {
1098
- const message = this.createAIMessage(content);
1099
- await this.append([message]);
1100
- }
1101
- };
1102
- }
1103
- function createSharedActivities(redis) {
1104
- return {
1105
- async appendToolResult(config) {
1106
- const { threadId, toolCallId, content } = config;
1107
- const thread = createThreadManager({ redis, threadId });
1108
- await thread.appendToolMessage(content, toolCallId);
1109
- },
1110
- async initializeThread(threadId) {
1111
- const thread = createThreadManager({ redis, threadId });
1112
- await thread.initialize();
1113
- },
1114
- async appendThreadMessages(threadId, messages) {
1115
- const thread = createThreadManager({ redis, threadId });
1116
- await thread.append(messages);
1117
- },
1118
- async appendHumanMessage(threadId, content) {
1119
- const thread = createThreadManager({ redis, threadId });
1120
- await thread.appendHumanMessage(content);
1121
- },
1122
- async parseToolCalls(storedMessage) {
1123
- const message = mapStoredMessageToChatMessage(storedMessage);
1124
- const toolCalls = message.tool_calls ?? [];
1125
- return toolCalls.map((toolCall) => ({
1126
- id: toolCall.id,
1127
- name: toolCall.name,
1128
- args: toolCall.args
1129
- }));
1130
- }
1131
- };
1132
- }
1133
-
1134
- // src/plugin.ts
1135
- var ZeitlichPlugin = class extends SimplePlugin {
1136
- constructor(options) {
1137
- super({
1138
- name: "ZeitlichPlugin",
1139
- activities: createSharedActivities(options.redis)
1140
- });
1141
- }
1142
- };
1143
- async function invokeModel(redis, { threadId, agentName, tools }, model, { systemPrompt }) {
1144
- const thread = createThreadManager({ redis, threadId });
1145
- const runId = v4_default();
1146
- const messages = await thread.load();
1147
- const response = await model.invoke(
1148
- [
1149
- new SystemMessage(systemPrompt),
1150
- ...mapStoredMessagesToChatMessages(messages)
1151
- ],
1152
- {
1153
- runName: agentName,
1154
- runId,
1155
- metadata: { thread_id: threadId },
1156
- tools
1157
- }
1158
- );
1159
- await thread.append([response.toDict()]);
1160
- return {
1161
- message: response.toDict(),
1162
- stopReason: response.response_metadata?.stop_reason ?? null,
1163
- usage: {
1164
- input_tokens: response.usage_metadata?.input_tokens,
1165
- output_tokens: response.usage_metadata?.output_tokens,
1166
- total_tokens: response.usage_metadata?.total_tokens
1167
- }
1168
- };
1169
- }
1170
- var handleAskUserQuestionToolResult = async (args) => {
1171
- const messages = args.questions.map(
1172
- ({ question, header, options, multiSelect }) => new AIMessage({
1173
- content: question,
1174
- additional_kwargs: {
1175
- header,
1176
- options,
1177
- multiSelect
1178
- }
1179
- }).toDict()
1180
- );
1181
- return { content: "Question submitted", result: { chatMessages: messages } };
1182
- };
1183
-
1184
- // src/tools/glob/handler.ts
1185
- function createGlobHandler(config) {
1186
- return async (args) => {
1187
- const { pattern, root } = args;
1188
- try {
1189
- const matches = await config.provider.glob(pattern, root);
1190
- if (matches.length === 0) {
1191
- return {
1192
- content: `No files found matching pattern: ${pattern}`,
1193
- result: { files: [] }
1194
- };
1195
- }
1196
- const paths = matches.map((node) => node.path);
1197
- const fileList = paths.map((p) => ` ${p}`).join("\n");
1198
- return {
1199
- content: `Found ${matches.length} file(s) matching "${pattern}":
1200
- ${fileList}`,
1201
- result: { files: matches }
1202
- };
1203
- } catch (error) {
1204
- const message = error instanceof Error ? error.message : "Unknown error";
1205
- return {
1206
- content: `Error searching for files: ${message}`,
1207
- result: { files: [] }
1208
- };
1209
- }
1210
- };
1211
- }
1212
-
1213
- // src/tools/grep/handler.ts
1214
- function formatMatch(match, showContext) {
1215
- const lines = [];
1216
- if (showContext && match.contextBefore?.length) {
1217
- for (let i = 0; i < match.contextBefore.length; i++) {
1218
- const lineNum = match.lineNumber - match.contextBefore.length + i;
1219
- lines.push(`${match.path}:${lineNum}-${match.contextBefore[i]}`);
1220
- }
1221
- }
1222
- lines.push(`${match.path}:${match.lineNumber}:${match.line}`);
1223
- if (showContext && match.contextAfter?.length) {
1224
- for (let i = 0; i < match.contextAfter.length; i++) {
1225
- const lineNum = match.lineNumber + 1 + i;
1226
- lines.push(`${match.path}:${lineNum}-${match.contextAfter[i]}`);
1227
- }
1228
- }
1229
- return lines.join("\n");
1230
- }
1231
- function createGrepHandler(config) {
1232
- return async (args) => {
1233
- const {
1234
- pattern,
1235
- ignoreCase,
1236
- maxMatches,
1237
- includePatterns,
1238
- excludePatterns,
1239
- contextLines
1240
- } = args;
1241
- try {
1242
- const matches = await config.provider.grep(pattern, {
1243
- ignoreCase,
1244
- maxMatches: maxMatches ?? 50,
1245
- includePatterns,
1246
- excludePatterns,
1247
- contextLines
1248
- });
1249
- if (matches.length === 0) {
1250
- return {
1251
- content: `No matches found for pattern: ${pattern}`,
1252
- result: { matches: [] }
1253
- };
1254
- }
1255
- const showContext = contextLines !== void 0 && contextLines > 0;
1256
- const formattedMatches = matches.map((m) => formatMatch(m, showContext)).join("\n");
1257
- return {
1258
- content: `Found ${matches.length} match(es) for "${pattern}":
1259
-
1260
- ${formattedMatches}`,
1261
- result: { matches }
1262
- };
1263
- } catch (error) {
1264
- const message = error instanceof Error ? error.message : "Unknown error";
1265
- return {
1266
- content: `Error searching file contents: ${message}`,
1267
- result: { matches: [] }
1268
- };
1269
- }
1270
- };
1271
- }
1272
-
1273
- // src/tools/read/handler.ts
1274
- function applyTextRange(content, offset, limit) {
1275
- if (offset === void 0 && limit === void 0) {
1276
- return content;
1277
- }
1278
- const lines = content.split("\n");
1279
- const startLine = offset !== void 0 ? Math.max(0, offset - 1) : 0;
1280
- const endLine = limit !== void 0 ? startLine + limit : lines.length;
1281
- const selectedLines = lines.slice(startLine, endLine);
1282
- return selectedLines.map((line, i) => {
1283
- const lineNum = (startLine + i + 1).toString().padStart(6, " ");
1284
- return `${lineNum}|${line}`;
1285
- }).join("\n");
1286
- }
1287
- function createReadHandler(config) {
1288
- return async (args) => {
1289
- const { path, offset, limit } = args;
1290
- if (!isPathInScope(path, config.scopedNodes)) {
1291
- return {
1292
- content: [
1293
- {
1294
- type: "text",
1295
- text: `Error: Path "${path}" is not within the available file system scope.`
1296
- }
1297
- ],
1298
- result: {
1299
- path,
1300
- content: {
1301
- type: "text",
1302
- content: "Error: Path is not within the available file system scope."
1303
- }
1304
- }
1305
- };
1306
- }
1307
- try {
1308
- const exists = await config.provider.exists(path);
1309
- if (!exists) {
1310
- return {
1311
- content: [
1312
- {
1313
- type: "text",
1314
- text: `Error: File "${path}" does not exist.`
1315
- }
1316
- ],
1317
- result: {
1318
- path,
1319
- content: { type: "text", content: "Error: File does not exist." }
1320
- }
1321
- };
1322
- }
1323
- const fileContent = await config.provider.read(path);
1324
- if (fileContent.type === "text") {
1325
- const processedContent = applyTextRange(
1326
- fileContent.content,
1327
- offset,
1328
- limit
1329
- );
1330
- let header = `File: ${path}`;
1331
- if (offset !== void 0 || limit !== void 0) {
1332
- const startLine = offset ?? 1;
1333
- const endInfo = limit ? `, showing ${limit} lines` : "";
1334
- header += ` (from line ${startLine}${endInfo})`;
1335
- }
1336
- return {
1337
- content: [
1338
- {
1339
- type: "text",
1340
- text: `${header}
1341
-
1342
- ${processedContent}`
1343
- }
1344
- ],
1345
- result: {
1346
- path,
1347
- content: {
1348
- type: "text",
1349
- content: `${header}
1350
-
1351
- ${processedContent}`
1352
- }
1353
- }
1354
- };
1355
- }
1356
- const messageContent = fileContentToMessageContent(fileContent);
1357
- return {
1358
- content: [
1359
- {
1360
- type: "text",
1361
- text: `File: ${path} (${fileContent.type})`
1362
- },
1363
- ...messageContent
1364
- ],
1365
- result: { path, content: fileContent }
1366
- };
1367
- } catch (error) {
1368
- const message = error instanceof Error ? error.message : "Unknown error";
1369
- return {
1370
- content: [
1371
- {
1372
- type: "text",
1373
- text: `Error reading file "${path}": ${message}`
1374
- }
1375
- ],
1376
- result: {
1377
- path,
1378
- content: {
1379
- type: "text",
1380
- content: `Error reading file "${path}": ${message}`
1381
- }
1382
- }
1383
- };
1384
- }
1385
- };
1386
- }
1387
-
1388
- // src/tools/write/handler.ts
1389
- function createWriteHandler(config) {
1390
- return async (args) => {
1391
- const { file_path, content } = args;
1392
- if (!isPathInScope(file_path, config.scopedNodes)) {
1393
- return {
1394
- content: `Error: Path "${file_path}" is not within the available file system scope.`,
1395
- result: {
1396
- path: file_path,
1397
- success: false,
1398
- created: false,
1399
- bytesWritten: 0
1400
- }
1401
- };
1402
- }
1403
- if (!config.skipReadCheck && !config.readFiles.has(file_path)) {
1404
- const exists = await config.provider.exists(file_path);
1405
- if (exists) {
1406
- return {
1407
- content: `Error: You must read "${file_path}" before writing to it. Use FileRead first.`,
1408
- result: {
1409
- path: file_path,
1410
- success: false,
1411
- created: false,
1412
- bytesWritten: 0
1413
- }
1414
- };
1415
- }
1416
- }
1417
- try {
1418
- const exists = await config.provider.exists(file_path);
1419
- if (!config.provider.write) {
1420
- return {
1421
- content: `Error: The file system provider does not support write operations.`,
1422
- result: {
1423
- path: file_path,
1424
- success: false,
1425
- created: false,
1426
- bytesWritten: 0
1427
- }
1428
- };
1429
- }
1430
- await config.provider.write(file_path, content);
1431
- const bytesWritten = Buffer.byteLength(content, "utf-8");
1432
- const action = exists ? "Updated" : "Created";
1433
- return {
1434
- content: `${action} file: ${file_path} (${bytesWritten} bytes)`,
1435
- result: {
1436
- path: file_path,
1437
- success: true,
1438
- created: !exists,
1439
- bytesWritten
1440
- }
1441
- };
1442
- } catch (error) {
1443
- const message = error instanceof Error ? error.message : "Unknown error";
1444
- return {
1445
- content: `Error writing file "${file_path}": ${message}`,
1446
- result: {
1447
- path: file_path,
1448
- success: false,
1449
- created: false,
1450
- bytesWritten: 0
1451
- }
1452
- };
1453
- }
1454
- };
1455
- }
1456
-
1457
- // src/tools/edit/handler.ts
1458
- function escapeRegExp(str) {
1459
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1460
- }
1461
- function createEditHandler(config) {
1462
- return async (args) => {
1463
- const { file_path, old_string, new_string, replace_all = false } = args;
1464
- if (old_string === new_string) {
1465
- return {
1466
- content: `Error: old_string and new_string must be different.`,
1467
- result: {
1468
- path: file_path,
1469
- success: false,
1470
- replacements: 0
1471
- }
1472
- };
1473
- }
1474
- if (!isPathInScope(file_path, config.scopedNodes)) {
1475
- return {
1476
- content: `Error: Path "${file_path}" is not within the available file system scope.`,
1477
- result: {
1478
- path: file_path,
1479
- success: false,
1480
- replacements: 0
1481
- }
1482
- };
1483
- }
1484
- if (!config.skipReadCheck && !config.readFiles.has(file_path)) {
1485
- return {
1486
- content: `Error: You must read "${file_path}" before editing it. Use FileRead first.`,
1487
- result: {
1488
- path: file_path,
1489
- success: false,
1490
- replacements: 0
1491
- }
1492
- };
1493
- }
1494
- try {
1495
- const exists = await config.provider.exists(file_path);
1496
- if (!exists) {
1497
- return {
1498
- content: `Error: File "${file_path}" does not exist.`,
1499
- result: {
1500
- path: file_path,
1501
- success: false,
1502
- replacements: 0
1503
- }
1504
- };
1505
- }
1506
- if (!config.provider.write) {
1507
- return {
1508
- content: `Error: The file system provider does not support write operations.`,
1509
- result: {
1510
- path: file_path,
1511
- success: false,
1512
- replacements: 0
1513
- }
1514
- };
1515
- }
1516
- const fileContent = await config.provider.read(file_path);
1517
- if (fileContent.type !== "text") {
1518
- return {
1519
- content: `Error: FileEdit only works with text files. "${file_path}" is ${fileContent.type}.`,
1520
- result: {
1521
- path: file_path,
1522
- success: false,
1523
- replacements: 0
1524
- }
1525
- };
1526
- }
1527
- const content = fileContent.content;
1528
- if (!content.includes(old_string)) {
1529
- return {
1530
- content: `Error: Could not find the specified text in "${file_path}". Make sure old_string matches exactly (whitespace-sensitive).`,
1531
- result: {
1532
- path: file_path,
1533
- success: false,
1534
- replacements: 0
1535
- }
1536
- };
1537
- }
1538
- const escapedOldString = escapeRegExp(old_string);
1539
- const globalRegex = new RegExp(escapedOldString, "g");
1540
- const occurrences = (content.match(globalRegex) || []).length;
1541
- if (!replace_all && occurrences > 1) {
1542
- return {
1543
- content: `Error: old_string appears ${occurrences} times in "${file_path}". Either provide more context to make it unique, or use replace_all: true.`,
1544
- result: {
1545
- path: file_path,
1546
- success: false,
1547
- replacements: 0
1548
- }
1549
- };
1550
- }
1551
- let newContent;
1552
- let replacements;
1553
- if (replace_all) {
1554
- newContent = content.split(old_string).join(new_string);
1555
- replacements = occurrences;
1556
- } else {
1557
- const index = content.indexOf(old_string);
1558
- newContent = content.slice(0, index) + new_string + content.slice(index + old_string.length);
1559
- replacements = 1;
1560
- }
1561
- await config.provider.write(file_path, newContent);
1562
- const summary = replace_all ? `Replaced ${replacements} occurrence(s)` : `Replaced 1 occurrence`;
1563
- return {
1564
- content: `${summary} in ${file_path}`,
1565
- result: {
1566
- path: file_path,
1567
- success: true,
1568
- replacements
1569
- }
1570
- };
1571
- } catch (error) {
1572
- const message = error instanceof Error ? error.message : "Unknown error";
1573
- return {
1574
- content: `Error editing file "${file_path}": ${message}`,
1575
- result: {
1576
- path: file_path,
1577
- success: false,
1578
- replacements: 0
1579
- }
1580
- };
1581
- }
1582
- };
1583
- }
1584
-
1585
- export { AGENT_HANDLER_NAMES, BaseFileSystemProvider, CompositeFileSystemProvider, InMemoryFileSystemProvider, ZeitlichPlugin, askUserQuestionTool, buildFileTreePrompt, createAgentStateManager, createEditHandler, createGlobHandler, createGrepHandler, createPromptManager, createReadHandler, createSession, createSharedActivities, createTaskHandler, createTaskTool, createToolRegistry, createToolRouter, createWriteHandler, editTool, fileContentToMessageContent, findNodeByPath, flattenFileTree, globTool, grepTool, handleAskUserQuestionToolResult, hasNoOtherToolCalls, hasTaskTool, invokeModel, isPathInScope, isTerminalStatus, readTool, withSubagentSupport, writeTool };
1586
- //# sourceMappingURL=index.mjs.map
1587
- //# sourceMappingURL=index.mjs.map