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.
@@ -0,0 +1,762 @@
1
+ 'use strict';
2
+
3
+ var workflow = require('@temporalio/workflow');
4
+ var z2 = require('zod');
5
+ var minimatch = require('minimatch');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
+
9
+ var z2__default = /*#__PURE__*/_interopDefault(z2);
10
+
11
+ // src/lib/session.ts
12
+ var TASK_TOOL = "Task";
13
+ function buildTaskDescription(subagents) {
14
+ const subagentList = subagents.map((s) => `- **${s.name}**: ${s.description}`).join("\n");
15
+ return `Launch a new agent to handle complex, multi-step tasks autonomously.
16
+
17
+ The ${TASK_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
18
+
19
+ Available agent types:
20
+
21
+ ${subagentList}
22
+
23
+ When using the ${TASK_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
24
+
25
+ Usage notes:
26
+
27
+ - Always include a short description (3-5 words) summarizing what the agent will do
28
+ - Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
29
+ - 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.
30
+ - Each invocation starts fresh - provide a detailed task description with all necessary context.
31
+ - Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.
32
+ - The agent's outputs should generally be trusted
33
+ - Clearly tell the agent what type of work you expect since it is not aware of the user's intent
34
+ - 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.`;
35
+ }
36
+ function createTaskTool(subagents) {
37
+ if (subagents.length === 0) {
38
+ throw new Error("createTaskTool requires at least one subagent");
39
+ }
40
+ const names = subagents.map((s) => s.name);
41
+ return {
42
+ name: TASK_TOOL,
43
+ description: buildTaskDescription(subagents),
44
+ schema: z2__default.default.object({
45
+ subagent: z2__default.default.enum(names).describe("The type of subagent to launch"),
46
+ description: z2__default.default.string().describe("A short (3-5 word) description of the task"),
47
+ prompt: z2__default.default.string().describe("The task for the agent to perform")
48
+ })
49
+ };
50
+ }
51
+ function createTaskHandler(subagents) {
52
+ const { workflowId: parentWorkflowId, taskQueue: parentTaskQueue } = workflow.workflowInfo();
53
+ return async (args, _toolCallId) => {
54
+ const config = subagents.find((s) => s.name === args.subagent);
55
+ if (!config) {
56
+ throw new Error(
57
+ `Unknown subagent: ${args.subagent}. Available: ${subagents.map((s) => s.name).join(", ")}`
58
+ );
59
+ }
60
+ const childWorkflowId = `${parentWorkflowId}-${args.subagent}-${workflow.uuid4()}`;
61
+ const childResult = await workflow.executeChild(config.workflowType, {
62
+ workflowId: childWorkflowId,
63
+ args: [{ prompt: args.prompt }],
64
+ taskQueue: config.taskQueue ?? parentTaskQueue
65
+ });
66
+ const validated = config.resultSchema ? config.resultSchema.parse(childResult) : childResult;
67
+ const content = typeof validated === "string" ? validated : JSON.stringify(validated, null, 2);
68
+ return {
69
+ content,
70
+ result: {
71
+ result: validated,
72
+ childWorkflowId
73
+ }
74
+ };
75
+ };
76
+ }
77
+
78
+ // src/lib/subagent-support.ts
79
+ function withSubagentSupport(userTools, config) {
80
+ if (config.subagents.length === 0) {
81
+ throw new Error("withSubagentSupport requires at least one subagent");
82
+ }
83
+ const taskTool = createTaskTool(config.subagents);
84
+ const taskHandler = createTaskHandler(config.subagents);
85
+ return {
86
+ tools: {
87
+ ...userTools,
88
+ Task: taskTool
89
+ },
90
+ taskHandler
91
+ };
92
+ }
93
+ function hasTaskTool(tools) {
94
+ return "Task" in tools;
95
+ }
96
+
97
+ // src/lib/session.ts
98
+ var createSession = async ({ threadId, agentName, maxTurns = 50, metadata = {} }, {
99
+ runAgent,
100
+ promptManager,
101
+ toolRouter,
102
+ toolRegistry,
103
+ hooks = {}
104
+ }) => {
105
+ const { initializeThread, appendHumanMessage, parseToolCalls } = workflow.proxyActivities({
106
+ startToCloseTimeout: "30m",
107
+ retry: {
108
+ maximumAttempts: 6,
109
+ initialInterval: "5s",
110
+ maximumInterval: "15m",
111
+ backoffCoefficient: 4
112
+ },
113
+ heartbeatTimeout: "5m"
114
+ });
115
+ const callSessionEnd = async (exitReason, turns) => {
116
+ if (hooks.onSessionEnd) {
117
+ await hooks.onSessionEnd({
118
+ threadId,
119
+ agentName,
120
+ exitReason,
121
+ turns,
122
+ metadata
123
+ });
124
+ }
125
+ };
126
+ return {
127
+ runSession: async (prompt, stateManager) => {
128
+ if (hooks.onSessionStart) {
129
+ await hooks.onSessionStart({
130
+ threadId,
131
+ agentName,
132
+ metadata
133
+ });
134
+ }
135
+ await initializeThread(threadId);
136
+ await appendHumanMessage(
137
+ threadId,
138
+ await promptManager.buildContextMessage(prompt)
139
+ );
140
+ let exitReason = "completed";
141
+ try {
142
+ while (stateManager.isRunning() && !stateManager.isTerminal() && stateManager.getTurns() < maxTurns) {
143
+ stateManager.incrementTurns();
144
+ const currentTurn = stateManager.getTurns();
145
+ const { message, stopReason } = await runAgent(
146
+ {
147
+ threadId,
148
+ agentName,
149
+ metadata
150
+ },
151
+ {
152
+ systemPrompt: await promptManager.getSystemPrompt()
153
+ }
154
+ );
155
+ if (stopReason === "end_turn") {
156
+ stateManager.complete();
157
+ exitReason = "completed";
158
+ return message;
159
+ }
160
+ const rawToolCalls = await parseToolCalls(message);
161
+ const parsedToolCalls = rawToolCalls.map(
162
+ (tc) => toolRegistry.parseToolCall(tc)
163
+ );
164
+ await toolRouter.processToolCalls(parsedToolCalls, {
165
+ turn: currentTurn
166
+ });
167
+ if (stateManager.getStatus() === "WAITING_FOR_INPUT") {
168
+ exitReason = "waiting_for_input";
169
+ break;
170
+ }
171
+ }
172
+ if (stateManager.getTurns() >= maxTurns && stateManager.isRunning()) {
173
+ exitReason = "max_turns";
174
+ }
175
+ } catch (error) {
176
+ exitReason = "failed";
177
+ throw error;
178
+ } finally {
179
+ await callSessionEnd(exitReason, stateManager.getTurns());
180
+ }
181
+ return null;
182
+ }
183
+ };
184
+ };
185
+
186
+ // src/lib/types.ts
187
+ function isTerminalStatus(status) {
188
+ return status === "COMPLETED" || status === "FAILED" || status === "CANCELLED";
189
+ }
190
+
191
+ // src/lib/state-manager.ts
192
+ function createAgentStateManager(config) {
193
+ let status = "RUNNING";
194
+ let version = 0;
195
+ let turns = 0;
196
+ const customState = { ...config?.initialState ?? {} };
197
+ function buildState() {
198
+ return {
199
+ status,
200
+ version,
201
+ turns,
202
+ ...customState
203
+ };
204
+ }
205
+ return {
206
+ getStatus() {
207
+ return status;
208
+ },
209
+ isRunning() {
210
+ return status === "RUNNING";
211
+ },
212
+ isTerminal() {
213
+ return isTerminalStatus(status);
214
+ },
215
+ getTurns() {
216
+ return turns;
217
+ },
218
+ getVersion() {
219
+ return version;
220
+ },
221
+ run() {
222
+ status = "RUNNING";
223
+ version++;
224
+ },
225
+ waitForInput() {
226
+ status = "WAITING_FOR_INPUT";
227
+ version++;
228
+ },
229
+ complete() {
230
+ status = "COMPLETED";
231
+ version++;
232
+ },
233
+ fail() {
234
+ status = "FAILED";
235
+ version++;
236
+ },
237
+ cancel() {
238
+ status = "CANCELLED";
239
+ version++;
240
+ },
241
+ incrementVersion() {
242
+ version++;
243
+ },
244
+ incrementTurns() {
245
+ turns++;
246
+ },
247
+ get(key) {
248
+ return customState[key];
249
+ },
250
+ set(key, value) {
251
+ customState[key] = value;
252
+ version++;
253
+ },
254
+ getCurrentState() {
255
+ return buildState();
256
+ },
257
+ shouldReturnFromWait(lastKnownVersion) {
258
+ return version > lastKnownVersion || isTerminalStatus(status);
259
+ }
260
+ };
261
+ }
262
+ var AGENT_HANDLER_NAMES = {
263
+ getAgentState: "getAgentState",
264
+ waitForStateChange: "waitForStateChange",
265
+ addMessage: "addMessage"
266
+ };
267
+
268
+ // src/lib/prompt-manager.ts
269
+ function createPromptManager(config) {
270
+ const { baseSystemPrompt, instructionsPrompt, buildContextMessage } = config;
271
+ async function resolvePrompt(prompt) {
272
+ if (typeof prompt === "function") {
273
+ return prompt();
274
+ }
275
+ return prompt;
276
+ }
277
+ return {
278
+ async getSystemPrompt() {
279
+ const base = await resolvePrompt(baseSystemPrompt);
280
+ const instructions = await resolvePrompt(instructionsPrompt);
281
+ return [base, instructions].join("\n");
282
+ },
283
+ async buildContextMessage(context) {
284
+ return buildContextMessage(context);
285
+ }
286
+ };
287
+ }
288
+
289
+ // src/lib/tool-registry.ts
290
+ function createToolRegistry(tools) {
291
+ const toolMap = /* @__PURE__ */ new Map();
292
+ for (const [_key, tool] of Object.entries(tools)) {
293
+ toolMap.set(tool.name, tool);
294
+ }
295
+ return {
296
+ parseToolCall(toolCall) {
297
+ const tool = toolMap.get(toolCall.name);
298
+ if (!tool) {
299
+ throw new Error(`Tool ${toolCall.name} not found`);
300
+ }
301
+ const parsedArgs = tool.schema.parse(toolCall.args);
302
+ return {
303
+ id: toolCall.id ?? "",
304
+ name: toolCall.name,
305
+ args: parsedArgs
306
+ };
307
+ },
308
+ getToolList() {
309
+ return Object.values(tools);
310
+ },
311
+ getTool(name) {
312
+ return tools[name];
313
+ },
314
+ hasTool(name) {
315
+ return toolMap.has(name);
316
+ },
317
+ getToolNames() {
318
+ return Array.from(toolMap.keys());
319
+ }
320
+ };
321
+ }
322
+
323
+ // src/lib/tool-router.ts
324
+ function createToolRouter(options, handlers) {
325
+ const { parallel = true, threadId, appendToolResult, hooks } = options;
326
+ async function processToolCall(toolCall, turn) {
327
+ const startTime = Date.now();
328
+ let effectiveArgs = toolCall.args;
329
+ if (hooks?.onPreToolUse) {
330
+ const preResult = await hooks.onPreToolUse({
331
+ toolCall,
332
+ threadId,
333
+ turn
334
+ });
335
+ if (preResult?.skip) {
336
+ await appendToolResult({
337
+ threadId,
338
+ toolCallId: toolCall.id,
339
+ content: JSON.stringify({
340
+ skipped: true,
341
+ reason: "Skipped by PreToolUse hook"
342
+ })
343
+ });
344
+ return null;
345
+ }
346
+ if (preResult?.modifiedArgs !== void 0) {
347
+ effectiveArgs = preResult.modifiedArgs;
348
+ }
349
+ }
350
+ const handler = handlers[toolCall.name];
351
+ let result;
352
+ let content;
353
+ try {
354
+ if (handler) {
355
+ const response = await handler(
356
+ effectiveArgs,
357
+ toolCall.id
358
+ );
359
+ result = response.result;
360
+ content = response.content;
361
+ } else {
362
+ result = { error: `Unknown tool: ${toolCall.name}` };
363
+ content = JSON.stringify(result, null, 2);
364
+ }
365
+ } catch (error) {
366
+ if (hooks?.onPostToolUseFailure) {
367
+ const failureResult = await hooks.onPostToolUseFailure({
368
+ toolCall,
369
+ error: error instanceof Error ? error : new Error(String(error)),
370
+ threadId,
371
+ turn
372
+ });
373
+ if (failureResult?.fallbackContent !== void 0) {
374
+ content = failureResult.fallbackContent;
375
+ result = { error: String(error), recovered: true };
376
+ } else if (failureResult?.suppress) {
377
+ content = JSON.stringify({ error: String(error), suppressed: true });
378
+ result = { error: String(error), suppressed: true };
379
+ } else {
380
+ throw error;
381
+ }
382
+ } else {
383
+ throw error;
384
+ }
385
+ }
386
+ await appendToolResult({ threadId, toolCallId: toolCall.id, content });
387
+ const toolResult = {
388
+ toolCallId: toolCall.id,
389
+ name: toolCall.name,
390
+ result
391
+ };
392
+ if (hooks?.onPostToolUse) {
393
+ const durationMs = Date.now() - startTime;
394
+ await hooks.onPostToolUse({
395
+ toolCall,
396
+ result: toolResult,
397
+ threadId,
398
+ turn,
399
+ durationMs
400
+ });
401
+ }
402
+ return toolResult;
403
+ }
404
+ return {
405
+ async processToolCalls(toolCalls, context) {
406
+ if (toolCalls.length === 0) {
407
+ return [];
408
+ }
409
+ const turn = context?.turn ?? 0;
410
+ if (parallel) {
411
+ const results2 = await Promise.all(
412
+ toolCalls.map((tc) => processToolCall(tc, turn))
413
+ );
414
+ return results2.filter(
415
+ (r) => r !== null
416
+ );
417
+ }
418
+ const results = [];
419
+ for (const toolCall of toolCalls) {
420
+ const result = await processToolCall(toolCall, turn);
421
+ if (result !== null) {
422
+ results.push(result);
423
+ }
424
+ }
425
+ return results;
426
+ },
427
+ async processToolCallsByName(toolCalls, toolName, handler) {
428
+ const matchingCalls = toolCalls.filter((tc) => tc.name === toolName);
429
+ if (matchingCalls.length === 0) {
430
+ return [];
431
+ }
432
+ const processOne = async (toolCall) => {
433
+ const response = await handler(
434
+ toolCall.args,
435
+ toolCall.id
436
+ );
437
+ await appendToolResult({
438
+ threadId,
439
+ toolCallId: toolCall.id,
440
+ content: response.content
441
+ });
442
+ return {
443
+ toolCallId: toolCall.id,
444
+ name: toolCall.name,
445
+ result: response.result
446
+ };
447
+ };
448
+ if (parallel) {
449
+ return Promise.all(matchingCalls.map(processOne));
450
+ }
451
+ const results = [];
452
+ for (const toolCall of matchingCalls) {
453
+ results.push(await processOne(toolCall));
454
+ }
455
+ return results;
456
+ },
457
+ filterByName(toolCalls, name) {
458
+ return toolCalls.filter(
459
+ (tc) => tc.name === name
460
+ );
461
+ },
462
+ hasToolCall(toolCalls, name) {
463
+ return toolCalls.some((tc) => tc.name === name);
464
+ },
465
+ getResultsByName(results, name) {
466
+ return results.filter(
467
+ (r) => r.name === name
468
+ );
469
+ }
470
+ };
471
+ }
472
+ function hasNoOtherToolCalls(toolCalls, excludeName) {
473
+ return toolCalls.filter((tc) => tc.name !== excludeName).length === 0;
474
+ }
475
+ var askUserQuestionTool = {
476
+ name: "AskUserQuestion",
477
+ description: `Use this tool when you need to ask the user questions during execution. This allows you to:
478
+
479
+ 1. Gather user preferences or requirements
480
+ 2. Clarify ambiguous instructions
481
+ 3. Get decisions on implementation choices as you work
482
+ 4. Offer choices to the user about what direction to take.
483
+
484
+ Usage notes:
485
+
486
+ * Users will always be able to select "Other" to provide custom text input
487
+ * Use multiSelect: true to allow multiple answers to be selected for a question
488
+ * If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label
489
+ `,
490
+ schema: z2__default.default.object({
491
+ questions: z2__default.default.array(
492
+ z2__default.default.object({
493
+ question: z2__default.default.string().describe("The full question text to display"),
494
+ header: z2__default.default.string().describe("Short label for the question (max 12 characters)"),
495
+ options: z2__default.default.array(
496
+ z2__default.default.object({
497
+ label: z2__default.default.string(),
498
+ description: z2__default.default.string()
499
+ })
500
+ ).min(0).max(4).describe("Array of 0-4 choices, each with label and description"),
501
+ multiSelect: z2__default.default.boolean().describe("If true, users can select multiple options")
502
+ })
503
+ )
504
+ }),
505
+ strict: true
506
+ };
507
+ var globTool = {
508
+ name: "Glob",
509
+ description: `Search for files matching a glob pattern within the available file system.
510
+
511
+ Usage:
512
+ - Use glob patterns like "**/*.ts" to find all TypeScript files
513
+ - Use "docs/**" to find all files in the docs directory
514
+ - Patterns are matched against virtual paths in the file system
515
+
516
+ Examples:
517
+ - "*.md" - Find all markdown files in the root
518
+ - "**/*.test.ts" - Find all test files recursively
519
+ - "src/**/*.ts" - Find all TypeScript files in src directory
520
+ `,
521
+ schema: z2.z.object({
522
+ pattern: z2.z.string().describe("Glob pattern to match files against"),
523
+ root: z2.z.string().optional().describe("Optional root directory to search from")
524
+ }),
525
+ strict: true
526
+ };
527
+ var grepTool = {
528
+ name: "Grep",
529
+ description: `Search file contents for a pattern within the available file system.
530
+
531
+ Usage:
532
+ - Searches for a regex pattern across file contents
533
+ - Returns matching lines with file paths and line numbers
534
+ - Can filter by file patterns and limit results
535
+
536
+ Examples:
537
+ - Search for "TODO" in all files
538
+ - Search for function definitions with "function.*handleClick"
539
+ - Search case-insensitively with ignoreCase: true
540
+ `,
541
+ schema: z2.z.object({
542
+ pattern: z2.z.string().describe("Regex pattern to search for in file contents"),
543
+ ignoreCase: z2.z.boolean().optional().describe("Case-insensitive search (default: false)"),
544
+ maxMatches: z2.z.number().optional().describe("Maximum number of matches to return (default: 50)"),
545
+ includePatterns: z2.z.array(z2.z.string()).optional().describe("Glob patterns to include (e.g., ['*.ts', '*.js'])"),
546
+ excludePatterns: z2.z.array(z2.z.string()).optional().describe("Glob patterns to exclude (e.g., ['*.test.ts'])"),
547
+ contextLines: z2.z.number().optional().describe("Number of context lines to show around matches")
548
+ }),
549
+ strict: true
550
+ };
551
+ var readTool = {
552
+ name: "FileRead",
553
+ description: `Read file contents with optional pagination.
554
+
555
+ Usage:
556
+ - Provide the virtual path to the file you want to read
557
+ - Supports text files, images, and PDFs
558
+ - For large files, use offset and limit to read specific portions
559
+
560
+ The tool returns the file content in an appropriate format:
561
+ - Text files: Plain text content
562
+ - Images: Base64-encoded image data
563
+ - PDFs: Extracted text content
564
+ `,
565
+ schema: z2.z.object({
566
+ path: z2.z.string().describe("Virtual path to the file to read"),
567
+ offset: z2.z.number().optional().describe(
568
+ "Line number to start reading from (1-indexed, for text files)"
569
+ ),
570
+ limit: z2.z.number().optional().describe("Maximum number of lines to read (for text files)")
571
+ }),
572
+ strict: true
573
+ };
574
+ var writeTool = {
575
+ name: "FileWrite",
576
+ description: `Create or overwrite a file with new content.
577
+
578
+ Usage:
579
+ - Provide the absolute virtual path to the file
580
+ - The file will be created if it doesn't exist
581
+ - If the file exists, it will be completely overwritten
582
+
583
+ IMPORTANT:
584
+ - You must read the file first (in this session) before writing to it
585
+ - This is an atomic write operation - the entire file is replaced
586
+ - Path must be absolute (e.g., "/docs/readme.md", not "docs/readme.md")
587
+ `,
588
+ schema: z2.z.object({
589
+ file_path: z2.z.string().describe("The absolute virtual path to the file to write"),
590
+ content: z2.z.string().describe("The content to write to the file")
591
+ }),
592
+ strict: true
593
+ };
594
+ var editTool = {
595
+ name: "FileEdit",
596
+ description: `Edit specific sections of a file by replacing text.
597
+
598
+ Usage:
599
+ - Provide the exact text to find and replace
600
+ - The old_string must match exactly (whitespace-sensitive)
601
+ - By default, only replaces the first occurrence
602
+ - Use replace_all: true to replace all occurrences
603
+
604
+ IMPORTANT:
605
+ - You must read the file first (in this session) before editing it
606
+ - old_string must be unique in the file (unless using replace_all)
607
+ - The operation fails if old_string is not found
608
+ - old_string and new_string must be different
609
+ `,
610
+ schema: z2.z.object({
611
+ file_path: z2.z.string().describe("The absolute virtual path to the file to modify"),
612
+ old_string: z2.z.string().describe("The exact text to replace"),
613
+ new_string: z2.z.string().describe(
614
+ "The text to replace it with (must be different from old_string)"
615
+ ),
616
+ replace_all: z2.z.boolean().optional().describe(
617
+ "If true, replace all occurrences of old_string (default: false)"
618
+ )
619
+ }),
620
+ strict: true
621
+ };
622
+
623
+ // src/lib/filesystem/types.ts
624
+ function fileContentToMessageContent(content) {
625
+ switch (content.type) {
626
+ case "text":
627
+ return [{ type: "text", text: content.content }];
628
+ case "image":
629
+ return [
630
+ {
631
+ type: "image_url",
632
+ image_url: {
633
+ url: `data:${content.mimeType};base64,${content.data}`
634
+ }
635
+ }
636
+ ];
637
+ case "pdf":
638
+ return [{ type: "text", text: content.content }];
639
+ }
640
+ }
641
+ var DEFAULT_HEADER = "Available files and directories:";
642
+ var DEFAULT_DESCRIPTION = "You have access to the following files. Use the Read, Glob, and Grep tools to explore them.";
643
+ function isExcluded(path, excludePatterns) {
644
+ if (!excludePatterns || excludePatterns.length === 0) {
645
+ return false;
646
+ }
647
+ return excludePatterns.some((pattern) => minimatch.minimatch(path, pattern));
648
+ }
649
+ function renderNode(node, options, depth, indent) {
650
+ const lines = [];
651
+ if (options.maxDepth !== void 0 && depth > options.maxDepth) {
652
+ return lines;
653
+ }
654
+ if (isExcluded(node.path, options.excludePatterns)) {
655
+ return lines;
656
+ }
657
+ const parts = node.path.split("/");
658
+ const name = parts[parts.length - 1] || node.path;
659
+ let line = indent;
660
+ if (node.type === "directory") {
661
+ line += `${name}/`;
662
+ } else {
663
+ line += name;
664
+ }
665
+ if (options.showMimeTypes && node.mimeType) {
666
+ line += ` [${node.mimeType}]`;
667
+ }
668
+ if (options.showDescriptions !== false && node.description) {
669
+ line += ` - ${node.description}`;
670
+ }
671
+ lines.push(line);
672
+ if (node.type === "directory" && node.children) {
673
+ const childIndent = indent + " ";
674
+ for (const child of node.children) {
675
+ lines.push(...renderNode(child, options, depth + 1, childIndent));
676
+ }
677
+ }
678
+ return lines;
679
+ }
680
+ function buildFileTreePrompt(nodes, options = {}) {
681
+ const header = options.headerText ?? DEFAULT_HEADER;
682
+ const description = options.descriptionText ?? DEFAULT_DESCRIPTION;
683
+ const lines = [];
684
+ for (const node of nodes) {
685
+ lines.push(...renderNode(node, options, 0, ""));
686
+ }
687
+ if (lines.length === 0) {
688
+ return `<file_system>
689
+ ${header}
690
+
691
+ ${description}
692
+
693
+ (no files available)
694
+ </file_system>`;
695
+ }
696
+ return `<file_system>
697
+ ${header}
698
+
699
+ ${lines.join("\n")}
700
+ </file_system>`;
701
+ }
702
+ function flattenFileTree(nodes) {
703
+ const paths = [];
704
+ function traverse(node) {
705
+ if (node.type === "file") {
706
+ paths.push(node.path);
707
+ }
708
+ if (node.children) {
709
+ for (const child of node.children) {
710
+ traverse(child);
711
+ }
712
+ }
713
+ }
714
+ for (const node of nodes) {
715
+ traverse(node);
716
+ }
717
+ return paths;
718
+ }
719
+ function isPathInScope(path, scopedNodes) {
720
+ const allowedPaths = flattenFileTree(scopedNodes);
721
+ return allowedPaths.includes(path);
722
+ }
723
+ function findNodeByPath(path, nodes) {
724
+ for (const node of nodes) {
725
+ if (node.path === path) {
726
+ return node;
727
+ }
728
+ if (node.children) {
729
+ const found = findNodeByPath(path, node.children);
730
+ if (found) {
731
+ return found;
732
+ }
733
+ }
734
+ }
735
+ return void 0;
736
+ }
737
+
738
+ exports.AGENT_HANDLER_NAMES = AGENT_HANDLER_NAMES;
739
+ exports.askUserQuestionTool = askUserQuestionTool;
740
+ exports.buildFileTreePrompt = buildFileTreePrompt;
741
+ exports.createAgentStateManager = createAgentStateManager;
742
+ exports.createPromptManager = createPromptManager;
743
+ exports.createSession = createSession;
744
+ exports.createTaskHandler = createTaskHandler;
745
+ exports.createTaskTool = createTaskTool;
746
+ exports.createToolRegistry = createToolRegistry;
747
+ exports.createToolRouter = createToolRouter;
748
+ exports.editTool = editTool;
749
+ exports.fileContentToMessageContent = fileContentToMessageContent;
750
+ exports.findNodeByPath = findNodeByPath;
751
+ exports.flattenFileTree = flattenFileTree;
752
+ exports.globTool = globTool;
753
+ exports.grepTool = grepTool;
754
+ exports.hasNoOtherToolCalls = hasNoOtherToolCalls;
755
+ exports.hasTaskTool = hasTaskTool;
756
+ exports.isPathInScope = isPathInScope;
757
+ exports.isTerminalStatus = isTerminalStatus;
758
+ exports.readTool = readTool;
759
+ exports.withSubagentSupport = withSubagentSupport;
760
+ exports.writeTool = writeTool;
761
+ //# sourceMappingURL=workflow.js.map
762
+ //# sourceMappingURL=workflow.js.map