zeitlich 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -14,18 +14,18 @@ var z13__default = /*#__PURE__*/_interopDefault(z13);
14
14
  var crypto__default = /*#__PURE__*/_interopDefault(crypto);
15
15
 
16
16
  // src/lib/session.ts
17
- var SUBAGENT_TOOL = "Subagent";
17
+ var SUBAGENT_TOOL_NAME = "Subagent";
18
18
  function buildSubagentDescription(subagents) {
19
19
  const subagentList = subagents.map((s) => `- **${s.agentName}**: ${s.description}`).join("\n");
20
20
  return `Launch a new agent to handle complex tasks autonomously.
21
21
 
22
- The ${SUBAGENT_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
22
+ The ${SUBAGENT_TOOL_NAME} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
23
23
 
24
24
  Available agent types:
25
25
 
26
26
  ${subagentList}
27
27
 
28
- When using the ${SUBAGENT_TOOL} tool, you must specify a subagent parameter to select which agent type to use.
28
+ When using the ${SUBAGENT_TOOL_NAME} tool, you must specify a subagent parameter to select which agent type to use.
29
29
 
30
30
  Usage notes:
31
31
 
@@ -44,7 +44,7 @@ function createSubagentTool(subagents) {
44
44
  }
45
45
  const names = subagents.map((s) => s.agentName);
46
46
  return {
47
- name: SUBAGENT_TOOL,
47
+ name: SUBAGENT_TOOL_NAME,
48
48
  description: buildSubagentDescription(subagents),
49
49
  schema: z13__default.default.object({
50
50
  subagent: z13__default.default.enum(names).describe("The type of subagent to launch"),
@@ -72,11 +72,12 @@ function createSubagentHandler(subagents) {
72
72
  args: [input],
73
73
  taskQueue: config.taskQueue ?? parentTaskQueue
74
74
  };
75
- const { toolResponse, data } = typeof config.workflow === "string" ? await workflow.executeChild(config.workflow, childOpts) : await workflow.executeChild(config.workflow, childOpts);
75
+ const { toolResponse, data, usage } = typeof config.workflow === "string" ? await workflow.executeChild(config.workflow, childOpts) : await workflow.executeChild(config.workflow, childOpts);
76
76
  const validated = config.resultSchema ? config.resultSchema.parse(data) : null;
77
77
  return {
78
78
  toolResponse,
79
- data: validated
79
+ data: validated,
80
+ ...usage && { usage }
80
81
  };
81
82
  };
82
83
  }
@@ -88,20 +89,17 @@ function createToolRouter(options) {
88
89
  for (const [_key, tool] of Object.entries(options.tools)) {
89
90
  toolMap.set(tool.name, tool);
90
91
  }
91
- const isEnabled = (tool) => tool.enabled !== false;
92
+ const isEnabled = (tool) => tool.enabled?.() ?? true;
92
93
  if (options.subagents) {
93
- const enabledSubagents = options.subagents.filter(
94
- (s) => s.enabled !== false
95
- );
96
- if (enabledSubagents.length > 0) {
94
+ if (options.subagents.length > 0) {
97
95
  const subagentHooksMap = /* @__PURE__ */ new Map();
98
- for (const s of enabledSubagents) {
96
+ for (const s of options.subagents) {
99
97
  if (s.hooks) subagentHooksMap.set(s.agentName, s.hooks);
100
98
  }
101
99
  const resolveSubagentName = (args) => args.subagent;
102
- toolMap.set("Subagent", {
103
- ...createSubagentTool(enabledSubagents),
104
- handler: createSubagentHandler(enabledSubagents),
100
+ toolMap.set(SUBAGENT_TOOL_NAME, {
101
+ ...createSubagentTool(options.subagents),
102
+ handler: createSubagentHandler(options.subagents),
105
103
  ...subagentHooksMap.size > 0 && {
106
104
  hooks: {
107
105
  onPreToolUse: async (ctx) => {
@@ -292,13 +290,19 @@ function createToolRouter(options) {
292
290
  return Array.from(toolMap.entries()).filter(([, tool]) => isEnabled(tool)).map(([name]) => name);
293
291
  },
294
292
  getToolDefinitions() {
295
- return Array.from(toolMap).filter(([, tool]) => isEnabled(tool)).map(([name, tool]) => ({
296
- name,
297
- description: tool.description,
298
- schema: tool.schema,
299
- strict: tool.strict,
300
- max_uses: tool.max_uses
301
- }));
293
+ const activeSubagents = options.subagents?.filter((subagent) => isEnabled(subagent)) ?? [];
294
+ return [
295
+ ...Array.from(toolMap).filter(
296
+ ([, tool]) => isEnabled(tool) && tool.name !== SUBAGENT_TOOL_NAME
297
+ ).map(([name, tool]) => ({
298
+ name,
299
+ description: tool.description,
300
+ schema: tool.schema,
301
+ strict: tool.strict,
302
+ max_uses: tool.max_uses
303
+ })),
304
+ ...activeSubagents.length > 0 ? [createSubagentTool(activeSubagents)] : []
305
+ ];
302
306
  },
303
307
  // --- Methods for processing tool calls ---
304
308
  async processToolCalls(toolCalls, context) {
@@ -411,6 +415,7 @@ function hasNoOtherToolCalls(toolCalls, excludeName) {
411
415
  var createSession = async ({
412
416
  threadId,
413
417
  agentName,
418
+ description,
414
419
  maxTurns = 50,
415
420
  metadata = {},
416
421
  runAgent,
@@ -450,7 +455,9 @@ var createSession = async ({
450
455
  }
451
456
  };
452
457
  return {
453
- runSession: async ({ stateManager }) => {
458
+ runSession: async ({
459
+ stateManager
460
+ }) => {
454
461
  workflow.setHandler(
455
462
  workflow.defineUpdate(`add${agentName}Message`),
456
463
  async (message) => {
@@ -477,7 +484,6 @@ var createSession = async ({
477
484
  metadata
478
485
  });
479
486
  }
480
- stateManager.setTools(toolRouter.getToolDefinitions());
481
487
  await initializeThread(threadId);
482
488
  if (appendSystemPrompt && systemPrompt && systemPrompt.trim() !== "") {
483
489
  await appendSystemMessage(threadId, systemPrompt);
@@ -488,15 +494,25 @@ var createSession = async ({
488
494
  while (stateManager.isRunning() && !stateManager.isTerminal() && stateManager.getTurns() < maxTurns) {
489
495
  stateManager.incrementTurns();
490
496
  const currentTurn = stateManager.getTurns();
491
- const { message, rawToolCalls } = await runAgent({
497
+ stateManager.setTools(toolRouter.getToolDefinitions());
498
+ const { message, rawToolCalls, usage } = await runAgent({
492
499
  threadId,
493
500
  agentName,
494
- metadata
501
+ metadata,
502
+ systemPrompt,
503
+ description
495
504
  });
505
+ if (usage) {
506
+ stateManager.updateUsage(usage);
507
+ }
496
508
  if (!toolRouter.hasTools() || rawToolCalls.length === 0) {
497
509
  stateManager.complete();
498
510
  exitReason = "completed";
499
- return message;
511
+ return {
512
+ finalMessage: message,
513
+ exitReason,
514
+ usage: stateManager.getTotalUsage()
515
+ };
500
516
  }
501
517
  const parsedToolCalls = [];
502
518
  for (const tc of rawToolCalls) {
@@ -513,9 +529,17 @@ var createSession = async ({
513
529
  });
514
530
  }
515
531
  }
516
- await toolRouter.processToolCalls(parsedToolCalls, {
517
- turn: currentTurn
518
- });
532
+ const toolCallResults = await toolRouter.processToolCalls(
533
+ parsedToolCalls,
534
+ {
535
+ turn: currentTurn
536
+ }
537
+ );
538
+ for (const result of toolCallResults) {
539
+ if (result.usage) {
540
+ stateManager.updateUsage(result.usage);
541
+ }
542
+ }
519
543
  if (stateManager.getStatus() === "WAITING_FOR_INPUT") {
520
544
  const conditionMet = await workflow.condition(
521
545
  () => stateManager.getStatus() === "RUNNING",
@@ -537,7 +561,11 @@ var createSession = async ({
537
561
  } finally {
538
562
  await callSessionEnd(exitReason, stateManager.getTurns());
539
563
  }
540
- return null;
564
+ return {
565
+ finalMessage: null,
566
+ exitReason,
567
+ usage: stateManager.getTotalUsage()
568
+ };
541
569
  }
542
570
  };
543
571
  };
@@ -574,6 +602,11 @@ function createAgentStateManager({
574
602
  let version = initialState?.version ?? 0;
575
603
  let turns = initialState?.turns ?? 0;
576
604
  let tools = initialState?.tools ?? [];
605
+ let totalInputTokens = 0;
606
+ let totalOutputTokens = 0;
607
+ let totalCachedWriteTokens = 0;
608
+ let totalCachedReadTokens = 0;
609
+ let totalReasonTokens = 0;
577
610
  const tasks = new Map(initialState?.tasks);
578
611
  const {
579
612
  status: _,
@@ -688,6 +721,23 @@ function createAgentStateManager({
688
721
  version++;
689
722
  }
690
723
  return deleted;
724
+ },
725
+ updateUsage(usage) {
726
+ totalInputTokens += usage.inputTokens ?? 0;
727
+ totalOutputTokens += usage.outputTokens ?? 0;
728
+ totalCachedWriteTokens += usage.cachedWriteTokens ?? 0;
729
+ totalCachedReadTokens += usage.cachedReadTokens ?? 0;
730
+ totalReasonTokens += usage.reasonTokens ?? 0;
731
+ },
732
+ getTotalUsage() {
733
+ return {
734
+ totalInputTokens,
735
+ totalOutputTokens,
736
+ totalCachedWriteTokens,
737
+ totalCachedReadTokens,
738
+ totalReasonTokens,
739
+ turns
740
+ };
691
741
  }
692
742
  };
693
743
  }
@@ -740,7 +790,7 @@ Examples:
740
790
  }),
741
791
  strict: true
742
792
  };
743
- var readTool = {
793
+ var readFileTool = {
744
794
  name: "FileRead",
745
795
  description: `Read file contents with optional pagination.
746
796
 
@@ -763,22 +813,21 @@ The tool returns the file content in an appropriate format:
763
813
  }),
