@perstack/runtime 0.0.75 → 0.0.77

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.
@@ -1,7 +1,7 @@
1
1
  import { getSkillManagersFromLockfile, getSkillManagers, closeSkillManagers, getSkillManagerByToolName, getToolSet } from './chunk-RG4QHAGG.js';
2
2
  import { readFileSync } from 'fs';
3
3
  import path from 'path';
4
- import { parseWithFriendlyError, lockfileSchema, runParamsSchema, createRuntimeEvent, knownModels, stopRunByExceededMaxSteps, continueToNextStep, stopRunByDelegate, stopRunByInteractiveTool, stopRunByError, retry, completeRun, finishToolCall, resolveToolResults, attemptCompletion, callDelegate, callInteractiveTool, callTools, resumeToolCalls, finishAllToolCalls, startGeneration, startRun } from '@perstack/core';
4
+ import { parseWithFriendlyError, lockfileSchema, runParamsSchema, createRuntimeEvent, knownModels, stopRunByExceededMaxSteps, continueToNextStep, stopRunByError, retry, createStreamingEvent, completeRun, finishToolCall, resolveToolResults, stopRunByInteractiveTool, skipDelegates, stopRunByDelegate, attemptCompletion, finishMcpTools, callTools, proceedToInteractiveTools, startGeneration, startRun, resumeFromStop } from '@perstack/core';
5
5
  import TOML from 'smol-toml';
6
6
  import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock';
7
7
  import { createAnthropic } from '@ai-sdk/anthropic';
@@ -12,17 +12,17 @@ import { createVertex } from '@ai-sdk/google-vertex';
12
12
  import { createOpenAI } from '@ai-sdk/openai';
13
13
  import { createOllama } from 'ollama-ai-provider-v2';
14
14
  import { ProxyAgent, fetch } from 'undici';
15
+ import { createId } from '@paralleldrive/cuid2';
15
16
  import { createApiClient } from '@perstack/api-client';
16
17
  import { setup, assign, createActor } from 'xstate';
17
18
  import { readFile } from 'fs/promises';
18
- import { createId } from '@paralleldrive/cuid2';
19
19
  import { dedent } from 'ts-dedent';
20
20
  import { APICallError, generateText, streamText } from 'ai';
21
21
 
22
22
  // package.json
23
23
  var package_default = {
24
24
  name: "@perstack/runtime",
25
- version: "0.0.75",
25
+ version: "0.0.77",
26
26
  description: "Perstack Runtime",
27
27
  author: "Wintermute Technologies, Inc.",
28
28
  license: "Apache-2.0",
@@ -319,9 +319,11 @@ function buildDelegationReturnState(currentSetting, resultCheckpoint, parentChec
319
319
  );
320
320
  }
321
321
  const { expert, toolCallId, toolName } = delegatedBy;
