@standardagents/builder 0.13.1 → 0.14.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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ProviderError, mapReasoningLevel, defineTool } from '@standardagents/spec';
2
2
  export { ProviderError, belongsToPackage, defineAgent, defineHook, defineModel, definePrompt, defineTool, isPacked, isVisibleInNamespace, mapReasoningLevel } from '@standardagents/spec';
3
3
  import { z } from 'zod';
4
- import { sip } from '@standardagents/sip';
4
+ import { transform, collect } from '@standardagents/sip';
5
5
  import * as fs4 from 'fs';
6
6
  import fs4__default from 'fs';
7
7
  import * as path8 from 'path';
@@ -193,6 +193,274 @@ var init_StreamManager = __esm({
193
193
  };
194
194
  }
195
195
  });
196
+
197
+ // src/agents/pricing.ts
198
+ function getGoogleFallbackPricing(modelId) {
199
+ const normalized = normalizeGoogleModelId(modelId);
200
+ const exact = GOOGLE_MODEL_PRICING[normalized];
201
+ if (exact) return { ...exact, source: "google-static" };
202
+ const prefixMatch = GOOGLE_MODEL_PRICING_PREFIXES.find((entry) => normalized.startsWith(entry.prefix));
203
+ if (prefixMatch) return { ...prefixMatch.pricing, source: "google-static" };
204
+ return null;
205
+ }
206
+ function getGroqFallbackPricing(modelId) {
207
+ const pricing = GROQ_MODEL_PRICING[normalizeModelId(modelId)];
208
+ return pricing ? { ...pricing, source: "groq-static" } : null;
209
+ }
210
+ function getXAIFallbackPricing(modelId) {
211
+ const pricing = XAI_MODEL_PRICING[normalizeModelId(modelId)];
212
+ return pricing ? { ...pricing, source: "xai-static" } : null;
213
+ }
214
+ function normalizeModelId(modelId) {
215
+ return (modelId || "").trim().toLowerCase();
216
+ }
217
+ function normalizeGoogleModelId(modelId) {
218
+ return normalizeModelId(modelId).replace(/^google\//, "").replace(/^models\//, "").replace(/^publishers\/google\/models\//, "");
219
+ }
220
+ function roundCost(value) {
221
+ return Number(value.toFixed(12));
222
+ }
223
+ function getCerebrasFallbackPricing(modelId) {
224
+ const pricing = CEREBRAS_MODEL_PRICING[normalizeModelId(modelId)];
225
+ return pricing ? { ...pricing, source: "cerebras-static" } : null;
226
+ }
227
+ function resolveModelPricing(modelDef, providerName) {
228
+ if (typeof modelDef.inputPrice === "number" && typeof modelDef.outputPrice === "number") {
229
+ return {
230
+ inputPrice: modelDef.inputPrice,
231
+ outputPrice: modelDef.outputPrice,
232
+ cachedPrice: modelDef.cachedPrice,
233
+ source: "model"
234
+ };
235
+ }
236
+ if (providerName === "cerebras") {
237
+ return getCerebrasFallbackPricing(modelDef.model);
238
+ }
239
+ if (providerName === "google") {
240
+ return getGoogleFallbackPricing(modelDef.model);
241
+ }
242
+ if (providerName === "groq") {
243
+ return getGroqFallbackPricing(modelDef.model);
244
+ }
245
+ if (providerName === "xai") {
246
+ return getXAIFallbackPricing(modelDef.model);
247
+ }
248
+ return null;
249
+ }
250
+ function calculateUsageCost(usage, pricing) {
251
+ if (!pricing) {
252
+ return null;
253
+ }
254
+ const cachedTokens = Math.max(usage.prompt_tokens_details?.cached_tokens || 0, 0);
255
+ const promptTokens = Math.max(usage.prompt_tokens || 0, 0);
256
+ const completionTokens = Math.max(usage.completion_tokens || 0, 0);
257
+ const reasoningTokens = pricing.source === "google-static" ? Math.max(usage.completion_tokens_details?.reasoning_tokens || 0, 0) : 0;
258
+ const billableOutputTokens = completionTokens + reasoningTokens;
259
+ const uncachedPromptTokens = Math.max(promptTokens - cachedTokens, 0);
260
+ const cachedTokenPrice = pricing.cachedPrice ?? pricing.inputPrice;
261
+ const costInput = roundCost(
262
+ (uncachedPromptTokens * pricing.inputPrice + cachedTokens * cachedTokenPrice) / TOKENS_PER_MILLION
263
+ );
264
+ const costOutput = roundCost(billableOutputTokens * pricing.outputPrice / TOKENS_PER_MILLION);
265
+ return {
266
+ costInput,
267
+ costOutput,
268
+ costTotal: roundCost(costInput + costOutput)
269
+ };
270
+ }
271
+ var TOKENS_PER_MILLION, CEREBRAS_MODEL_PRICING, GOOGLE_MODEL_PRICING, GOOGLE_MODEL_PRICING_PREFIXES, GROQ_MODEL_PRICING, XAI_MODEL_PRICING;
272
+ var init_pricing = __esm({
273
+ "src/agents/pricing.ts"() {
274
+ TOKENS_PER_MILLION = 1e6;
275
+ CEREBRAS_MODEL_PRICING = {
276
+ "zai-glm-4.7": {
277
+ inputPrice: 2.25,
278
+ outputPrice: 2.75
279
+ },
280
+ "gpt-oss-120b": {
281
+ inputPrice: 0.35,
282
+ outputPrice: 0.75
283
+ },
284
+ "llama3.1-8b": {
285
+ inputPrice: 0.1,
286
+ outputPrice: 0.1
287
+ },
288
+ "qwen-3-235b-a22b-instruct-2507": {
289
+ inputPrice: 0.6,
290
+ outputPrice: 1.2
291
+ }
292
+ };
293
+ GOOGLE_MODEL_PRICING = {
294
+ "gemini-3-pro-preview": {
295
+ inputPrice: 2,
296
+ outputPrice: 12,
297
+ cachedPrice: 0.2
298
+ },
299
+ "gemini-3.1-pro-preview": {
300
+ inputPrice: 2,
301
+ outputPrice: 12,
302
+ cachedPrice: 0.2
303
+ },
304
+ "gemini-2.5-pro": {
305
+ inputPrice: 1.25,
306
+ outputPrice: 10,
307
+ cachedPrice: 0.125
308
+ },
309
+ "gemini-2.5-flash": {
310
+ inputPrice: 0.3,
311
+ outputPrice: 2.5,
312
+ cachedPrice: 0.03
313
+ },
314
+ "gemini-2.5-flash-lite": {
315
+ inputPrice: 0.1,
316
+ outputPrice: 0.4,
317
+ cachedPrice: 0.01
318
+ },
319
+ "gemini-3-flash-preview": {
320
+ inputPrice: 0.5,
321
+ outputPrice: 3,
322
+ cachedPrice: 0.05
323
+ },
324
+ "gemini-3.1-flash-lite-preview": {
325
+ inputPrice: 0.25,
326
+ outputPrice: 1.5,
327
+ cachedPrice: 0.025
328
+ },
329
+ "deep-research-pro-preview-12-2025": {
330
+ inputPrice: 2,
331
+ outputPrice: 12,
332
+ cachedPrice: 0.2
333
+ },
334
+ "gemini-2.0-flash": {
335
+ inputPrice: 0.1,
336
+ outputPrice: 0.4,
337
+ cachedPrice: 0.025
338
+ },
339
+ "gemini-2.0-flash-001": {
340
+ inputPrice: 0.1,
341
+ outputPrice: 0.4,
342
+ cachedPrice: 0.025
343
+ },
344
+ "gemini-2.0-flash-lite": {
345
+ inputPrice: 0.075,
346
+ outputPrice: 0.3
347
+ },
348
+ "gemini-2.0-flash-lite-001": {
349
+ inputPrice: 0.075,
350
+ outputPrice: 0.3
351
+ },
352
+ "gemini-2.5-computer-use-preview-10-2025": {
353
+ inputPrice: 1.25,
354
+ outputPrice: 10
355
+ },
356
+ "gemini-2.5-flash-image": {
357
+ inputPrice: 0.3,
358
+ outputPrice: 0
359
+ },
360
+ "gemini-3.1-flash-image-preview": {
361
+ inputPrice: 0.5,
362
+ outputPrice: 3
363
+ },
364
+ "gemini-3-pro-image-preview": {
365
+ inputPrice: 2,
366
+ outputPrice: 0
367
+ },
368
+ "nano-banana-pro-preview": {
369
+ inputPrice: 2,
370
+ outputPrice: 0
371
+ },
372
+ "gemma-4-31b-it": {
373
+ inputPrice: 0,
374
+ outputPrice: 0,
375
+ cachedPrice: 0
376
+ }
377
+ };
378
+ GOOGLE_MODEL_PRICING_PREFIXES = [
379
+ {
380
+ prefix: "gemini-3.1-pro-preview",
381
+ pricing: GOOGLE_MODEL_PRICING["gemini-3.1-pro-preview"]
382
+ },
383
+ {
384
+ prefix: "gemini-3-pro-preview",
385
+ pricing: GOOGLE_MODEL_PRICING["gemini-3-pro-preview"]
386
+ },
387
+ {
388
+ prefix: "gemini-3-flash-preview",
389
+ pricing: GOOGLE_MODEL_PRICING["gemini-3-flash-preview"]
390
+ },
391
+ {
392
+ prefix: "gemini-3.1-flash-lite-preview",
393
+ pricing: GOOGLE_MODEL_PRICING["gemini-3.1-flash-lite-preview"]
394
+ },
395
+ {
396
+ prefix: "gemini-2.5-flash-lite-preview-",
397
+ pricing: GOOGLE_MODEL_PRICING["gemini-2.5-flash-lite"]
398
+ },
399
+ {
400
+ prefix: "gemini-flash-latest",
401
+ pricing: GOOGLE_MODEL_PRICING["gemini-2.5-flash"]
402
+ },
403
+ {
404
+ prefix: "gemini-flash-lite-latest",
405
+ pricing: GOOGLE_MODEL_PRICING["gemini-2.5-flash-lite"]
406
+ },
407
+ {
408
+ prefix: "gemini-pro-latest",
409
+ pricing: GOOGLE_MODEL_PRICING["gemini-2.5-pro"]
410
+ },
411
+ {
412
+ prefix: "gemma-4-",
413
+ pricing: {
414
+ inputPrice: 0,
415
+ outputPrice: 0,
416
+ cachedPrice: 0
417
+ }
418
+ },
419
+ {
420
+ prefix: "gemma-3-",
421
+ pricing: {
422
+ inputPrice: 0,
423
+ outputPrice: 0,
424
+ cachedPrice: 0
425
+ }
426
+ },
427
+ {
428
+ prefix: "gemma-3n-",
429
+ pricing: {
430
+ inputPrice: 0,
431
+ outputPrice: 0,
432
+ cachedPrice: 0
433
+ }
434
+ }
435
+ ];
436
+ GROQ_MODEL_PRICING = {
437
+ "llama-3.1-8b-instant": { inputPrice: 0.05, outputPrice: 0.08 },
438
+ "llama-3.3-70b-versatile": { inputPrice: 0.59, outputPrice: 0.79 },
439
+ "meta-llama/llama-4-scout-17b-16e-instruct": { inputPrice: 0.11, outputPrice: 0.34 },
440
+ "moonshotai/kimi-k2-instruct": { inputPrice: 1, outputPrice: 3 },
441
+ "openai/gpt-oss-120b": { inputPrice: 0.15, cachedPrice: 0.075, outputPrice: 0.6 },
442
+ "openai/gpt-oss-20b": { inputPrice: 0.075, cachedPrice: 0.037, outputPrice: 0.3 },
443
+ "qwen/qwen3-32b": { inputPrice: 0.29, outputPrice: 0.59 }
444
+ };
445
+ XAI_MODEL_PRICING = {
446
+ "grok-4-0709": { inputPrice: 30, cachedPrice: 7.5, outputPrice: 150 },
447
+ "grok-4": { inputPrice: 30, cachedPrice: 7.5, outputPrice: 150 },
448
+ "grok-4-latest": { inputPrice: 30, cachedPrice: 7.5, outputPrice: 150 },
449
+ "grok-4-fast-reasoning": { inputPrice: 2, cachedPrice: 0.5, outputPrice: 5 },
450
+ "grok-4-fast-non-reasoning": { inputPrice: 2, cachedPrice: 0.5, outputPrice: 5 },
451
+ "grok-4-1-fast-reasoning": { inputPrice: 2, cachedPrice: 0.5, outputPrice: 5 },
452
+ "grok-4-1-fast-non-reasoning": { inputPrice: 2, cachedPrice: 0.5, outputPrice: 5 },
453
+ "grok-4.20-0309-reasoning": { inputPrice: 20, cachedPrice: 2, outputPrice: 60 },
454
+ "grok-4.20-0309-non-reasoning": { inputPrice: 20, cachedPrice: 2, outputPrice: 60 },
455
+ "grok-4.20-multi-agent-0309": { inputPrice: 20, cachedPrice: 2, outputPrice: 60 },
456
+ "grok-code-fast-1": { inputPrice: 2, cachedPrice: 0.2, outputPrice: 15 },
457
+ "grok-3": { inputPrice: 30, cachedPrice: 7.5, outputPrice: 150 },
458
+ "grok-3-latest": { inputPrice: 30, cachedPrice: 7.5, outputPrice: 150 },
459
+ "grok-3-mini": { inputPrice: 3, cachedPrice: 0.75, outputPrice: 5 },
460
+ "grok-3-mini-latest": { inputPrice: 3, cachedPrice: 0.75, outputPrice: 5 }
461
+ };
462
+ }
463
+ });
196
464
  var init_types2 = __esm({
197
465
  "src/agents/providers/types.ts"() {
198
466
  }
@@ -648,6 +916,12 @@ var init_ProviderRegistry = __esm({
648
916
  if (modelDef.providerOptions?.baseUrl) {
649
917
  config.baseUrl = modelDef.providerOptions.baseUrl;
650
918
  }
919
+ if (providerName === "cloudflare" && !config.baseUrl && env.CLOUDFLARE_ACCOUNT_ID) {
920
+ config.baseUrl = `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/ai/v1`;
921
+ }
922
+ if (providerName === "cloudflare" && env.CLOUDFLARE_ACCOUNT_ID) {
923
+ config.accountId = env.CLOUDFLARE_ACCOUNT_ID;
924
+ }
651
925
  return this.cacheAndReturn(modelName, providerFactory(config), modelDef);
652
926
  }
653
927
  buildResult(provider, modelDef) {
@@ -662,11 +936,14 @@ var init_ProviderRegistry = __esm({
662
936
  */
663
937
  getApiKeyForProvider(providerName, env) {
664
938
  const apiKeyEnvVarMap = {
939
+ cloudflare: "CLOUDFLARE_API_TOKEN",
665
940
  cerebras: "CEREBRAS_API_KEY",
941
+ google: "GOOGLE_API_KEY",
942
+ groq: "GROQ_API_KEY",
666
943
  openai: "OPENAI_API_KEY",
667
944
  openrouter: "OPENROUTER_API_KEY",
668
945
  anthropic: "ANTHROPIC_API_KEY",
669
- google: "GOOGLE_API_KEY"
946
+ xai: "XAI_API_KEY"
670
947
  };
671
948
  const envVar = apiKeyEnvVarMap[providerName.toLowerCase()];
672
949
  if (envVar && env[envVar]) {
@@ -716,6 +993,13 @@ function modelSupportsImageInput(modelDef) {
716
993
  }
717
994
  return true;
718
995
  }
996
+ function modelSupportsToolCalls(modelDef) {
997
+ const supportsToolCalls = modelDef.capabilities?.supportsToolCalls;
998
+ if (typeof supportsToolCalls === "boolean") {
999
+ return supportsToolCalls;
1000
+ }
1001
+ return true;
1002
+ }
719
1003
  function filterImagesFromProviderMessages(messages) {
720
1004
  let removedUserImageParts = 0;
721
1005
  let removedToolImageAttachments = 0;
@@ -767,6 +1051,77 @@ function filterImagesFromProviderMessages(messages) {
767
1051
  removedToolImageAttachments
768
1052
  };
769
1053
  }
1054
+ function filterEmptyAssistantProviderMessages(messages) {
1055
+ return messages.filter((message) => {
1056
+ if (message.role !== "assistant") return true;
1057
+ const hasToolCalls = Array.isArray(message.toolCalls) && message.toolCalls.length > 0;
1058
+ const hasReasoning = typeof message.reasoning === "string" ? message.reasoning.trim().length > 0 : Boolean(message.reasoningDetails);
1059
+ const hasContent = typeof message.content === "string" ? message.content.trim().length > 0 : message.content !== null;
1060
+ return hasToolCalls || hasReasoning || hasContent;
1061
+ });
1062
+ }
1063
+ function buildSyntheticMissingToolResult(toolCall) {
1064
+ return {
1065
+ role: "tool",
1066
+ tool_call_id: toolCall.id,
1067
+ name: toolCall.function.name,
1068
+ toolName: toolCall.function.name,
1069
+ content: `Tool result missing from conversation history for prior call "${toolCall.function.name}". Treat this as a failed tool call.`
1070
+ };
1071
+ }
1072
+ function normalizeToolCallMessageSequence(messages) {
1073
+ const normalized = [];
1074
+ let pending = null;
1075
+ const flushPending = () => {
1076
+ if (!pending) {
1077
+ return;
1078
+ }
1079
+ normalized.push(pending.assistantMessage);
1080
+ for (const toolCall of pending.expectedToolCalls) {
1081
+ const matchedResult = pending.matchedResults.get(toolCall.id);
1082
+ normalized.push(matchedResult ?? buildSyntheticMissingToolResult(toolCall));
1083
+ }
1084
+ if (pending.deferredMessages.length > 0) {
1085
+ normalized.push(...normalizeToolCallMessageSequence(pending.deferredMessages));
1086
+ }
1087
+ pending = null;
1088
+ };
1089
+ for (const message of messages) {
1090
+ const isAssistantToolCallMessage = message.role === "assistant" && Array.isArray(message.tool_calls) && message.tool_calls.length > 0;
1091
+ if (!pending) {
1092
+ if (!isAssistantToolCallMessage) {
1093
+ normalized.push(message);
1094
+ continue;
1095
+ }
1096
+ const toolCalls = message.tool_calls ?? [];
1097
+ const expectedToolCalls = toolCalls.filter(
1098
+ (toolCall) => Boolean(toolCall && typeof toolCall.id === "string" && toolCall.function?.name)
1099
+ );
1100
+ if (expectedToolCalls.length === 0) {
1101
+ normalized.push(message);
1102
+ continue;
1103
+ }
1104
+ pending = {
1105
+ assistantMessage: message,
1106
+ expectedToolCalls,
1107
+ matchedResults: /* @__PURE__ */ new Map(),
1108
+ deferredMessages: []
1109
+ };
1110
+ continue;
1111
+ }
1112
+ const matchesPendingToolResult = message.role === "tool" && typeof message.tool_call_id === "string" && pending.expectedToolCalls.some((toolCall) => toolCall.id === message.tool_call_id) && !pending.matchedResults.has(message.tool_call_id);
1113
+ if (matchesPendingToolResult) {
1114
+ pending.matchedResults.set(message.tool_call_id, message);
1115
+ if (pending.matchedResults.size === pending.expectedToolCalls.length) {
1116
+ flushPending();
1117
+ }
1118
+ continue;
1119
+ }
1120
+ pending.deferredMessages.push(message);
1121
+ }
1122
+ flushPending();
1123
+ return normalized;
1124
+ }
770
1125
  function stripBase64FromMessages(messages, imagePathMap) {
771
1126
  return messages.map((msg) => {
772
1127
  if (msg.role === "user" && Array.isArray(msg.content)) {
@@ -910,27 +1265,34 @@ function transformToolChoice(toolChoice) {
910
1265
  return void 0;
911
1266
  }
912
1267
  function buildRequestBody(context, modelDef) {
913
- const transformedMessages = transformMessages(context.messages);
1268
+ const normalizedMessages = normalizeToolCallMessageSequence(context.messages);
1269
+ const transformedMessages = transformMessages(normalizedMessages);
914
1270
  const supportsImageInput = modelSupportsImageInput(modelDef);
1271
+ const supportsToolCalls = modelSupportsToolCalls(modelDef);
915
1272
  let requestMessages = transformedMessages;
916
1273
  let visionFiltering;
917
1274
  if (!supportsImageInput) {
918
1275
  const filtered = filterImagesFromProviderMessages(transformedMessages);
919
1276
  requestMessages = filtered.messages;
920
- visionFiltering = {
921
- enabled: true,
922
- reason: "model_no_vision",
923
- removedUserImageParts: filtered.removedUserImageParts,
924
- removedToolImageAttachments: filtered.removedToolImageAttachments
925
- };
1277
+ if (filtered.removedUserImageParts > 0 || filtered.removedToolImageAttachments > 0) {
1278
+ visionFiltering = {
1279
+ enabled: true,
1280
+ reason: "model_no_vision",
1281
+ removedUserImageParts: filtered.removedUserImageParts,
1282
+ removedToolImageAttachments: filtered.removedToolImageAttachments
1283
+ };
1284
+ }
926
1285
  }
1286
+ requestMessages = filterEmptyAssistantProviderMessages(requestMessages);
1287
+ const tools = supportsToolCalls ? transformTools(context.tools) : void 0;
1288
+ const toolChoice = supportsToolCalls ? transformToolChoice(context.tool_choice) : void 0;
927
1289
  return {
928
1290
  requestBody: {
929
1291
  model: modelDef.model,
930
1292
  messages: requestMessages,
931
- tools: transformTools(context.tools),
932
- toolChoice: transformToolChoice(context.tool_choice),
933
- parallelToolCalls: context.parallel_tool_calls,
1293
+ tools,
1294
+ toolChoice,
1295
+ parallelToolCalls: supportsToolCalls ? context.parallel_tool_calls : void 0,
934
1296
  reasoning: context.reasoning ? {
935
1297
  level: reasoningEffortToLevel(context.reasoning.effort),
936
1298
  maxTokens: context.reasoning.max_tokens,
@@ -972,6 +1334,7 @@ function convertUsage(usage) {
972
1334
  var NON_VISION_PLACEHOLDER_TEXT, LLMRequest;
973
1335
  var init_LLMRequest = __esm({
974
1336
  "src/agents/LLMRequest.ts"() {
1337
+ init_pricing();
975
1338
  init_types();
976
1339
  NON_VISION_PLACEHOLDER_TEXT = "[Image omitted: model does not support vision]";
977
1340
  LLMRequest = class {
@@ -1081,7 +1444,7 @@ var init_LLMRequest = __esm({
1081
1444
  timestamp: Date.now()
1082
1445
  });
1083
1446
  const response = await this.callModel(actualModelId, context, state, logId);
1084
- await this.logSuccess(response, state, actualModelId, startTime, context, logId);
1447
+ await this.logSuccess(response, state, actualModelId, startTime, context, logId, modelDef);
1085
1448
  state.emitTelemetry?.({
1086
1449
  type: "llm_response",
1087
1450
  tokens: response.usage.total_tokens,
@@ -1406,10 +1769,14 @@ var init_LLMRequest = __esm({
1406
1769
  /**
1407
1770
  * Update log with successful response data (best-effort, non-blocking)
1408
1771
  */
1409
- static async logSuccess(response, state, modelId, startTime, context, logId) {
1772
+ static async logSuccess(response, state, modelId, startTime, context, logId, modelDef) {
1410
1773
  try {
1411
1774
  const toolsCalled = response.tool_calls ? JSON.stringify(response.tool_calls.map((tc) => tc.function.name)) : null;
1412
- const cost_total = response.usage.cost ? parseFloat(response.usage.cost) : null;
1775
+ const providerName = response._provider?.name;
1776
+ const resolvedPricing = resolveModelPricing(modelDef, providerName);
1777
+ const calculatedCost = calculateUsageCost(response.usage, resolvedPricing);
1778
+ const providerReportedCost = typeof response.usage.cost === "number" ? response.usage.cost : typeof response.usage.cost === "string" ? parseFloat(response.usage.cost) : null;
1779
+ const cost_total = providerReportedCost != null && !Number.isNaN(providerReportedCost) ? providerReportedCost : calculatedCost?.costTotal ?? null;
1413
1780
  const actualProvider = response.usage.provider;
1414
1781
  const aggregateResponse = response._aggregate_response;
1415
1782
  const responseBody = aggregateResponse ? JSON.stringify(aggregateResponse) : JSON.stringify(response);
@@ -1450,6 +1817,8 @@ var init_LLMRequest = __esm({
1450
1817
  output_tokens: response.usage.completion_tokens,
1451
1818
  reasoning_tokens: response.usage.completion_tokens_details?.reasoning_tokens || 0,
1452
1819
  total_tokens: response.usage.total_tokens,
1820
+ cost_input: calculatedCost?.costInput,
1821
+ cost_output: calculatedCost?.costOutput,
1453
1822
  latency_ms: Date.now() - startTime,
1454
1823
  finish_reason: response.finish_reason,
1455
1824
  tools_called: toolsCalled ?? void 0,
@@ -1474,15 +1843,17 @@ var init_LLMRequest = __esm({
1474
1843
  output_tokens = ?4,
1475
1844
  reasoning_tokens = ?5,
1476
1845
  total_tokens = ?6,
1477
- latency_ms = ?7,
1478
- finish_reason = ?8,
1479
- tools_called = ?9,
1480
- cost_total = ?10,
1481
- is_complete = ?11,
1482
- reasoning_content = ?12,
1483
- provider_tools = ?13,
1484
- actual_provider = ?14
1485
- WHERE id = ?15
1846
+ cost_input = ?7,
1847
+ cost_output = ?8,
1848
+ latency_ms = ?9,
1849
+ finish_reason = ?10,
1850
+ tools_called = ?11,
1851
+ cost_total = ?12,
1852
+ is_complete = ?13,
1853
+ reasoning_content = ?14,
1854
+ provider_tools = ?15,
1855
+ actual_provider = ?16
1856
+ WHERE id = ?17
1486
1857
  `,
1487
1858
  logData.response_body,
1488
1859
  logData.input_tokens,
@@ -1490,6 +1861,8 @@ var init_LLMRequest = __esm({
1490
1861
  logData.output_tokens,
1491
1862
  logData.reasoning_tokens,
1492
1863
  logData.total_tokens,
1864
+ logData.cost_input ?? null,
1865
+ logData.cost_output ?? null,
1493
1866
  logData.latency_ms,
1494
1867
  logData.finish_reason,
1495
1868
  logData.tools_called,
@@ -1836,7 +2209,7 @@ function parseBindingObject(binding) {
1836
2209
  attachmentsProperty: typeof binding.attachmentsProperty === "string" ? binding.attachmentsProperty : null
1837
2210
  };
1838
2211
  }
1839
- function resolveSessionToolBinding(binding, legacyTool) {
2212
+ function resolveSessionToolBinding(binding) {
1840
2213
  if (typeof binding === "string") {
1841
2214
  return {
1842
2215
  toolName: binding,
@@ -1851,7 +2224,7 @@ function resolveSessionToolBinding(binding, legacyTool) {
1851
2224
  }
1852
2225
  }
1853
2226
  return {
1854
- toolName: typeof legacyTool === "string" ? legacyTool : null,
2227
+ toolName: null,
1855
2228
  messageProperty: null,
1856
2229
  attachmentsProperty: null
1857
2230
  };
@@ -1859,60 +2232,51 @@ function resolveSessionToolBinding(binding, legacyTool) {
1859
2232
  function getResolvedSessionBindingsFromSide(side) {
1860
2233
  const config = side ?? {};
1861
2234
  return {
1862
- stop: resolveSessionToolBinding(
1863
- config.sessionStop,
1864
- config.endSessionTool
1865
- ),
1866
- fail: resolveSessionToolBinding(
1867
- config.sessionFail,
1868
- config.failSessionTool
1869
- ),
1870
- status: resolveSessionToolBinding(
1871
- config.sessionStatus,
1872
- config.statusTool
1873
- )
2235
+ stop: resolveSessionToolBinding(config.sessionStop),
2236
+ fail: resolveSessionToolBinding(config.sessionFail),
2237
+ status: resolveSessionToolBinding(config.sessionStatus)
1874
2238
  };
1875
2239
  }
1876
2240
  function getAgentSessionBinding(agent, side, kind) {
1877
2241
  if (side === "a") {
1878
2242
  if (kind === "stop") {
1879
2243
  return {
1880
- toolName: agent.side_a_end_session_tool,
1881
- messageProperty: agent.side_a_end_session_message_property,
1882
- attachmentsProperty: agent.side_a_end_session_attachments_property
2244
+ toolName: agent.side_a_session_stop_tool,
2245
+ messageProperty: agent.side_a_session_stop_message_property,
2246
+ attachmentsProperty: agent.side_a_session_stop_attachments_property
1883
2247
  };
1884
2248
  }
1885
2249
  if (kind === "fail") {
1886
2250
  return {
1887
- toolName: agent.side_a_fail_session_tool,
1888
- messageProperty: agent.side_a_fail_session_message_property,
1889
- attachmentsProperty: agent.side_a_fail_session_attachments_property
2251
+ toolName: agent.side_a_session_fail_tool,
2252
+ messageProperty: agent.side_a_session_fail_message_property,
2253
+ attachmentsProperty: agent.side_a_session_fail_attachments_property
1890
2254
  };
1891
2255
  }
1892
2256
  return {
1893
- toolName: agent.side_a_status_tool,
1894
- messageProperty: agent.side_a_status_message_property,
1895
- attachmentsProperty: agent.side_a_status_attachments_property
2257
+ toolName: agent.side_a_session_status_tool,
2258
+ messageProperty: agent.side_a_session_status_message_property,
2259
+ attachmentsProperty: agent.side_a_session_status_attachments_property
1896
2260
  };
1897
2261
  }
1898
2262
  if (kind === "stop") {
1899
2263
  return {
1900
- toolName: agent.side_b_end_session_tool,
1901
- messageProperty: agent.side_b_end_session_message_property,
1902
- attachmentsProperty: agent.side_b_end_session_attachments_property
2264
+ toolName: agent.side_b_session_stop_tool,
2265
+ messageProperty: agent.side_b_session_stop_message_property,
2266
+ attachmentsProperty: agent.side_b_session_stop_attachments_property
1903
2267
  };
1904
2268
  }
1905
2269
  if (kind === "fail") {
1906
2270
  return {
1907
- toolName: agent.side_b_fail_session_tool,
1908
- messageProperty: agent.side_b_fail_session_message_property,
1909
- attachmentsProperty: agent.side_b_fail_session_attachments_property
2271
+ toolName: agent.side_b_session_fail_tool,
2272
+ messageProperty: agent.side_b_session_fail_message_property,
2273
+ attachmentsProperty: agent.side_b_session_fail_attachments_property
1910
2274
  };
1911
2275
  }
1912
2276
  return {
1913
- toolName: agent.side_b_status_tool,
1914
- messageProperty: agent.side_b_status_message_property,
1915
- attachmentsProperty: agent.side_b_status_attachments_property
2277
+ toolName: agent.side_b_session_status_tool,
2278
+ messageProperty: agent.side_b_session_status_message_property,
2279
+ attachmentsProperty: agent.side_b_session_status_attachments_property
1916
2280
  };
1917
2281
  }
1918
2282
  var init_sessionTools = __esm({
@@ -2939,15 +3303,15 @@ var init_ToolExecutor = __esm({
2939
3303
  side_a_stop_tool: null,
2940
3304
  side_a_stop_tool_response_property: null,
2941
3305
  side_a_max_steps: null,
2942
- side_a_end_session_tool: null,
2943
- side_a_end_session_message_property: null,
2944
- side_a_end_session_attachments_property: null,
2945
- side_a_fail_session_tool: null,
2946
- side_a_fail_session_message_property: null,
2947
- side_a_fail_session_attachments_property: null,
2948
- side_a_status_tool: null,
2949
- side_a_status_message_property: null,
2950
- side_a_status_attachments_property: null,
3306
+ side_a_session_stop_tool: null,
3307
+ side_a_session_stop_message_property: null,
3308
+ side_a_session_stop_attachments_property: null,
3309
+ side_a_session_fail_tool: null,
3310
+ side_a_session_fail_message_property: null,
3311
+ side_a_session_fail_attachments_property: null,
3312
+ side_a_session_status_tool: null,
3313
+ side_a_session_status_message_property: null,
3314
+ side_a_session_status_attachments_property: null,
2951
3315
  // Side B configuration (unused for prompt tools)
2952
3316
  side_b_label: null,
2953
3317
  side_b_agent_prompt: null,
@@ -2955,15 +3319,15 @@ var init_ToolExecutor = __esm({
2955
3319
  side_b_stop_tool: null,
2956
3320
  side_b_stop_tool_response_property: null,
2957
3321
  side_b_max_steps: null,
2958
- side_b_end_session_tool: null,
2959
- side_b_end_session_message_property: null,
2960
- side_b_end_session_attachments_property: null,
2961
- side_b_fail_session_tool: null,
2962
- side_b_fail_session_message_property: null,
2963
- side_b_fail_session_attachments_property: null,
2964
- side_b_status_tool: null,
2965
- side_b_status_message_property: null,
2966
- side_b_status_attachments_property: null
3322
+ side_b_session_stop_tool: null,
3323
+ side_b_session_stop_message_property: null,
3324
+ side_b_session_stop_attachments_property: null,
3325
+ side_b_session_fail_tool: null,
3326
+ side_b_session_fail_message_property: null,
3327
+ side_b_session_fail_attachments_property: null,
3328
+ side_b_session_status_tool: null,
3329
+ side_b_session_status_message_property: null,
3330
+ side_b_session_status_attachments_property: null
2967
3331
  };
2968
3332
  let userMessageContent;
2969
3333
  let userMessageAttachments;
@@ -4176,8 +4540,8 @@ ${result ?? error ?? "No result content."}${attachmentSummary}`;
4176
4540
  state.currentSide,
4177
4541
  "status"
4178
4542
  );
4179
- const statusTool = statusBinding.toolName;
4180
- if (!statusTool || statusTool !== toolName) {
4543
+ const sessionStatusToolName = statusBinding.toolName;
4544
+ if (!sessionStatusToolName || sessionStatusToolName !== toolName) {
4181
4545
  return;
4182
4546
  }
4183
4547
  const mappedValue = statusBinding.messageProperty && args ? args[statusBinding.messageProperty] : void 0;
@@ -4361,9 +4725,9 @@ ${result ?? error ?? "No result content."}${attachmentSummary}`;
4361
4725
  const baseError = processedResult.error?.trim() || "Tool execution failed";
4362
4726
  content = `Failed to execute tool: ${baseError}`;
4363
4727
  }
4364
- const endSessionTool = stopBinding.toolName;
4365
- const failSessionTool = failBinding.toolName;
4366
- const shouldAppendAttachmentPaths = (!endSessionTool || call.function.name !== endSessionTool) && (!failSessionTool || call.function.name !== failSessionTool);
4728
+ const sessionStopToolName = stopBinding.toolName;
4729
+ const sessionFailToolName = failBinding.toolName;
4730
+ const shouldAppendAttachmentPaths = (!sessionStopToolName || call.function.name !== sessionStopToolName) && (!sessionFailToolName || call.function.name !== sessionFailToolName);
4367
4731
  if (shouldAppendAttachmentPaths && attachmentRefs && attachmentRefs.length > 0) {
4368
4732
  const attachmentPaths = attachmentRefs.map((ref) => `Attachment path for "${ref.name}": ${ref.path}`).join("\n");
4369
4733
  content += `
@@ -5559,10 +5923,16 @@ function svgToDataUri(svg) {
5559
5923
  const encoded = encodeURIComponent(svg).replace(/'/g, "%27").replace(/"/g, "%22");
5560
5924
  return `data:image/svg+xml,${encoded}`;
5561
5925
  }
5926
+ function normalizeIcon(icon) {
5927
+ if (icon.startsWith("data:") || icon.endsWith(".svg") || icon.includes(".svg?")) {
5928
+ return icon;
5929
+ }
5930
+ return svgToDataUri(icon);
5931
+ }
5562
5932
  function getOpenAIIconDataUri() {
5563
- return svgToDataUri(OPENAI_ICON);
5933
+ return normalizeIcon(OPENAI_ICON);
5564
5934
  }
5565
- var DEFAULT_REASONING_LEVELS, OPENAI_NATIVE_TOOLS, OPENAI_ICON, OpenAIProvider, openaiProviderOptions, openai;
5935
+ var DEFAULT_REASONING_LEVELS, OPENAI_NATIVE_TOOLS, openai_default, OPENAI_ICON, OpenAIProvider, openaiProviderOptions, openai;
5566
5936
  var init_dist = __esm({
5567
5937
  "../openai/dist/index.js"() {
5568
5938
  DEFAULT_REASONING_LEVELS = {
@@ -5577,10 +5947,8 @@ var init_dist = __esm({
5577
5947
  "code_interpreter",
5578
5948
  "file_search"
5579
5949
  ]);
5580
- OPENAI_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48" fill="none">
5581
- <rect width="48" height="48" rx="24" fill="white"/>
5582
- <path d="M19.3418 18.5599V14.7599C19.3418 14.4399 19.4608 14.1998 19.7382 14.04L27.3102 9.63997C28.3409 9.03999 29.5699 8.76014 30.8383 8.76014C35.5954 8.76014 38.6085 12.4802 38.6085 16.4401C38.6085 16.72 38.6085 17.04 38.5687 17.3601L30.7194 12.72C30.2437 12.4401 29.7678 12.4401 29.2922 12.72L19.3418 18.5599ZM37.0226 33.36V24.2799C37.0226 23.7197 36.7846 23.3197 36.309 23.0398L26.3586 17.1998L29.6093 15.3197C29.8868 15.1599 30.1247 15.1599 30.4022 15.3197L37.9741 19.7197C40.1547 20.9999 41.6213 23.7197 41.6213 26.3596C41.6213 29.3995 39.8375 32.1999 37.0226 33.36ZM17.0029 25.3601L13.7522 23.4402C13.4748 23.2804 13.3557 23.0402 13.3557 22.7202V13.9203C13.3557 9.64039 16.6065 6.40016 21.0069 6.40016C22.6722 6.40016 24.2179 6.96029 25.5265 7.96025L17.7168 12.5204C17.2412 12.8003 17.0033 13.2002 17.0033 13.7605L17.0029 25.3601ZM24 29.44L19.3418 26.8001V21.2003L24 18.5604L28.6578 21.2003V26.8001L24 29.44ZM26.993 41.6002C25.3278 41.6002 23.7821 41.04 22.4735 40.0402L30.2831 35.4799C30.7588 35.2001 30.9967 34.8001 30.9967 34.2399V22.6399L34.2873 24.5598C34.5646 24.7196 34.6837 24.9597 34.6837 25.2798V34.0797C34.6837 38.3596 31.3931 41.6002 26.993 41.6002ZM17.5975 32.6802L10.0255 28.2803C7.84493 27.0001 6.37833 24.2803 6.37833 21.6404C6.37833 18.5604 8.20193 15.8004 11.0164 14.6403V23.7602C11.0164 24.3204 11.2544 24.7204 11.73 25.0003L21.641 30.8001L18.3902 32.6802C18.1129 32.84 17.8749 32.84 17.5975 32.6802ZM17.1617 39.2402C12.682 39.2402 9.39151 35.8402 9.39151 31.6401C9.39151 31.3201 9.43125 31.0001 9.47066 30.68L17.2803 35.2402C17.7559 35.5201 18.2319 35.5201 18.7074 35.2402L28.6578 29.4404V33.2404C28.6578 33.5605 28.5388 33.8005 28.2614 33.9604L20.6894 38.3604C19.6586 38.9603 18.4301 39.2402 17.1617 39.2402ZM26.993 44C31.7899 44 35.7936 40.5601 36.7057 36C41.1457 34.8399 44 30.6399 44 26.36C44 23.5598 42.8108 20.8401 40.6701 18.88C40.8683 18.0399 40.9872 17.1998 40.9872 16.3602C40.9872 10.6403 36.3885 6.35998 31.0763 6.35998C30.0062 6.35998 28.9754 6.51979 27.9446 6.88001C26.1604 5.11992 23.7025 4 21.0069 4C16.2101 4 12.2064 7.4398 11.2943 12C6.8543 13.1601 4 17.3601 4 21.6399C4 24.4401 5.18916 27.1599 7.32995 29.1199C7.13174 29.96 7.01277 30.8001 7.01277 31.6398C7.01277 37.3597 11.6114 41.6399 16.9236 41.6399C17.9938 41.6399 19.0246 41.4801 20.0554 41.1199C21.8392 42.88 24.2971 44 26.993 44Z" fill="black"/>
5583
- </svg>`;
5950
+ openai_default = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" fill="none" viewBox="0 0 128 128"><g clip-path="url(%23clip0_2138_504)"><g clip-path="url(%23clip1_2138_504)"><path fill="%23000" d="M118.824 52.388a31.9 31.9 0 0 0-2.74-26.192 32.25 32.25 0 0 0-34.736-15.472A31.9 31.9 0 0 0 57.296 0C43.28-.032 30.844 8.992 26.532 22.328A31.9 31.9 0 0 0 5.208 37.796C-1.828 49.924-.224 65.212 9.176 75.612a31.9 31.9 0 0 0 2.74 26.192 32.25 32.25 0 0 0 34.736 15.472 31.88 31.88 0 0 0 24.052 10.72c14.024.036 26.464-8.996 30.776-22.344a31.9 31.9 0 0 0 21.324-15.468 32.26 32.26 0 0 0-3.976-37.804zm-48.112 67.244a23.9 23.9 0 0 1-15.356-5.552c.196-.104.536-.292.756-.428L81.6 98.932a4.14 4.14 0 0 0 2.096-3.628V59.372l10.772 6.22a.38.38 0 0 1 .208.296v29.756c-.016 13.232-10.732 23.96-23.964 23.988M19.176 97.62a23.88 23.88 0 0 1-2.86-16.072c.188.112.52.316.756.452L42.56 96.72a4.15 4.15 0 0 0 4.188 0l31.116-17.968v12.44a.4.4 0 0 1-.152.332L51.948 106.4c-11.476 6.608-26.132 2.68-32.768-8.78zm-6.708-55.636a23.9 23.9 0 0 1 12.484-10.516c0 .22-.012.608-.012.88v29.444a4.15 4.15 0 0 0 2.092 3.624L58.148 83.38 47.376 89.6a.38.38 0 0 1-.364.032L21.244 74.744c-11.452-6.632-15.38-21.284-8.78-32.756zm88.504 20.596L69.856 44.612l10.772-6.216a.38.38 0 0 1 .364-.032L106.76 53.24c11.472 6.628 15.404 21.304 8.776 32.776a23.98 23.98 0 0 1-12.48 10.512V66.204a4.14 4.14 0 0 0-2.08-3.624zm10.72-16.136c-.188-.116-.52-.316-.756-.452l-25.488-14.72a4.15 4.15 0 0 0-4.188 0L50.144 49.24V36.8a.4.4 0 0 1 .152-.332L76.06 21.604c11.476-6.62 26.148-2.68 32.764 8.8a23.98 23.98 0 0 1 2.86 16.04zM44.288 68.616l-10.776-6.22a.38.38 0 0 1-.208-.296V32.344C33.312 19.096 44.06 8.36 57.308 8.368a23.98 23.98 0 0 1 15.336 5.552c-.196.104-.532.292-.756.428L46.4 29.068a4.14 4.14 0 0 0-2.096 3.624l-.016 35.916zM50.14 56 64 47.996l13.86 8V72L64 80l-13.86-8z"/></g></g><defs><clipPath id="clip0_2138_504"><path fill="%23fff" d="M0 0h128v128H0z"/></clipPath><clipPath id="clip1_2138_504"><path fill="%23fff" d="M0 0h128v128H0z"/></clipPath></defs></svg>';
5951
+ OPENAI_ICON = openai_default;
5584
5952
  OpenAIProvider = class _OpenAIProvider {
5585
5953
  name = "openai";
5586
5954
  specificationVersion = "1";
@@ -6588,30 +6956,30 @@ var init_FlowEngine = __esm({
6588
6956
  side_a_stop_tool: newAgentDef.sideA?.stopTool ?? null,
6589
6957
  side_a_stop_tool_response_property: newAgentDef.sideA?.stopToolResponseProperty ?? null,
6590
6958
  side_a_max_steps: newAgentDef.sideA?.maxSteps ?? null,
6591
- side_a_end_session_tool: sideASession.stop.toolName,
6592
- side_a_end_session_message_property: sideASession.stop.messageProperty,
6593
- side_a_end_session_attachments_property: sideASession.stop.attachmentsProperty,
6594
- side_a_fail_session_tool: sideASession.fail.toolName,
6595
- side_a_fail_session_message_property: sideASession.fail.messageProperty,
6596
- side_a_fail_session_attachments_property: sideASession.fail.attachmentsProperty,
6597
- side_a_status_tool: sideASession.status.toolName,
6598
- side_a_status_message_property: sideASession.status.messageProperty,
6599
- side_a_status_attachments_property: sideASession.status.attachmentsProperty,
6959
+ side_a_session_stop_tool: sideASession.stop.toolName,
6960
+ side_a_session_stop_message_property: sideASession.stop.messageProperty,
6961
+ side_a_session_stop_attachments_property: sideASession.stop.attachmentsProperty,
6962
+ side_a_session_fail_tool: sideASession.fail.toolName,
6963
+ side_a_session_fail_message_property: sideASession.fail.messageProperty,
6964
+ side_a_session_fail_attachments_property: sideASession.fail.attachmentsProperty,
6965
+ side_a_session_status_tool: sideASession.status.toolName,
6966
+ side_a_session_status_message_property: sideASession.status.messageProperty,
6967
+ side_a_session_status_attachments_property: sideASession.status.attachmentsProperty,
6600
6968
  side_b_label: newAgentDef.sideB?.label ?? null,
6601
6969
  side_b_agent_prompt: newAgentDef.sideB?.prompt ?? null,
6602
6970
  side_b_stop_on_response: newAgentDef.sideB?.stopOnResponse ?? false,
6603
6971
  side_b_stop_tool: newAgentDef.sideB?.stopTool ?? null,
6604
6972
  side_b_stop_tool_response_property: newAgentDef.sideB?.stopToolResponseProperty ?? null,
6605
6973
  side_b_max_steps: newAgentDef.sideB?.maxSteps ?? null,
6606
- side_b_end_session_tool: sideBSession.stop.toolName,
6607
- side_b_end_session_message_property: sideBSession.stop.messageProperty,
6608
- side_b_end_session_attachments_property: sideBSession.stop.attachmentsProperty,
6609
- side_b_fail_session_tool: sideBSession.fail.toolName,
6610
- side_b_fail_session_message_property: sideBSession.fail.messageProperty,
6611
- side_b_fail_session_attachments_property: sideBSession.fail.attachmentsProperty,
6612
- side_b_status_tool: sideBSession.status.toolName,
6613
- side_b_status_message_property: sideBSession.status.messageProperty,
6614
- side_b_status_attachments_property: sideBSession.status.attachmentsProperty
6974
+ side_b_session_stop_tool: sideBSession.stop.toolName,
6975
+ side_b_session_stop_message_property: sideBSession.stop.messageProperty,
6976
+ side_b_session_stop_attachments_property: sideBSession.stop.attachmentsProperty,
6977
+ side_b_session_fail_tool: sideBSession.fail.toolName,
6978
+ side_b_session_fail_message_property: sideBSession.fail.messageProperty,
6979
+ side_b_session_fail_attachments_property: sideBSession.fail.attachmentsProperty,
6980
+ side_b_session_status_tool: sideBSession.status.toolName,
6981
+ side_b_session_status_message_property: sideBSession.status.messageProperty,
6982
+ side_b_session_status_attachments_property: sideBSession.status.attachmentsProperty
6615
6983
  };
6616
6984
  const { sideAPrompt, sideBPrompt } = await this.loadAgentAndPrompts(
6617
6985
  agentConfig,
@@ -7402,7 +7770,7 @@ var init_FlowEngine = __esm({
7402
7770
  role: row.role,
7403
7771
  content: row.content,
7404
7772
  created_at: row.created_at,
7405
- silent: row.silent === 1,
7773
+ silent: this.isSilentMessageRow(row.silent),
7406
7774
  attachments: row.attachments,
7407
7775
  metadata: parsedMetadata,
7408
7776
  subagent_id: this.extractSubagentIdFromMetadata(row.metadata)
@@ -7555,12 +7923,6 @@ var init_FlowEngine = __esm({
7555
7923
  const completedMessages = state.messageHistory.filter(
7556
7924
  (msg) => msg.status !== "pending"
7557
7925
  );
7558
- const toolCallsWithResponses = /* @__PURE__ */ new Set();
7559
- for (const msg of completedMessages) {
7560
- if (msg.role === "tool" && msg.tool_call_id) {
7561
- toolCallsWithResponses.add(msg.tool_call_id);
7562
- }
7563
- }
7564
7926
  const recentMessageThreshold = state.prompt.recentImageThreshold ?? 10;
7565
7927
  const oldMessageThreshold = completedMessages.length - recentMessageThreshold;
7566
7928
  let messageIndex = 0;
@@ -7623,11 +7985,12 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
7623
7985
  messageContent = msg.content || "";
7624
7986
  }
7625
7987
  messageIndex++;
7988
+ const shouldIncludeAssistantToolCalls = includePastTools && role === "assistant" && Boolean(msg.tool_calls);
7626
7989
  const messageToAdd = {
7627
7990
  role,
7628
7991
  content: messageContent,
7629
- tool_calls: includePastTools && msg.tool_calls ? JSON.parse(msg.tool_calls) : void 0,
7630
- tool_call_id: includePastTools && msg.tool_call_id ? msg.tool_call_id : void 0,
7992
+ tool_calls: shouldIncludeAssistantToolCalls ? JSON.parse(msg.tool_calls) : void 0,
7993
+ tool_call_id: includePastTools && msg.role === "tool" && msg.tool_call_id ? msg.tool_call_id : void 0,
7631
7994
  name: msg.name || void 0,
7632
7995
  // For tool messages, also set toolName for provider transformers (e.g., OpenAI image_generation)
7633
7996
  toolName: msg.role === "tool" ? msg.name : void 0
@@ -7677,24 +8040,7 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
7677
8040
  messageToAdd.reasoning_details = reasoningDetailsArray;
7678
8041
  }
7679
8042
  }
7680
- if (includePastTools && msg.role === "assistant" && msg.tool_calls) {
7681
- const toolCalls = JSON.parse(msg.tool_calls);
7682
- const matchedToolCalls = toolCalls.filter(
7683
- (toolCall) => toolCallsWithResponses.has(toolCall.id)
7684
- );
7685
- if (msg.content || matchedToolCalls.length > 0) {
7686
- if (matchedToolCalls.length === 0) {
7687
- delete messageToAdd.tool_calls;
7688
- } else if (matchedToolCalls.length !== toolCalls.length) {
7689
- messageToAdd.tool_calls = matchedToolCalls;
7690
- }
7691
- messages.push(messageToAdd);
7692
- } else {
7693
- console.warn(`[FlowEngine] Skipping assistant message ${msg.id} - no content and no tool calls with responses`);
7694
- }
7695
- } else {
7696
- messages.push(messageToAdd);
7697
- }
8043
+ messages.push(messageToAdd);
7698
8044
  }
7699
8045
  const maxSteps = state.currentSide === "a" ? state.agentConfig.side_a_max_steps : state.agentConfig.side_b_max_steps;
7700
8046
  if (typeof maxSteps === "number" && !isNaN(maxSteps)) {
@@ -9360,14 +9706,14 @@ ${lines.join("\n\n")}`
9360
9706
  * Check if stop condition is met
9361
9707
  */
9362
9708
  static checkStopCondition(state, response) {
9363
- const failSessionTool = getAgentSessionBinding(
9709
+ const sessionFailToolName = getAgentSessionBinding(
9364
9710
  state.agentConfig,
9365
9711
  state.currentSide,
9366
9712
  "fail"
9367
9713
  ).toolName;
9368
- if (failSessionTool) {
9714
+ if (sessionFailToolName) {
9369
9715
  const matchingFailSessionCalls = response.tool_calls?.filter(
9370
- (call) => call.function.name === failSessionTool
9716
+ (call) => call.function.name === sessionFailToolName
9371
9717
  ) ?? [];
9372
9718
  if (matchingFailSessionCalls.length > 0) {
9373
9719
  const hasSuccessfulFailSessionCall = matchingFailSessionCalls.some(
@@ -9376,11 +9722,11 @@ ${lines.join("\n\n")}`
9376
9722
  if (hasSuccessfulFailSessionCall) {
9377
9723
  state.stopped = true;
9378
9724
  state.stoppedBy = state.currentSide;
9379
- state.stopReason = `Fail session tool called: ${failSessionTool}`;
9725
+ state.stopReason = `sessionFail tool called: ${sessionFailToolName}`;
9380
9726
  state.stopReasonCode = "session_fail";
9381
9727
  state.emitTelemetry?.({
9382
9728
  type: "stopped",
9383
- reason: `Fail session tool called: ${failSessionTool}`,
9729
+ reason: `sessionFail tool called: ${sessionFailToolName}`,
9384
9730
  side: state.currentSide,
9385
9731
  timestamp: Date.now()
9386
9732
  });
@@ -9395,14 +9741,14 @@ ${lines.join("\n\n")}`
9395
9741
  };
9396
9742
  }
9397
9743
  }
9398
- const endSessionTool = getAgentSessionBinding(
9744
+ const sessionStopToolName = getAgentSessionBinding(
9399
9745
  state.agentConfig,
9400
9746
  state.currentSide,
9401
9747
  "stop"
9402
9748
  ).toolName;
9403
- if (endSessionTool) {
9749
+ if (sessionStopToolName) {
9404
9750
  const matchingEndSessionCalls = response.tool_calls?.filter(
9405
- (call) => call.function.name === endSessionTool
9751
+ (call) => call.function.name === sessionStopToolName
9406
9752
  ) ?? [];
9407
9753
  if (matchingEndSessionCalls.length > 0) {
9408
9754
  const hasSuccessfulEndSessionCall = matchingEndSessionCalls.some(
@@ -9411,11 +9757,11 @@ ${lines.join("\n\n")}`
9411
9757
  if (hasSuccessfulEndSessionCall) {
9412
9758
  state.stopped = true;
9413
9759
  state.stoppedBy = state.currentSide;
9414
- state.stopReason = `End session tool called: ${endSessionTool}`;
9760
+ state.stopReason = `sessionStop tool called: ${sessionStopToolName}`;
9415
9761
  state.stopReasonCode = "session_stop";
9416
9762
  state.emitTelemetry?.({
9417
9763
  type: "stopped",
9418
- reason: `End session tool called: ${endSessionTool}`,
9764
+ reason: `sessionStop tool called: ${sessionStopToolName}`,
9419
9765
  side: state.currentSide,
9420
9766
  timestamp: Date.now()
9421
9767
  });
@@ -9507,16 +9853,13 @@ ${lines.join("\n\n")}`
9507
9853
  )?.[1];
9508
9854
  return msg.role === "tool" && referencedSubagentId !== void 0 && (typeof msg.subagent_id === "string" && msg.subagent_id.trim().length > 0 || typeof msg.name === "string");
9509
9855
  }
9856
+ static isSilentMessageRow(value) {
9857
+ return value === 1 || value === true;
9858
+ }
9510
9859
  static filterOrphanedToolCalls(messages) {
9511
- const toolResultIds = /* @__PURE__ */ new Set();
9512
- for (const msg of messages) {
9513
- if (msg.role === "tool" && msg.tool_call_id) {
9514
- toolResultIds.add(msg.tool_call_id);
9515
- }
9516
- }
9517
9860
  const assistantToolCallIds = /* @__PURE__ */ new Set();
9518
9861
  for (const msg of messages) {
9519
- if (msg.role === "assistant" && msg.tool_calls) {
9862
+ if ((msg.role === "assistant" || msg.role === "user") && msg.tool_calls) {
9520
9863
  try {
9521
9864
  const toolCalls = JSON.parse(msg.tool_calls);
9522
9865
  for (const call of toolCalls) {
@@ -9542,40 +9885,6 @@ ${lines.join("\n\n")}`
9542
9885
  continue;
9543
9886
  }
9544
9887
  }
9545
- if (msg.role === "assistant" && msg.tool_calls) {
9546
- try {
9547
- const toolCalls = JSON.parse(msg.tool_calls);
9548
- const matchedToolCalls = toolCalls.filter(
9549
- (call) => toolResultIds.has(call.id)
9550
- );
9551
- if (matchedToolCalls.length === 0 && toolCalls.length > 0) {
9552
- if (msg.content) {
9553
- console.warn(`[FlowEngine] Filtering tool_calls from message ${msg.id} - no matching tool results`);
9554
- warnedRemovedCount += 1;
9555
- filtered.push({
9556
- ...msg,
9557
- tool_calls: null
9558
- });
9559
- continue;
9560
- } else {
9561
- console.warn(`[FlowEngine] Filtering assistant message ${msg.id} - no content and no tool calls with results`);
9562
- warnedRemovedCount += 1;
9563
- continue;
9564
- }
9565
- }
9566
- if (matchedToolCalls.length !== toolCalls.length) {
9567
- console.warn(`[FlowEngine] Filtering ${toolCalls.length - matchedToolCalls.length} orphaned tool_calls from message ${msg.id}`);
9568
- warnedRemovedCount += 1;
9569
- filtered.push({
9570
- ...msg,
9571
- tool_calls: JSON.stringify(matchedToolCalls)
9572
- });
9573
- continue;
9574
- }
9575
- } catch (error) {
9576
- console.error(`Failed to parse tool_calls for message ${msg.id}:`, error);
9577
- }
9578
- }
9579
9888
  filtered.push(msg);
9580
9889
  }
9581
9890
  const removedCount = messages.length - filtered.length;
@@ -9646,14 +9955,18 @@ ${lines.join("\n\n")}`
9646
9955
  request_sent_at: row.request_sent_at,
9647
9956
  response_completed_at: row.response_completed_at,
9648
9957
  status: row.status,
9649
- silent: row.silent === 1,
9958
+ silent: this.isSilentMessageRow(row.silent),
9650
9959
  tool_status: row.tool_status,
9651
9960
  parent_id: row.parent_id,
9652
9961
  depth: row.depth,
9653
9962
  reasoning_content: row.reasoning_content,
9654
9963
  reasoning_details: row.reasoning_details
9655
9964
  }));
9656
- return this.runFilterMessagesHook(thread.instance, state, this.filterOrphanedToolCalls(messages));
9965
+ return this.runFilterMessagesHook(
9966
+ thread.instance,
9967
+ state,
9968
+ this.filterOrphanedToolCalls(messages)
9969
+ );
9657
9970
  } catch (error) {
9658
9971
  console.error("Error loading message history:", error);
9659
9972
  return [];
@@ -10871,22 +11184,42 @@ __export(image_processing_exports, {
10871
11184
  needsProcessing: () => needsProcessing,
10872
11185
  processImage: () => processImage
10873
11186
  });
11187
+ function clampQuality(quality) {
11188
+ return Math.max(1, Math.min(100, Math.round(quality)));
11189
+ }
11190
+ async function collectTransformedImage(input, width, height, quality) {
11191
+ const image = transform(input, { width, height, quality: clampQuality(quality) });
11192
+ const { data, info } = await collect(image);
11193
+ return {
11194
+ data,
11195
+ mimeType: "image/jpeg",
11196
+ width: info.width,
11197
+ height: info.height
11198
+ };
11199
+ }
11200
+ async function transformToTargetSize(input, maxWidth, maxHeight, maxBytes, quality) {
11201
+ let currentQuality = clampQuality(quality);
11202
+ let result = await collectTransformedImage(input, maxWidth, maxHeight, currentQuality);
11203
+ while (result.data.byteLength > maxBytes && currentQuality > MIN_QUALITY) {
11204
+ currentQuality -= 10;
11205
+ result = await collectTransformedImage(input, maxWidth, maxHeight, currentQuality);
11206
+ }
11207
+ while (result.data.byteLength > maxBytes) {
11208
+ const scaleFactor = Math.sqrt(maxBytes / result.data.byteLength) * 0.9;
11209
+ const nextWidth = Math.max(1, Math.min(result.width - 1, Math.round(result.width * scaleFactor)));
11210
+ const nextHeight = Math.max(1, Math.min(result.height - 1, Math.round(result.height * scaleFactor)));
11211
+ if (nextWidth >= result.width && nextHeight >= result.height) {
11212
+ break;
11213
+ }
11214
+ result = await collectTransformedImage(input, nextWidth, nextHeight, currentQuality);
11215
+ }
11216
+ return result;
11217
+ }
10874
11218
  async function processImage(input, inputMimeType) {
10875
11219
  if (input.byteLength > MAX_INPUT_SIZE) {
10876
11220
  throw new Error(`Image too large: ${input.byteLength} bytes exceeds ${MAX_INPUT_SIZE} byte limit`);
10877
11221
  }
10878
- const result = await sip.process(input, {
10879
- maxWidth: MAX_DIMENSION,
10880
- maxHeight: MAX_DIMENSION,
10881
- maxBytes: MAX_SIZE,
10882
- quality: 85
10883
- });
10884
- return {
10885
- data: result.data,
10886
- mimeType: "image/jpeg",
10887
- width: result.width,
10888
- height: result.height
10889
- };
11222
+ return await transformToTargetSize(input, MAX_DIMENSION, MAX_DIMENSION, MAX_SIZE, 85);
10890
11223
  }
10891
11224
  function needsProcessing(data, mimeType) {
10892
11225
  const binaryLength = Math.ceil(data.length * 3 / 4);
@@ -10908,12 +11241,13 @@ function arrayBufferToBase64(buffer) {
10908
11241
  }
10909
11242
  return btoa(binary);
10910
11243
  }
10911
- var MAX_SIZE, MAX_DIMENSION, MAX_INPUT_SIZE;
11244
+ var MAX_SIZE, MAX_DIMENSION, MAX_INPUT_SIZE, MIN_QUALITY;
10912
11245
  var init_image_processing = __esm({
10913
11246
  "src/image-processing/index.ts"() {
10914
11247
  MAX_SIZE = 1.5 * 1024 * 1024;
10915
11248
  MAX_DIMENSION = 4096;
10916
11249
  MAX_INPUT_SIZE = 20 * 1024 * 1024;
11250
+ MIN_QUALITY = 45;
10917
11251
  }
10918
11252
  });
10919
11253
  var TSCONFIG_CONTENT = `{
@@ -11093,7 +11427,6 @@ function generateTypesContent(config) {
11093
11427
  const agents = agentResults.map((a) => a.name);
11094
11428
  const callables = [...prompts, ...agents, ...tools];
11095
11429
  return `// Auto-generated by @standardagents/builder - DO NOT EDIT
11096
- // Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}
11097
11430
  //
11098
11431
  // This file augments the StandardAgentSpec namespace declared in @standardagents/spec
11099
11432
  // to provide type-safe references for your models, prompts, agents, tools, and hooks.
@@ -11382,7 +11715,7 @@ declare module 'virtual:@standardagents/builder' {
11382
11715
  offset?: number,
11383
11716
  order?: 'ASC' | 'DESC'
11384
11717
  ): Promise<GetLogsResult>;
11385
- getLogDetails(logId: string): Promise<ThreadLogDetails>;
11718
+ getLogDetails(logId: string): Promise<ThreadLogDetails | null>;
11386
11719
 
11387
11720
  // Thread management methods
11388
11721
  getThreadMeta(threadId: string): Promise<ThreadMetaResult>;
@@ -11638,14 +11971,23 @@ function ensureDir(dir) {
11638
11971
  fs4__default.mkdirSync(dir, { recursive: true });
11639
11972
  }
11640
11973
  }
11974
+ function writeFileIfChanged(filePath, content) {
11975
+ if (fs4__default.existsSync(filePath)) {
11976
+ const existing = fs4__default.readFileSync(filePath, "utf-8");
11977
+ if (existing === content) {
11978
+ return;
11979
+ }
11980
+ }
11981
+ fs4__default.writeFileSync(filePath, content);
11982
+ }
11641
11983
  function generateTypes(config) {
11642
11984
  ensureDir(config.outputDir);
11643
11985
  const typesContent = generateTypesContent(config);
11644
- fs4__default.writeFileSync(path8__default.join(config.outputDir, "types.d.ts"), typesContent);
11986
+ writeFileIfChanged(path8__default.join(config.outputDir, "types.d.ts"), typesContent);
11645
11987
  const virtualModuleContent = generateVirtualModuleContent();
11646
- fs4__default.writeFileSync(path8__default.join(config.outputDir, "virtual-module.d.ts"), virtualModuleContent);
11647
- fs4__default.writeFileSync(path8__default.join(config.outputDir, "tsconfig.json"), TSCONFIG_CONTENT);
11648
- fs4__default.writeFileSync(path8__default.join(config.outputDir, ".gitignore"), "*\n");
11988
+ writeFileIfChanged(path8__default.join(config.outputDir, "virtual-module.d.ts"), virtualModuleContent);
11989
+ writeFileIfChanged(path8__default.join(config.outputDir, "tsconfig.json"), TSCONFIG_CONTENT);
11990
+ writeFileIfChanged(path8__default.join(config.outputDir, ".gitignore"), "*\n");
11649
11991
  }
11650
11992
  function needsRegeneration(config) {
11651
11993
  const typesPath = path8__default.join(config.outputDir, "types.d.ts");
@@ -12254,18 +12596,12 @@ function formatSideConfig(config) {
12254
12596
  }
12255
12597
  if (config.sessionStop) {
12256
12598
  parts.push(` sessionStop: ${formatSessionBinding(config.sessionStop)},`);
12257
- } else if (config.endSessionTool) {
12258
- parts.push(` endSessionTool: '${escapeString3(config.endSessionTool)}',`);
12259
12599
  }
12260
12600
  if (config.sessionFail) {
12261
12601
  parts.push(` sessionFail: ${formatSessionBinding(config.sessionFail)},`);
12262
- } else if (config.failSessionTool) {
12263
- parts.push(` failSessionTool: '${escapeString3(config.failSessionTool)}',`);
12264
12602
  }
12265
12603
  if (config.sessionStatus) {
12266
12604
  parts.push(` sessionStatus: ${formatSessionBinding(config.sessionStatus)},`);
12267
- } else if (config.statusTool) {
12268
- parts.push(` statusTool: '${escapeString3(config.statusTool)}',`);
12269
12605
  }
12270
12606
  if (config.manualStopCondition) {
12271
12607
  parts.push(` manualStopCondition: ${config.manualStopCondition},`);
@@ -12292,23 +12628,47 @@ function formatSessionBinding(binding) {
12292
12628
 
12293
12629
  // src/providers/catalog.ts
12294
12630
  var FIRST_PARTY_PROVIDERS = [
12631
+ {
12632
+ name: "cloudflare",
12633
+ package: "@standardagents/cloudflare",
12634
+ label: "Cloudflare Workers AI",
12635
+ envKeys: ["CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"]
12636
+ },
12295
12637
  {
12296
12638
  name: "cerebras",
12297
12639
  package: "@standardagents/cerebras",
12298
12640
  label: "Cerebras",
12299
- envKey: "CEREBRAS_API_KEY"
12641
+ envKeys: ["CEREBRAS_API_KEY"]
12642
+ },
12643
+ {
12644
+ name: "google",
12645
+ package: "@standardagents/google",
12646
+ label: "Google Gemini",
12647
+ envKeys: ["GOOGLE_API_KEY"]
12648
+ },
12649
+ {
12650
+ name: "groq",
12651
+ package: "@standardagents/groq",
12652
+ label: "Groq",
12653
+ envKeys: ["GROQ_API_KEY"]
12300
12654
  },
12301
12655
  {
12302
12656
  name: "openai",
12303
12657
  package: "@standardagents/openai",
12304
12658
  label: "OpenAI",
12305
- envKey: "OPENAI_API_KEY"
12659
+ envKeys: ["OPENAI_API_KEY"]
12306
12660
  },
12307
12661
  {
12308
12662
  name: "openrouter",
12309
12663
  package: "@standardagents/openrouter",
12310
12664
  label: "OpenRouter",
12311
- envKey: "OPENROUTER_API_KEY"
12665
+ envKeys: ["OPENROUTER_API_KEY"]
12666
+ },
12667
+ {
12668
+ name: "xai",
12669
+ package: "@standardagents/xai",
12670
+ label: "xAI",
12671
+ envKeys: ["XAI_API_KEY"]
12312
12672
  }
12313
12673
  ];
12314
12674
  function humanizeProviderName(name) {
@@ -12320,7 +12680,7 @@ function packageToCustomProvider(pkg) {
12320
12680
  name,
12321
12681
  package: pkg,
12322
12682
  label: humanizeProviderName(name),
12323
- envKey: `${name.toUpperCase().replace(/-/g, "_")}_API_KEY`,
12683
+ envKeys: [`${name.toUpperCase().replace(/-/g, "_")}_API_KEY`],
12324
12684
  isCustom: true
12325
12685
  };
12326
12686
  }
@@ -12910,34 +13270,28 @@ function transformAgentData(data) {
12910
13270
  transformed.sideA.maxSteps = data.side_a_max_steps;
12911
13271
  }
12912
13272
  const sideASessionStop = toSessionBinding(
12913
- data.side_a_session_stop_tool ?? data.side_a_end_session_tool,
13273
+ data.side_a_session_stop_tool,
12914
13274
  data.side_a_session_stop_message_property,
12915
13275
  data.side_a_session_stop_attachments_property
12916
13276
  );
12917
13277
  if (sideASessionStop !== void 0) {
12918
13278
  transformed.sideA.sessionStop = sideASessionStop;
12919
- } else if (data.side_a_end_session_tool) {
12920
- transformed.sideA.endSessionTool = data.side_a_end_session_tool;
12921
13279
  }
12922
13280
  const sideASessionFail = toSessionBinding(
12923
- data.side_a_session_fail_tool ?? data.side_a_fail_session_tool,
13281
+ data.side_a_session_fail_tool,
12924
13282
  data.side_a_session_fail_message_property,
12925
13283
  data.side_a_session_fail_attachments_property
12926
13284
  );
12927
13285
  if (sideASessionFail !== void 0) {
12928
13286
  transformed.sideA.sessionFail = sideASessionFail;
12929
- } else if (data.side_a_fail_session_tool) {
12930
- transformed.sideA.failSessionTool = data.side_a_fail_session_tool;
12931
13287
  }
12932
13288
  const sideASessionStatus = toSessionBinding(
12933
- data.side_a_session_status_tool ?? data.side_a_status_tool,
13289
+ data.side_a_session_status_tool,
12934
13290
  data.side_a_session_status_message_property,
12935
13291
  data.side_a_session_status_attachments_property
12936
13292
  );
12937
13293
  if (sideASessionStatus !== void 0) {
12938
13294
  transformed.sideA.sessionStatus = sideASessionStatus;
12939
- } else if (data.side_a_status_tool) {
12940
- transformed.sideA.statusTool = data.side_a_status_tool;
12941
13295
  }
12942
13296
  if (data.side_a_manual_stop_condition !== void 0) {
12943
13297
  transformed.sideA.manualStopCondition = data.side_a_manual_stop_condition;
@@ -12962,34 +13316,28 @@ function transformAgentData(data) {
12962
13316
  transformed.sideB.maxSteps = data.side_b_max_steps;
12963
13317
  }
12964
13318
  const sideBSessionStop = toSessionBinding(
12965
- data.side_b_session_stop_tool ?? data.side_b_end_session_tool,
13319
+ data.side_b_session_stop_tool,
12966
13320
  data.side_b_session_stop_message_property,
12967
13321
  data.side_b_session_stop_attachments_property
12968
13322
  );
12969
13323
  if (sideBSessionStop !== void 0) {
12970
13324
  transformed.sideB.sessionStop = sideBSessionStop;
12971
- } else if (data.side_b_end_session_tool) {
12972
- transformed.sideB.endSessionTool = data.side_b_end_session_tool;
12973
13325
  }
12974
13326
  const sideBSessionFail = toSessionBinding(
12975
- data.side_b_session_fail_tool ?? data.side_b_fail_session_tool,
13327
+ data.side_b_session_fail_tool,
12976
13328
  data.side_b_session_fail_message_property,
12977
13329
  data.side_b_session_fail_attachments_property
12978
13330
  );
12979
13331
  if (sideBSessionFail !== void 0) {
12980
13332
  transformed.sideB.sessionFail = sideBSessionFail;
12981
- } else if (data.side_b_fail_session_tool) {
12982
- transformed.sideB.failSessionTool = data.side_b_fail_session_tool;
12983
13333
  }
12984
13334
  const sideBSessionStatus = toSessionBinding(
12985
- data.side_b_session_status_tool ?? data.side_b_status_tool,
13335
+ data.side_b_session_status_tool,
12986
13336
  data.side_b_session_status_message_property,
12987
13337
  data.side_b_session_status_attachments_property
12988
13338
  );
12989
13339
  if (sideBSessionStatus !== void 0) {
12990
13340
  transformed.sideB.sessionStatus = sideBSessionStatus;
12991
- } else if (data.side_b_status_tool) {
12992
- transformed.sideB.statusTool = data.side_b_status_tool;
12993
13341
  }
12994
13342
  if (data.side_b_manual_stop_condition !== void 0) {
12995
13343
  transformed.sideB.manualStopCondition = data.side_b_manual_stop_condition;
@@ -17500,11 +17848,11 @@ export function getVisibleToolNames() {
17500
17848
  import { DurableThread as _BaseDurableThread } from '@standardagents/builder/runtime';
17501
17849
  import { DurableAgentBuilder as _BaseDurableAgentBuilder } from '@standardagents/builder/runtime';
17502
17850
 
17503
- // Import sip WASM module and initializer
17851
+ // Import sip WASM module and readiness helper
17504
17852
  // Static import allows workerd to pre-compile the WASM at bundle time
17505
17853
  // WASM is bundled in builder's dist to avoid transitive dependency resolution issues
17506
17854
  import _sipWasm from '@standardagents/builder/dist/sip.wasm';
17507
- import { initWithWasmModule as _initSipWasm } from '@standardagents/sip';
17855
+ import { ready as _initSipWasm } from '@standardagents/sip';
17508
17856
 
17509
17857
  // Re-export router from virtual:@standardagents-routes
17510
17858
  export { router } from 'virtual:@standardagents-routes';
@@ -17548,7 +17896,7 @@ export class DurableThread extends _BaseDurableThread {
17548
17896
  // blockConcurrencyWhile ensures WASM is ready before handling any requests
17549
17897
  // Pass the statically imported WASM module for workerd to pre-compile
17550
17898
  ctx.blockConcurrencyWhile(async () => {
17551
- await _initSipWasm(_sipWasm);
17899
+ await _initSipWasm({ wasm: _sipWasm });
17552
17900
  });
17553
17901
  }
17554
17902
 
@@ -20717,7 +21065,7 @@ var DurableThread = class extends DurableObject {
20717
21065
  true
20718
21066
  );
20719
21067
  const terminalToolNames = await this.getTerminalSessionToolNames(agentId);
20720
- const failSessionToolNames = terminalToolNames.fail;
21068
+ const sessionFailToolNames = terminalToolNames.fail;
20721
21069
  const hasTerminalSessionTools = terminalToolNames.all.size > 0;
20722
21070
  const latestInRunCursor = await this.ctx.storage.sql.exec(
20723
21071
  `
@@ -20772,7 +21120,7 @@ var DurableThread = class extends DurableObject {
20772
21120
  return { status: "success", result: "Subagent completed." };
20773
21121
  }
20774
21122
  const attachments = hasTerminalSessionTools && !selectedTerminalRow ? void 0 : this.parseAttachmentRefsJson(row.attachments);
20775
- const isFailSessionTerminal = row.role === "tool" && !!row.name && failSessionToolNames.has(row.name);
21123
+ const isFailSessionTerminal = row.role === "tool" && !!row.name && sessionFailToolNames.has(row.name);
20776
21124
  const isSuccessfulTerminalSessionCall = selectedTerminalRow && row.role === "tool" && !!row.name && terminalToolNames.all.has(row.name) && row.tool_status !== "error";
20777
21125
  if (isFailSessionTerminal) {
20778
21126
  await emitParentHandoffStatus("failure");
@@ -21160,7 +21508,7 @@ ${paths.join("\n")}`;
21160
21508
  return;
21161
21509
  }
21162
21510
  const terminalToolNames = await this.getTerminalSessionToolNames(agentName);
21163
- const failSessionToolNames = terminalToolNames.fail;
21511
+ const sessionFailToolNames = terminalToolNames.fail;
21164
21512
  const hasTerminalSessionTools = terminalToolNames.all.size > 0;
21165
21513
  const latest = await this.getLatestTopLevelMessage();
21166
21514
  if (!latest && !hasTerminalSessionTools) {
@@ -21170,7 +21518,7 @@ ${paths.join("\n")}`;
21170
21518
  return;
21171
21519
  }
21172
21520
  const isTerminalSessionMessage = !!latest && latest.role === "tool" && !!latest.name && terminalToolNames.all.has(latest.name);
21173
- const isFailSessionTerminal = isTerminalSessionMessage && !!latest.name && failSessionToolNames.has(latest.name);
21521
+ const isFailSessionTerminal = isTerminalSessionMessage && !!latest.name && sessionFailToolNames.has(latest.name);
21174
21522
  const isSuccessfulTerminalSessionMessage = isTerminalSessionMessage && latest?.tool_status !== "error";
21175
21523
  const isFailureWithoutTerminalMessage = hasTerminalSessionTools && !isSuccessfulTerminalSessionMessage;
21176
21524
  const isErrorTerminal = latest?.tool_status === "error" || isFailSessionTerminal || isFailureWithoutTerminalMessage;
@@ -21728,9 +22076,9 @@ ${resultContent}${attachmentSummary}`;
21728
22076
  `,
21729
22077
  logId
21730
22078
  );
21731
- const row = result.one();
22079
+ const row = result.toArray()[0] ?? null;
21732
22080
  if (!row) {
21733
- throw new Error(`Log not found: ${logId}`);
22081
+ return null;
21734
22082
  }
21735
22083
  let messageHistory = null;
21736
22084
  if (row.request_body) {
@@ -22186,30 +22534,30 @@ ${resultContent}${attachmentSummary}`;
22186
22534
  side_a_stop_tool: agentDef.sideA?.stopTool,
22187
22535
  side_a_stop_tool_response_property: agentDef.sideA?.stopToolResponseProperty,
22188
22536
  side_a_max_steps: agentDef.sideA?.maxSteps,
22189
- side_a_end_session_tool: sideASession.stop.toolName,
22190
- side_a_end_session_message_property: sideASession.stop.messageProperty,
22191
- side_a_end_session_attachments_property: sideASession.stop.attachmentsProperty,
22192
- side_a_fail_session_tool: sideASession.fail.toolName,
22193
- side_a_fail_session_message_property: sideASession.fail.messageProperty,
22194
- side_a_fail_session_attachments_property: sideASession.fail.attachmentsProperty,
22195
- side_a_status_tool: sideASession.status.toolName,
22196
- side_a_status_message_property: sideASession.status.messageProperty,
22197
- side_a_status_attachments_property: sideASession.status.attachmentsProperty,
22537
+ side_a_session_stop_tool: sideASession.stop.toolName,
22538
+ side_a_session_stop_message_property: sideASession.stop.messageProperty,
22539
+ side_a_session_stop_attachments_property: sideASession.stop.attachmentsProperty,
22540
+ side_a_session_fail_tool: sideASession.fail.toolName,
22541
+ side_a_session_fail_message_property: sideASession.fail.messageProperty,
22542
+ side_a_session_fail_attachments_property: sideASession.fail.attachmentsProperty,
22543
+ side_a_session_status_tool: sideASession.status.toolName,
22544
+ side_a_session_status_message_property: sideASession.status.messageProperty,
22545
+ side_a_session_status_attachments_property: sideASession.status.attachmentsProperty,
22198
22546
  side_b_label: agentDef.sideB?.label,
22199
22547
  side_b_agent_prompt: qualifyPromptName(agentDef.sideB?.prompt),
22200
22548
  side_b_stop_on_response: agentDef.sideB?.stopOnResponse ?? false,
22201
22549
  side_b_stop_tool: agentDef.sideB?.stopTool,
22202
22550
  side_b_stop_tool_response_property: agentDef.sideB?.stopToolResponseProperty,
22203
22551
  side_b_max_steps: agentDef.sideB?.maxSteps,
22204
- side_b_end_session_tool: sideBSession.stop.toolName,
22205
- side_b_end_session_message_property: sideBSession.stop.messageProperty,
22206
- side_b_end_session_attachments_property: sideBSession.stop.attachmentsProperty,
22207
- side_b_fail_session_tool: sideBSession.fail.toolName,
22208
- side_b_fail_session_message_property: sideBSession.fail.messageProperty,
22209
- side_b_fail_session_attachments_property: sideBSession.fail.attachmentsProperty,
22210
- side_b_status_tool: sideBSession.status.toolName,
22211
- side_b_status_message_property: sideBSession.status.messageProperty,
22212
- side_b_status_attachments_property: sideBSession.status.attachmentsProperty
22552
+ side_b_session_stop_tool: sideBSession.stop.toolName,
22553
+ side_b_session_stop_message_property: sideBSession.stop.messageProperty,
22554
+ side_b_session_stop_attachments_property: sideBSession.stop.attachmentsProperty,
22555
+ side_b_session_fail_tool: sideBSession.fail.toolName,
22556
+ side_b_session_fail_message_property: sideBSession.fail.messageProperty,
22557
+ side_b_session_fail_attachments_property: sideBSession.fail.attachmentsProperty,
22558
+ side_b_session_status_tool: sideBSession.status.toolName,
22559
+ side_b_session_status_message_property: sideBSession.status.messageProperty,
22560
+ side_b_session_status_attachments_property: sideBSession.status.attachmentsProperty
22213
22561
  };
22214
22562
  const agentBuilderId = this.env.AGENT_BUILDER.idFromName("singleton");
22215
22563
  const agentBuilder = this.env.AGENT_BUILDER.get(agentBuilderId);
@@ -22372,30 +22720,30 @@ ${resultContent}${attachmentSummary}`;
22372
22720
  side_a_stop_tool: agentDef.sideA?.stopTool,
22373
22721
  side_a_stop_tool_response_property: agentDef.sideA?.stopToolResponseProperty,
22374
22722
  side_a_max_steps: agentDef.sideA?.maxSteps,
22375
- side_a_end_session_tool: sideASession.stop.toolName,
22376
- side_a_end_session_message_property: sideASession.stop.messageProperty,
22377
- side_a_end_session_attachments_property: sideASession.stop.attachmentsProperty,
22378
- side_a_fail_session_tool: sideASession.fail.toolName,
22379
- side_a_fail_session_message_property: sideASession.fail.messageProperty,
22380
- side_a_fail_session_attachments_property: sideASession.fail.attachmentsProperty,
22381
- side_a_status_tool: sideASession.status.toolName,
22382
- side_a_status_message_property: sideASession.status.messageProperty,
22383
- side_a_status_attachments_property: sideASession.status.attachmentsProperty,
22723
+ side_a_session_stop_tool: sideASession.stop.toolName,
22724
+ side_a_session_stop_message_property: sideASession.stop.messageProperty,
22725
+ side_a_session_stop_attachments_property: sideASession.stop.attachmentsProperty,
22726
+ side_a_session_fail_tool: sideASession.fail.toolName,
22727
+ side_a_session_fail_message_property: sideASession.fail.messageProperty,
22728
+ side_a_session_fail_attachments_property: sideASession.fail.attachmentsProperty,
22729
+ side_a_session_status_tool: sideASession.status.toolName,
22730
+ side_a_session_status_message_property: sideASession.status.messageProperty,
22731
+ side_a_session_status_attachments_property: sideASession.status.attachmentsProperty,
22384
22732
  side_b_label: agentDef.sideB?.label,
22385
22733
  side_b_agent_prompt: qualifyPromptName(agentDef.sideB?.prompt),
22386
22734
  side_b_stop_on_response: agentDef.sideB?.stopOnResponse ?? false,
22387
22735
  side_b_stop_tool: agentDef.sideB?.stopTool,
22388
22736
  side_b_stop_tool_response_property: agentDef.sideB?.stopToolResponseProperty,
22389
22737
  side_b_max_steps: agentDef.sideB?.maxSteps,
22390
- side_b_end_session_tool: sideBSession.stop.toolName,
22391
- side_b_end_session_message_property: sideBSession.stop.messageProperty,
22392
- side_b_end_session_attachments_property: sideBSession.stop.attachmentsProperty,
22393
- side_b_fail_session_tool: sideBSession.fail.toolName,
22394
- side_b_fail_session_message_property: sideBSession.fail.messageProperty,
22395
- side_b_fail_session_attachments_property: sideBSession.fail.attachmentsProperty,
22396
- side_b_status_tool: sideBSession.status.toolName,
22397
- side_b_status_message_property: sideBSession.status.messageProperty,
22398
- side_b_status_attachments_property: sideBSession.status.attachmentsProperty
22738
+ side_b_session_stop_tool: sideBSession.stop.toolName,
22739
+ side_b_session_stop_message_property: sideBSession.stop.messageProperty,
22740
+ side_b_session_stop_attachments_property: sideBSession.stop.attachmentsProperty,
22741
+ side_b_session_fail_tool: sideBSession.fail.toolName,
22742
+ side_b_session_fail_message_property: sideBSession.fail.messageProperty,
22743
+ side_b_session_fail_attachments_property: sideBSession.fail.attachmentsProperty,
22744
+ side_b_session_status_tool: sideBSession.status.toolName,
22745
+ side_b_session_status_message_property: sideBSession.status.messageProperty,
22746
+ side_b_session_status_attachments_property: sideBSession.status.attachmentsProperty
22399
22747
  };
22400
22748
  const messageId = crypto.randomUUID();
22401
22749
  const timestamp = Date.now() * 1e3;
@@ -22517,30 +22865,30 @@ ${resultContent}${attachmentSummary}`;
22517
22865
  side_a_stop_tool: agentDef.sideA?.stopTool,
22518
22866
  side_a_stop_tool_response_property: agentDef.sideA?.stopToolResponseProperty,
22519
22867
  side_a_max_steps: agentDef.sideA?.maxSteps,
22520
- side_a_end_session_tool: sideASession.stop.toolName,
22521
- side_a_end_session_message_property: sideASession.stop.messageProperty,
22522
- side_a_end_session_attachments_property: sideASession.stop.attachmentsProperty,
22523
- side_a_fail_session_tool: sideASession.fail.toolName,
22524
- side_a_fail_session_message_property: sideASession.fail.messageProperty,
22525
- side_a_fail_session_attachments_property: sideASession.fail.attachmentsProperty,
22526
- side_a_status_tool: sideASession.status.toolName,
22527
- side_a_status_message_property: sideASession.status.messageProperty,
22528
- side_a_status_attachments_property: sideASession.status.attachmentsProperty,
22868
+ side_a_session_stop_tool: sideASession.stop.toolName,
22869
+ side_a_session_stop_message_property: sideASession.stop.messageProperty,
22870
+ side_a_session_stop_attachments_property: sideASession.stop.attachmentsProperty,
22871
+ side_a_session_fail_tool: sideASession.fail.toolName,
22872
+ side_a_session_fail_message_property: sideASession.fail.messageProperty,
22873
+ side_a_session_fail_attachments_property: sideASession.fail.attachmentsProperty,
22874
+ side_a_session_status_tool: sideASession.status.toolName,
22875
+ side_a_session_status_message_property: sideASession.status.messageProperty,
22876
+ side_a_session_status_attachments_property: sideASession.status.attachmentsProperty,
22529
22877
  side_b_label: agentDef.sideB?.label,
22530
22878
  side_b_agent_prompt: qualifyPromptName(agentDef.sideB?.prompt),
22531
22879
  side_b_stop_on_response: agentDef.sideB?.stopOnResponse ?? false,
22532
22880
  side_b_stop_tool: agentDef.sideB?.stopTool,
22533
22881
  side_b_stop_tool_response_property: agentDef.sideB?.stopToolResponseProperty,
22534
22882
  side_b_max_steps: agentDef.sideB?.maxSteps,
22535
- side_b_end_session_tool: sideBSession.stop.toolName,
22536
- side_b_end_session_message_property: sideBSession.stop.messageProperty,
22537
- side_b_end_session_attachments_property: sideBSession.stop.attachmentsProperty,
22538
- side_b_fail_session_tool: sideBSession.fail.toolName,
22539
- side_b_fail_session_message_property: sideBSession.fail.messageProperty,
22540
- side_b_fail_session_attachments_property: sideBSession.fail.attachmentsProperty,
22541
- side_b_status_tool: sideBSession.status.toolName,
22542
- side_b_status_message_property: sideBSession.status.messageProperty,
22543
- side_b_status_attachments_property: sideBSession.status.attachmentsProperty
22883
+ side_b_session_stop_tool: sideBSession.stop.toolName,
22884
+ side_b_session_stop_message_property: sideBSession.stop.messageProperty,
22885
+ side_b_session_stop_attachments_property: sideBSession.stop.attachmentsProperty,
22886
+ side_b_session_fail_tool: sideBSession.fail.toolName,
22887
+ side_b_session_fail_message_property: sideBSession.fail.messageProperty,
22888
+ side_b_session_fail_attachments_property: sideBSession.fail.attachmentsProperty,
22889
+ side_b_session_status_tool: sideBSession.status.toolName,
22890
+ side_b_session_status_message_property: sideBSession.status.messageProperty,
22891
+ side_b_session_status_attachments_property: sideBSession.status.attachmentsProperty
22544
22892
  };
22545
22893
  const { StreamManager: StreamManager2 } = await Promise.resolve().then(() => (init_StreamManager(), StreamManager_exports));
22546
22894
  const stream = new StreamManager2();