zeitlich 0.1.0 → 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 +732 -1077
  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 +547 -422
  15. package/dist/workflow.js.map +1 -1
  16. package/package.json +25 -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 -1582
  53. package/dist/index.mjs.map +0 -1
  54. package/dist/workflow-DeVGEXSc.d.mts +0 -1201
  55. package/dist/workflow-DeVGEXSc.d.ts +0 -1201
  56. package/dist/workflow.d.mts +0 -4
  57. package/dist/workflow.mjs +0 -734
  58. package/dist/workflow.mjs.map +0 -1
@@ -0,0 +1,914 @@
1
+ 'use strict';
2
+
3
+ var workflow = require('@temporalio/workflow');
4
+ var z4 = require('zod');
5
+
6
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
+
8
+ var z4__default = /*#__PURE__*/_interopDefault(z4);
9
+
10
+ // src/lib/session.ts
11
+ var TASK_TOOL = "Task";
12
+ function buildTaskDescription(subagents) {
13
+ const subagentList = subagents.map((s) => `- **${s.name}**: ${s.description}`).join("\n");
14
+ return `Launch a new agent to handle complex, multi-step tasks autonomously.
15
+
16
+ The ${TASK_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
17
+
18
+ Available agent types:
19
+
20
+ ${subagentList}
21
+
22
+ When using the ${TASK_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
23
+
24
+ Usage notes:
25
+
26
+ - Always include a short description (3-5 words) summarizing what the agent will do
27
+ - Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses
28
+ - 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.
29
+ - Each invocation starts fresh - provide a detailed task description with all necessary context.
30
+ - Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.
31
+ - The agent's outputs should generally be trusted
32
+ - Clearly tell the agent what type of work you expect since it is not aware of the user's intent
33
+ - 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.`;
34
+ }
35
+ function createTaskTool(subagents) {
36
+ if (subagents.length === 0) {
37
+ throw new Error("createTaskTool requires at least one subagent");
38
+ }
39
+ const names = subagents.map((s) => s.name);
40
+ return {
41
+ name: TASK_TOOL,
42
+ description: buildTaskDescription(subagents),
43
+ schema: z4__default.default.object({
44
+ subagent: z4__default.default.enum(names).describe("The type of subagent to launch"),
45
+ description: z4__default.default.string().describe("A short (3-5 word) description of the task"),
46
+ prompt: z4__default.default.string().describe("The task for the agent to perform")
47
+ })
48
+ };
49
+ }
50
+ function createTaskHandler(subagents) {
51
+ const { workflowId: parentWorkflowId, taskQueue: parentTaskQueue } = workflow.workflowInfo();
52
+ return async (args) => {
53
+ const config = subagents.find((s) => s.name === args.subagent);
54
+ if (!config) {
55
+ throw new Error(
56
+ `Unknown subagent: ${args.subagent}. Available: ${subagents.map((s) => s.name).join(", ")}`
57
+ );
58
+ }
59
+ const childWorkflowId = `${parentWorkflowId}-${args.subagent}-${workflow.uuid4()}`;
60
+ const childResult = await workflow.executeChild(config.workflowType, {
61
+ workflowId: childWorkflowId,
62
+ args: [{ prompt: args.prompt }],
63
+ taskQueue: config.taskQueue ?? parentTaskQueue
64
+ });
65
+ const validated = config.resultSchema ? config.resultSchema.parse(childResult) : childResult;
66
+ const content = typeof validated === "string" ? validated : JSON.stringify(validated, null, 2);
67
+ return {
68
+ content,
69
+ result: {
70
+ result: validated,
71
+ childWorkflowId
72
+ }
73
+ };
74
+ };
75
+ }
76
+ var createBashToolDescription = ({
77
+ fileTree
78
+ }) => `tool to execute bash commands, the file tree is: ${fileTree}`;
79
+ var bashTool = {
80
+ name: "Bash",
81
+ description: "tool to execute bash commands",
82
+ schema: z4__default.default.object({
83
+ command: z4__default.default.string().describe("stringified command to be executed inside the Bash")
84
+ }),
85
+ strict: true
86
+ };
87
+ var taskCreateTool = {
88
+ name: "TaskCreate",
89
+ 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.
90
+ It also helps the user understand the progress of the task and overall progress of their requests.
91
+
92
+ ## When to Use This Tool
93
+
94
+ Use this tool proactively in these scenarios:
95
+
96
+ - Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
97
+ - Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
98
+ - User explicitly requests todo list - When the user directly asks you to use the todo list
99
+ - User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
100
+ - After receiving new instructions - Immediately capture user requirements as tasks
101
+ - When you start working on a task - Mark it as in_progress BEFORE beginning work
102
+ - After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
103
+
104
+ ## When NOT to Use This Tool
105
+
106
+ Skip using this tool when:
107
+ - There is only a single, straightforward task
108
+ - The task is trivial and tracking it provides no organizational benefit
109
+ - The task can be completed in less than 3 trivial steps
110
+ - The task is purely conversational or informational
111
+
112
+ 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.
113
+
114
+ ## Task Fields
115
+
116
+ - **subject**: A brief, actionable title in imperative form (e.g., "Fix authentication bug in login flow")
117
+ - **description**: Detailed description of what needs to be done, including context and acceptance criteria
118
+ - **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.
119
+
120
+ **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\`.
121
+
122
+ ## Tips
123
+
124
+ - Create tasks with clear, specific subjects that describe the outcome
125
+ - Include enough detail in the description for another agent to understand and complete the task
126
+ - After creating tasks, use TaskUpdate to set up dependencies (blocks/blockedBy) if needed
127
+ - Check TaskList first to avoid creating duplicate tasks`,
128
+ schema: z4__default.default.object({
129
+ subject: z4__default.default.string().describe(
130
+ 'A brief, actionable title in imperative form (e.g., "Fix authentication bug in login flow")'
131
+ ),
132
+ description: z4__default.default.string().describe(
133
+ "Detailed description of what needs to be done, including context and acceptance criteria"
134
+ ),
135
+ activeForm: z4__default.default.string().describe(
136
+ '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.'
137
+ ),
138
+ metadata: z4__default.default.record(z4__default.default.string(), z4__default.default.string()).describe("Arbitrary key-value pairs for tracking")
139
+ })
140
+ };
141
+
142
+ // src/lib/tool-router.ts
143
+ var buildIntoolDefinitions = {
144
+ [bashTool.name]: bashTool,
145
+ [taskCreateTool.name]: taskCreateTool
146
+ };
147
+ function createToolRouter(options) {
148
+ const { appendToolResult } = workflow.proxyActivities({
149
+ startToCloseTimeout: "2m",
150
+ retry: {
151
+ maximumAttempts: 3,
152
+ initialInterval: "5s",
153
+ maximumInterval: "15m",
154
+ backoffCoefficient: 4
155
+ }
156
+ });
157
+ const toolMap = /* @__PURE__ */ new Map();
158
+ for (const [_key, tool] of Object.entries(options.tools)) {
159
+ toolMap.set(tool.name, tool);
160
+ }
161
+ if (options.subagents) {
162
+ toolMap.set("Task", {
163
+ ...createTaskTool(options.subagents),
164
+ handler: createTaskHandler(options.subagents)
165
+ });
166
+ }
167
+ if (options.buildInTools) {
168
+ for (const [key, value] of Object.entries(options.buildInTools)) {
169
+ if (key === bashTool.name) {
170
+ toolMap.set(key, {
171
+ ...buildIntoolDefinitions[key],
172
+ description: createBashToolDescription({
173
+ fileTree: options.fileTree
174
+ }),
175
+ handler: value
176
+ });
177
+ } else {
178
+ toolMap.set(key, {
179
+ ...buildIntoolDefinitions[key],
180
+ handler: value
181
+ });
182
+ }
183
+ }
184
+ }
185
+ async function processToolCall(toolCall, turn, handlerContext) {
186
+ const startTime = Date.now();
187
+ let effectiveArgs = toolCall.args;
188
+ if (options.hooks?.onPreToolUse) {
189
+ const preResult = await options.hooks.onPreToolUse({
190
+ toolCall,
191
+ threadId: options.threadId,
192
+ turn
193
+ });
194
+ if (preResult?.skip) {
195
+ await appendToolResult({
196
+ threadId: options.threadId,
197
+ toolCallId: toolCall.id,
198
+ content: JSON.stringify({
199
+ skipped: true,
200
+ reason: "Skipped by PreToolUse hook"
201
+ })
202
+ });
203
+ return null;
204
+ }
205
+ if (preResult?.modifiedArgs !== void 0) {
206
+ effectiveArgs = preResult.modifiedArgs;
207
+ }
208
+ }
209
+ const tool = toolMap.get(toolCall.name);
210
+ let result;
211
+ let content;
212
+ try {
213
+ if (tool) {
214
+ const response = await tool.handler(
215
+ effectiveArgs,
216
+ handlerContext ?? {}
217
+ );
218
+ result = response.result;
219
+ content = response.content;
220
+ } else {
221
+ result = { error: `Unknown tool: ${toolCall.name}` };
222
+ content = JSON.stringify(result, null, 2);
223
+ }
224
+ } catch (error) {
225
+ if (options.hooks?.onPostToolUseFailure) {
226
+ const failureResult = await options.hooks.onPostToolUseFailure({
227
+ toolCall,
228
+ error: error instanceof Error ? error : new Error(String(error)),
229
+ threadId: options.threadId,
230
+ turn
231
+ });
232
+ if (failureResult?.fallbackContent !== void 0) {
233
+ content = failureResult.fallbackContent;
234
+ result = { error: String(error), recovered: true };
235
+ } else if (failureResult?.suppress) {
236
+ content = JSON.stringify({ error: String(error), suppressed: true });
237
+ result = { error: String(error), suppressed: true };
238
+ } else {
239
+ throw error;
240
+ }
241
+ } else {
242
+ throw error;
243
+ }
244
+ }
245
+ await appendToolResult({
246
+ threadId: options.threadId,
247
+ toolCallId: toolCall.id,
248
+ content
249
+ });
250
+ const toolResult = {
251
+ toolCallId: toolCall.id,
252
+ name: toolCall.name,
253
+ result
254
+ };
255
+ if (options.hooks?.onPostToolUse) {
256
+ const durationMs = Date.now() - startTime;
257
+ await options.hooks.onPostToolUse({
258
+ toolCall,
259
+ result: toolResult,
260
+ threadId: options.threadId,
261
+ turn,
262
+ durationMs
263
+ });
264
+ }
265
+ return toolResult;
266
+ }
267
+ return {
268
+ // --- Methods from registry ---
269
+ hasTools() {
270
+ return toolMap.size > 0;
271
+ },
272
+ parseToolCall(toolCall) {
273
+ const tool = toolMap.get(toolCall.name);
274
+ if (!tool) {
275
+ throw new Error(`Tool ${toolCall.name} not found`);
276
+ }
277
+ const parsedArgs = tool.schema.parse(toolCall.args);
278
+ return {
279
+ id: toolCall.id ?? "",
280
+ name: toolCall.name,
281
+ args: parsedArgs
282
+ };
283
+ },
284
+ hasTool(name) {
285
+ return toolMap.has(name);
286
+ },
287
+ getToolNames() {
288
+ return Array.from(toolMap.keys());
289
+ },
290
+ getToolDefinitions() {
291
+ return Array.from(toolMap).map(([name, tool]) => ({
292
+ name,
293
+ description: tool.description,
294
+ schema: tool.schema,
295
+ strict: tool.strict,
296
+ max_uses: tool.max_uses
297
+ }));
298
+ },
299
+ // --- Methods for processing tool calls ---
300
+ async processToolCalls(toolCalls, context) {
301
+ if (toolCalls.length === 0) {
302
+ return [];
303
+ }
304
+ const turn = context?.turn ?? 0;
305
+ const handlerContext = context?.handlerContext;
306
+ if (options.parallel) {
307
+ const results2 = await Promise.all(
308
+ toolCalls.map((tc) => processToolCall(tc, turn, handlerContext))
309
+ );
310
+ return results2.filter(
311
+ (r) => r !== null
312
+ );
313
+ }
314
+ const results = [];
315
+ for (const toolCall of toolCalls) {
316
+ const result = await processToolCall(toolCall, turn, handlerContext);
317
+ if (result !== null) {
318
+ results.push(result);
319
+ }
320
+ }
321
+ return results;
322
+ },
323
+ async processToolCallsByName(toolCalls, toolName, handler, context) {
324
+ const matchingCalls = toolCalls.filter((tc) => tc.name === toolName);
325
+ if (matchingCalls.length === 0) {
326
+ return [];
327
+ }
328
+ const handlerContext = context?.handlerContext ?? {};
329
+ const processOne = async (toolCall) => {
330
+ const response = await handler(
331
+ toolCall.args,
332
+ handlerContext
333
+ );
334
+ await appendToolResult({
335
+ threadId: options.threadId,
336
+ toolCallId: toolCall.id,
337
+ content: response.content
338
+ });
339
+ return {
340
+ toolCallId: toolCall.id,
341
+ name: toolCall.name,
342
+ result: response.result
343
+ };
344
+ };
345
+ if (options.parallel) {
346
+ return Promise.all(matchingCalls.map(processOne));
347
+ }
348
+ const results = [];
349
+ for (const toolCall of matchingCalls) {
350
+ results.push(await processOne(toolCall));
351
+ }
352
+ return results;
353
+ },
354
+ // --- Utility methods ---
355
+ filterByName(toolCalls, name) {
356
+ return toolCalls.filter(
357
+ (tc) => tc.name === name
358
+ );
359
+ },
360
+ hasToolCall(toolCalls, name) {
361
+ return toolCalls.some((tc) => tc.name === name);
362
+ },
363
+ getResultsByName(results, name) {
364
+ return results.filter((r) => r.name === name);
365
+ }
366
+ };
367
+ }
368
+ function hasNoOtherToolCalls(toolCalls, excludeName) {
369
+ return toolCalls.filter((tc) => tc.name !== excludeName).length === 0;
370
+ }
371
+
372
+ // src/lib/session.ts
373
+ async function resolvePrompt(prompt) {
374
+ if (typeof prompt === "function") {
375
+ return prompt();
376
+ }
377
+ return prompt;
378
+ }
379
+ var createSession = async ({
380
+ threadId,
381
+ agentName,
382
+ maxTurns = 50,
383
+ metadata = {},
384
+ runAgent,
385
+ baseSystemPrompt,
386
+ instructionsPrompt,
387
+ buildContextMessage,
388
+ buildFileTree = async () => "",
389
+ subagents,
390
+ tools = {},
391
+ processToolsInParallel = true,
392
+ buildInTools = {},
393
+ hooks = {}
394
+ }) => {
395
+ const {
396
+ initializeThread,
397
+ appendHumanMessage,
398
+ parseToolCalls,
399
+ appendToolResult,
400
+ appendSystemMessage
401
+ } = workflow.proxyActivities({
402
+ startToCloseTimeout: "30m",
403
+ retry: {
404
+ maximumAttempts: 6,
405
+ initialInterval: "5s",
406
+ maximumInterval: "15m",
407
+ backoffCoefficient: 4
408
+ },
409
+ heartbeatTimeout: "5m"
410
+ });
411
+ const fileTree = await buildFileTree();
412
+ const toolRouter = createToolRouter({
413
+ tools,
414
+ threadId,
415
+ hooks,
416
+ buildInTools,
417
+ fileTree,
418
+ subagents,
419
+ parallel: processToolsInParallel
420
+ });
421
+ const callSessionEnd = async (exitReason, turns) => {
422
+ if (hooks.onSessionEnd) {
423
+ await hooks.onSessionEnd({
424
+ threadId,
425
+ agentName,
426
+ exitReason,
427
+ turns,
428
+ metadata
429
+ });
430
+ }
431
+ };
432
+ return {
433
+ runSession: async ({ stateManager }) => {
434
+ if (hooks.onSessionStart) {
435
+ await hooks.onSessionStart({
436
+ threadId,
437
+ agentName,
438
+ metadata
439
+ });
440
+ }
441
+ stateManager.setTools(toolRouter.getToolDefinitions());
442
+ await initializeThread(threadId);
443
+ await appendSystemMessage(
444
+ threadId,
445
+ [
446
+ await resolvePrompt(baseSystemPrompt),
447
+ await resolvePrompt(instructionsPrompt)
448
+ ].join("\n")
449
+ );
450
+ await appendHumanMessage(threadId, await buildContextMessage());
451
+ let exitReason = "completed";
452
+ try {
453
+ while (stateManager.isRunning() && !stateManager.isTerminal() && stateManager.getTurns() < maxTurns) {
454
+ stateManager.incrementTurns();
455
+ const currentTurn = stateManager.getTurns();
456
+ const { message, stopReason } = await runAgent({
457
+ threadId,
458
+ agentName,
459
+ metadata
460
+ });
461
+ if (stopReason === "end_turn") {
462
+ stateManager.complete();
463
+ exitReason = "completed";
464
+ return message;
465
+ }
466
+ if (!toolRouter.hasTools()) {
467
+ stateManager.complete();
468
+ exitReason = "completed";
469
+ return message;
470
+ }
471
+ const rawToolCalls = await parseToolCalls(message);
472
+ const parsedToolCalls = rawToolCalls.filter((tc) => tc.name !== "Task").map((tc) => toolRouter.parseToolCall(tc));
473
+ const taskToolCalls = subagents && subagents.length > 0 ? rawToolCalls.filter((tc) => tc.name === "Task").map((tc) => {
474
+ const parsedArgs = createTaskTool(subagents).schema.parse(
475
+ tc.args
476
+ );
477
+ return {
478
+ id: tc.id ?? "",
479
+ name: tc.name,
480
+ args: parsedArgs
481
+ };
482
+ }) : [];
483
+ await toolRouter.processToolCalls(
484
+ [...parsedToolCalls, ...taskToolCalls],
485
+ {
486
+ turn: currentTurn
487
+ }
488
+ );
489
+ if (stateManager.getStatus() === "WAITING_FOR_INPUT") {
490
+ exitReason = "waiting_for_input";
491
+ break;
492
+ }
493
+ }
494
+ if (stateManager.getTurns() >= maxTurns && stateManager.isRunning()) {
495
+ exitReason = "max_turns";
496
+ }
497
+ } catch (error) {
498
+ exitReason = "failed";
499
+ throw error;
500
+ } finally {
501
+ await callSessionEnd(exitReason, stateManager.getTurns());
502
+ }
503
+ return null;
504
+ }
505
+ };
506
+ };
507
+
508
+ // src/lib/types.ts
509
+ function isTerminalStatus(status) {
510
+ return status === "COMPLETED" || status === "FAILED" || status === "CANCELLED";
511
+ }
512
+
513
+ // src/lib/state-manager.ts
514
+ var getStateQuery = workflow.defineQuery("getState");
515
+ function createAgentStateManager(initialState) {
516
+ let status = initialState?.status ?? "RUNNING";
517
+ let version = initialState?.version ?? 0;
518
+ let turns = initialState?.turns ?? 0;
519
+ let tools = initialState?.tools ?? [];
520
+ const tasks = new Map(initialState?.tasks);
521
+ const {
522
+ status: _,
523
+ version: __,
524
+ turns: ___,
525
+ tasks: ____,
526
+ tools: _____,
527
+ ...custom
528
+ } = initialState ?? {};
529
+ const customState = custom;
530
+ function buildState() {
531
+ return {
532
+ status,
533
+ version,
534
+ turns,
535
+ tools,
536
+ ...customState
537
+ };
538
+ }
539
+ workflow.setHandler(getStateQuery, () => {
540
+ return buildState();
541
+ });
542
+ return {
543
+ getStatus() {
544
+ return status;
545
+ },
546
+ isRunning() {
547
+ return status === "RUNNING";
548
+ },
549
+ isTerminal() {
550
+ return isTerminalStatus(status);
551
+ },
552
+ getTurns() {
553
+ return turns;
554
+ },
555
+ getVersion() {
556
+ return version;
557
+ },
558
+ run() {
559
+ status = "RUNNING";
560
+ version++;
561
+ },
562
+ waitForInput() {
563
+ status = "WAITING_FOR_INPUT";
564
+ version++;
565
+ },
566
+ complete() {
567
+ status = "COMPLETED";
568
+ version++;
569
+ },
570
+ fail() {
571
+ status = "FAILED";
572
+ version++;
573
+ },
574
+ cancel() {
575
+ status = "CANCELLED";
576
+ version++;
577
+ },
578
+ incrementVersion() {
579
+ version++;
580
+ },
581
+ incrementTurns() {
582
+ turns++;
583
+ },
584
+ get(key) {
585
+ return customState[key];
586
+ },
587
+ set(key, value) {
588
+ customState[key] = value;
589
+ version++;
590
+ },
591
+ getCurrentState() {
592
+ return buildState();
593
+ },
594
+ shouldReturnFromWait(lastKnownVersion) {
595
+ return version > lastKnownVersion || isTerminalStatus(status);
596
+ },
597
+ getTasks() {
598
+ return Array.from(tasks.values());
599
+ },
600
+ getTask(id) {
601
+ return tasks.get(id);
602
+ },
603
+ setTask(task) {
604
+ tasks.set(task.id, task);
605
+ version++;
606
+ },
607
+ setTools(newTools) {
608
+ tools = newTools;
609
+ },
610
+ deleteTask(id) {
611
+ const deleted = tasks.delete(id);
612
+ if (deleted) {
613
+ version++;
614
+ }
615
+ return deleted;
616
+ }
617
+ };
618
+ }
619
+ var AGENT_HANDLER_NAMES = {
620
+ getAgentState: "getAgentState",
621
+ waitForStateChange: "waitForStateChange",
622
+ addMessage: "addMessage"
623
+ };
624
+ var askUserQuestionTool = {
625
+ name: "AskUserQuestion",
626
+ description: `Use this tool when you need to ask the user questions during execution. This allows you to:
627
+
628
+ 1. Gather user preferences or requirements
629
+ 2. Clarify ambiguous instructions
630
+ 3. Get decisions on implementation choices as you work
631
+ 4. Offer choices to the user about what direction to take.
632
+
633
+ Usage notes:
634
+
635
+ * Users will always be able to select "Other" to provide custom text input
636
+ * Use multiSelect: true to allow multiple answers to be selected for a question
637
+ * If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label
638
+ `,
639
+ schema: z4__default.default.object({
640
+ questions: z4__default.default.array(
641
+ z4__default.default.object({
642
+ question: z4__default.default.string().describe("The full question text to display"),
643
+ header: z4__default.default.string().describe("Short label for the question (max 12 characters)"),
644
+ options: z4__default.default.array(
645
+ z4__default.default.object({
646
+ label: z4__default.default.string(),
647
+ description: z4__default.default.string()
648
+ })
649
+ ).min(0).max(4).describe("Array of 0-4 choices, each with label and description"),
650
+ multiSelect: z4__default.default.boolean().describe("If true, users can select multiple options")
651
+ })
652
+ )
653
+ }),
654
+ strict: true
655
+ };
656
+ var globTool = {
657
+ name: "Glob",
658
+ description: `Search for files matching a glob pattern within the available file system.
659
+
660
+ Usage:
661
+ - Use glob patterns like "**/*.ts" to find all TypeScript files
662
+ - Use "docs/**" to find all files in the docs directory
663
+ - Patterns are matched against virtual paths in the file system
664
+
665
+ Examples:
666
+ - "*.md" - Find all markdown files in the root
667
+ - "**/*.test.ts" - Find all test files recursively
668
+ - "src/**/*.ts" - Find all TypeScript files in src directory
669
+ `,
670
+ schema: z4.z.object({
671
+ pattern: z4.z.string().describe("Glob pattern to match files against"),
672
+ root: z4.z.string().optional().describe("Optional root directory to search from")
673
+ }),
674
+ strict: true
675
+ };
676
+ var grepTool = {
677
+ name: "Grep",
678
+ description: `Search file contents for a pattern within the available file system.
679
+
680
+ Usage:
681
+ - Searches for a regex pattern across file contents
682
+ - Returns matching lines with file paths and line numbers
683
+ - Can filter by file patterns and limit results
684
+
685
+ Examples:
686
+ - Search for "TODO" in all files
687
+ - Search for function definitions with "function.*handleClick"
688
+ - Search case-insensitively with ignoreCase: true
689
+ `,
690
+ schema: z4.z.object({
691
+ pattern: z4.z.string().describe("Regex pattern to search for in file contents"),
692
+ ignoreCase: z4.z.boolean().optional().describe("Case-insensitive search (default: false)"),
693
+ maxMatches: z4.z.number().optional().describe("Maximum number of matches to return (default: 50)"),
694
+ includePatterns: z4.z.array(z4.z.string()).optional().describe("Glob patterns to include (e.g., ['*.ts', '*.js'])"),
695
+ excludePatterns: z4.z.array(z4.z.string()).optional().describe("Glob patterns to exclude (e.g., ['*.test.ts'])"),
696
+ contextLines: z4.z.number().optional().describe("Number of context lines to show around matches")
697
+ }),
698
+ strict: true
699
+ };
700
+ var readTool = {
701
+ name: "FileRead",
702
+ description: `Read file contents with optional pagination.
703
+
704
+ Usage:
705
+ - Provide the virtual path to the file you want to read
706
+ - Supports text files, images, and PDFs
707
+ - For large files, use offset and limit to read specific portions
708
+
709
+ The tool returns the file content in an appropriate format:
710
+ - Text files: Plain text content
711
+ - Images: Base64-encoded image data
712
+ - PDFs: Extracted text content
713
+ `,
714
+ schema: z4.z.object({
715
+ path: z4.z.string().describe("Virtual path to the file to read"),
716
+ offset: z4.z.number().optional().describe(
717
+ "Line number to start reading from (1-indexed, for text files)"
718
+ ),
719
+ limit: z4.z.number().optional().describe("Maximum number of lines to read (for text files)")
720
+ }),
721
+ strict: true
722
+ };
723
+ var writeTool = {
724
+ name: "FileWrite",
725
+ description: `Create or overwrite a file with new content.
726
+
727
+ Usage:
728
+ - Provide the absolute virtual path to the file
729
+ - The file will be created if it doesn't exist
730
+ - If the file exists, it will be completely overwritten
731
+
732
+ IMPORTANT:
733
+ - You must read the file first (in this session) before writing to it
734
+ - This is an atomic write operation - the entire file is replaced
735
+ - Path must be absolute (e.g., "/docs/readme.md", not "docs/readme.md")
736
+ `,
737
+ schema: z4.z.object({
738
+ file_path: z4.z.string().describe("The absolute virtual path to the file to write"),
739
+ content: z4.z.string().describe("The content to write to the file")
740
+ }),
741
+ strict: true
742
+ };
743
+ var editTool = {
744
+ name: "FileEdit",
745
+ description: `Edit specific sections of a file by replacing text.
746
+
747
+ Usage:
748
+ - Provide the exact text to find and replace
749
+ - The old_string must match exactly (whitespace-sensitive)
750
+ - By default, only replaces the first occurrence
751
+ - Use replace_all: true to replace all occurrences
752
+
753
+ IMPORTANT:
754
+ - You must read the file first (in this session) before editing it
755
+ - old_string must be unique in the file (unless using replace_all)
756
+ - The operation fails if old_string is not found
757
+ - old_string and new_string must be different
758
+ `,
759
+ schema: z4.z.object({
760
+ file_path: z4.z.string().describe("The absolute virtual path to the file to modify"),
761
+ old_string: z4.z.string().describe("The exact text to replace"),
762
+ new_string: z4.z.string().describe(
763
+ "The text to replace it with (must be different from old_string)"
764
+ ),
765
+ replace_all: z4.z.boolean().optional().describe(
766
+ "If true, replace all occurrences of old_string (default: false)"
767
+ )
768
+ }),
769
+ strict: true
770
+ };
771
+
772
+ // src/tools/task-create/handler.ts
773
+ function createTaskCreateHandler({
774
+ stateManager,
775
+ idGenerator
776
+ }) {
777
+ return (args) => {
778
+ const task = {
779
+ id: idGenerator(),
780
+ subject: args.subject,
781
+ description: args.description,
782
+ activeForm: args.activeForm,
783
+ status: "pending",
784
+ metadata: args.metadata ?? {},
785
+ blockedBy: [],
786
+ blocks: []
787
+ };
788
+ stateManager.setTask(task);
789
+ return {
790
+ content: JSON.stringify(task, null, 2),
791
+ result: task
792
+ };
793
+ };
794
+ }
795
+ var taskGetTool = {
796
+ name: "TaskGet",
797
+ description: `Retrieve full task details including dependencies.`,
798
+ schema: z4__default.default.object({
799
+ taskId: z4__default.default.string().describe("The ID of the task to get")
800
+ })
801
+ };
802
+
803
+ // src/tools/task-get/handler.ts
804
+ function createTaskGetHandler(stateManager) {
805
+ return (args) => {
806
+ const task = stateManager.getTask(args.taskId) ?? null;
807
+ if (!task) {
808
+ return {
809
+ content: JSON.stringify({ error: `Task not found: ${args.taskId}` }),
810
+ result: null
811
+ };
812
+ }
813
+ return {
814
+ content: JSON.stringify(task, null, 2),
815
+ result: task
816
+ };
817
+ };
818
+ }
819
+ var taskListTool = {
820
+ name: "TaskList",
821
+ description: `List all tasks with current state.`,
822
+ schema: z4__default.default.object({})
823
+ };
824
+
825
+ // src/tools/task-list/handler.ts
826
+ function createTaskListHandler(stateManager) {
827
+ return (_args) => {
828
+ const taskList = stateManager.getTasks();
829
+ return {
830
+ content: JSON.stringify(taskList, null, 2),
831
+ result: taskList
832
+ };
833
+ };
834
+ }
835
+ var taskUpdateTool = {
836
+ name: "TaskUpdate",
837
+ description: `Update status, add blockers, modify details.`,
838
+ schema: z4__default.default.object({
839
+ taskId: z4__default.default.string().describe("The ID of the task to get"),
840
+ status: z4__default.default.enum(["pending", "in_progress", "completed"]).describe("The status of the task"),
841
+ addBlockedBy: z4__default.default.array(z4__default.default.string()).describe("The IDs of the tasks that are blocking this task"),
842
+ addBlocks: z4__default.default.array(z4__default.default.string()).describe("The IDs of the tasks that this task is blocking")
843
+ })
844
+ };
845
+
846
+ // src/tools/task-update/handler.ts
847
+ function createTaskUpdateHandler(stateManager) {
848
+ return (args) => {
849
+ const task = stateManager.getTask(args.taskId);
850
+ if (!task) {
851
+ return {
852
+ content: JSON.stringify({ error: `Task not found: ${args.taskId}` }),
853
+ result: null
854
+ };
855
+ }
856
+ if (args.status) {
857
+ task.status = args.status;
858
+ }
859
+ if (args.addBlockedBy) {
860
+ for (const blockerId of args.addBlockedBy) {
861
+ if (!task.blockedBy.includes(blockerId)) {
862
+ task.blockedBy.push(blockerId);
863
+ }
864
+ const blockerTask = stateManager.getTask(blockerId);
865
+ if (blockerTask && !blockerTask.blocks.includes(task.id)) {
866
+ blockerTask.blocks.push(task.id);
867
+ stateManager.setTask(blockerTask);
868
+ }
869
+ }
870
+ }
871
+ if (args.addBlocks) {
872
+ for (const blockedId of args.addBlocks) {
873
+ if (!task.blocks.includes(blockedId)) {
874
+ task.blocks.push(blockedId);
875
+ }
876
+ const blockedTask = stateManager.getTask(blockedId);
877
+ if (blockedTask && !blockedTask.blockedBy.includes(task.id)) {
878
+ blockedTask.blockedBy.push(task.id);
879
+ stateManager.setTask(blockedTask);
880
+ }
881
+ }
882
+ }
883
+ stateManager.setTask(task);
884
+ return {
885
+ content: JSON.stringify(task, null, 2),
886
+ result: task
887
+ };
888
+ };
889
+ }
890
+
891
+ exports.AGENT_HANDLER_NAMES = AGENT_HANDLER_NAMES;
892
+ exports.askUserQuestionTool = askUserQuestionTool;
893
+ exports.bashTool = bashTool;
894
+ exports.createAgentStateManager = createAgentStateManager;
895
+ exports.createSession = createSession;
896
+ exports.createTaskCreateHandler = createTaskCreateHandler;
897
+ exports.createTaskGetHandler = createTaskGetHandler;
898
+ exports.createTaskListHandler = createTaskListHandler;
899
+ exports.createTaskTool = createTaskTool;
900
+ exports.createTaskUpdateHandler = createTaskUpdateHandler;
901
+ exports.createToolRouter = createToolRouter;
902
+ exports.editTool = editTool;
903
+ exports.globTool = globTool;
904
+ exports.grepTool = grepTool;
905
+ exports.hasNoOtherToolCalls = hasNoOtherToolCalls;
906
+ exports.isTerminalStatus = isTerminalStatus;
907
+ exports.readTool = readTool;
908
+ exports.taskCreateTool = taskCreateTool;
909
+ exports.taskGetTool = taskGetTool;
910
+ exports.taskListTool = taskListTool;
911
+ exports.taskUpdateTool = taskUpdateTool;
912
+ exports.writeTool = writeTool;
913
+ //# sourceMappingURL=workflow.cjs.map
914
+ //# sourceMappingURL=workflow.cjs.map