764
814
  strict: true
765
815
  };
766
- var writeTool = {
816
+ var writeFileTool = {
767
817
  name: "FileWrite",
768
818
  description: `Create or overwrite a file with new content.
769
819
 
770
820
  Usage:
771
- - Provide the absolute path to the file
772
821
  - The file will be created if it doesn't exist
773
822
  - If the file exists, it will be completely overwritten
774
823
 
775
824
  IMPORTANT:
776
825
  - You must read the file first (in this session) before writing to it
777
826
  - This is an atomic write operation - the entire file is replaced
778
- - Path must be absolute (e.g., "/docs/readme.md", not "docs/readme.md")
827
+ - Path must be relative to the root of the file system (e.g., "docs/readme.md", not "/docs/readme.md")
779
828
  `,
780
829
  schema: z13.z.object({
781
- file_path: z13.z.string().describe("The absolute path to the file to write"),
830
+ file_path: z13.z.string().describe("The path to the file to write"),
782
831
  content: z13.z.string().describe("The content to write to the file")
783
832
  }),
784
833
  strict: true
@@ -1040,7 +1089,7 @@ Usage notes:
1040
1089
  };
1041
1090
 
1042
1091
  // src/tools/ask-user-question/handler.ts
1043
- var createAskUserQuestionHandler = () => (args) => {
1092
+ var createAskUserQuestionHandler = () => async (args) => {
1044
1093
  return {
1045
1094
  toolResponse: "Question submitted",
1046
1095
  data: { questions: args.questions }
@@ -1239,9 +1288,11 @@ async function invokeModel({
1239
1288
  args: tc.args
1240
1289
  })),
1241
1290
  usage: {
1242
- input_tokens: response.usage_metadata?.input_tokens,
1243
- output_tokens: response.usage_metadata?.output_tokens,
1244
- total_tokens: response.usage_metadata?.total_tokens
1291
+ inputTokens: response.usage_metadata?.input_tokens,
1292
+ outputTokens: response.usage_metadata?.output_tokens,
1293
+ reasonTokens: response.usage_metadata?.output_token_details?.reasoning,
1294
+ cachedWriteTokens: response.usage_metadata?.input_token_details?.cache_creation,
1295
+ cachedReadTokens: response.usage_metadata?.input_token_details?.cache_read
1245
1296
  }
1246
1297
  };
1247
1298
  }
@@ -1442,13 +1493,13 @@ exports.hasNoOtherToolCalls = hasNoOtherToolCalls;
1442
1493
  exports.invokeModel = invokeModel;
1443
1494
  exports.isTerminalStatus = isTerminalStatus;
1444
1495
  exports.proxyDefaultThreadOps = proxyDefaultThreadOps;
1445
- exports.readTool = readTool;
1496
+ exports.readFileTool = readFileTool;
1446
1497
  exports.taskCreateTool = taskCreateTool;
1447
1498
  exports.taskGetTool = taskGetTool;
1448
1499
  exports.taskListTool = taskListTool;
1449
1500
  exports.taskUpdateTool = taskUpdateTool;
1450
1501
  exports.toTree = toTree;
1451
1502
  exports.withAutoAppend = withAutoAppend;
1452
- exports.writeTool = writeTool;
1503
+ exports.writeFileTool = writeFileTool;
1453
1504
  //# sourceMappingURL=index.cjs.map
1454
1505
  //# sourceMappingURL=index.cjs.map