zeitlich 0.1.0

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