zeitlich 0.1.1 → 0.2.1

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 +168 -180
  2. package/dist/index.cjs +1337 -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 +764 -1091
  7. package/dist/index.js.map +1 -1
  8. package/dist/workflow-CCoHnc3B.d.cts +943 -0
  9. package/dist/workflow-CCoHnc3B.d.ts +943 -0
  10. package/dist/workflow.cjs +930 -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 +559 -423
  15. package/dist/workflow.js.map +1 -1
  16. package/package.json +14 -13
  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 +45 -0
  31. package/src/tools/bash/tool.ts +36 -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 +22 -0
  51. package/dist/index.d.mts +0 -152
  52. package/dist/index.mjs +0 -1587
  53. package/dist/index.mjs.map +0 -1
  54. package/dist/workflow-7_MT-5-w.d.mts +0 -1203
  55. package/dist/workflow-7_MT-5-w.d.ts +0 -1203
  56. package/dist/workflow.d.mts +0 -4
  57. package/dist/workflow.mjs +0 -739
  58. package/dist/workflow.mjs.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,1337 @@
1
+ 'use strict';
2
+
3
+ var workflow = require('@temporalio/workflow');
4
+ var z4 = require('zod');
5
+ var plugin = require('@temporalio/plugin');
6
+ var messages = require('@langchain/core/messages');
7
+ var crypto = require('crypto');
8
+ var activity = require('@temporalio/activity');
9
+ var justBash = require('just-bash');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
+
13
+ var z4__default = /*#__PURE__*/_interopDefault(z4);
14
+ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
15
+
16
+ // src/lib/session.ts
17
+ var TASK_TOOL = "Task";
18
+ function buildTaskDescription(subagents) {
19
+ const subagentList = subagents.map((s) => `- **${s.name}**: ${s.description}`).join("\n");
20
+ return `Launch a new agent to handle complex, multi-step tasks autonomously.
21
+
22
+ The ${TASK_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
23
+
24
+ Available agent types:
25
+
26
+ ${subagentList}
27
+
28
+ When using the ${TASK_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
29
+
30
+ Usage notes:
31
+
32
+ - Always include a short description (3-5 words) summarizing what the agent will do
33
+ - Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
34
+ - 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.
35
+ - Each invocation starts fresh - provide a detailed task description with all necessary context.
36
+ - Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.
37
+ - The agent's outputs should generally be trusted
38
+ - Clearly tell the agent what type of work you expect since it is not aware of the user's intent
39
+ - 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.`;
40
+ }
41
+ function createTaskTool(subagents) {
42
+ if (subagents.length === 0) {
43
+ throw new Error("createTaskTool requires at least one subagent");
44
+ }
45
+ const names = subagents.map((s) => s.name);
46
+ return {
47
+ name: TASK_TOOL,
48
+ description: buildTaskDescription(subagents),
49
+ schema: z4__default.default.object({
50
+ subagent: z4__default.default.enum(names).describe("The type of subagent to launch"),
51
+ description: z4__default.default.string().describe("A short (3-5 word) description of the task"),
52
+ prompt: z4__default.default.string().describe("The task for the agent to perform")
53
+ })
54
+ };
55
+ }
56
+ function createTaskHandler(subagents) {
57
+ const { workflowId: parentWorkflowId, taskQueue: parentTaskQueue } = workflow.workflowInfo();
58
+ return async (args) => {
59
+ const config = subagents.find((s) => s.name === args.subagent);
60
+ if (!config) {
61
+ throw new Error(
62
+ `Unknown subagent: ${args.subagent}. Available: ${subagents.map((s) => s.name).join(", ")}`
63
+ );
64
+ }
65
+ const childWorkflowId = `${parentWorkflowId}-${args.subagent}-${workflow.uuid4()}`;
66
+ const childResult = await workflow.executeChild(config.workflowType, {
67
+ workflowId: childWorkflowId,
68
+ args: [{ prompt: args.prompt }],
69
+ taskQueue: config.taskQueue ?? parentTaskQueue
70
+ });
71
+ const validated = config.resultSchema ? config.resultSchema.parse(childResult) : childResult;
72
+ const content = typeof validated === "string" ? validated : JSON.stringify(validated, null, 2);
73
+ return {
74
+ content,
75
+ result: {
76
+ result: validated,
77
+ childWorkflowId
78
+ }
79
+ };
80
+ };
81
+ }
82
+ var createBashToolDescription = ({
83
+ fileTree
84
+ }) => `Execute shell commands in a bash environment.
85
+
86
+ Use this tool to:
87
+ - Run shell commands (ls, cat, grep, find, etc.)
88
+ - Execute scripts and chain commands with pipes (|) or logical operators (&&, ||)
89
+ - Inspect files and directories
90
+
91
+ Current file tree:
92
+ ${fileTree}`;
93
+ var bashTool = {
94
+ name: "Bash",
95
+ description: `Execute shell commands in a sandboxed bash environment.
96
+
97
+ Use this tool to:
98
+ - Run shell commands (ls, cat, grep, find, etc.)
99
+ - Execute scripts and chain commands with pipes (|) or logical operators (&&, ||)
100
+ - Inspect files and directories
101
+ `,
102
+ schema: z4__default.default.object({
103
+ command: z4__default.default.string().describe(
104
+ "The bash command to execute. Can include pipes (|), redirects (>, >>), logical operators (&&, ||), and shell features like command substitution $(...)."
105
+ )
106
+ }),
107
+ strict: true
108
+ };
109
+ var taskCreateTool = {
110
+ name: "TaskCreate",
111
+ description: `Use this tool to create a structured task list for the control test. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
112
+ It also helps the user understand the progress of the task and overall progress of their requests.
113
+
114
+ ## When to Use This Tool
115
+
116
+ Use this tool proactively in these scenarios:
117
+
118
+ - Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
119
+ - Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
120
+ - User explicitly requests todo list - When the user directly asks you to use the todo list
121
+ - User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
122
+ - After receiving new instructions - Immediately capture user requirements as tasks
123
+ - When you start working on a task - Mark it as in_progress BEFORE beginning work
124
+ - After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
125
+
126
+ ## When NOT to Use This Tool
127
+
128
+ Skip using this tool when:
129
+ - There is only a single, straightforward task
130
+ - The task is trivial and tracking it provides no organizational benefit
131
+ - The task can be completed in less than 3 trivial steps
132
+ - The task is purely conversational or informational
133
+
134
+ NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
135
+
136
+ ## Task Fields
137
+
138
+ - **subject**: A brief, actionable title in imperative form (e.g., "Fix authentication bug in login flow")
139
+ - **description**: Detailed description of what needs to be done, including context and acceptance criteria
140
+ - **activeForm**: Present continuous form shown in spinner when task is in_progress (e.g., "Fixing authentication bug"). This is displayed to the user while you work on the task.
141
+
142
+ **IMPORTANT**: Always provide activeForm when creating tasks. The subject should be imperative ("Run tests") while activeForm should be present continuous ("Running tests"). All tasks are created with status \`pending\`.
143
+
144
+ ## Tips
145
+
146
+ - Create tasks with clear, specific subjects that describe the outcome
147
+ - Include enough detail in the description for another agent to understand and complete the task
148
+ - After creating tasks, use TaskUpdate to set up dependencies (blocks/blockedBy) if needed
149
+ - Check TaskList first to avoid creating duplicate tasks`,
150
+ schema: z4__default.default.object({
151
+ subject: z4__default.default.string().describe(
152
+ 'A brief, actionable title in imperative form (e.g., "Fix authentication bug in login flow")'
153
+ ),
154
+ description: z4__default.default.string().describe(
155
+ "Detailed description of what needs to be done, including context and acceptance criteria"
156
+ ),
157
+ activeForm: z4__default.default.string().describe(
158
+ 'Present continuous form shown in spinner when task is in_progress (e.g., "Fixing authentication bug"). This is displayed to the user while you work on the task.'
159
+ ),
160
+ metadata: z4__default.default.record(z4__default.default.string(), z4__default.default.string()).describe("Arbitrary key-value pairs for tracking")
161
+ })
162
+ };
163
+
164
+ // src/lib/tool-router.ts
165
+ var buildIntoolDefinitions = {
166
+ [bashTool.name]: bashTool,
167
+ [taskCreateTool.name]: taskCreateTool
168
+ };
169
+ function createToolRouter(options) {
170
+ const { appendToolResult } = workflow.proxyActivities({
171
+ startToCloseTimeout: "2m",
172
+ retry: {
173
+ maximumAttempts: 3,
174
+ initialInterval: "5s",
175
+ maximumInterval: "15m",
176
+ backoffCoefficient: 4
177
+ }
178
+ });
179
+ const toolMap = /* @__PURE__ */ new Map();
180
+ for (const [_key, tool] of Object.entries(options.tools)) {
181
+ toolMap.set(tool.name, tool);
182
+ }
183
+ if (options.subagents) {
184
+ toolMap.set("Task", {
185
+ ...createTaskTool(options.subagents),
186
+ handler: createTaskHandler(options.subagents)
187
+ });
188
+ }
189
+ if (options.buildInTools) {
190
+ for (const [key, value] of Object.entries(options.buildInTools)) {
191
+ if (key === bashTool.name) {
192
+ toolMap.set(key, {
193
+ ...buildIntoolDefinitions[key],
194
+ description: createBashToolDescription({
195
+ fileTree: options.fileTree
196
+ }),
197
+ handler: value
198
+ });
199
+ } else {
200
+ toolMap.set(key, {
201
+ ...buildIntoolDefinitions[key],
202
+ handler: value
203
+ });
204
+ }
205
+ }
206
+ }
207
+ async function processToolCall(toolCall, turn, handlerContext) {
208
+ const startTime = Date.now();
209
+ let effectiveArgs = toolCall.args;
210
+ if (options.hooks?.onPreToolUse) {
211
+ const preResult = await options.hooks.onPreToolUse({
212
+ toolCall,
213
+ threadId: options.threadId,
214
+ turn
215
+ });
216
+ if (preResult?.skip) {
217
+ await appendToolResult({
218
+ threadId: options.threadId,
219
+ toolCallId: toolCall.id,
220
+ content: JSON.stringify({
221
+ skipped: true,
222
+ reason: "Skipped by PreToolUse hook"
223
+ })
224
+ });
225
+ return null;
226
+ }
227
+ if (preResult?.modifiedArgs !== void 0) {
228
+ effectiveArgs = preResult.modifiedArgs;
229
+ }
230
+ }
231
+ const tool = toolMap.get(toolCall.name);
232
+ let result;
233
+ let content;
234
+ try {
235
+ if (tool) {
236
+ const response = await tool.handler(
237
+ effectiveArgs,
238
+ handlerContext ?? {}
239
+ );
240
+ result = response.result;
241
+ content = response.content;
242
+ } else {
243
+ result = { error: `Unknown tool: ${toolCall.name}` };
244
+ content = JSON.stringify(result, null, 2);
245
+ }
246
+ } catch (error) {
247
+ if (options.hooks?.onPostToolUseFailure) {
248
+ const failureResult = await options.hooks.onPostToolUseFailure({
249
+ toolCall,
250
+ error: error instanceof Error ? error : new Error(String(error)),
251
+ threadId: options.threadId,
252
+ turn
253
+ });
254
+ if (failureResult?.fallbackContent !== void 0) {
255
+ content = failureResult.fallbackContent;
256
+ result = { error: String(error), recovered: true };
257
+ } else if (failureResult?.suppress) {
258
+ content = JSON.stringify({ error: String(error), suppressed: true });
259
+ result = { error: String(error), suppressed: true };
260
+ } else {
261
+ throw error;
262
+ }
263
+ } else {
264
+ throw error;
265
+ }
266
+ }
267
+ await appendToolResult({
268
+ threadId: options.threadId,
269
+ toolCallId: toolCall.id,
270
+ content
271
+ });
272
+ const toolResult = {
273
+ toolCallId: toolCall.id,
274
+ name: toolCall.name,
275
+ result
276
+ };
277
+ if (options.hooks?.onPostToolUse) {
278
+ const durationMs = Date.now() - startTime;
279
+ await options.hooks.onPostToolUse({
280
+ toolCall,
281
+ result: toolResult,
282
+ threadId: options.threadId,
283
+ turn,
284
+ durationMs
285
+ });
286
+ }
287
+ return toolResult;
288
+ }
289
+ return {
290
+ // --- Methods from registry ---
291
+ hasTools() {
292
+ return toolMap.size > 0;
293
+ },
294
+ parseToolCall(toolCall) {
295
+ const tool = toolMap.get(toolCall.name);
296
+ if (!tool) {
297
+ throw new Error(`Tool ${toolCall.name} not found`);
298
+ }
299
+ const parsedArgs = tool.schema.parse(toolCall.args);
300
+ return {
301
+ id: toolCall.id ?? "",
302
+ name: toolCall.name,
303
+ args: parsedArgs
304
+ };
305
+ },
306
+ hasTool(name) {
307
+ return toolMap.has(name);
308
+ },
309
+ getToolNames() {
310
+ return Array.from(toolMap.keys());
311
+ },
312
+ getToolDefinitions() {
313
+ return Array.from(toolMap).map(([name, tool]) => ({
314
+ name,
315
+ description: tool.description,
316
+ schema: tool.schema,
317
+ strict: tool.strict,
318
+ max_uses: tool.max_uses
319
+ }));
320
+ },
321
+ // --- Methods for processing tool calls ---
322
+ async processToolCalls(toolCalls, context) {
323
+ if (toolCalls.length === 0) {
324
+ return [];
325
+ }
326
+ const turn = context?.turn ?? 0;
327
+ const handlerContext = context?.handlerContext;
328
+ if (options.parallel) {
329
+ const results2 = await Promise.all(
330
+ toolCalls.map((tc) => processToolCall(tc, turn, handlerContext))
331
+ );
332
+ return results2.filter(
333
+ (r) => r !== null
334
+ );
335
+ }
336
+ const results = [];
337
+ for (const toolCall of toolCalls) {
338
+ const result = await processToolCall(toolCall, turn, handlerContext);
339
+ if (result !== null) {
340
+ results.push(result);
341
+ }
342
+ }
343
+ return results;
344
+ },
345
+ async processToolCallsByName(toolCalls, toolName, handler, context) {
346
+ const matchingCalls = toolCalls.filter((tc) => tc.name === toolName);
347
+ if (matchingCalls.length === 0) {
348
+ return [];
349
+ }
350
+ const handlerContext = context?.handlerContext ?? {};
351
+ const processOne = async (toolCall) => {
352
+ const response = await handler(
353
+ toolCall.args,
354
+ handlerContext
355
+ );
356
+ await appendToolResult({
357
+ threadId: options.threadId,
358
+ toolCallId: toolCall.id,
359
+ content: response.content
360
+ });
361
+ return {
362
+ toolCallId: toolCall.id,
363
+ name: toolCall.name,
364
+ result: response.result
365
+ };
366
+ };
367
+ if (options.parallel) {
368
+ return Promise.all(matchingCalls.map(processOne));
369
+ }
370
+ const results = [];
371
+ for (const toolCall of matchingCalls) {
372
+ results.push(await processOne(toolCall));
373
+ }
374
+ return results;
375
+ },
376
+ // --- Utility methods ---
377
+ filterByName(toolCalls, name) {
378
+ return toolCalls.filter(
379
+ (tc) => tc.name === name
380
+ );
381
+ },
382
+ hasToolCall(toolCalls, name) {
383
+ return toolCalls.some((tc) => tc.name === name);
384
+ },
385
+ getResultsByName(results, name) {
386
+ return results.filter((r) => r.name === name);
387
+ }
388
+ };
389
+ }
390
+ function hasNoOtherToolCalls(toolCalls, excludeName) {
391
+ return toolCalls.filter((tc) => tc.name !== excludeName).length === 0;
392
+ }
393
+
394
+ // src/lib/session.ts
395
+ async function resolvePrompt(prompt) {
396
+ if (typeof prompt === "function") {
397
+ return prompt();
398
+ }
399
+ return prompt;
400
+ }
401
+ var createSession = async ({
402
+ threadId,
403
+ agentName,
404
+ maxTurns = 50,
405
+ metadata = {},
406
+ runAgent,
407
+ baseSystemPrompt,
408
+ instructionsPrompt,
409
+ buildContextMessage,
410
+ buildFileTree = async () => "",
411
+ subagents,
412
+ tools = {},
413
+ processToolsInParallel = true,
414
+ buildInTools = {},
415
+ hooks = {}
416
+ }) => {
417
+ const {
418
+ initializeThread,
419
+ appendHumanMessage,
420
+ parseToolCalls,
421
+ appendToolResult,
422
+ appendSystemMessage
423
+ } = workflow.proxyActivities({
424
+ startToCloseTimeout: "30m",
425
+ retry: {
426
+ maximumAttempts: 6,
427
+ initialInterval: "5s",
428
+ maximumInterval: "15m",
429
+ backoffCoefficient: 4
430
+ },
431
+ heartbeatTimeout: "5m"
432
+ });
433
+ const fileTree = await buildFileTree();
434
+ const toolRouter = createToolRouter({
435
+ tools,
436
+ threadId,
437
+ hooks,
438
+ buildInTools,
439
+ fileTree,
440
+ subagents,
441
+ parallel: processToolsInParallel
442
+ });
443
+ const callSessionEnd = async (exitReason, turns) => {
444
+ if (hooks.onSessionEnd) {
445
+ await hooks.onSessionEnd({
446
+ threadId,
447
+ agentName,
448
+ exitReason,
449
+ turns,
450
+ metadata
451
+ });
452
+ }
453
+ };
454
+ return {
455
+ runSession: async ({ stateManager }) => {
456
+ if (hooks.onSessionStart) {
457
+ await hooks.onSessionStart({
458
+ threadId,
459
+ agentName,
460
+ metadata
461
+ });
462
+ }
463
+ stateManager.setTools(toolRouter.getToolDefinitions());
464
+ await initializeThread(threadId);
465
+ await appendSystemMessage(
466
+ threadId,
467
+ [
468
+ await resolvePrompt(baseSystemPrompt),
469
+ await resolvePrompt(instructionsPrompt)
470
+ ].join("\n")
471
+ );
472
+ await appendHumanMessage(threadId, await buildContextMessage());
473
+ let exitReason = "completed";
474
+ try {
475
+ while (stateManager.isRunning() && !stateManager.isTerminal() && stateManager.getTurns() < maxTurns) {
476
+ stateManager.incrementTurns();
477
+ const currentTurn = stateManager.getTurns();
478
+ const { message, stopReason } = await runAgent({
479
+ threadId,
480
+ agentName,
481
+ metadata
482
+ });
483
+ if (stopReason === "end_turn") {
484
+ stateManager.complete();
485
+ exitReason = "completed";
486
+ return message;
487
+ }
488
+ if (!toolRouter.hasTools()) {
489
+ stateManager.complete();
490
+ exitReason = "completed";
491
+ return message;
492
+ }
493
+ const rawToolCalls = await parseToolCalls(message);
494
+ const parsedToolCalls = rawToolCalls.filter((tc) => tc.name !== "Task").map((tc) => toolRouter.parseToolCall(tc));
495
+ const taskToolCalls = subagents && subagents.length > 0 ? rawToolCalls.filter((tc) => tc.name === "Task").map((tc) => {
496
+ const parsedArgs = createTaskTool(subagents).schema.parse(
497
+ tc.args
498
+ );
499
+ return {
500
+ id: tc.id ?? "",
501
+ name: tc.name,
502
+ args: parsedArgs
503
+ };
504
+ }) : [];
505
+ await toolRouter.processToolCalls(
506
+ [...parsedToolCalls, ...taskToolCalls],
507
+ {
508
+ turn: currentTurn
509
+ }
510
+ );
511
+ if (stateManager.getStatus() === "WAITING_FOR_INPUT") {
512
+ exitReason = "waiting_for_input";
513
+ break;
514
+ }
515
+ }
516
+ if (stateManager.getTurns() >= maxTurns && stateManager.isRunning()) {
517
+ exitReason = "max_turns";
518
+ }
519
+ } catch (error) {
520
+ exitReason = "failed";
521
+ throw error;
522
+ } finally {
523
+ await callSessionEnd(exitReason, stateManager.getTurns());
524
+ }
525
+ return null;
526
+ }
527
+ };
528
+ };
529
+
530
+ // src/lib/types.ts
531
+ function isTerminalStatus(status) {
532
+ return status === "COMPLETED" || status === "FAILED" || status === "CANCELLED";
533
+ }
534
+
535
+ // src/lib/state-manager.ts
536
+ var getStateQuery = workflow.defineQuery("getState");
537
+ function createAgentStateManager(initialState) {
538
+ let status = initialState?.status ?? "RUNNING";
539
+ let version = initialState?.version ?? 0;
540
+ let turns = initialState?.turns ?? 0;
541
+ let tools = initialState?.tools ?? [];
542
+ const tasks = new Map(initialState?.tasks);
543
+ const {
544
+ status: _,
545
+ version: __,
546
+ turns: ___,
547
+ tasks: ____,
548
+ tools: _____,
549
+ ...custom
550
+ } = initialState ?? {};
551
+ const customState = custom;
552
+ function buildState() {
553
+ return {
554
+ status,
555
+ version,
556
+ turns,
557
+ tools,
558
+ ...customState
559
+ };
560
+ }
561
+ workflow.setHandler(getStateQuery, () => {
562
+ return buildState();
563
+ });
564
+ return {
565
+ getStatus() {
566
+ return status;
567
+ },
568
+ isRunning() {
569
+ return status === "RUNNING";
570
+ },
571
+ isTerminal() {
572
+ return isTerminalStatus(status);
573
+ },
574
+ getTurns() {
575
+ return turns;
576
+ },
577
+ getVersion() {
578
+ return version;
579
+ },
580
+ run() {
581
+ status = "RUNNING";
582
+ version++;
583
+ },
584
+ waitForInput() {
585
+ status = "WAITING_FOR_INPUT";
586
+ version++;
587
+ },
588
+ complete() {
589
+ status = "COMPLETED";
590
+ version++;
591
+ },
592
+ fail() {
593
+ status = "FAILED";
594
+ version++;
595
+ },
596
+ cancel() {
597
+ status = "CANCELLED";
598
+ version++;
599
+ },
600
+ incrementVersion() {
601
+ version++;
602
+ },
603
+ incrementTurns() {
604
+ turns++;
605
+ },
606
+ get(key) {
607
+ return customState[key];
608
+ },
609
+ set(key, value) {
610
+ customState[key] = value;
611
+ version++;
612
+ },
613
+ getCurrentState() {
614
+ return buildState();
615
+ },
616
+ shouldReturnFromWait(lastKnownVersion) {
617
+ return version > lastKnownVersion || isTerminalStatus(status);
618
+ },
619
+ getTasks() {
620
+ return Array.from(tasks.values());
621
+ },
622
+ getTask(id) {
623
+ return tasks.get(id);
624
+ },
625
+ setTask(task) {
626
+ tasks.set(task.id, task);
627
+ version++;
628
+ },
629
+ setTools(newTools) {
630
+ tools = newTools;
631
+ },
632
+ deleteTask(id) {
633
+ const deleted = tasks.delete(id);
634
+ if (deleted) {
635
+ version++;
636
+ }
637
+ return deleted;
638
+ }
639
+ };
640
+ }
641
+ var AGENT_HANDLER_NAMES = {
642
+ getAgentState: "getAgentState",
643
+ waitForStateChange: "waitForStateChange",
644
+ addMessage: "addMessage"
645
+ };
646
+ var askUserQuestionTool = {
647
+ name: "AskUserQuestion",
648
+ description: `Use this tool when you need to ask the user questions during execution. This allows you to:
649
+
650
+ 1. Gather user preferences or requirements
651
+ 2. Clarify ambiguous instructions
652
+ 3. Get decisions on implementation choices as you work
653
+ 4. Offer choices to the user about what direction to take.
654
+
655
+ Usage notes:
656
+
657
+ * Users will always be able to select "Other" to provide custom text input
658
+ * Use multiSelect: true to allow multiple answers to be selected for a question
659
+ * If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label
660
+ `,
661
+ schema: z4__default.default.object({
662
+ questions: z4__default.default.array(
663
+ z4__default.default.object({
664
+ question: z4__default.default.string().describe("The full question text to display"),
665
+ header: z4__default.default.string().describe("Short label for the question (max 12 characters)"),
666
+ options: z4__default.default.array(
667
+ z4__default.default.object({
668
+ label: z4__default.default.string(),
669
+ description: z4__default.default.string()
670
+ })
671
+ ).min(0).max(4).describe("Array of 0-4 choices, each with label and description"),
672
+ multiSelect: z4__default.default.boolean().describe("If true, users can select multiple options")
673
+ })
674
+ )
675
+ }),
676
+ strict: true
677
+ };
678
+ var globTool = {
679
+ name: "Glob",
680
+ description: `Search for files matching a glob pattern within the available file system.
681
+
682
+ Usage:
683
+ - Use glob patterns like "**/*.ts" to find all TypeScript files
684
+ - Use "docs/**" to find all files in the docs directory
685
+ - Patterns are matched against virtual paths in the file system
686
+
687
+ Examples:
688
+ - "*.md" - Find all markdown files in the root
689
+ - "**/*.test.ts" - Find all test files recursively
690
+ - "src/**/*.ts" - Find all TypeScript files in src directory
691
+ `,
692
+ schema: z4.z.object({
693
+ pattern: z4.z.string().describe("Glob pattern to match files against"),
694
+ root: z4.z.string().optional().describe("Optional root directory to search from")
695
+ }),
696
+ strict: true
697
+ };
698
+ var grepTool = {
699
+ name: "Grep",
700
+ description: `Search file contents for a pattern within the available file system.
701
+
702
+ Usage:
703
+ - Searches for a regex pattern across file contents
704
+ - Returns matching lines with file paths and line numbers
705
+ - Can filter by file patterns and limit results
706
+
707
+ Examples:
708
+ - Search for "TODO" in all files
709
+ - Search for function definitions with "function.*handleClick"
710
+ - Search case-insensitively with ignoreCase: true
711
+ `,
712
+ schema: z4.z.object({
713
+ pattern: z4.z.string().describe("Regex pattern to search for in file contents"),
714
+ ignoreCase: z4.z.boolean().optional().describe("Case-insensitive search (default: false)"),
715
+ maxMatches: z4.z.number().optional().describe("Maximum number of matches to return (default: 50)"),
716
+ includePatterns: z4.z.array(z4.z.string()).optional().describe("Glob patterns to include (e.g., ['*.ts', '*.js'])"),
717
+ excludePatterns: z4.z.array(z4.z.string()).optional().describe("Glob patterns to exclude (e.g., ['*.test.ts'])"),
718
+ contextLines: z4.z.number().optional().describe("Number of context lines to show around matches")
719
+ }),
720
+ strict: true
721
+ };
722
+ var readTool = {
723
+ name: "FileRead",
724
+ description: `Read file contents with optional pagination.
725
+
726
+ Usage:
727
+ - Provide the virtual path to the file you want to read
728
+ - Supports text files, images, and PDFs
729
+ - For large files, use offset and limit to read specific portions
730
+
731
+ The tool returns the file content in an appropriate format:
732
+ - Text files: Plain text content
733
+ - Images: Base64-encoded image data
734
+ - PDFs: Extracted text content
735
+ `,
736
+ schema: z4.z.object({
737
+ path: z4.z.string().describe("Virtual path to the file to read"),
738
+ offset: z4.z.number().optional().describe(
739
+ "Line number to start reading from (1-indexed, for text files)"
740
+ ),
741
+ limit: z4.z.number().optional().describe("Maximum number of lines to read (for text files)")
742
+ }),
743
+ strict: true
744
+ };
745
+ var writeTool = {
746
+ name: "FileWrite",
747
+ description: `Create or overwrite a file with new content.
748
+
749
+ Usage:
750
+ - Provide the absolute virtual path to the file
751
+ - The file will be created if it doesn't exist
752
+ - If the file exists, it will be completely overwritten
753
+
754
+ IMPORTANT:
755
+ - You must read the file first (in this session) before writing to it
756
+ - This is an atomic write operation - the entire file is replaced
757
+ - Path must be absolute (e.g., "/docs/readme.md", not "docs/readme.md")
758
+ `,
759
+ schema: z4.z.object({
760
+ file_path: z4.z.string().describe("The absolute virtual path to the file to write"),
761
+ content: z4.z.string().describe("The content to write to the file")
762
+ }),
763
+ strict: true
764
+ };
765
+ var editTool = {
766
+ name: "FileEdit",
767
+ description: `Edit specific sections of a file by replacing text.
768
+
769
+ Usage:
770
+ - Provide the exact text to find and replace
771
+ - The old_string must match exactly (whitespace-sensitive)
772
+ - By default, only replaces the first occurrence
773
+ - Use replace_all: true to replace all occurrences
774
+
775
+ IMPORTANT:
776
+ - You must read the file first (in this session) before editing it
777
+ - old_string must be unique in the file (unless using replace_all)
778
+ - The operation fails if old_string is not found
779
+ - old_string and new_string must be different
780
+ `,
781
+ schema: z4.z.object({
782
+ file_path: z4.z.string().describe("The absolute virtual path to the file to modify"),
783
+ old_string: z4.z.string().describe("The exact text to replace"),
784
+ new_string: z4.z.string().describe(
785
+ "The text to replace it with (must be different from old_string)"
786
+ ),
787
+ replace_all: z4.z.boolean().optional().describe(
788
+ "If true, replace all occurrences of old_string (default: false)"
789
+ )
790
+ }),
791
+ strict: true
792
+ };
793
+
794
+ // src/tools/task-create/handler.ts
795
+ function createTaskCreateHandler({
796
+ stateManager,
797
+ idGenerator
798
+ }) {
799
+ return (args) => {
800
+ const task = {
801
+ id: idGenerator(),
802
+ subject: args.subject,
803
+ description: args.description,
804
+ activeForm: args.activeForm,
805
+ status: "pending",
806
+ metadata: args.metadata ?? {},
807
+ blockedBy: [],
808
+ blocks: []
809
+ };
810
+ stateManager.setTask(task);
811
+ return {
812
+ content: JSON.stringify(task, null, 2),
813
+ result: task
814
+ };
815
+ };
816
+ }
817
+ var taskGetTool = {
818
+ name: "TaskGet",
819
+ description: `Retrieve full task details including dependencies.`,
820
+ schema: z4__default.default.object({
821
+ taskId: z4__default.default.string().describe("The ID of the task to get")
822
+ })
823
+ };
824
+
825
+ // src/tools/task-get/handler.ts
826
+ function createTaskGetHandler(stateManager) {
827
+ return (args) => {
828
+ const task = stateManager.getTask(args.taskId) ?? null;
829
+ if (!task) {
830
+ return {
831
+ content: JSON.stringify({ error: `Task not found: ${args.taskId}` }),
832
+ result: null
833
+ };
834
+ }
835
+ return {
836
+ content: JSON.stringify(task, null, 2),
837
+ result: task
838
+ };
839
+ };
840
+ }
841
+ var taskListTool = {
842
+ name: "TaskList",
843
+ description: `List all tasks with current state.`,
844
+ schema: z4__default.default.object({})
845
+ };
846
+
847
+ // src/tools/task-list/handler.ts
848
+ function createTaskListHandler(stateManager) {
849
+ return (_args) => {
850
+ const taskList = stateManager.getTasks();
851
+ return {
852
+ content: JSON.stringify(taskList, null, 2),
853
+ result: taskList
854
+ };
855
+ };
856
+ }
857
+ var taskUpdateTool = {
858
+ name: "TaskUpdate",
859
+ description: `Update status, add blockers, modify details.`,
860
+ schema: z4__default.default.object({
861
+ taskId: z4__default.default.string().describe("The ID of the task to get"),
862
+ status: z4__default.default.enum(["pending", "in_progress", "completed"]).describe("The status of the task"),
863
+ addBlockedBy: z4__default.default.array(z4__default.default.string()).describe("The IDs of the tasks that are blocking this task"),
864
+ addBlocks: z4__default.default.array(z4__default.default.string()).describe("The IDs of the tasks that this task is blocking")
865
+ })
866
+ };
867
+
868
+ // src/tools/task-update/handler.ts
869
+ function createTaskUpdateHandler(stateManager) {
870
+ return (args) => {
871
+ const task = stateManager.getTask(args.taskId);
872
+ if (!task) {
873
+ return {
874
+ content: JSON.stringify({ error: `Task not found: ${args.taskId}` }),
875
+ result: null
876
+ };
877
+ }
878
+ if (args.status) {
879
+ task.status = args.status;
880
+ }
881
+ if (args.addBlockedBy) {
882
+ for (const blockerId of args.addBlockedBy) {
883
+ if (!task.blockedBy.includes(blockerId)) {
884
+ task.blockedBy.push(blockerId);
885
+ }
886
+ const blockerTask = stateManager.getTask(blockerId);
887
+ if (blockerTask && !blockerTask.blocks.includes(task.id)) {
888
+ blockerTask.blocks.push(task.id);
889
+ stateManager.setTask(blockerTask);
890
+ }
891
+ }
892
+ }
893
+ if (args.addBlocks) {
894
+ for (const blockedId of args.addBlocks) {
895
+ if (!task.blocks.includes(blockedId)) {
896
+ task.blocks.push(blockedId);
897
+ }
898
+ const blockedTask = stateManager.getTask(blockedId);
899
+ if (blockedTask && !blockedTask.blockedBy.includes(task.id)) {
900
+ blockedTask.blockedBy.push(task.id);
901
+ stateManager.setTask(blockedTask);
902
+ }
903
+ }
904
+ }
905
+ stateManager.setTask(task);
906
+ return {
907
+ content: JSON.stringify(task, null, 2),
908
+ result: task
909
+ };
910
+ };
911
+ }
912
+
913
+ // node_modules/uuid/dist/esm-node/stringify.js
914
+ var byteToHex = [];
915
+ for (let i = 0; i < 256; ++i) {
916
+ byteToHex.push((i + 256).toString(16).slice(1));
917
+ }
918
+ function unsafeStringify(arr, offset = 0) {
919
+ 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();
920
+ }
921
+ var rnds8Pool = new Uint8Array(256);
922
+ var poolPtr = rnds8Pool.length;
923
+ function rng() {
924
+ if (poolPtr > rnds8Pool.length - 16) {
925
+ crypto__default.default.randomFillSync(rnds8Pool);
926
+ poolPtr = 0;
927
+ }
928
+ return rnds8Pool.slice(poolPtr, poolPtr += 16);
929
+ }
930
+ var native_default = {
931
+ randomUUID: crypto__default.default.randomUUID
932
+ };
933
+
934
+ // node_modules/uuid/dist/esm-node/v4.js
935
+ function v4(options, buf, offset) {
936
+ if (native_default.randomUUID && !buf && !options) {
937
+ return native_default.randomUUID();
938
+ }
939
+ options = options || {};
940
+ const rnds = options.random || (options.rng || rng)();
941
+ rnds[6] = rnds[6] & 15 | 64;
942
+ rnds[8] = rnds[8] & 63 | 128;
943
+ if (buf) {
944
+ offset = offset || 0;
945
+ for (let i = 0; i < 16; ++i) {
946
+ buf[offset + i] = rnds[i];
947
+ }
948
+ return buf;
949
+ }
950
+ return unsafeStringify(rnds);
951
+ }
952
+ var v4_default = v4;
953
+
954
+ // src/lib/thread-manager.ts
955
+ var THREAD_TTL_SECONDS = 60 * 60 * 24 * 90;
956
+ function getThreadKey(threadId, key) {
957
+ return `thread:${threadId}:${key}`;
958
+ }
959
+ function createThreadManager(config) {
960
+ const { redis, threadId, key = "messages" } = config;
961
+ const redisKey = getThreadKey(threadId, key);
962
+ return {
963
+ async initialize() {
964
+ await redis.del(redisKey);
965
+ },
966
+ async load() {
967
+ const data = await redis.lrange(redisKey, 0, -1);
968
+ return data.map((item) => JSON.parse(item));
969
+ },
970
+ async append(messages) {
971
+ if (messages.length > 0) {
972
+ await redis.rpush(redisKey, ...messages.map((m) => JSON.stringify(m)));
973
+ await redis.expire(redisKey, THREAD_TTL_SECONDS);
974
+ }
975
+ },
976
+ async delete() {
977
+ await redis.del(redisKey);
978
+ },
979
+ createHumanMessage(content) {
980
+ return new messages.HumanMessage({
981
+ id: v4_default(),
982
+ content
983
+ }).toDict();
984
+ },
985
+ createAIMessage(content, kwargs) {
986
+ return new messages.AIMessage({
987
+ id: v4_default(),
988
+ content,
989
+ additional_kwargs: kwargs ? {
990
+ header: kwargs.header,
991
+ options: kwargs.options,
992
+ multiSelect: kwargs.multiSelect
993
+ } : void 0
994
+ }).toDict();
995
+ },
996
+ createToolMessage(content, toolCallId) {
997
+ return new messages.ToolMessage({
998
+ // Cast needed due to langchain type compatibility
999
+ content,
1000
+ tool_call_id: toolCallId
1001
+ }).toDict();
1002
+ },
1003
+ createSystemMessage(content) {
1004
+ return new messages.SystemMessage({
1005
+ content
1006
+ }).toDict();
1007
+ },
1008
+ async appendSystemMessage(content) {
1009
+ const message = this.createSystemMessage(content);
1010
+ await this.append([message]);
1011
+ },
1012
+ async appendHumanMessage(content) {
1013
+ const message = this.createHumanMessage(content);
1014
+ await this.append([message]);
1015
+ },
1016
+ async appendToolMessage(content, toolCallId) {
1017
+ const message = this.createToolMessage(content, toolCallId);
1018
+ await this.append([message]);
1019
+ },
1020
+ async appendAIMessage(content) {
1021
+ const message = this.createAIMessage(content);
1022
+ await this.append([message]);
1023
+ }
1024
+ };
1025
+ }
1026
+ function createSharedActivities(redis) {
1027
+ return {
1028
+ async appendSystemMessage(threadId, content) {
1029
+ const thread = createThreadManager({ redis, threadId });
1030
+ await thread.appendSystemMessage(content);
1031
+ },
1032
+ async appendToolResult(config) {
1033
+ const { threadId, toolCallId, content } = config;
1034
+ const thread = createThreadManager({ redis, threadId });
1035
+ await thread.appendToolMessage(content, toolCallId);
1036
+ },
1037
+ async initializeThread(threadId) {
1038
+ const thread = createThreadManager({ redis, threadId });
1039
+ await thread.initialize();
1040
+ },
1041
+ async appendThreadMessages(threadId, messages) {
1042
+ const thread = createThreadManager({ redis, threadId });
1043
+ await thread.append(messages);
1044
+ },
1045
+ async appendHumanMessage(threadId, content) {
1046
+ const thread = createThreadManager({ redis, threadId });
1047
+ await thread.appendHumanMessage(content);
1048
+ },
1049
+ async parseToolCalls(storedMessage) {
1050
+ const message = messages.mapStoredMessageToChatMessage(storedMessage);
1051
+ const toolCalls = message.tool_calls ?? [];
1052
+ return toolCalls.map((toolCall) => ({
1053
+ id: toolCall.id,
1054
+ name: toolCall.name,
1055
+ args: toolCall.args
1056
+ }));
1057
+ }
1058
+ };
1059
+ }
1060
+
1061
+ // src/plugin.ts
1062
+ var ZeitlichPlugin = class extends plugin.SimplePlugin {
1063
+ constructor(options) {
1064
+ super({
1065
+ name: "ZeitlichPlugin",
1066
+ activities: createSharedActivities(options.redis)
1067
+ });
1068
+ }
1069
+ };
1070
+ async function invokeModel({
1071
+ redis,
1072
+ model,
1073
+ client,
1074
+ config: { threadId, agentName }
1075
+ }) {
1076
+ const thread = createThreadManager({ redis, threadId });
1077
+ const runId = v4_default();
1078
+ const info = activity.Context.current().info;
1079
+ const parentWorkflowId = info.workflowExecution.workflowId;
1080
+ const parentRunId = info.workflowExecution.runId;
1081
+ const handle = client.getHandle(parentWorkflowId, parentRunId);
1082
+ const { tools } = await handle.query(getStateQuery);
1083
+ const messages$1 = await thread.load();
1084
+ const response = await model.invoke(
1085
+ [...messages.mapStoredMessagesToChatMessages(messages$1)],
1086
+ {
1087
+ runName: agentName,
1088
+ runId,
1089
+ metadata: { thread_id: threadId },
1090
+ tools
1091
+ }
1092
+ );
1093
+ await thread.append([response.toDict()]);
1094
+ return {
1095
+ message: response.toDict(),
1096
+ stopReason: response.response_metadata?.stop_reason ?? null,
1097
+ usage: {
1098
+ input_tokens: response.usage_metadata?.input_tokens,
1099
+ output_tokens: response.usage_metadata?.output_tokens,
1100
+ total_tokens: response.usage_metadata?.total_tokens
1101
+ }
1102
+ };
1103
+ }
1104
+ var handleAskUserQuestionToolResult = async (args) => {
1105
+ const messages$1 = args.questions.map(
1106
+ ({ question, header, options, multiSelect }) => new messages.AIMessage({
1107
+ content: question,
1108
+ additional_kwargs: {
1109
+ header,
1110
+ options,
1111
+ multiSelect
1112
+ }
1113
+ }).toDict()
1114
+ );
1115
+ return { content: "Question submitted", result: { chatMessages: messages$1 } };
1116
+ };
1117
+ async function globHandler(_args, fs) {
1118
+ new justBash.Bash({ fs });
1119
+ return Promise.resolve({
1120
+ content: "Hello, world!",
1121
+ result: { files: [] }
1122
+ });
1123
+ }
1124
+
1125
+ // src/tools/edit/handler.ts
1126
+ function escapeRegExp(str) {
1127
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1128
+ }
1129
+ async function editHandler(args, fs) {
1130
+ const { file_path, old_string, new_string, replace_all = false } = args;
1131
+ if (old_string === new_string) {
1132
+ return {
1133
+ content: `Error: old_string and new_string must be different.`,
1134
+ result: {
1135
+ path: file_path,
1136
+ success: false,
1137
+ replacements: 0
1138
+ }
1139
+ };
1140
+ }
1141
+ try {
1142
+ const exists = await fs.exists(file_path);
1143
+ if (!exists) {
1144
+ return {
1145
+ content: `Error: File "${file_path}" does not exist.`,
1146
+ result: {
1147
+ path: file_path,
1148
+ success: false,
1149
+ replacements: 0
1150
+ }
1151
+ };
1152
+ }
1153
+ const content = await fs.readFile(file_path);
1154
+ if (!content.includes(old_string)) {
1155
+ return {
1156
+ content: `Error: Could not find the specified text in "${file_path}". Make sure old_string matches exactly (whitespace-sensitive).`,
1157
+ result: {
1158
+ path: file_path,
1159
+ success: false,
1160
+ replacements: 0
1161
+ }
1162
+ };
1163
+ }
1164
+ const escapedOldString = escapeRegExp(old_string);
1165
+ const globalRegex = new RegExp(escapedOldString, "g");
1166
+ const occurrences = (content.match(globalRegex) || []).length;
1167
+ if (!replace_all && occurrences > 1) {
1168
+ return {
1169
+ content: `Error: old_string appears ${occurrences} times in "${file_path}". Either provide more context to make it unique, or use replace_all: true.`,
1170
+ result: {
1171
+ path: file_path,
1172
+ success: false,
1173
+ replacements: 0
1174
+ }
1175
+ };
1176
+ }
1177
+ let newContent;
1178
+ let replacements;
1179
+ if (replace_all) {
1180
+ newContent = content.split(old_string).join(new_string);
1181
+ replacements = occurrences;
1182
+ } else {
1183
+ const index = content.indexOf(old_string);
1184
+ newContent = content.slice(0, index) + new_string + content.slice(index + old_string.length);
1185
+ replacements = 1;
1186
+ }
1187
+ await fs.writeFile(file_path, newContent);
1188
+ const summary = replace_all ? `Replaced ${replacements} occurrence(s)` : `Replaced 1 occurrence`;
1189
+ return {
1190
+ content: `${summary} in ${file_path}`,
1191
+ result: {
1192
+ path: file_path,
1193
+ success: true,
1194
+ replacements
1195
+ }
1196
+ };
1197
+ } catch (error) {
1198
+ const message = error instanceof Error ? error.message : "Unknown error";
1199
+ return {
1200
+ content: `Error editing file "${file_path}": ${message}`,
1201
+ result: {
1202
+ path: file_path,
1203
+ success: false,
1204
+ replacements: 0
1205
+ }
1206
+ };
1207
+ }
1208
+ }
1209
+ var handleBashTool = (bashOptions) => async (args, _context) => {
1210
+ const { command } = args;
1211
+ const mergedOptions = {
1212
+ ...bashOptions,
1213
+ executionLimits: {
1214
+ maxStringLength: 52428800,
1215
+ // 50MB default
1216
+ ...bashOptions.executionLimits
1217
+ }
1218
+ };
1219
+ const bash = new justBash.Bash(mergedOptions);
1220
+ try {
1221
+ const { exitCode, stderr, stdout } = await bash.exec(command);
1222
+ const bashExecOut = { exitCode, stderr, stdout };
1223
+ return {
1224
+ content: `Exit code: ${exitCode}
1225
+
1226
+ stdout:
1227
+ ${stdout}
1228
+
1229
+ stderr:
1230
+ ${stderr}`,
1231
+ result: bashExecOut
1232
+ };
1233
+ } catch (error) {
1234
+ const err = error instanceof Error ? error : new Error("Unknown error");
1235
+ return {
1236
+ content: `Error executing bash command: ${err.message}`,
1237
+ result: null
1238
+ };
1239
+ }
1240
+ };
1241
+
1242
+ // src/lib/fs.ts
1243
+ var basename = (path, separator) => {
1244
+ if (path[path.length - 1] === separator) path = path.slice(0, -1);
1245
+ const lastSlashIndex = path.lastIndexOf(separator);
1246
+ return lastSlashIndex === -1 ? path : path.slice(lastSlashIndex + 1);
1247
+ };
1248
+ var printTree = async (tab = "", children) => {
1249
+ let str = "";
1250
+ let last = children.length - 1;
1251
+ for (; last >= 0; last--) if (children[last]) break;
1252
+ for (let i = 0; i <= last; i++) {
1253
+ const fn = children[i];
1254
+ if (!fn) continue;
1255
+ const isLast = i === last;
1256
+ const child = await fn(tab + (isLast ? " " : "\u2502") + " ");
1257
+ const branch = child ? isLast ? "\u2514\u2500" : "\u251C\u2500" : "\u2502";
1258
+ str += "\n" + tab + branch + (child ? " " + child : "");
1259
+ }
1260
+ return str;
1261
+ };
1262
+ var toTree = async (fs, opts = {}) => {
1263
+ const separator = opts.separator || "/";
1264
+ let dir = opts.dir || separator;
1265
+ if (dir[dir.length - 1] !== separator) dir += separator;
1266
+ const tab = opts.tab || "";
1267
+ const depth = opts.depth ?? 10;
1268
+ const sort = opts.sort ?? true;
1269
+ let subtree = " (...)";
1270
+ if (depth > 0) {
1271
+ const list = await fs.readdirWithFileTypes?.(dir) || [];
1272
+ if (sort) {
1273
+ list.sort((a, b) => {
1274
+ if (a.isDirectory && b.isDirectory) {
1275
+ return a.name.toString().localeCompare(b.name.toString());
1276
+ } else if (a.isDirectory) {
1277
+ return -1;
1278
+ } else if (b.isDirectory) {
1279
+ return 1;
1280
+ } else {
1281
+ return a.name.toString().localeCompare(b.name.toString());
1282
+ }
1283
+ });
1284
+ }
1285
+ subtree = await printTree(
1286
+ tab,
1287
+ list.map((entry) => async (tab2) => {
1288
+ if (entry.isDirectory) {
1289
+ return toTree(fs, {
1290
+ dir: dir + entry.name,
1291
+ depth: depth - 1,
1292
+ tab: tab2
1293
+ });
1294
+ } else if (entry.isSymbolicLink) {
1295
+ return "" + entry.name + " \u2192 " + await fs.readlink(dir + entry.name);
1296
+ } else {
1297
+ return "" + entry.name;
1298
+ }
1299
+ })
1300
+ );
1301
+ }
1302
+ const base = basename(dir, separator) + separator;
1303
+ return base + subtree;
1304
+ };
1305
+
1306
+ exports.AGENT_HANDLER_NAMES = AGENT_HANDLER_NAMES;
1307
+ exports.ZeitlichPlugin = ZeitlichPlugin;
1308
+ exports.askUserQuestionTool = askUserQuestionTool;
1309
+ exports.bashTool = bashTool;
1310
+ exports.createAgentStateManager = createAgentStateManager;
1311
+ exports.createSession = createSession;
1312
+ exports.createSharedActivities = createSharedActivities;
1313
+ exports.createTaskCreateHandler = createTaskCreateHandler;
1314
+ exports.createTaskGetHandler = createTaskGetHandler;
1315
+ exports.createTaskListHandler = createTaskListHandler;
1316
+ exports.createTaskTool = createTaskTool;
1317
+ exports.createTaskUpdateHandler = createTaskUpdateHandler;
1318
+ exports.createToolRouter = createToolRouter;
1319
+ exports.editHandler = editHandler;
1320
+ exports.editTool = editTool;
1321
+ exports.globHandler = globHandler;
1322
+ exports.globTool = globTool;
1323
+ exports.grepTool = grepTool;
1324
+ exports.handleAskUserQuestionToolResult = handleAskUserQuestionToolResult;
1325
+ exports.handleBashTool = handleBashTool;
1326
+ exports.hasNoOtherToolCalls = hasNoOtherToolCalls;
1327
+ exports.invokeModel = invokeModel;
1328
+ exports.isTerminalStatus = isTerminalStatus;
1329
+ exports.readTool = readTool;
1330
+ exports.taskCreateTool = taskCreateTool;
1331
+ exports.taskGetTool = taskGetTool;
1332
+ exports.taskListTool = taskListTool;
1333
+ exports.taskUpdateTool = taskUpdateTool;
1334
+ exports.toTree = toTree;
1335
+ exports.writeTool = writeTool;
1336
+ //# sourceMappingURL=index.cjs.map
1337
+ //# sourceMappingURL=index.cjs.map