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