322
+ const newRunId = createId();
322
323
  return {
323
324
  setting: {
324
325
  ...currentSetting,
326
+ runId: newRunId,
325
327
  expertKey: expert.key,
326
328
  input: {
327
329
  interactiveToolCallResult: {
@@ -334,6 +336,7 @@ function buildDelegationReturnState(currentSetting, resultCheckpoint, parentChec
334
336
  },
335
337
  checkpoint: {
336
338
  ...parentCheckpoint,
339
+ runId: newRunId,
337
340
  stepNumber: resultCheckpoint.stepNumber,
338
341
  usage: resultCheckpoint.usage,
339
342
  pendingToolCalls: parentCheckpoint.pendingToolCalls,
@@ -541,15 +544,18 @@ async function classifyToolCalls(toolCalls, skillManagers) {
541
544
  return classified;
542
545
  }
543
546
 
544
- // src/state-machine/states/calling-delegate.ts
545
- async function callingDelegateLogic({
547
+ // src/state-machine/states/calling-delegates.ts
548
+ async function callingDelegatesLogic({
546
549
  setting,
547
550
  checkpoint,
548
551
  step,
549
552
  skillManagers
550
553
  }) {
551
- if (!step.pendingToolCalls || step.pendingToolCalls.length === 0) {
552
- throw new Error("No pending tool calls found");
554
+ if (step.pendingToolCalls === void 0 || step.partialToolResults === void 0) {
555
+ throw new Error("CallingDelegates: tool handling state is undefined (invariant violation)");
556
+ }
557
+ if (step.pendingToolCalls.length === 0) {
558
+ return skipDelegates(setting, checkpoint, {});
553
559
  }
554
560
  const toolCallTypes = await Promise.all(
555
561
  step.pendingToolCalls.map(async (tc) => ({
@@ -560,7 +566,7 @@ async function callingDelegateLogic({
560
566
  const delegateToolCalls = toolCallTypes.filter((t) => t.type === "delegate").map((t) => t.toolCall);
561
567
  const nonDelegateToolCalls = toolCallTypes.filter((t) => t.type !== "delegate").map((t) => t.toolCall);
562
568
  if (delegateToolCalls.length === 0) {
563
- throw new Error("No delegate tool calls found");
569
+ return skipDelegates(setting, checkpoint, {});
564
570
  }
565
571
  const delegations = await Promise.all(
566
572
  delegateToolCalls.map(async (tc) => {
@@ -588,7 +594,7 @@ async function callingDelegateLogic({
588
594
  ...checkpoint,
589
595
  status: "stoppedByDelegate",
590
596
  delegateTo: delegations,
591
- pendingToolCalls: nonDelegateToolCalls.length > 0 ? nonDelegateToolCalls : void 0,
597
+ pendingToolCalls: nonDelegateToolCalls,
592
598
  partialToolResults: step.partialToolResults
593
599
  },
594
600
  step: {
@@ -597,21 +603,26 @@ async function callingDelegateLogic({
597
603
  }
598
604
  });
599
605
  }
600
- async function callingInteractiveToolLogic({
606
+ async function callingInteractiveToolsLogic({
601
607
  setting,
602
608
  checkpoint,
603
609
  step
604
610
  }) {
605
- if (!step.pendingToolCalls || step.pendingToolCalls.length === 0) {
606
- throw new Error("No pending tool calls found");
611
+ if (step.pendingToolCalls === void 0 || step.partialToolResults === void 0) {
612
+ throw new Error(
613
+ "CallingInteractiveTools: tool handling state is undefined (invariant violation)"
614
+ );
615
+ }
616
+ if (step.pendingToolCalls.length === 0) {
617
+ return resolveToolResults(setting, checkpoint, {
618
+ toolResults: step.partialToolResults
619
+ });
607
620
  }
608
- const currentToolCall = step.pendingToolCalls[0];
609
- const remainingToolCalls = step.pendingToolCalls.slice(1);
610
621
  return stopRunByInteractiveTool(setting, checkpoint, {
611
622
  checkpoint: {
612
623
  ...checkpoint,
613
624
  status: "stoppedByInteractiveTool",
614
- pendingToolCalls: [currentToolCall, ...remainingToolCalls],
625
+ pendingToolCalls: step.pendingToolCalls,
615
626
  partialToolResults: step.partialToolResults
616
627
  },
617
628
  step: {
@@ -620,109 +631,6 @@ async function callingInteractiveToolLogic({
620
631
  }
621
632
  });
622
633
  }
623
- function hasRemainingTodos(toolResult) {
624
- const firstPart = toolResult.result[0];
625
- if (!firstPart || firstPart.type !== "textPart") {
626
- return false;
627
- }
628
- try {
629
- const parsed = JSON.parse(firstPart.text);
630
- return Array.isArray(parsed.remainingTodos) && parsed.remainingTodos.length > 0;
631
- } catch {
632
- return false;
633
- }
634
- }
635
- async function callingToolLogic({
636
- setting,
637
- checkpoint,
638
- step,
639
- skillManagers
640
- }) {
641
- const pendingToolCalls = step.pendingToolCalls ?? step.toolCalls ?? [];
642
- if (pendingToolCalls.length === 0) {
643
- throw new Error("No tool calls found");
644
- }
645
- const toolResults = step.toolResults ? [...step.toolResults] : [];
646
- const attemptCompletionTool = pendingToolCalls.find(
647
- (tc) => tc.skillName === "@perstack/base" && tc.toolName === "attemptCompletion"
648
- );
649
- if (attemptCompletionTool) {
650
- const toolResult = await toolExecutorFactory.execute(
651
- attemptCompletionTool,
652
- "mcp",
653
- skillManagers
654
- );
655
- if (hasRemainingTodos(toolResult)) {
656
- return resolveToolResults(setting, checkpoint, { toolResults: [toolResult] });
657
- }
658
- return attemptCompletion(setting, checkpoint, { toolResult });
659
- }
660
- const classified = await classifyToolCalls(pendingToolCalls, skillManagers);
661
- if (classified.mcp.length > 0) {
662
- const mcpResults = await Promise.all(
663
- classified.mcp.map((c) => toolExecutorFactory.execute(c.toolCall, "mcp", skillManagers))
664
- );
665
- toolResults.push(...mcpResults);
666
- }
667
- if (classified.delegate.length > 0) {
668
- const delegateToolCalls = classified.delegate.map((c) => c.toolCall);
669
- const interactiveToolCalls = classified.interactive.map((c) => c.toolCall);
670
- step.partialToolResults = toolResults;
671
- step.pendingToolCalls = [...delegateToolCalls, ...interactiveToolCalls];
672
- return callDelegate(setting, checkpoint, {
673
- newMessage: checkpoint.messages[checkpoint.messages.length - 1],
674
- toolCalls: delegateToolCalls,
675
- usage: step.usage
676
- });
677
- }
678
- if (classified.interactive.length > 0) {
679
- const interactiveToolCall = classified.interactive[0]?.toolCall;
680
- if (!interactiveToolCall) {
681
- throw new Error("No interactive tool call found");
682
- }
683
- const interactiveToolCalls = classified.interactive.map((c) => c.toolCall);
684
- step.partialToolResults = toolResults;
685
- step.pendingToolCalls = interactiveToolCalls;
686
- return callInteractiveTool(setting, checkpoint, {
687
- newMessage: checkpoint.messages[checkpoint.messages.length - 1],
688
- toolCall: interactiveToolCall,
689
- usage: step.usage
690
- });
691
- }
692
- return resolveToolResults(setting, checkpoint, { toolResults });
693
- }
694
- async function finishingStepLogic({
695
- setting,
696
- checkpoint,
697
- step
698
- }) {
699
- if (setting.maxSteps !== void 0 && checkpoint.stepNumber >= setting.maxSteps) {
700
- return stopRunByExceededMaxSteps(setting, checkpoint, {
701
- checkpoint: {
702
- ...checkpoint,
703
- status: "stoppedByExceededMaxSteps"
704
- },
705
- step: {
706
- ...step,
707
- finishedAt: Date.now()
708
- }
709
- });
710
- }
711
- return continueToNextStep(setting, checkpoint, {
712
- checkpoint: {
713
- ...checkpoint
714
- },
715
- step: {
716
- ...step,
717
- finishedAt: Date.now()
718
- },
719
- nextCheckpoint: {
720
- ...checkpoint,
721
- id: createId(),
722
- stepNumber: checkpoint.stepNumber + 1
723
- }
724
- });
725
- }
726
634
  function createUserMessage(contents) {
727
635
  return {
728
636
  type: "userMessage",
@@ -934,7 +842,146 @@ function toolResultPartToCoreToolResultPart(part) {
934
842
  };
935
843
  }
936
844
 
937
- // src/state-machine/states/generating-run-result.ts
845
+ // src/state-machine/states/calling-mcp-tools.ts
846
+ function hasRemainingTodos(toolResult) {
847
+ const firstPart = toolResult.result[0];
848
+ if (!firstPart || firstPart.type !== "textPart") {
849
+ return false;
850
+ }
851
+ try {
852
+ const parsed = JSON.parse(firstPart.text);
853
+ return Array.isArray(parsed.remainingTodos) && parsed.remainingTodos.length > 0;
854
+ } catch {
855
+ return false;
856
+ }
857
+ }
858
+ function extractTextFromLastMessage(checkpoint) {
859
+ const lastMessage = checkpoint.messages[checkpoint.messages.length - 1];
860
+ if (!lastMessage || lastMessage.type !== "expertMessage") {
861
+ return void 0;
862
+ }
863
+ const textPart = lastMessage.contents.find((c) => c.type === "textPart");
864
+ if (!textPart || textPart.type !== "textPart") {
865
+ return void 0;
866
+ }
867
+ const text = textPart.text.trim();
868
+ return text.length > 0 ? text : void 0;
869
+ }
870
+ async function callingMcpToolsLogic({
871
+ setting,
872
+ checkpoint,
873
+ step,
874
+ skillManagers
875
+ }) {
876
+ if (step.pendingToolCalls === void 0 || step.partialToolResults === void 0) {
877
+ throw new Error("CallingMcpTools: tool handling state is undefined (invariant violation)");
878
+ }
879
+ if (step.pendingToolCalls.length === 0) {
880
+ throw new Error("CallingMcpTools: pendingToolCalls is empty (invariant violation)");
881
+ }
882
+ const pendingToolCalls = step.pendingToolCalls;
883
+ const toolResults = [...step.partialToolResults];
884
+ const attemptCompletionTool = pendingToolCalls.find(
885
+ (tc) => tc.skillName === "@perstack/base" && tc.toolName === "attemptCompletion"
886
+ );
887
+ if (attemptCompletionTool) {
888
+ const toolResult = await toolExecutorFactory.execute(
889
+ attemptCompletionTool,
890
+ "mcp",
891
+ skillManagers
892
+ );
893
+ if (hasRemainingTodos(toolResult)) {
894
+ return resolveToolResults(setting, checkpoint, { toolResults: [toolResult] });
895
+ }
896
+ const existingText = extractTextFromLastMessage(checkpoint);
897
+ if (existingText) {
898
+ const toolResultPart = {
899
+ type: "toolResultPart",
900
+ toolCallId: toolResult.id,
901
+ toolName: attemptCompletionTool.toolName,
902
+ contents: toolResult.result.filter(
903
+ (part) => part.type === "textPart" || part.type === "imageInlinePart" || part.type === "fileInlinePart"
904
+ )
905
+ };
906
+ const toolMessage = createToolMessage([toolResultPart]);
907
+ const expertMessage = createExpertMessage([{ type: "textPart", text: existingText }]);
908
+ const newMessages = [toolMessage, expertMessage];
909
+ const newUsage = sumUsage(checkpoint.usage, createEmptyUsage());
910
+ return completeRun(setting, checkpoint, {
911
+ checkpoint: {
912
+ ...checkpoint,
913
+ messages: [...checkpoint.messages, ...newMessages],
914
+ usage: newUsage,
915
+ contextWindowUsage: checkpoint.contextWindow ? calculateContextWindowUsage(newUsage, checkpoint.contextWindow) : void 0,
916
+ status: "completed",
917
+ // Clear tool handling state on completion
918
+ pendingToolCalls: void 0,
919
+ partialToolResults: void 0
920
+ },
921
+ step: {
922
+ ...step,
923
+ newMessages: [...step.newMessages, ...newMessages],
924
+ toolResults: [toolResult],
925
+ finishedAt: Date.now()
926
+ },
927
+ text: existingText,
928
+ usage: createEmptyUsage()
929
+ });
930
+ }
931
+ return attemptCompletion(setting, checkpoint, { toolResult });
932
+ }
933
+ const classified = await classifyToolCalls(pendingToolCalls, skillManagers);
934
+ if (classified.mcp.length > 0) {
935
+ const mcpResults = await Promise.all(
936
+ classified.mcp.map((c) => toolExecutorFactory.execute(c.toolCall, "mcp", skillManagers))
937
+ );
938
+ toolResults.push(...mcpResults);
939
+ }
940
+ const delegateToolCalls = classified.delegate.map((c) => c.toolCall);
941
+ const interactiveToolCalls = classified.interactive.map((c) => c.toolCall);
942
+ if (delegateToolCalls.length > 0 || interactiveToolCalls.length > 0) {
943
+ return finishMcpTools(setting, checkpoint, {
944
+ partialToolResults: toolResults,
945
+ pendingToolCalls: [...delegateToolCalls, ...interactiveToolCalls]
946
+ });
947
+ }
948
+ return resolveToolResults(setting, checkpoint, { toolResults });
949
+ }
950
+ async function finishingStepLogic({
951
+ setting,
952
+ checkpoint,
953
+ step
954
+ }) {
955
+ if (setting.maxSteps !== void 0 && checkpoint.stepNumber >= setting.maxSteps) {
956
+ return stopRunByExceededMaxSteps(setting, checkpoint, {
957
+ checkpoint: {
958
+ ...checkpoint,
959
+ status: "stoppedByExceededMaxSteps"
960
+ },
961
+ step: {
962
+ ...step,
963
+ finishedAt: Date.now()
964
+ }
965
+ });
966
+ }
967
+ return continueToNextStep(setting, checkpoint, {
968
+ checkpoint: {
969
+ ...checkpoint
970
+ },
971
+ step: {
972
+ ...step,
973
+ finishedAt: Date.now()
974
+ },
975
+ nextCheckpoint: {
976
+ ...checkpoint,
977
+ id: createId(),
978
+ stepNumber: checkpoint.stepNumber + 1,
979
+ // Clear tool handling state for next step
980
+ pendingToolCalls: void 0,
981
+ partialToolResults: void 0
982
+ }
983
+ });
984
+ }
938
985
  async function generatingRunResultLogic({
939
986
  setting,
940
987
  checkpoint,
@@ -962,20 +1009,27 @@ async function generatingRunResultLogic({
962
1009
  let reasoningCompletedViaCallback = false;
963
1010
  const callbacks = {
964
1011
  onReasoningStart: () => {
965
- eventListener(createRuntimeEvent("startReasoning", setting.jobId, setting.runId, {}));
1012
+ eventListener(createStreamingEvent("startStreamingReasoning", setting, checkpoint, {}));
966
1013
  },
967
1014
  onReasoningDelta: (delta) => {
968
- eventListener(createRuntimeEvent("streamReasoning", setting.jobId, setting.runId, { delta }));
1015
+ eventListener(createStreamingEvent("streamReasoning", setting, checkpoint, { delta }));
969
1016
  },
970
1017
  onReasoningComplete: (text2) => {
971
- eventListener(createRuntimeEvent("completeReasoning", setting.jobId, setting.runId, { text: text2 }));
1018
+ eventListener(
1019
+ createStreamingEvent("completeStreamingReasoning", setting, checkpoint, { text: text2 })
1020
+ );
972
1021
  reasoningCompletedViaCallback = true;
973
1022
  },
974
1023
  onResultStart: () => {
975
- eventListener(createRuntimeEvent("startRunResult", setting.jobId, setting.runId, {}));
1024
+ eventListener(createStreamingEvent("startStreamingRunResult", setting, checkpoint, {}));
976
1025
  },
977
1026
  onResultDelta: (delta) => {
978
- eventListener(createRuntimeEvent("streamRunResult", setting.jobId, setting.runId, { delta }));
1027
+ eventListener(createStreamingEvent("streamRunResult", setting, checkpoint, { delta }));
1028
+ },
1029
+ onResultComplete: (text2) => {
1030
+ eventListener(
1031
+ createStreamingEvent("completeStreamingRunResult", setting, checkpoint, { text: text2 })
1032
+ );
979
1033
  }
980
1034
  };
981
1035
  const executionResult = await llmExecutor.streamText(
@@ -1029,7 +1083,7 @@ async function generatingRunResultLogic({
1029
1083
  const newMessages = [toolMessage, createExpertMessage(expertContents)];
1030
1084
  if (thinkingText && !reasoningCompletedViaCallback) {
1031
1085
  await eventListener(
1032
- createRuntimeEvent("completeReasoning", setting.jobId, setting.runId, {
1086
+ createStreamingEvent("completeStreamingReasoning", setting, checkpoint, {
1033
1087
  text: thinkingText
1034
1088
  })
1035
1089
  );
@@ -1041,7 +1095,10 @@ async function generatingRunResultLogic({
1041
1095
  messages: [...messages, ...newMessages],
1042
1096
  usage: newUsage,
1043
1097
  contextWindowUsage: checkpoint.contextWindow ? calculateContextWindowUsage(newUsage, checkpoint.contextWindow) : void 0,
1044
- status: "completed"
1098
+ status: "completed",
1099
+ // Clear tool handling state on completion
1100
+ pendingToolCalls: void 0,
1101
+ partialToolResults: void 0
1045
1102
  },
1046
1103
  step: {
1047
1104
  ...step,
@@ -1100,13 +1157,15 @@ async function generatingToolCallLogic({
1100
1157
  let reasoningCompletedViaCallback = false;
1101
1158
  const callbacks = {
1102
1159
  onReasoningStart: () => {
1103
- eventListener(createRuntimeEvent("startReasoning", setting.jobId, setting.runId, {}));
1160
+ eventListener(createStreamingEvent("startStreamingReasoning", setting, checkpoint, {}));
1104
1161
  },
1105
1162
  onReasoningDelta: (delta) => {
1106
- eventListener(createRuntimeEvent("streamReasoning", setting.jobId, setting.runId, { delta }));
1163
+ eventListener(createStreamingEvent("streamReasoning", setting, checkpoint, { delta }));
1107
1164
  },
1108
1165
  onReasoningComplete: (text2) => {
1109
- eventListener(createRuntimeEvent("completeReasoning", setting.jobId, setting.runId, { text: text2 }));
1166
+ eventListener(
1167
+ createStreamingEvent("completeStreamingReasoning", setting, checkpoint, { text: text2 })
1168
+ );
1110
1169
  reasoningCompletedViaCallback = true;
1111
1170
  }
1112
1171
  // onResultStart and onResultDelta intentionally not set - result streaming only in GeneratingRunResult
@@ -1161,7 +1220,7 @@ async function generatingToolCallLogic({
1161
1220
  const newUsage = sumUsage(checkpoint.usage, usage);
1162
1221
  if (thinkingText && !reasoningCompletedViaCallback) {
1163
1222
  await eventListener(
1164
- createRuntimeEvent("completeReasoning", setting.jobId, setting.runId, {
1223
+ createStreamingEvent("completeStreamingReasoning", setting, checkpoint, {
1165
1224
  text: thinkingText
1166
1225
  })
1167
1226
  );
@@ -1172,7 +1231,10 @@ async function generatingToolCallLogic({
1172
1231
  messages: [...messages, newMessage],
1173
1232
  usage: newUsage,
1174
1233
  contextWindowUsage: checkpoint.contextWindow ? calculateContextWindowUsage(newUsage, checkpoint.contextWindow) : void 0,
1175
- status: "completed"
1234
+ status: "completed",
1235
+ // Clear tool handling state on completion
1236
+ pendingToolCalls: void 0,
1237
+ partialToolResults: void 0
1176
1238
  },
1177
1239
  step: {
1178
1240
  ...step,
@@ -1221,7 +1283,7 @@ async function generatingToolCallLogic({
1221
1283
  const allToolCalls = buildToolCalls(sorted);
1222
1284
  if (thinkingText && !reasoningCompletedViaCallback) {
1223
1285
  await eventListener(
1224
- createRuntimeEvent("completeReasoning", setting.jobId, setting.runId, {
1286
+ createStreamingEvent("completeStreamingReasoning", setting, checkpoint, {
1225
1287
  text: thinkingText
1226
1288
  })
1227
1289
  );
@@ -1313,8 +1375,8 @@ function getMetaInstruction(startedAt) {
1313
1375
  2. Select Tools: Choose the next tool call based on current state, task planning, relevant knowledge, and available data APIs
1314
1376
  3. Wait for Execution: The selected tool action will be executed by the sandbox environment with new observations added to the event stream
1315
1377
  4. Iterate: Choose only one tool call per iteration, patiently repeat the above steps until task completion
1316
- 5. Notify Task Completion: Call the attemptCompletion tool to inform the user when the task is complete
1317
- 6. Generate Final Results: Produce a final result that clearly describes each task you performed, step by step
1378
+ 5. Notify Task Completion: Call attemptCompletion ONLY - do NOT include any text response with this tool call
1379
+ 6. Generate Final Results: AFTER attemptCompletion returns, you will be prompted to produce a final result in a SEPARATE response
1318
1380
 
1319
1381
  Conditions for ending the agent loop:
1320
1382
  If any of the following apply, **immediately call the attemptCompletion tool**.
@@ -1436,11 +1498,10 @@ async function initLogic({
1436
1498
  const updatedCheckpoint = {
1437
1499
  ...checkpoint,
1438
1500
  partialToolResults: updatedPartialResults,
1439
- pendingToolCalls: updatedPendingToolCalls.length > 0 ? updatedPendingToolCalls : void 0
1501
+ pendingToolCalls: updatedPendingToolCalls
1440
1502
  };
1441
- return startRun(setting, updatedCheckpoint, {
1442
- initialCheckpoint: updatedCheckpoint,
1443
- inputMessages: []
1503
+ return resumeFromStop(setting, checkpoint, {
1504
+ checkpoint: updatedCheckpoint
1444
1505
  });
1445
1506
  }
1446
1507
  default:
@@ -1457,25 +1518,6 @@ async function preparingForStepLogic({
1457
1518
  setting,
1458
1519
  checkpoint
1459
1520
  }) {
1460
- if (checkpoint.pendingToolCalls && checkpoint.pendingToolCalls.length > 0) {
1461
- return resumeToolCalls(setting, checkpoint, {
1462
- pendingToolCalls: checkpoint.pendingToolCalls,
1463
- partialToolResults: checkpoint.partialToolResults ?? []
1464
- });
1465
- }
1466
- if (checkpoint.partialToolResults && checkpoint.partialToolResults.length > 0) {
1467
- const toolResultParts = checkpoint.partialToolResults.map((tr) => ({
1468
- type: "toolResultPart",
1469
- toolCallId: tr.id,
1470
- toolName: tr.toolName,
1471
- contents: tr.result.filter(
1472
- (part) => part.type === "textPart" || part.type === "imageInlinePart" || part.type === "fileInlinePart"
1473
- )
1474
- }));
1475
- return finishAllToolCalls(setting, checkpoint, {
1476
- newMessages: [createToolMessage(toolResultParts)]
1477
- });
1478
- }
1479
1521
  return startGeneration(setting, checkpoint, {
1480
1522
  messages: checkpoint.messages
1481
1523
  });
@@ -1485,10 +1527,11 @@ async function resolvingToolResultLogic({
1485
1527
  checkpoint,
1486
1528
  step
1487
1529
  }) {
1488
- if (!step.toolCalls || !step.toolResults || step.toolResults.length === 0) {
1489
- throw new Error("No tool calls or tool results found");
1530
+ if (step.toolResults === void 0 || step.toolResults.length === 0) {
1531
+ throw new Error("ResolvingToolResult: toolResults is undefined or empty (invariant violation)");
1490
1532
  }
1491
- const toolResultParts = step.toolResults.map((toolResult) => {
1533
+ const toolResults = step.toolResults;
1534
+ const toolResultParts = toolResults.map((toolResult) => {
1492
1535
  const toolCall = step.toolCalls?.find((tc) => tc.id === toolResult.id);
1493
1536
  return {
1494
1537
  type: "toolResultPart",
@@ -1503,6 +1546,23 @@ async function resolvingToolResultLogic({
1503
1546
  newMessages: [createToolMessage(toolResultParts)]
1504
1547
  });
1505
1548
  }
1549
+ async function resumingFromStopLogic({
1550
+ setting,
1551
+ checkpoint
1552
+ }) {
1553
+ if (checkpoint.pendingToolCalls === void 0 || checkpoint.partialToolResults === void 0) {
1554
+ throw new Error("ResumingFromStop: tool handling state is undefined (invariant violation)");
1555
+ }
1556
+ if (checkpoint.pendingToolCalls.length > 0) {
1557
+ return proceedToInteractiveTools(setting, checkpoint, {
1558
+ pendingToolCalls: checkpoint.pendingToolCalls,
1559
+ partialToolResults: checkpoint.partialToolResults
1560
+ });
1561
+ }
1562
+ return resolveToolResults(setting, checkpoint, {
1563
+ toolResults: checkpoint.partialToolResults
1564
+ });
1565
+ }
1506
1566
 
1507
1567
  // src/state-machine/machine.ts
1508
1568
  var runtimeStateMachine = setup({
@@ -1512,7 +1572,7 @@ var runtimeStateMachine = setup({
1512
1572
  events: {}
1513
1573
  }
1514
1574
  }).createMachine({
1515
- /** @xstate-layout N4IgpgJg5mDOIC5QCUCuA7AdASXQSwBcBiWAgQwCcC10BtABgF1FQAHAe1kL3fRZAAeiAKz0AzJgDsAJgAsksZNlixs+gDZZAGhABPRIszCAjGIAcY4crPHhJyQF8HOmpgAKFMK0p50UAGLsFADKBF4k5FQA4mDoYBRkBDx0TPwcXEm8-EIIZmaymPRK8saSopL00tI6+gjq9JjSltLG9HnqZkqdTi4YmDFxCUl+ACrs7AA2AMJkExNEngQUugzMSCDp3FnrOcam0pgAnHbS9GeSZsIq6jWIh2KHUsYd9MbSwl2S6j0grgPxiV8UDGkxmcyIAGNZhMQRNVmlOFs+DtEPt1Jg3odpGVbFcrLcENIzOjbGYipIZMpnmYfn9YgDhsDxtNoZDobgwgkIUkAG5gWHw9abTLI0C7ImSTDqYTY2S45TCCwE54HUr1WRXSqHcRVWl9f5DIGwsHzKFzAAiYAmYCgiTAgrYiJF2VRYnoj1ehwskkOZTEz2EBMMJnMFnezxUF2+zl+fRNRuZCzgkz5sOQcFQEwID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fCHDAp+FKuNKBPNCSlgaOIeQttWxS0DO1bKdY9HvH9D+FotMcFFXwVAEaaFyrqLirbBo1M7KvFUDJCiRJGgalUM3LEMk5R30GEdKAJ0MxZicWQlQEklAyillWVoZgUF1isG0MoDEsF0yBnYkGyNeQa0mNE3CtgiIYnEEBToFwvS+mVPkU20l8JWG1OIHJsE/AcyZmAEpNlbBqEwLo7yVRbY3HatPfCXUOgfCsGSTQmk+hyymorbevSloykeFYCkrxfqrmJiIaRRQ7JbP8Q8PyoQYasEgGsxA2JWiNB/jjdQTRqb1IkP6OwRF8KMSAbnBwQA */
1516
1576
  id: "Run",
1517
1577
  initial: "Init",
1518
1578
  context: ({ input }) => ({
@@ -1538,15 +1598,22 @@ var runtimeStateMachine = setup({
1538
1598
  checkpoint: ({ context, event }) => ({
1539
1599
  ...context.checkpoint,
1540
1600
  status: "proceeding",
1541
- messages: [...context.checkpoint.messages, ...event.inputMessages],
1542
- pendingToolCalls: event.initialCheckpoint.pendingToolCalls,
1543
- partialToolResults: event.initialCheckpoint.partialToolResults
1601
+ messages: [...context.checkpoint.messages, ...event.inputMessages]
1544
1602
  }),
1545
1603
  step: ({ context, event }) => ({
1546
1604
  ...context.step,
1547
1605
  inputMessages: event.inputMessages
1548
1606
  })
1549
1607
  })
1608
+ },
1609
+ resumeFromStop: {
1610
+ target: "ResumingFromStop",
1611
+ actions: assign({
1612
+ checkpoint: ({ event }) => ({
1613
+ ...event.checkpoint,
1614
+ status: "proceeding"
1615
+ })
1616
+ })
1550
1617
  }
1551
1618
  }
1552
1619
  },
@@ -1563,36 +1630,45 @@ var runtimeStateMachine = setup({
1563
1630
  startedAt: event.timestamp
1564
1631
  })
1565
1632
  })
1566
- },
1567
- resumeToolCalls: {
1568
- target: "CallingTool",
1633
+ }
1634
+ }
1635
+ },
1636
+ ResumingFromStop: {
1637
+ on: {
1638
+ proceedToInteractiveTools: {
1639
+ target: "CallingInteractiveTools",
1569
1640
  actions: assign({
1570
1641
  step: ({ context, event }) => ({
1571
1642
  stepNumber: context.checkpoint.stepNumber,
1572
- inputMessages: context.step.inputMessages ?? [],
1573
- newMessages: context.step.newMessages,
1574
- toolCalls: context.step.toolCalls,
1575
- toolResults: event.partialToolResults,
1643
+ inputMessages: [],
1644
+ newMessages: [],
1645
+ toolCalls: context.checkpoint.pendingToolCalls ?? [],
1646
+ toolResults: [],
1576
1647
  pendingToolCalls: event.pendingToolCalls,
1577
- usage: context.step.usage,
1578
- startedAt: context.step.startedAt
1648
+ partialToolResults: event.partialToolResults,
1649
+ usage: createEmptyUsage(),
1650
+ startedAt: Date.now()
1579
1651
  })
1580
1652
  })
1581
1653
  },
1582
- finishAllToolCalls: {
1583
- target: "FinishingStep",
1654
+ resolveToolResults: {
1655
+ target: "ResolvingToolResult",
1584
1656
  actions: assign({
1585
- checkpoint: ({ context, event }) => ({
1657
+ checkpoint: ({ context }) => ({
1586
1658
  ...context.checkpoint,
1587
- messages: [...context.checkpoint.messages, ...event.newMessages],
1588
1659
  pendingToolCalls: void 0,
1589
1660
  partialToolResults: void 0
1590
1661
  }),
1591
1662
  step: ({ context, event }) => ({
1592
- ...context.step,
1593
- newMessages: [...context.step.newMessages, ...event.newMessages],
1594
- toolResults: context.checkpoint.partialToolResults,
1595
- pendingToolCalls: void 0
1663
+ stepNumber: context.checkpoint.stepNumber,
1664
+ inputMessages: [],
1665
+ newMessages: [],
1666
+ toolCalls: [],
1667
+ toolResults: event.toolResults,
1668
+ pendingToolCalls: void 0,
1669
+ partialToolResults: void 0,
1670
+ usage: createEmptyUsage(),
1671
+ startedAt: Date.now()
1596
1672
  })
1597
1673
  })
1598
1674
  }
@@ -1642,50 +1718,7 @@ var runtimeStateMachine = setup({
1642
1718
  })
1643
1719
  },
1644
1720
  callTools: {
1645
- target: "CallingTool",
1646
- actions: assign({
1647
- checkpoint: ({ context, event }) => {
1648
- const newUsage = sumUsage(context.checkpoint.usage, event.usage);
1649
- return {
1650
- ...context.checkpoint,
1651
- messages: [...context.checkpoint.messages, event.newMessage],
1652
- usage: newUsage,
1653
- contextWindowUsage: context.checkpoint.contextWindow ? calculateContextWindowUsage(newUsage, context.checkpoint.contextWindow) : void 0,
1654
- retryCount: 0
1655
- };
1656
- },
1657
- step: ({ context, event }) => ({
1658
- ...context.step,
1659
- newMessages: [event.newMessage],
1660
- toolCalls: event.toolCalls,
1661
- usage: sumUsage(context.step.usage, event.usage)
1662
- })
1663
- })
1664
- },
1665
- callInteractiveTool: {
1666
- target: "CallingInteractiveTool",
1667
- actions: assign({
1668
- checkpoint: ({ context, event }) => {
1669
- const newUsage = sumUsage(context.checkpoint.usage, event.usage);
1670
- return {
1671
- ...context.checkpoint,
1672
- messages: [...context.checkpoint.messages, event.newMessage],
1673
- usage: newUsage,
1674
- contextWindowUsage: context.checkpoint.contextWindow ? calculateContextWindowUsage(newUsage, context.checkpoint.contextWindow) : void 0,
1675
- retryCount: 0
1676
- // Reset on successful generation
1677
- };
1678
- },
1679
- step: ({ context, event }) => ({
1680
- ...context.step,
1681
- newMessages: [event.newMessage],
1682
- toolCalls: [event.toolCall],
1683
- usage: sumUsage(context.step.usage, event.usage)
1684
- })
1685
- })
1686
- },
1687
- callDelegate: {
1688
- target: "CallingDelegate",
1721
+ target: "CallingMcpTools",
1689
1722
  actions: assign({
1690
1723
  checkpoint: ({ context, event }) => {
1691
1724
  const newUsage = sumUsage(context.checkpoint.usage, event.usage);
@@ -1695,20 +1728,22 @@ var runtimeStateMachine = setup({
1695
1728
  usage: newUsage,
1696
1729
  contextWindowUsage: context.checkpoint.contextWindow ? calculateContextWindowUsage(newUsage, context.checkpoint.contextWindow) : void 0,
1697
1730
  retryCount: 0
1698
- // Reset on successful generation
1699
1731
  };
1700
1732
  },
1701
1733
  step: ({ context, event }) => ({
1702
1734
  ...context.step,
1703
1735
  newMessages: [event.newMessage],
1704
1736
  toolCalls: event.toolCalls,
1705
- usage: sumUsage(context.step.usage, event.usage)
1737
+ usage: sumUsage(context.step.usage, event.usage),
1738
+ // Initialize tool handling state
1739
+ pendingToolCalls: event.toolCalls,
1740
+ partialToolResults: []
1706
1741
  })
1707
1742
  })
1708
1743
  }
1709
1744
  }
1710
1745
  },
1711
- CallingTool: {
1746
+ CallingMcpTools: {
1712
1747
  on: {
1713
1748
  resolveToolResults: {
1714
1749
  target: "ResolvingToolResult",
@@ -1729,27 +1764,65 @@ var runtimeStateMachine = setup({
1729
1764
  })
1730
1765
  })
1731
1766
  },
1732
- callDelegate: {
1733
- target: "CallingDelegate",
1767
+ finishMcpTools: {
1768
+ target: "CallingDelegates",
1734
1769
  actions: assign({
1735
- step: ({ context }) => ({
1770
+ step: ({ context, event }) => ({
1736
1771
  ...context.step,
1737
- toolCalls: context.step.toolCalls,
1738
- toolResults: context.step.toolResults,
1739
- pendingToolCalls: context.step.pendingToolCalls,
1740
- partialToolResults: context.step.partialToolResults
1772
+ partialToolResults: event.partialToolResults,
1773
+ pendingToolCalls: event.pendingToolCalls
1774
+ })
1775
+ })
1776
+ },
1777
+ completeRun: {
1778
+ target: "Stopped",
1779
+ actions: assign({
1780
+ checkpoint: ({ event }) => ({ ...event.checkpoint, retryCount: 0 }),
1781
+ step: ({ event }) => ({
1782
+ ...event.step,
1783
+ inputMessages: void 0
1784
+ })
1785
+ })
1786
+ }
1787
+ }
1788
+ },
1789
+ CallingDelegates: {
1790
+ on: {
1791
+ stopRunByDelegate: {
1792
+ target: "Stopped",
1793
+ actions: assign({
1794
+ checkpoint: ({ event }) => event.checkpoint,
1795
+ step: ({ event }) => ({
1796
+ ...event.step,
1797
+ inputMessages: void 0
1798
+ })
1799
+ })
1800
+ },
1801
+ skipDelegates: {
1802
+ target: "CallingInteractiveTools"
1803
+ }
1804
+ }
1805
+ },
1806
+ CallingInteractiveTools: {
1807
+ on: {
1808
+ stopRunByInteractiveTool: {
1809
+ target: "Stopped",
1810
+ actions: assign({
1811
+ checkpoint: ({ event }) => event.checkpoint,
1812
+ step: ({ event }) => ({
1813
+ ...event.step,
1814
+ inputMessages: void 0
1741
1815
  })
1742
1816
  })
1743
1817
  },
1744
- callInteractiveTool: {
1745
- target: "CallingInteractiveTool",
1818
+ resolveToolResults: {
1819
+ target: "ResolvingToolResult",
1746
1820
  actions: assign({
1747
- step: ({ context }) => ({
1821
+ step: ({ context, event }) => ({
1748
1822
  ...context.step,
1749
- toolCalls: context.step.toolCalls,
1750
- toolResults: context.step.toolResults,
1751
- pendingToolCalls: context.step.pendingToolCalls,
1752
- partialToolResults: context.step.partialToolResults
1823
+ toolResults: event.toolResults,
1824
+ pendingToolCalls: void 0,
1825
+ partialToolResults: void 0
1753
1826
  })
1754
1827
  })
1755
1828
  }
@@ -1817,34 +1890,6 @@ var runtimeStateMachine = setup({
1817
1890
  }
1818
1891
  }
1819
1892
  },
1820
- CallingInteractiveTool: {
1821
- on: {
1822
- stopRunByInteractiveTool: {
1823
- target: "Stopped",
1824
- actions: assign({
1825
- checkpoint: ({ event }) => event.checkpoint,
1826
- step: ({ event }) => ({
1827
- ...event.step,
1828
- inputMessages: void 0
1829
- })
1830
- })
1831
- }
1832
- }
1833
- },
1834
- CallingDelegate: {
1835
- on: {
1836
- stopRunByDelegate: {
1837
- target: "Stopped",
1838
- actions: assign({
1839
- checkpoint: ({ event }) => event.checkpoint,
1840
- step: ({ event }) => ({
1841
- ...event.step,
1842
- inputMessages: void 0
1843
- })
1844
- })
1845
- }
1846
- }
1847
- },
1848
1893
  FinishingStep: {
1849
1894
  on: {
1850
1895
  continueToNextStep: {
@@ -1878,12 +1923,13 @@ var runtimeStateMachine = setup({
1878
1923
  var StateMachineLogics = {
1879
1924
  Init: initLogic,
1880
1925
  PreparingForStep: preparingForStepLogic,
1926
+ ResumingFromStop: resumingFromStopLogic,
1881
1927
  GeneratingToolCall: generatingToolCallLogic,
1882
- CallingTool: callingToolLogic,
1928
+ CallingMcpTools: callingMcpToolsLogic,
1929
+ CallingDelegates: callingDelegatesLogic,
1930
+ CallingInteractiveTools: callingInteractiveToolsLogic,
1883
1931
  ResolvingToolResult: resolvingToolResultLogic,
1884
1932
  GeneratingRunResult: generatingRunResultLogic,
1885
- CallingInteractiveTool: callingInteractiveToolLogic,
1886
- CallingDelegate: callingDelegateLogic,
1887
1933
  FinishingStep: finishingStepLogic
1888
1934
  };
1889
1935
  var DefaultActorFactory = class {
@@ -2002,15 +2048,17 @@ var SingleDelegationStrategy = class {
2002
2048
  }
2003
2049
  const delegation = delegations[0];
2004
2050
  const { expert, toolCallId, toolName, query } = delegation;
2051
+ const childRunId = createId();
2005
2052
  const nextSetting = {
2006
2053
  ...setting,
2054
+ runId: childRunId,
2007
2055
  expertKey: expert.key,
2008
2056
  input: { text: query }
2009
2057
  };
2010
2058
  const nextCheckpoint = {
2011
2059
  id: context.id,
2012
2060
  jobId: setting.jobId,
2013
- runId: setting.runId,
2061
+ runId: childRunId,
2014
2062
  status: "init",
2015
2063
  stepNumber: context.stepNumber,
2016
2064
  messages: [],
@@ -2028,7 +2076,9 @@ var SingleDelegationStrategy = class {
2028
2076
  },
2029
2077
  toolCallId,
2030
2078
  toolName,
2031
- checkpointId: context.id
2079
+ checkpointId: context.id,
2080
+ runId: setting.runId
2081
+ // Parent's runId for traceability
2032
2082
  },
2033
2083
  usage: context.usage,
2034
2084
  contextWindow: context.contextWindow,
@@ -2078,8 +2128,10 @@ var ParallelDelegationStrategy = class {
2078
2128
  const remainingPendingToolCalls = context.pendingToolCalls?.filter(
2079
2129
  (tc) => !processedToolCallIds.has(tc.id) && tc.id !== firstDelegation.toolCallId
2080
2130
  );
2131
+ const returnRunId = createId();
2081
2132
  const nextSetting = {
2082
2133
  ...setting,
2134
+ runId: returnRunId,
2083
2135
  expertKey: parentExpert.key,
2084
2136
  input: {
2085
2137
  interactiveToolCallResult: {
@@ -2093,7 +2145,7 @@ var ParallelDelegationStrategy = class {
2093
2145
  const nextCheckpoint = {
2094
2146
  id: context.id,
2095
2147
  jobId: setting.jobId,
2096
- runId: setting.runId,
2148
+ runId: returnRunId,
2097
2149
  status: "stoppedByDelegate",
2098
2150
  stepNumber: maxStepNumber,
2099
2151
  messages: context.messages,
@@ -2143,7 +2195,8 @@ var ParallelDelegationStrategy = class {
2143
2195
  },
2144
2196
  toolCallId,
2145
2197
  toolName,
2146
- checkpointId: parentContext.id
2198
+ checkpointId: parentContext.id,
2199
+ runId: parentSetting.runId
2147
2200
  },
2148
2201
  usage: createEmptyUsage(),
2149
2202
  contextWindow: parentContext.contextWindow
@@ -2390,10 +2443,14 @@ function convertSkill(skill) {
2390
2443
  };
2391
2444
  }
2392
2445
  try {
2446
+ const parsed = JSON.parse(skill.definition);
2447
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
2448
+ throw new Error("Definition must be a JSON object");
2449
+ }
2393
2450
  return {
2394
2451
  type: "custom",
2395
2452
  name: skill.name,
2396
- mcp_config: JSON.parse(skill.definition)
2453
+ mcp_config: parsed
2397
2454
  };
2398
2455
  } catch (error) {
2399
2456
  throw new Error(
@@ -2552,10 +2609,9 @@ function buildAzureOpenAITools(client, toolNames, options) {
2552
2609
  case "fileSearch": {
2553
2610
  const vectorStoreIds = options?.fileSearch?.vectorStoreIds;
2554
2611
  if (!vectorStoreIds || vectorStoreIds.length === 0) {
2555
- console.warn(
2612
+ throw new Error(
2556
2613
  "Azure OpenAI fileSearch tool requires vectorStoreIds. Set providerToolOptions.fileSearch.vectorStoreIds to use this tool."
2557
2614
  );
2558
- break;
2559
2615
  }
2560
2616
  const fileSearchTool = client.tools.fileSearch({
2561
2617
  vectorStoreIds,
@@ -2867,10 +2923,9 @@ function buildGoogleTools(client, toolNames, options) {
2867
2923
  case "fileSearch": {
2868
2924
  const storeNames = options?.fileSearch?.vectorStoreIds;
2869
2925
  if (!storeNames || storeNames.length === 0) {
2870
- console.warn(
2926
+ throw new Error(
2871
2927
  "Google fileSearch tool requires fileSearchStoreNames. Set providerToolOptions.fileSearch.vectorStoreIds to use this tool."
2872
2928
  );
2873
- break;
2874
2929
  }
2875
2930
  const fileSearchTool = client.tools.fileSearch({
2876
2931
  fileSearchStoreNames: storeNames,
@@ -3088,10 +3143,9 @@ function buildOpenAITools(client, toolNames, options) {
3088
3143
  case "fileSearch": {
3089
3144
  const vectorStoreIds = options?.fileSearch?.vectorStoreIds;
3090
3145
  if (!vectorStoreIds || vectorStoreIds.length === 0) {
3091
- console.warn(
3146
+ throw new Error(
3092
3147
  "OpenAI fileSearch tool requires vectorStoreIds. Set providerToolOptions.fileSearch.vectorStoreIds to use this tool."
3093
3148
  );
3094
- break;
3095
3149
  }
3096
3150
  const fileSearchTool = client.tools.fileSearch({
3097
3151
  vectorStoreIds,
@@ -3462,6 +3516,9 @@ var LLMExecutor = class {
3462
3516
  const usage = await streamResult.usage;
3463
3517
  const reasoning = await streamResult.reasoning;
3464
3518
  const response = await streamResult.response;
3519
+ if (resultStarted) {
3520
+ callbacks.onResultComplete?.(text);
3521
+ }
3465
3522
  const result = {
3466
3523
  text,
3467
3524
  toolCalls,
@@ -3665,5 +3722,5 @@ async function run(runInput, options) {
3665
3722
  }
3666
3723
 
3667
3724
  export { findLockfile, getLockfileExpertToolDefinitions, getModel, loadLockfile, package_default, run, runtimeStateMachine };
3668
- //# sourceMappingURL=chunk-ITK5SV5X.js.map
3669
- //# sourceMappingURL=chunk-ITK5SV5X.js.map
3725
+ //# sourceMappingURL=chunk-J26GYDJQ.js.map
3726
+ //# sourceMappingURL=chunk-J26GYDJQ.js.map