steward-cli 0.18.0 → 0.19.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/cli.js CHANGED
@@ -51550,9 +51550,10 @@ function rehydrateSessionHistory(sessionData, projection) {
51550
51550
  textAccum += (textAccum ? `
51551
51551
  ` : "") + part.text;
51552
51552
  } else if (part.type === "tool-call") {
51553
- let parsedInput = part.input ?? {};
51554
- if (typeof part.input === "string") {
51555
- const trimmed = part.input.trim();
51553
+ const rawInput = part.args ?? part.input;
51554
+ let parsedInput = rawInput ?? {};
51555
+ if (typeof rawInput === "string") {
51556
+ const trimmed = rawInput.trim();
51556
51557
  if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
51557
51558
  try {
51558
51559
  parsedInput = JSON.parse(trimmed);
@@ -51584,7 +51585,10 @@ function rehydrateSessionHistory(sessionData, projection) {
51584
51585
  const isError = Boolean(part.isError);
51585
51586
  const toolName = existing?.name ?? part.toolName ?? "tool";
51586
51587
  const argsSummary = existing?.args ? JSON.stringify(existing.args) : "";
51587
- let outputVal = part.output;
51588
+ let outputVal = part.result ?? part.output;
51589
+ if (outputVal && typeof outputVal === "object" && outputVal.type === "json" && "value" in outputVal) {
51590
+ outputVal = outputVal.value;
51591
+ }
51588
51592
  if (typeof outputVal === "string") {
51589
51593
  const trimmed = outputVal.trim();
51590
51594
  if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
@@ -51639,9 +51643,26 @@ import {
51639
51643
  import { dirname as dirname2, join as join2 } from "node:path";
51640
51644
  var MAX_TOOL_OUTPUT_SUMMARY_CHARS = 16000;
51641
51645
  var MAX_TOOL_ERROR_CHARS = 4000;
51642
- var STATUS_VERBS = ["Baked", "Brewed", "Churned", "Swooped", "Crafted", "Cooked"];
51646
+ var STATUS_VERBS = [
51647
+ "Forged",
51648
+ "Synthesized",
51649
+ "Crafted",
51650
+ "Hacked",
51651
+ "Refactored",
51652
+ "Cooked",
51653
+ "Brewed",
51654
+ "Compiled",
51655
+ "Marshaled",
51656
+ "Orchestrated",
51657
+ "Assembled",
51658
+ "Dispatched",
51659
+ "Iterated",
51660
+ "Shipped",
51661
+ "Polished",
51662
+ "Engineered"
51663
+ ];
51643
51664
  function chooseTurnStatusVerb() {
51644
- return STATUS_VERBS[Math.floor(Math.random() * STATUS_VERBS.length)] ?? "Baked";
51665
+ return STATUS_VERBS[Math.floor(Math.random() * STATUS_VERBS.length)] ?? "Engineered";
51645
51666
  }
51646
51667
  function getSessionLogsRootDir() {
51647
51668
  return join2(dirname2(getSessionsRootDir()), "session-logs");
@@ -52146,14 +52167,15 @@ class MutationLockManager {
52146
52167
  releaseCurrent = resolve;
52147
52168
  });
52148
52169
  const previousLock = this.locks.get(canonicalPath) ?? Promise.resolve();
52149
- this.locks.set(canonicalPath, previousLock.then(() => currentLock, () => currentLock));
52170
+ const chainedTail = previousLock.then(() => currentLock, () => currentLock);
52171
+ this.locks.set(canonicalPath, chainedTail);
52150
52172
  await previousLock;
52151
52173
  let released = false;
52152
52174
  return () => {
52153
52175
  if (!released) {
52154
52176
  released = true;
52155
52177
  releaseCurrent();
52156
- if (this.locks.get(canonicalPath) === currentLock) {
52178
+ if (this.locks.get(canonicalPath) === chainedTail) {
52157
52179
  this.locks.delete(canonicalPath);
52158
52180
  }
52159
52181
  }
@@ -52770,7 +52792,6 @@ async function executeRewind(options) {
52770
52792
  manifest.turns = manifest.turns.filter((t) => keptTurns.some((kt) => kt.id === t.turnId));
52771
52793
  await saveCheckpointManifest(workspaceHash, session.id, manifest);
52772
52794
  }
52773
- rewindJournal.phase = "session-committed";
52774
52795
  await deletePendingJournal(workspaceHash, session.id);
52775
52796
  return {
52776
52797
  success: true,
@@ -69750,7 +69771,12 @@ class ToolCatalog {
69750
69771
  const modeLabel = MODES[mode]?.label ?? mode;
69751
69772
  throw new Error(`Tool "${name}" is not available in ${modeLabel} mode.`);
69752
69773
  }
69753
- return def.execute(args, context);
69774
+ try {
69775
+ return await def.execute(args, context);
69776
+ } catch (err) {
69777
+ const msg = err instanceof Error ? err.message : String(err);
69778
+ throw new Error(msg || `Tool execution failed for "${name}".`);
69779
+ }
69754
69780
  }
69755
69781
  });
69756
69782
  }
@@ -70762,6 +70788,24 @@ function getPlatformShell() {
70762
70788
  var MAX_OUTPUT_BYTES = 5 * 1024 * 1024;
70763
70789
  var MAX_MEMORY_BUFFER_BYTES = 500 * 1024;
70764
70790
  var DEFAULT_HANDOFF_DEADLINE_MS = 12000;
70791
+ var PROVIDER_SECRET_ENV_KEYS = [
70792
+ "ANTHROPIC_API_KEY",
70793
+ "GEMINI_API_KEY",
70794
+ "GOOGLE_GENERATIVE_AI_API_KEY",
70795
+ "OPENAI_API_KEY",
70796
+ "XAI_API_KEY",
70797
+ "MISTRAL_API_KEY",
70798
+ "DEEPSEEK_API_KEY",
70799
+ "OPENROUTER_API_KEY",
70800
+ "CUSTOM_API_KEY"
70801
+ ];
70802
+ function getFilteredChildEnv() {
70803
+ const env = { ...process.env };
70804
+ for (const key of PROVIDER_SECRET_ENV_KEYS) {
70805
+ delete env[key];
70806
+ }
70807
+ return env;
70808
+ }
70765
70809
 
70766
70810
  class ShellExecution {
70767
70811
  taskId;
@@ -70833,7 +70877,7 @@ class ShellExecution {
70833
70877
  }
70834
70878
  const child = spawn(shell, childArgs, {
70835
70879
  cwd: this.cwd,
70836
- env: { ...process.env },
70880
+ env: getFilteredChildEnv(),
70837
70881
  stdio: ["pipe", "pipe", "pipe"],
70838
70882
  detached: process.platform !== "win32"
70839
70883
  });
@@ -71066,6 +71110,40 @@ Process error: ${err.message}
71066
71110
  }
71067
71111
 
71068
71112
  // src/packages/agents/src/tools/bash/command-policy.ts
71113
+ import { existsSync as existsSync13, realpathSync as realpathSync4 } from "node:fs";
71114
+ import { homedir as homedir5 } from "node:os";
71115
+ import { isAbsolute as isAbsolute6, resolve as resolve9, sep as sep4 } from "node:path";
71116
+ function expandHome(filepath) {
71117
+ if (filepath === "~") {
71118
+ return homedir5();
71119
+ }
71120
+ if (filepath.startsWith("~/") || filepath.startsWith("~\\")) {
71121
+ return resolve9(homedir5(), filepath.slice(2));
71122
+ }
71123
+ return filepath;
71124
+ }
71125
+ function normalizeRoot(inputPath) {
71126
+ let absolute = resolve9(inputPath);
71127
+ try {
71128
+ absolute = realpathSync4(absolute);
71129
+ } catch {}
71130
+ if (absolute.length > 1 && absolute.endsWith(sep4)) {
71131
+ absolute = absolute.slice(0, -1);
71132
+ }
71133
+ if (process.platform === "darwin" || process.platform === "win32") {
71134
+ return absolute.toLowerCase();
71135
+ }
71136
+ return absolute;
71137
+ }
71138
+ function isContainedInWorkspace(targetPath, workspaceRoot) {
71139
+ const normTarget = normalizeRoot(targetPath);
71140
+ const normBase = normalizeRoot(workspaceRoot);
71141
+ if (normTarget === normBase) {
71142
+ return true;
71143
+ }
71144
+ const prefix = normBase.endsWith(sep4) ? normBase : `${normBase}${sep4}`;
71145
+ return normTarget.startsWith(prefix);
71146
+ }
71069
71147
  var SAFE_EXACT_STANDALONE = new Set([
71070
71148
  "pwd",
71071
71149
  "whoami",
@@ -71173,7 +71251,31 @@ function parseTokens(cmd) {
71173
71251
  }
71174
71252
  return tokens;
71175
71253
  }
71176
- function isStrictlyReadOnlyCommand(tokens) {
71254
+ function arePathTokensInsideWorkspace(tokens, startIndex, cwd) {
71255
+ for (let i = startIndex;i < tokens.length; i++) {
71256
+ const tok = tokens[i];
71257
+ if (tok.startsWith("-")) {
71258
+ continue;
71259
+ }
71260
+ const expanded = expandHome(tok);
71261
+ const resolved = isAbsolute6(expanded) ? resolve9(expanded) : resolve9(cwd, expanded);
71262
+ if (!isContainedInWorkspace(resolved, cwd)) {
71263
+ return false;
71264
+ }
71265
+ if (existsSync13(resolved)) {
71266
+ try {
71267
+ const real = realpathSync4(resolved);
71268
+ if (!isContainedInWorkspace(real, cwd)) {
71269
+ return false;
71270
+ }
71271
+ } catch {
71272
+ return false;
71273
+ }
71274
+ }
71275
+ }
71276
+ return true;
71277
+ }
71278
+ function isStrictlyReadOnlyCommand(tokens, cwd) {
71177
71279
  if (tokens.length === 0)
71178
71280
  return true;
71179
71281
  const exe = tokens[0].toLowerCase();
@@ -71208,15 +71310,30 @@ function isStrictlyReadOnlyCommand(tokens) {
71208
71310
  return false;
71209
71311
  }
71210
71312
  }
71313
+ if (cwd && !arePathTokensInsideWorkspace(tokens, 2, cwd)) {
71314
+ return false;
71315
+ }
71211
71316
  return true;
71212
71317
  }
71213
71318
  if (exe === "ls") {
71319
+ if (cwd && !arePathTokensInsideWorkspace(tokens, 1, cwd)) {
71320
+ return false;
71321
+ }
71214
71322
  return true;
71215
71323
  }
71216
71324
  if (exe === "echo" || exe === "printf") {
71217
71325
  return true;
71218
71326
  }
71219
71327
  if (exe === "head" || exe === "tail" || exe === "wc") {
71328
+ for (let i = 1;i < tokens.length; i++) {
71329
+ const tok = tokens[i];
71330
+ if (tok === "-f" || tok === "--follow") {
71331
+ return false;
71332
+ }
71333
+ }
71334
+ if (cwd && !arePathTokensInsideWorkspace(tokens, 1, cwd)) {
71335
+ return false;
71336
+ }
71220
71337
  return true;
71221
71338
  }
71222
71339
  if (exe === "cat") {
@@ -71228,6 +71345,9 @@ function isStrictlyReadOnlyCommand(tokens) {
71228
71345
  }
71229
71346
  }
71230
71347
  }
71348
+ if (cwd && !arePathTokensInsideWorkspace(tokens, 1, cwd)) {
71349
+ return false;
71350
+ }
71231
71351
  return true;
71232
71352
  }
71233
71353
  if (exe === "grep") {
@@ -71237,6 +71357,9 @@ function isStrictlyReadOnlyCommand(tokens) {
71237
71357
  return false;
71238
71358
  }
71239
71359
  }
71360
+ if (cwd && !arePathTokensInsideWorkspace(tokens, 1, cwd)) {
71361
+ return false;
71362
+ }
71240
71363
  return true;
71241
71364
  }
71242
71365
  if (exe === "rg") {
@@ -71246,6 +71369,9 @@ function isStrictlyReadOnlyCommand(tokens) {
71246
71369
  return false;
71247
71370
  }
71248
71371
  }
71372
+ if (cwd && !arePathTokensInsideWorkspace(tokens, 1, cwd)) {
71373
+ return false;
71374
+ }
71249
71375
  return true;
71250
71376
  }
71251
71377
  if (exe === "find") {
@@ -71255,11 +71381,14 @@ function isStrictlyReadOnlyCommand(tokens) {
71255
71381
  return false;
71256
71382
  }
71257
71383
  }
71384
+ if (cwd && !arePathTokensInsideWorkspace(tokens, 1, cwd)) {
71385
+ return false;
71386
+ }
71258
71387
  return true;
71259
71388
  }
71260
71389
  return false;
71261
71390
  }
71262
- function classifySingleSegment(segment) {
71391
+ function classifySingleSegment(segment, cwd) {
71263
71392
  const trimmed = segment.trim();
71264
71393
  if (!trimmed)
71265
71394
  return "SAFE_READ_ONLY";
@@ -71269,12 +71398,12 @@ function classifySingleSegment(segment) {
71269
71398
  const tokens = parseTokens(trimmed);
71270
71399
  if (tokens.length === 0)
71271
71400
  return "SAFE_READ_ONLY";
71272
- if (isStrictlyReadOnlyCommand(tokens)) {
71401
+ if (isStrictlyReadOnlyCommand(tokens, cwd)) {
71273
71402
  return "SAFE_READ_ONLY";
71274
71403
  }
71275
71404
  return "REQUIRES_APPROVAL";
71276
71405
  }
71277
- function classifyCommand(command) {
71406
+ function classifyCommand(command, cwd) {
71278
71407
  const trimmed = command.trim();
71279
71408
  if (!trimmed)
71280
71409
  return "SAFE_READ_ONLY";
@@ -71282,7 +71411,7 @@ function classifyCommand(command) {
71282
71411
  if (segments.length === 0)
71283
71412
  return "SAFE_READ_ONLY";
71284
71413
  for (const seg of segments) {
71285
- const decision = classifySingleSegment(seg);
71414
+ const decision = classifySingleSegment(seg, cwd);
71286
71415
  if (decision !== "SAFE_READ_ONLY") {
71287
71416
  return decision;
71288
71417
  }
@@ -71292,7 +71421,7 @@ function classifyCommand(command) {
71292
71421
 
71293
71422
  // src/packages/agents/src/tools/bash/permissions.ts
71294
71423
  async function evaluateBashPermission(req, context) {
71295
- const policy = classifyCommand(req.command);
71424
+ const policy = classifyCommand(req.command, context.cwd);
71296
71425
  if (policy === "SAFE_READ_ONLY") {
71297
71426
  return { allowed: true };
71298
71427
  }
@@ -71496,10 +71625,14 @@ var taskListTool = {
71496
71625
  };
71497
71626
  }
71498
71627
  };
71628
+
71629
+ // src/packages/agents/src/tools/web-fetch/index.ts
71630
+ import { lookup } from "node:dns/promises";
71631
+ import { isIP } from "node:net";
71499
71632
  // package.json
71500
71633
  var package_default = {
71501
71634
  name: "steward-cli",
71502
- version: "0.18.0",
71635
+ version: "0.19.0",
71503
71636
  description: "Interactive AI engineering assistant for the terminal with human-in-the-loop control across local and frontier models.",
71504
71637
  author: "sapirrior",
71505
71638
  license: "MIT",
@@ -71529,7 +71662,7 @@ var package_default = {
71529
71662
  "@ai-sdk/mistral": "4.0.43",
71530
71663
  "@ai-sdk/openai": "4.0.65",
71531
71664
  "@ai-sdk/openai-compatible": "3.0.47",
71532
- "@ai-sdk/xai": "4.0.58",
71665
+ "@ai-sdk/xai": "5.0.5",
71533
71666
  ai: "7.0.97",
71534
71667
  chalk: "6.0.0",
71535
71668
  "cli-highlight": "2.1.11",
@@ -71547,6 +71680,103 @@ var package_default = {
71547
71680
 
71548
71681
  // src/packages/agents/src/tools/web-fetch/index.ts
71549
71682
  var VERSION4 = package_default.version || "0.0.0";
71683
+ var MAX_FETCH_BYTES = 2 * 1024 * 1024;
71684
+ var MAX_REDIRECTS = 3;
71685
+ function isPrivateOrReservedIPv4(ip) {
71686
+ const parts = ip.split(".").map(Number);
71687
+ if (parts.length !== 4 || parts.some((p) => isNaN(p) || p < 0 || p > 255)) {
71688
+ return true;
71689
+ }
71690
+ const [b0, b1] = parts;
71691
+ if (b0 === 0)
71692
+ return true;
71693
+ if (b0 === 10)
71694
+ return true;
71695
+ if (b0 === 127)
71696
+ return true;
71697
+ if (b0 === 169 && b1 === 254)
71698
+ return true;
71699
+ if (b0 === 172 && b1 !== undefined && b1 >= 16 && b1 <= 31)
71700
+ return true;
71701
+ if (b0 === 192 && b1 === 168)
71702
+ return true;
71703
+ if (b0 === 192 && b1 === 0)
71704
+ return true;
71705
+ if (b0 === 198 && (b1 === 18 || b1 === 19))
71706
+ return true;
71707
+ if (b0 === 100 && b1 !== undefined && b1 >= 64 && b1 <= 127)
71708
+ return true;
71709
+ if (b0 !== undefined && b0 >= 224)
71710
+ return true;
71711
+ return false;
71712
+ }
71713
+ function isPrivateOrReservedIPv6(ip) {
71714
+ const normalized = ip.toLowerCase();
71715
+ if (normalized === "::" || normalized === "::1")
71716
+ return true;
71717
+ if (normalized.startsWith("::ffff:")) {
71718
+ const ipv4 = normalized.slice(7);
71719
+ return isPrivateOrReservedIPv4(ipv4);
71720
+ }
71721
+ if (normalized.startsWith("fe80:") || normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb")) {
71722
+ return true;
71723
+ }
71724
+ if (normalized.startsWith("fc") || normalized.startsWith("fd")) {
71725
+ return true;
71726
+ }
71727
+ if (normalized.startsWith("ff")) {
71728
+ return true;
71729
+ }
71730
+ return false;
71731
+ }
71732
+ function isPrivateIP(ip) {
71733
+ const version = isIP(ip);
71734
+ if (version === 4) {
71735
+ return isPrivateOrReservedIPv4(ip);
71736
+ }
71737
+ if (version === 6) {
71738
+ return isPrivateOrReservedIPv6(ip);
71739
+ }
71740
+ return true;
71741
+ }
71742
+ async function validateSafeUrl(urlStr) {
71743
+ let parsed;
71744
+ try {
71745
+ parsed = new URL(urlStr);
71746
+ } catch {
71747
+ throw new Error(`Invalid URL format: "${urlStr}"`);
71748
+ }
71749
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
71750
+ throw new Error(`Forbidden protocol: "${parsed.protocol}". Only HTTP and HTTPS are allowed.`);
71751
+ }
71752
+ const hostname = parsed.hostname;
71753
+ if (!hostname || hostname === "localhost" || hostname.endsWith(".local") || hostname.endsWith(".internal")) {
71754
+ throw new Error(`Access to local or private host "${hostname}" is blocked for security.`);
71755
+ }
71756
+ if (isIP(hostname)) {
71757
+ if (isPrivateIP(hostname)) {
71758
+ throw new Error(`Access to private/local IP address "${hostname}" is blocked for security.`);
71759
+ }
71760
+ return parsed;
71761
+ }
71762
+ try {
71763
+ const addresses = await lookup(hostname, { all: true });
71764
+ if (!addresses || addresses.length === 0) {
71765
+ throw new Error(`Could not resolve hostname "${hostname}".`);
71766
+ }
71767
+ for (const addr of addresses) {
71768
+ if (isPrivateIP(addr.address)) {
71769
+ throw new Error(`Access to host "${hostname}" is blocked because it resolves to private IP (${addr.address}).`);
71770
+ }
71771
+ }
71772
+ } catch (err) {
71773
+ if (err.message && err.message.includes("blocked because it resolves")) {
71774
+ throw err;
71775
+ }
71776
+ throw new Error(`DNS resolution failed for "${hostname}": ${err.message || String(err)}`);
71777
+ }
71778
+ return parsed;
71779
+ }
71550
71780
  var webFetchInputSchema = object({
71551
71781
  url: string2().url().describe("The HTTP or HTTPS URL to fetch content from."),
71552
71782
  maxCharacters: number2().int().min(500).max(50000).optional().describe("Maximum number of characters to extract from the content. Defaults to 12000.")
@@ -71558,6 +71788,35 @@ function cleanHtmlContent(html) {
71558
71788
 
71559
71789
  `).trim();
71560
71790
  }
71791
+ async function fetchWithSsrfProtection(initialUrl, signal) {
71792
+ let currentUrl = initialUrl;
71793
+ let redirects = 0;
71794
+ while (redirects <= MAX_REDIRECTS) {
71795
+ const validatedUrl = await validateSafeUrl(currentUrl);
71796
+ const response = await fetch(validatedUrl.toString(), {
71797
+ method: "GET",
71798
+ headers: {
71799
+ "User-Agent": `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 (steward-agent/${VERSION4}; +https://github.com/sapirrior/steward)`,
71800
+ Accept: "text/html,application/xhtml+xml,application/json,text/plain;q=0.9,*/*;q=0.8",
71801
+ "Accept-Language": "en-US,en;q=0.9"
71802
+ },
71803
+ redirect: "manual",
71804
+ signal
71805
+ });
71806
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
71807
+ const location = response.headers.get("location");
71808
+ if (!location) {
71809
+ throw new Error(`Redirect response (${response.status}) missing Location header.`);
71810
+ }
71811
+ const nextUrl = new URL(location, validatedUrl).toString();
71812
+ currentUrl = nextUrl;
71813
+ redirects++;
71814
+ continue;
71815
+ }
71816
+ return { response, finalUrl: currentUrl };
71817
+ }
71818
+ throw new Error(`Too many redirects (exceeded limit of ${MAX_REDIRECTS}).`);
71819
+ }
71561
71820
  var webFetchTool = {
71562
71821
  name: "web_fetch",
71563
71822
  displayName: "Web",
@@ -71582,20 +71841,35 @@ var webFetchTool = {
71582
71841
  const maxChars = args.maxCharacters ?? 12000;
71583
71842
  const timeoutSignal = AbortSignal.timeout(15000);
71584
71843
  const signal = context.abortSignal ? AbortSignal.any([context.abortSignal, timeoutSignal]) : timeoutSignal;
71585
- const response = await fetch(args.url, {
71586
- method: "GET",
71587
- headers: {
71588
- "User-Agent": `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 (steward-agent/${VERSION4}; +https://github.com/sapirrior/steward)`,
71589
- Accept: "text/html,application/xhtml+xml,application/json,text/plain;q=0.9,*/*;q=0.8",
71590
- "Accept-Language": "en-US,en;q=0.9"
71591
- },
71592
- signal
71593
- });
71844
+ const { response, finalUrl } = await fetchWithSsrfProtection(args.url, signal);
71594
71845
  if (!response.ok) {
71595
71846
  throw new Error(`HTTP fetch failed with status ${response.status} (${response.statusText})`);
71596
71847
  }
71597
71848
  const contentType = response.headers.get("content-type") || "text/plain";
71598
- const rawText = await response.text();
71849
+ let rawText;
71850
+ if (response.body) {
71851
+ const reader = response.body.getReader();
71852
+ const chunks = [];
71853
+ let totalBytes = 0;
71854
+ while (true) {
71855
+ const { done, value } = await reader.read();
71856
+ if (done)
71857
+ break;
71858
+ if (value) {
71859
+ totalBytes += value.byteLength;
71860
+ if (totalBytes > MAX_FETCH_BYTES) {
71861
+ chunks.push(value.slice(0, value.byteLength - (totalBytes - MAX_FETCH_BYTES)));
71862
+ await reader.cancel();
71863
+ break;
71864
+ }
71865
+ chunks.push(value);
71866
+ }
71867
+ }
71868
+ const decoder = new TextDecoder("utf-8");
71869
+ rawText = chunks.map((c) => decoder.decode(c, { stream: true })).join("") + decoder.decode();
71870
+ } else {
71871
+ rawText = await response.text();
71872
+ }
71599
71873
  let cleanText;
71600
71874
  if (contentType.includes("text/html") || rawText.includes("<html")) {
71601
71875
  cleanText = cleanHtmlContent(rawText);
@@ -71607,7 +71881,7 @@ var webFetchTool = {
71607
71881
 
71608
71882
  [...content truncated]` : cleanText;
71609
71883
  return {
71610
- url: args.url,
71884
+ url: finalUrl,
71611
71885
  status: response.status,
71612
71886
  contentType,
71613
71887
  content,
@@ -71720,7 +71994,7 @@ var webSearchTool = {
71720
71994
  };
71721
71995
  // src/packages/services/src/todos/store.ts
71722
71996
  import {
71723
- existsSync as existsSync13,
71997
+ existsSync as existsSync14,
71724
71998
  mkdirSync as mkdirSync9,
71725
71999
  readFileSync as readFileSync12,
71726
72000
  renameSync as renameSync6,
@@ -71734,13 +72008,13 @@ import { join as join13 } from "node:path";
71734
72008
  import { randomUUID as randomUUID6 } from "node:crypto";
71735
72009
 
71736
72010
  // src/packages/services/src/paths.ts
71737
- import { homedir as homedir5 } from "node:os";
72011
+ import { homedir as homedir6 } from "node:os";
71738
72012
  import { dirname as dirname6, join as join12 } from "node:path";
71739
72013
  function getStewardHomeDir() {
71740
72014
  if (process.env.STEWARD_SETTINGS_DIR) {
71741
72015
  return process.env.STEWARD_SETTINGS_DIR;
71742
72016
  }
71743
- return join12(homedir5(), ".steward");
72017
+ return join12(homedir6(), ".steward");
71744
72018
  }
71745
72019
  function getSettingsDir2() {
71746
72020
  if (process.env.STEWARD_SETTINGS_DIR) {
@@ -71850,7 +72124,7 @@ function validateTodoList(todos) {
71850
72124
  }
71851
72125
  async function readTodoList(sessionId) {
71852
72126
  const filePath = getSessionTodosFilePath(sessionId);
71853
- if (!existsSync13(filePath)) {
72127
+ if (!existsSync14(filePath)) {
71854
72128
  return null;
71855
72129
  }
71856
72130
  const raw = readFileSync12(filePath, "utf-8");
@@ -71883,7 +72157,7 @@ async function writeTodoList(sessionId, todos) {
71883
72157
  const validated = validateTodoList(todos);
71884
72158
  const safeSessionId = sanitizeSessionId(sessionId);
71885
72159
  const dir = getSessionTodosDir(safeSessionId);
71886
- if (!existsSync13(dir)) {
72160
+ if (!existsSync14(dir)) {
71887
72161
  mkdirSync9(dir, { recursive: true, mode: 448 });
71888
72162
  }
71889
72163
  const payload = {
@@ -71907,7 +72181,7 @@ async function writeTodoList(sessionId, todos) {
71907
72181
  renameSync6(tempPath, targetPath);
71908
72182
  } catch (err) {
71909
72183
  try {
71910
- if (existsSync13(tempPath)) {
72184
+ if (existsSync14(tempPath)) {
71911
72185
  unlinkSync6(tempPath);
71912
72186
  }
71913
72187
  } catch {}
@@ -71952,7 +72226,7 @@ async function updateTodoItem(sessionId, todoId, updates) {
71952
72226
  const validated = validateTodoList(updatedTodos);
71953
72227
  const safeSessionId = sanitizeSessionId(sessionId);
71954
72228
  const dir = getSessionTodosDir(safeSessionId);
71955
- if (!existsSync13(dir)) {
72229
+ if (!existsSync14(dir)) {
71956
72230
  mkdirSync9(dir, { recursive: true, mode: 448 });
71957
72231
  }
71958
72232
  const payload = {
@@ -71976,7 +72250,7 @@ async function updateTodoItem(sessionId, todoId, updates) {
71976
72250
  renameSync6(tempPath, targetPath);
71977
72251
  } catch (err) {
71978
72252
  try {
71979
- if (existsSync13(tempPath)) {
72253
+ if (existsSync14(tempPath)) {
71980
72254
  unlinkSync6(tempPath);
71981
72255
  }
71982
72256
  } catch {}
@@ -72012,9 +72286,24 @@ function formatTodoCheckbox(status) {
72012
72286
  function formatTodoListSummary(todos, maxItems = 10) {
72013
72287
  const visible = todos.slice(0, maxItems);
72014
72288
  const hiddenCount = todos.length - visible.length;
72015
- const lines = visible.map((t, i) => `${i + 1}. ${formatTodoCheckbox(t.status)} ${t.description}`);
72289
+ const lines = visible.map((t, i) => {
72290
+ const raw = `${i + 1}. ${formatTodoCheckbox(t.status)} ${t.description}`;
72291
+ if (t.status === "completed") {
72292
+ return strikethrough(c.muted(raw));
72293
+ }
72294
+ if (t.status === "in_progress") {
72295
+ return bold(c.text(raw));
72296
+ }
72297
+ if (t.status === "cancelled") {
72298
+ return strikethrough(c.muted(raw));
72299
+ }
72300
+ if (t.status === "blocked") {
72301
+ return c.warning(raw);
72302
+ }
72303
+ return c.text(raw);
72304
+ });
72016
72305
  if (hiddenCount > 0) {
72017
- lines.push(`… and ${hiddenCount} more`);
72306
+ lines.push(c.muted(`… and ${hiddenCount} more`));
72018
72307
  }
72019
72308
  return lines.join(`
72020
72309
  `);
@@ -72029,10 +72318,8 @@ var todoWriteTool = {
72029
72318
  summarizeArgs(args) {
72030
72319
  if (!args.todos || args.todos.length === 0)
72031
72320
  return "";
72032
- if (args.todos.length <= 2) {
72033
- return args.todos.map((t) => `"${t.description}"`).join(", ");
72034
- }
72035
- return `"${args.todos[0]?.description}", "${args.todos[1]?.description}", +${args.todos.length - 2} more`;
72321
+ const count = args.todos.length;
72322
+ return `${count} items`;
72036
72323
  },
72037
72324
  async execute(args, context) {
72038
72325
  if (!context.sessionId) {
@@ -72045,8 +72332,7 @@ var todoWriteTool = {
72045
72332
  const total = list.length;
72046
72333
  const header = `Added ${total} todos`;
72047
72334
  const details = formatTodoListSummary(list);
72048
- return `${header}
72049
- ${details}`;
72335
+ return { headline: header, detail: { kind: "pre-styled", text: details } };
72050
72336
  }
72051
72337
  };
72052
72338
 
@@ -72074,9 +72360,24 @@ function formatTodoCheckbox2(status) {
72074
72360
  function formatTodoListSummary2(todos, maxItems = 10) {
72075
72361
  const visible = todos.slice(0, maxItems);
72076
72362
  const hiddenCount = todos.length - visible.length;
72077
- const lines = visible.map((t, i) => `${i + 1}. ${formatTodoCheckbox2(t.status)} ${t.description}`);
72363
+ const lines = visible.map((t, i) => {
72364
+ const raw = `${i + 1}. ${formatTodoCheckbox2(t.status)} ${t.description}`;
72365
+ if (t.status === "completed") {
72366
+ return strikethrough(c.muted(raw));
72367
+ }
72368
+ if (t.status === "in_progress") {
72369
+ return bold(c.text(raw));
72370
+ }
72371
+ if (t.status === "cancelled") {
72372
+ return strikethrough(c.muted(raw));
72373
+ }
72374
+ if (t.status === "blocked") {
72375
+ return c.warning(raw);
72376
+ }
72377
+ return c.text(raw);
72378
+ });
72078
72379
  if (hiddenCount > 0) {
72079
- lines.push(`… and ${hiddenCount} more`);
72380
+ lines.push(c.muted(`… and ${hiddenCount} more`));
72080
72381
  }
72081
72382
  return lines.join(`
72082
72383
  `);
@@ -72089,12 +72390,11 @@ var todoUpdateTool = {
72089
72390
  description: "Updates a single todo item status or description in the current session. Cannot create new items or update multiple items at once.",
72090
72391
  parameters: todoUpdateParamsSchema,
72091
72392
  summarizeArgs(args) {
72092
- const parts = [`id: "${args.id}"`];
72093
72393
  if (args.status)
72094
- parts.push(`status: "${args.status}"`);
72095
- if (args.description)
72096
- parts.push(`desc: "${args.description}"`);
72097
- return parts.join(", ");
72394
+ return args.status;
72395
+ if (args.id)
72396
+ return args.id;
72397
+ return "";
72098
72398
  },
72099
72399
  async execute(args, context) {
72100
72400
  if (!context.sessionId) {
@@ -72106,17 +72406,23 @@ var todoUpdateTool = {
72106
72406
  });
72107
72407
  },
72108
72408
  summarize(args, result) {
72109
- if (!result || !result.todos) {
72409
+ let resolved = result;
72410
+ if (typeof resolved === "string") {
72411
+ try {
72412
+ resolved = JSON.parse(resolved);
72413
+ } catch {}
72414
+ }
72415
+ if (!resolved || !resolved.todos) {
72110
72416
  return `Todo ${args.id} updated`;
72111
72417
  }
72112
- const total = result.todos.length;
72113
- const completed = result.todos.filter((t) => t.status === "completed").length;
72114
- const updatedItem = result.todos.find((t) => t.id === args.id);
72418
+ const result2 = resolved;
72419
+ const total = result2.todos.length;
72420
+ const completed = result2.todos.filter((t) => t.status === "completed").length;
72421
+ const updatedItem = result2.todos.find((t) => t.id === args.id);
72115
72422
  const statusText = updatedItem?.status ?? args.status ?? "updated";
72116
72423
  const header = `Todo ${args.id} ${statusText} · ${completed}/${total} done`;
72117
- const details = formatTodoListSummary2(result.todos);
72118
- return `${header}
72119
- ${details}`;
72424
+ const details = formatTodoListSummary2(result2.todos);
72425
+ return { headline: header, detail: { kind: "pre-styled", text: details } };
72120
72426
  }
72121
72427
  };
72122
72428
 
@@ -72140,9 +72446,20 @@ function formatTodoCheckbox3(status) {
72140
72446
  function formatTodoListSummary3(todos, maxItems = 10) {
72141
72447
  const visible = todos.slice(0, maxItems);
72142
72448
  const hiddenCount = todos.length - visible.length;
72143
- const lines = visible.map((t, i) => `${i + 1}. ${formatTodoCheckbox3(t.status)} ${t.description}`);
72449
+ const lines = visible.map((t, i) => {
72450
+ const raw = `${i + 1}. ${formatTodoCheckbox3(t.status)} ${t.description}`;
72451
+ if (t.status === "completed")
72452
+ return strikethrough(c.muted(raw));
72453
+ if (t.status === "in_progress")
72454
+ return bold(c.text(raw));
72455
+ if (t.status === "cancelled")
72456
+ return strikethrough(c.muted(raw));
72457
+ if (t.status === "blocked")
72458
+ return c.warning(raw);
72459
+ return c.text(raw);
72460
+ });
72144
72461
  if (hiddenCount > 0) {
72145
- lines.push(`… and ${hiddenCount} more`);
72462
+ lines.push(c.muted(`… and ${hiddenCount} more`));
72146
72463
  }
72147
72464
  return lines.join(`
72148
72465
  `);
@@ -72176,22 +72493,28 @@ var todoReadTool = {
72176
72493
  };
72177
72494
  },
72178
72495
  summarize(_args, result) {
72179
- if (!result || !result.hasTodos || result.todos.length === 0) {
72496
+ let resolved = result ?? null;
72497
+ if (typeof resolved === "string") {
72498
+ try {
72499
+ resolved = JSON.parse(resolved);
72500
+ } catch {}
72501
+ }
72502
+ const todos = resolved && Array.isArray(resolved.todos) ? resolved.todos : undefined;
72503
+ if (!todos || todos.length === 0) {
72180
72504
  return "No active todos";
72181
72505
  }
72182
- const total = result.todos.length;
72183
- const completed = result.todos.filter((t) => t.status === "completed").length;
72184
- const active = result.todos.find((t) => t.status === "in_progress");
72506
+ const total = todos.length;
72507
+ const completed = todos.filter((t) => t.status === "completed").length;
72508
+ const active = todos.find((t) => t.status === "in_progress");
72185
72509
  const header = active ? `Todos ${completed}/${total} done · ▶ ${active.description}` : `Todos ${completed}/${total} done`;
72186
- const details = formatTodoListSummary3(result.todos);
72187
- return `${header}
72188
- ${details}`;
72510
+ const details = formatTodoListSummary3(todos);
72511
+ return { headline: header, detail: { kind: "pre-styled", text: details } };
72189
72512
  }
72190
72513
  };
72191
72514
  // src/packages/agents/src/skills/discovery.ts
72192
- import { existsSync as existsSync14, readdirSync as readdirSync5, readFileSync as readFileSync13, statSync as statSync6 } from "node:fs";
72193
- import { homedir as homedir6 } from "node:os";
72194
- import { isAbsolute as isAbsolute6, join as join14, normalize, resolve as resolve9, sep as sep4 } from "node:path";
72515
+ import { existsSync as existsSync15, readdirSync as readdirSync5, readFileSync as readFileSync13, statSync as statSync6 } from "node:fs";
72516
+ import { homedir as homedir7 } from "node:os";
72517
+ import { isAbsolute as isAbsolute7, join as join14, normalize, resolve as resolve10, sep as sep5 } from "node:path";
72195
72518
  var MAX_SKILL_FILE_SIZE = 64 * 1024;
72196
72519
  function parseSkillFrontmatter(content) {
72197
72520
  const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
@@ -72245,12 +72568,12 @@ function unquote(str) {
72245
72568
  function discoverSkills(cwd = process.cwd()) {
72246
72569
  const targets = [
72247
72570
  { dir: join14(cwd, ".agents", "skills"), source: "workspace" },
72248
- { dir: join14(homedir6(), ".agents", "skills"), source: "user-agents" },
72249
- { dir: join14(homedir6(), ".steward", "skills"), source: "user-steward" }
72571
+ { dir: join14(homedir7(), ".agents", "skills"), source: "user-agents" },
72572
+ { dir: join14(homedir7(), ".steward", "skills"), source: "user-steward" }
72250
72573
  ];
72251
72574
  const skillMap = new Map;
72252
72575
  for (const target of targets) {
72253
- if (!existsSync14(target.dir)) {
72576
+ if (!existsSync15(target.dir)) {
72254
72577
  continue;
72255
72578
  }
72256
72579
  try {
@@ -72261,7 +72584,7 @@ function discoverSkills(cwd = process.cwd()) {
72261
72584
  const skillDir = join14(target.dir, entry.name);
72262
72585
  const skillMdPath = join14(skillDir, "SKILL.md");
72263
72586
  const fallbackMdPath = join14(skillDir, "skill.md");
72264
- const resolvedFile = existsSync14(skillMdPath) ? skillMdPath : existsSync14(fallbackMdPath) ? fallbackMdPath : null;
72587
+ const resolvedFile = existsSync15(skillMdPath) ? skillMdPath : existsSync15(fallbackMdPath) ? fallbackMdPath : null;
72265
72588
  if (!resolvedFile)
72266
72589
  continue;
72267
72590
  try {
@@ -72299,20 +72622,20 @@ function readSkillResource(name, relativePath, cwd = process.cwd(), maxBytes = M
72299
72622
  targetFilePath = skill.filePath;
72300
72623
  } else {
72301
72624
  const trimmedPath = relativePath.trim();
72302
- if (isAbsolute6(trimmedPath)) {
72625
+ if (isAbsolute7(trimmedPath)) {
72303
72626
  throw new Error(`Invalid skill resource path: absolute paths are not permitted (${trimmedPath})`);
72304
72627
  }
72305
72628
  const normalizedRelative = normalize(trimmedPath);
72306
- if (normalizedRelative.startsWith("..") || normalizedRelative.includes(`${sep4}..`)) {
72629
+ if (normalizedRelative.startsWith("..") || normalizedRelative.includes(`${sep5}..`)) {
72307
72630
  throw new Error(`Invalid skill resource path: directory traversal ("..") is forbidden (${trimmedPath})`);
72308
72631
  }
72309
- targetFilePath = resolve9(skill.dirPath, normalizedRelative);
72310
- const resolvedDir = resolve9(skill.dirPath);
72311
- if (!targetFilePath.startsWith(resolvedDir + sep4) && targetFilePath !== resolvedDir) {
72632
+ targetFilePath = resolve10(skill.dirPath, normalizedRelative);
72633
+ const resolvedDir = resolve10(skill.dirPath);
72634
+ if (!targetFilePath.startsWith(resolvedDir + sep5) && targetFilePath !== resolvedDir) {
72312
72635
  throw new Error(`Resource "${trimmedPath}" resolves outside skill directory`);
72313
72636
  }
72314
72637
  }
72315
- if (!existsSync14(targetFilePath)) {
72638
+ if (!existsSync15(targetFilePath)) {
72316
72639
  throw new Error(`Skill resource file "${targetFilePath}" does not exist`);
72317
72640
  }
72318
72641
  const stat = statSync6(targetFilePath);
@@ -72390,6 +72713,22 @@ var skillReadTool = {
72390
72713
  }
72391
72714
  };
72392
72715
  // src/packages/agents/src/tools/summary.ts
72716
+ function summarizeToolArgs(toolDef, args) {
72717
+ if (toolDef?.summarizeArgs && args) {
72718
+ try {
72719
+ return toolDef.summarizeArgs(args);
72720
+ } catch {}
72721
+ }
72722
+ if (!args)
72723
+ return "";
72724
+ if (typeof args === "string")
72725
+ return args;
72726
+ try {
72727
+ return JSON.stringify(args);
72728
+ } catch {
72729
+ return String(args);
72730
+ }
72731
+ }
72393
72732
  function summarizeToolResult(toolDef, args, result, isError = false) {
72394
72733
  if (isError)
72395
72734
  return;
@@ -72432,9 +72771,10 @@ function formatPlainToolSummary(summary) {
72432
72771
  return;
72433
72772
  if (!summary.detail)
72434
72773
  return summary.headline;
72435
- if (summary.detail.kind === "text") {
72774
+ if (summary.detail.kind === "text" || summary.detail.kind === "pre-styled") {
72775
+ const text = summary.detail.kind === "pre-styled" ? summary.detail.text.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "") : summary.detail.text;
72436
72776
  return `${summary.headline}
72437
- ${summary.detail.text}`;
72777
+ ${text}`;
72438
72778
  }
72439
72779
  if (summary.detail.kind === "code") {
72440
72780
  const lines = summary.detail.text.split(/\r?\n/);
@@ -72941,13 +73281,23 @@ function classifyError(error) {
72941
73281
  originalError: error
72942
73282
  };
72943
73283
  }
72944
- if (lower.includes("fetch failed") || lower.includes("econnrefused") || lower.includes("enotfound") || lower.includes("timeout")) {
73284
+ if (lower.includes("fetch failed") || lower.includes("econnrefused") || lower.includes("enotfound") || lower.includes("connectionrefused") || lower.includes("unable to connect") || lower.includes("cannot connect to api") || lower.includes("timeout")) {
72945
73285
  return {
72946
73286
  category: "network",
72947
- shortMessage: "Network connection dropped / timed out",
73287
+ shortMessage: "Unable to connect to model API server",
72948
73288
  isRetryable: true,
72949
73289
  retryAfterSec: 4,
72950
- suggestedAction: "Check your internet connection and provider status",
73290
+ suggestedAction: "Verify network connection, local model server (e.g. Ollama/vLLM), or endpoint URL",
73291
+ originalError: error
73292
+ };
73293
+ }
73294
+ if (error?.name === "AI_NoOutputGeneratedError" || lower.includes("no output generated")) {
73295
+ return {
73296
+ category: "server-error",
73297
+ shortMessage: "Model generated empty output",
73298
+ isRetryable: true,
73299
+ retryAfterSec: 3,
73300
+ suggestedAction: "The provider closed the stream without content. Retrying or switching models may help",
72951
73301
  originalError: error
72952
73302
  };
72953
73303
  }
@@ -72960,7 +73310,7 @@ function classifyError(error) {
72960
73310
  };
72961
73311
  }
72962
73312
  // src/packages/services/src/errors/logger.ts
72963
- import { appendFileSync as appendFileSync3, existsSync as existsSync15, mkdirSync as mkdirSync10, writeFileSync as writeFileSync4 } from "node:fs";
73313
+ import { appendFileSync as appendFileSync3, existsSync as existsSync16, mkdirSync as mkdirSync10, writeFileSync as writeFileSync4 } from "node:fs";
72964
73314
  import { join as join15 } from "node:path";
72965
73315
  var SENSITIVE_KEY_REGEX = /api[_-]?key|token|secret|password|auth|credential|bearer/i;
72966
73316
  function getLogsRootDir() {
@@ -73049,7 +73399,7 @@ function logError(error, contextInfo) {
73049
73399
  const rootDir = getLogsRootDir();
73050
73400
  const { date, time } = getLogDateTime();
73051
73401
  const dateDir = join15(rootDir, date);
73052
- if (!existsSync15(dateDir)) {
73402
+ if (!existsSync16(dateDir)) {
73053
73403
  mkdirSync10(dateDir, { recursive: true });
73054
73404
  }
73055
73405
  const logPath = join15(dateDir, `${time}.log`);
@@ -73078,7 +73428,7 @@ function logError(error, contextInfo) {
73078
73428
  ` + JSON.stringify(logEntry, null, 2) + `
73079
73429
 
73080
73430
  `;
73081
- if (existsSync15(logPath)) {
73431
+ if (existsSync16(logPath)) {
73082
73432
  appendFileSync3(logPath, formatted, "utf-8");
73083
73433
  } else {
73084
73434
  writeFileSync4(logPath, formatted, "utf-8");
@@ -73117,11 +73467,18 @@ function setupGlobalErrorHandlers() {
73117
73467
  process.on("uncaughtException", (error) => {
73118
73468
  const logPath = logError(error, { source: "uncaughtException", fatal: true });
73119
73469
  emergencyRestoreTerminal();
73470
+ const classified = classifyError(error);
73120
73471
  process.stderr.write(`
73121
- \x1B[31m✖ Fatal error in Steward:\x1B[0m ${error.message || String(error)}
73472
+ \x1B[31m✖ Fatal error in Steward:\x1B[0m ${classified.shortMessage}
73122
73473
  `);
73474
+ if (classified.suggestedAction) {
73475
+ process.stderr.write(`\x1B[36mℹ ${classified.suggestedAction}\x1B[0m
73476
+ `);
73477
+ }
73123
73478
  if (error.stack) {
73124
- process.stderr.write(`\x1B[90m${error.stack}\x1B[0m
73479
+ process.stderr.write(`
73480
+ \x1B[90mTechnical details:
73481
+ ${error.stack}\x1B[0m
73125
73482
  `);
73126
73483
  }
73127
73484
  if (logPath) {
@@ -73132,7 +73489,28 @@ function setupGlobalErrorHandlers() {
73132
73489
  process.exit(1);
73133
73490
  });
73134
73491
  process.on("unhandledRejection", (reason) => {
73135
- logError(reason, { source: "unhandledRejection", fatal: false });
73492
+ const logPath = logError(reason, { source: "unhandledRejection", fatal: true });
73493
+ emergencyRestoreTerminal();
73494
+ const classified = classifyError(reason);
73495
+ process.stderr.write(`
73496
+ \x1B[31m✖ Unhandled asynchronous rejection:\x1B[0m ${classified.shortMessage}
73497
+ `);
73498
+ if (classified.suggestedAction) {
73499
+ process.stderr.write(`\x1B[36mℹ ${classified.suggestedAction}\x1B[0m
73500
+ `);
73501
+ }
73502
+ if (reason instanceof Error && reason.stack) {
73503
+ process.stderr.write(`
73504
+ \x1B[90mTechnical details:
73505
+ ${reason.stack}\x1B[0m
73506
+ `);
73507
+ }
73508
+ if (logPath) {
73509
+ process.stderr.write(`\x1B[33mℹ Detailed diagnostics saved to: ${logPath}\x1B[0m
73510
+
73511
+ `);
73512
+ }
73513
+ process.exit(1);
73136
73514
  });
73137
73515
  }
73138
73516
  // src/packages/agents/src/engine/constants.ts
@@ -107523,20 +107901,20 @@ var _a38;
107523
107901
  var _b31;
107524
107902
  var AISDKError4 = class _AISDKError extends (_b31 = Error, _a38 = symbol31, _b31) {
107525
107903
  constructor({
107526
- name: name15,
107904
+ name: name16,
107527
107905
  message,
107528
107906
  cause
107529
107907
  }) {
107530
107908
  super(message);
107531
107909
  this[_a38] = true;
107532
- this.name = name15;
107910
+ this.name = name16;
107533
107911
  this.cause = cause;
107534
107912
  }
107535
107913
  static isInstance(error) {
107536
107914
  return _AISDKError.hasMarker(error, marker30);
107537
107915
  }
107538
- static hasMarker(error, marker16) {
107539
- const markerSymbol = Symbol.for(marker16);
107916
+ static hasMarker(error, marker17) {
107917
+ const markerSymbol = Symbol.for(marker17);
107540
107918
  return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
107541
107919
  }
107542
107920
  };
@@ -107585,114 +107963,124 @@ var EmptyResponseBodyError4 = class extends (_b36 = AISDKError4, _a39 = symbol36
107585
107963
  return AISDKError4.hasMarker(error, marker39);
107586
107964
  }
107587
107965
  };
107588
- function getErrorMessage4(error) {
107589
- if (error == null) {
107590
- return "unknown error";
107591
- }
107592
- if (typeof error === "string") {
107593
- return error;
107594
- }
107595
- if (error instanceof Error) {
107596
- return error.toString();
107597
- }
107598
- return JSON.stringify(error);
107599
- }
107600
- var name36 = "AI_InvalidArgumentError";
107966
+ var name36 = "AI_EvaluationUnsupportedQuestionTypeError";
107601
107967
  var marker46 = `vercel.ai.error.${name36}`;
107602
107968
  var symbol46 = Symbol.for(marker46);
107603
107969
  var _a46;
107604
107970
  var _b46;
107605
- var InvalidArgumentError5 = class extends (_b46 = AISDKError4, _a46 = symbol46, _b46) {
107971
+ var EvaluationUnsupportedQuestionTypeError = class extends (_b46 = AISDKError4, _a46 = symbol46, _b46) {
107606
107972
  constructor({
107607
- message,
107608
- cause,
107609
- argument
107973
+ questionId,
107974
+ questionType,
107975
+ provider,
107976
+ modelId,
107977
+ message = `Question "${questionId}" has type "${questionType}", which is not supported by provider "${provider}" and model "${modelId}".`
107610
107978
  }) {
107611
- super({ name: name36, message, cause });
107979
+ super({ name: name36, message });
107612
107980
  this[_a46] = true;
107613
- this.argument = argument;
107981
+ this.questionId = questionId;
107982
+ this.questionType = questionType;
107983
+ this.provider = provider;
107984
+ this.modelId = modelId;
107614
107985
  }
107615
107986
  static isInstance(error) {
107616
107987
  return AISDKError4.hasMarker(error, marker46);
107617
107988
  }
107618
107989
  };
107619
- var name46 = "AI_InvalidPromptError";
107990
+ function getErrorMessage4(error) {
107991
+ if (error == null) {
107992
+ return "unknown error";
107993
+ }
107994
+ if (typeof error === "string") {
107995
+ return error;
107996
+ }
107997
+ if (error instanceof Error) {
107998
+ return error.toString();
107999
+ }
108000
+ return JSON.stringify(error);
108001
+ }
108002
+ var name46 = "AI_InvalidArgumentError";
107620
108003
  var marker56 = `vercel.ai.error.${name46}`;
107621
108004
  var symbol56 = Symbol.for(marker56);
107622
108005
  var _a56;
107623
108006
  var _b56;
107624
- var InvalidPromptError4 = class extends (_b56 = AISDKError4, _a56 = symbol56, _b56) {
108007
+ var InvalidArgumentError5 = class extends (_b56 = AISDKError4, _a56 = symbol56, _b56) {
107625
108008
  constructor({
107626
- prompt,
107627
108009
  message,
107628
- cause
108010
+ cause,
108011
+ argument
107629
108012
  }) {
107630
- super({ name: name46, message: `Invalid prompt: ${message}`, cause });
108013
+ super({ name: name46, message, cause });
107631
108014
  this[_a56] = true;
107632
- this.prompt = prompt;
108015
+ this.argument = argument;
107633
108016
  }
107634
108017
  static isInstance(error) {
107635
108018
  return AISDKError4.hasMarker(error, marker56);
107636
108019
  }
107637
108020
  };
107638
- var name56 = "AI_InvalidResponseDataError";
108021
+ var name56 = "AI_InvalidPromptError";
107639
108022
  var marker66 = `vercel.ai.error.${name56}`;
107640
108023
  var symbol66 = Symbol.for(marker66);
107641
108024
  var _a66;
107642
108025
  var _b66;
107643
- var InvalidResponseDataError4 = class extends (_b66 = AISDKError4, _a66 = symbol66, _b66) {
108026
+ var InvalidPromptError4 = class extends (_b66 = AISDKError4, _a66 = symbol66, _b66) {
107644
108027
  constructor({
107645
- data,
107646
- message = `Invalid response data: ${JSON.stringify(data)}.`
108028
+ prompt,
108029
+ message,
108030
+ cause
107647
108031
  }) {
107648
- super({ name: name56, message });
108032
+ super({ name: name56, message: `Invalid prompt: ${message}`, cause });
107649
108033
  this[_a66] = true;
107650
- this.data = data;
108034
+ this.prompt = prompt;
107651
108035
  }
107652
108036
  static isInstance(error) {
107653
108037
  return AISDKError4.hasMarker(error, marker66);
107654
108038
  }
107655
108039
  };
107656
- var name66 = "AI_JSONParseError";
108040
+ var name66 = "AI_InvalidResponseDataError";
107657
108041
  var marker76 = `vercel.ai.error.${name66}`;
107658
108042
  var symbol76 = Symbol.for(marker76);
107659
108043
  var _a76;
107660
108044
  var _b76;
107661
- var JSONParseError4 = class extends (_b76 = AISDKError4, _a76 = symbol76, _b76) {
107662
- constructor({ text, cause }) {
107663
- super({
107664
- name: name66,
107665
- message: `JSON parsing failed: Text: ${text}.
107666
- Error message: ${getErrorMessage4(cause)}`,
107667
- cause
107668
- });
108045
+ var InvalidResponseDataError4 = class extends (_b76 = AISDKError4, _a76 = symbol76, _b76) {
108046
+ constructor({
108047
+ data,
108048
+ message = `Invalid response data: ${JSON.stringify(data)}.`
108049
+ }) {
108050
+ super({ name: name66, message });
107669
108051
  this[_a76] = true;
107670
- this.text = text;
108052
+ this.data = data;
107671
108053
  }
107672
108054
  static isInstance(error) {
107673
108055
  return AISDKError4.hasMarker(error, marker76);
107674
108056
  }
107675
108057
  };
107676
- var name76 = "AI_LoadAPIKeyError";
108058
+ var name76 = "AI_JSONParseError";
107677
108059
  var marker86 = `vercel.ai.error.${name76}`;
107678
108060
  var symbol86 = Symbol.for(marker86);
107679
108061
  var _a86;
107680
108062
  var _b86;
107681
- var LoadAPIKeyError4 = class extends (_b86 = AISDKError4, _a86 = symbol86, _b86) {
107682
- constructor({ message }) {
107683
- super({ name: name76, message });
108063
+ var JSONParseError4 = class extends (_b86 = AISDKError4, _a86 = symbol86, _b86) {
108064
+ constructor({ text, cause }) {
108065
+ super({
108066
+ name: name76,
108067
+ message: `JSON parsing failed: Text: ${text}.
108068
+ Error message: ${getErrorMessage4(cause)}`,
108069
+ cause
108070
+ });
107684
108071
  this[_a86] = true;
108072
+ this.text = text;
107685
108073
  }
107686
108074
  static isInstance(error) {
107687
108075
  return AISDKError4.hasMarker(error, marker86);
107688
108076
  }
107689
108077
  };
107690
- var name86 = "AI_LoadSettingError";
108078
+ var name86 = "AI_LoadAPIKeyError";
107691
108079
  var marker96 = `vercel.ai.error.${name86}`;
107692
108080
  var symbol96 = Symbol.for(marker96);
107693
108081
  var _a96;
107694
108082
  var _b96;
107695
- var LoadSettingError4 = class extends (_b96 = AISDKError4, _a96 = symbol96, _b96) {
108083
+ var LoadAPIKeyError4 = class extends (_b96 = AISDKError4, _a96 = symbol96, _b96) {
107696
108084
  constructor({ message }) {
107697
108085
  super({ name: name86, message });
107698
108086
  this[_a96] = true;
@@ -107701,15 +108089,13 @@ var LoadSettingError4 = class extends (_b96 = AISDKError4, _a96 = symbol96, _b96
107701
108089
  return AISDKError4.hasMarker(error, marker96);
107702
108090
  }
107703
108091
  };
107704
- var name96 = "AI_NoContentGeneratedError";
108092
+ var name96 = "AI_LoadSettingError";
107705
108093
  var marker106 = `vercel.ai.error.${name96}`;
107706
108094
  var symbol106 = Symbol.for(marker106);
107707
108095
  var _a106;
107708
108096
  var _b106;
107709
- var NoContentGeneratedError4 = class extends (_b106 = AISDKError4, _a106 = symbol106, _b106) {
107710
- constructor({
107711
- message = "No content generated."
107712
- } = {}) {
108097
+ var LoadSettingError4 = class extends (_b106 = AISDKError4, _a106 = symbol106, _b106) {
108098
+ constructor({ message }) {
107713
108099
  super({ name: name96, message });
107714
108100
  this[_a106] = true;
107715
108101
  }
@@ -107717,74 +108103,90 @@ var NoContentGeneratedError4 = class extends (_b106 = AISDKError4, _a106 = symbo
107717
108103
  return AISDKError4.hasMarker(error, marker106);
107718
108104
  }
107719
108105
  };
107720
- var name106 = "AI_NoSuchModelError";
108106
+ var name106 = "AI_NoContentGeneratedError";
107721
108107
  var marker116 = `vercel.ai.error.${name106}`;
107722
108108
  var symbol116 = Symbol.for(marker116);
107723
108109
  var _a116;
107724
108110
  var _b116;
107725
- var NoSuchModelError4 = class extends (_b116 = AISDKError4, _a116 = symbol116, _b116) {
108111
+ var NoContentGeneratedError4 = class extends (_b116 = AISDKError4, _a116 = symbol116, _b116) {
107726
108112
  constructor({
107727
- errorName = name106,
107728
- modelId,
107729
- modelType,
107730
- message = `No such ${modelType}: ${modelId}`
107731
- }) {
107732
- super({ name: errorName, message });
108113
+ message = "No content generated."
108114
+ } = {}) {
108115
+ super({ name: name106, message });
107733
108116
  this[_a116] = true;
107734
- this.modelId = modelId;
107735
- this.modelType = modelType;
107736
108117
  }
107737
108118
  static isInstance(error) {
107738
108119
  return AISDKError4.hasMarker(error, marker116);
107739
108120
  }
107740
108121
  };
107741
- var name115 = "AI_NoSuchProviderReferenceError";
108122
+ var name115 = "AI_NoSuchModelError";
107742
108123
  var marker125 = `vercel.ai.error.${name115}`;
107743
108124
  var symbol125 = Symbol.for(marker125);
107744
108125
  var _a125;
107745
108126
  var _b125;
107746
- var NoSuchProviderReferenceError4 = class extends (_b125 = AISDKError4, _a125 = symbol125, _b125) {
108127
+ var NoSuchModelError4 = class extends (_b125 = AISDKError4, _a125 = symbol125, _b125) {
107747
108128
  constructor({
107748
- provider,
107749
- reference,
107750
- message = `No provider reference found for provider '${provider}'. Available providers: ${Object.keys(reference).join(", ")}`
108129
+ errorName = name115,
108130
+ modelId,
108131
+ modelType,
108132
+ message = `No such ${modelType}: ${modelId}`
107751
108133
  }) {
107752
- super({ name: name115, message });
108134
+ super({ name: errorName, message });
107753
108135
  this[_a125] = true;
107754
- this.provider = provider;
107755
- this.reference = reference;
108136
+ this.modelId = modelId;
108137
+ this.modelType = modelType;
107756
108138
  }
107757
108139
  static isInstance(error) {
107758
108140
  return AISDKError4.hasMarker(error, marker125);
107759
108141
  }
107760
108142
  };
107761
- var name125 = "AI_TooManyEmbeddingValuesForCallError";
108143
+ var name125 = "AI_NoSuchProviderReferenceError";
107762
108144
  var marker135 = `vercel.ai.error.${name125}`;
107763
108145
  var symbol135 = Symbol.for(marker135);
107764
108146
  var _a135;
107765
108147
  var _b135;
107766
- var TooManyEmbeddingValuesForCallError4 = class extends (_b135 = AISDKError4, _a135 = symbol135, _b135) {
108148
+ var NoSuchProviderReferenceError4 = class extends (_b135 = AISDKError4, _a135 = symbol135, _b135) {
108149
+ constructor({
108150
+ provider,
108151
+ reference,
108152
+ message = `No provider reference found for provider '${provider}'. Available providers: ${Object.keys(reference).join(", ")}`
108153
+ }) {
108154
+ super({ name: name125, message });
108155
+ this[_a135] = true;
108156
+ this.provider = provider;
108157
+ this.reference = reference;
108158
+ }
108159
+ static isInstance(error) {
108160
+ return AISDKError4.hasMarker(error, marker135);
108161
+ }
108162
+ };
108163
+ var name135 = "AI_TooManyEmbeddingValuesForCallError";
108164
+ var marker145 = `vercel.ai.error.${name135}`;
108165
+ var symbol145 = Symbol.for(marker145);
108166
+ var _a145;
108167
+ var _b145;
108168
+ var TooManyEmbeddingValuesForCallError4 = class extends (_b145 = AISDKError4, _a145 = symbol145, _b145) {
107767
108169
  constructor(options) {
107768
108170
  super({
107769
- name: name125,
108171
+ name: name135,
107770
108172
  message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
107771
108173
  });
107772
- this[_a135] = true;
108174
+ this[_a145] = true;
107773
108175
  this.provider = options.provider;
107774
108176
  this.modelId = options.modelId;
107775
108177
  this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
107776
108178
  this.values = options.values;
107777
108179
  }
107778
108180
  static isInstance(error) {
107779
- return AISDKError4.hasMarker(error, marker135);
108181
+ return AISDKError4.hasMarker(error, marker145);
107780
108182
  }
107781
108183
  };
107782
- var name135 = "AI_TypeValidationError";
107783
- var marker145 = `vercel.ai.error.${name135}`;
107784
- var symbol145 = Symbol.for(marker145);
107785
- var _a145;
107786
- var _b145;
107787
- var TypeValidationError4 = class _TypeValidationError extends (_b145 = AISDKError4, _a145 = symbol145, _b145) {
108184
+ var name145 = "AI_TypeValidationError";
108185
+ var marker155 = `vercel.ai.error.${name145}`;
108186
+ var symbol155 = Symbol.for(marker155);
108187
+ var _a155;
108188
+ var _b155;
108189
+ var TypeValidationError4 = class _TypeValidationError extends (_b155 = AISDKError4, _a155 = symbol155, _b155) {
107788
108190
  constructor({
107789
108191
  value,
107790
108192
  cause,
@@ -107807,46 +108209,46 @@ var TypeValidationError4 = class _TypeValidationError extends (_b145 = AISDKErro
107807
108209
  contextPrefix += ")";
107808
108210
  }
107809
108211
  super({
107810
- name: name135,
108212
+ name: name145,
107811
108213
  message: `${contextPrefix}: Value: ${JSON.stringify(value)}.
107812
108214
  Error message: ${getErrorMessage4(cause)}`,
107813
108215
  cause
107814
108216
  });
107815
- this[_a145] = true;
108217
+ this[_a155] = true;
107816
108218
  this.value = value;
107817
108219
  this.context = context;
107818
108220
  }
107819
108221
  static isInstance(error) {
107820
- return AISDKError4.hasMarker(error, marker145);
108222
+ return AISDKError4.hasMarker(error, marker155);
107821
108223
  }
107822
108224
  static wrap({
107823
108225
  value,
107824
108226
  cause,
107825
108227
  context
107826
108228
  }) {
107827
- var _a16, _b16, _c;
107828
- if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a16 = cause.context) == null ? undefined : _a16.field) === (context == null ? undefined : context.field) && ((_b16 = cause.context) == null ? undefined : _b16.entityName) === (context == null ? undefined : context.entityName) && ((_c = cause.context) == null ? undefined : _c.entityId) === (context == null ? undefined : context.entityId)) {
108229
+ var _a17, _b17, _c;
108230
+ if (_TypeValidationError.isInstance(cause) && cause.value === value && ((_a17 = cause.context) == null ? undefined : _a17.field) === (context == null ? undefined : context.field) && ((_b17 = cause.context) == null ? undefined : _b17.entityName) === (context == null ? undefined : context.entityName) && ((_c = cause.context) == null ? undefined : _c.entityId) === (context == null ? undefined : context.entityId)) {
107829
108231
  return cause;
107830
108232
  }
107831
108233
  return new _TypeValidationError({ value, cause, context });
107832
108234
  }
107833
108235
  };
107834
- var name145 = "AI_UnsupportedFunctionalityError";
107835
- var marker155 = `vercel.ai.error.${name145}`;
107836
- var symbol155 = Symbol.for(marker155);
107837
- var _a155;
107838
- var _b155;
107839
- var UnsupportedFunctionalityError4 = class extends (_b155 = AISDKError4, _a155 = symbol155, _b155) {
108236
+ var name153 = "AI_UnsupportedFunctionalityError";
108237
+ var marker163 = `vercel.ai.error.${name153}`;
108238
+ var symbol163 = Symbol.for(marker163);
108239
+ var _a163;
108240
+ var _b163;
108241
+ var UnsupportedFunctionalityError4 = class extends (_b163 = AISDKError4, _a163 = symbol163, _b163) {
107840
108242
  constructor({
107841
108243
  functionality,
107842
108244
  message = `'${functionality}' functionality not supported.`
107843
108245
  }) {
107844
- super({ name: name145, message });
107845
- this[_a155] = true;
108246
+ super({ name: name153, message });
108247
+ this[_a163] = true;
107846
108248
  this.functionality = functionality;
107847
108249
  }
107848
108250
  static isInstance(error) {
107849
- return AISDKError4.hasMarker(error, marker155);
108251
+ return AISDKError4.hasMarker(error, marker163);
107850
108252
  }
107851
108253
  };
107852
108254
 
@@ -108135,7 +108537,7 @@ function getRuntimeEnvironmentUserAgent4(globalThisAny = globalThis) {
108135
108537
  return "runtime/unknown";
108136
108538
  }
108137
108539
  function isAbortError4(error) {
108138
- return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
108540
+ return (error instanceof Error || typeof DOMException === "function" && error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError");
108139
108541
  }
108140
108542
  var FETCH_FAILED_ERROR_MESSAGES4 = ["fetch failed", "failed to fetch"];
108141
108543
  var RETRYABLE_NETWORK_ERROR_CODES4 = /* @__PURE__ */ new Set([
@@ -108209,7 +108611,7 @@ function handleFetchError4({
108209
108611
  }
108210
108612
  return error;
108211
108613
  }
108212
- var VERSION14 = "5.0.40";
108614
+ var VERSION14 = "5.0.45";
108213
108615
  function normalizeHeaders4(headers) {
108214
108616
  if (headers == null) {
108215
108617
  return {};
@@ -108353,7 +108755,7 @@ var imageMediaTypeSignatures4 = [
108353
108755
  0,
108354
108756
  0,
108355
108757
  0,
108356
- 32,
108758
+ null,
108357
108759
  102,
108358
108760
  116,
108359
108761
  121,
@@ -108370,7 +108772,7 @@ var imageMediaTypeSignatures4 = [
108370
108772
  0,
108371
108773
  0,
108372
108774
  0,
108373
- 32,
108775
+ null,
108374
108776
  102,
108375
108777
  116,
108376
108778
  121,
@@ -108389,6 +108791,22 @@ var documentMediaTypeSignatures4 = [
108389
108791
  }
108390
108792
  ];
108391
108793
  var audioMediaTypeSignaturesWithoutMp44 = [
108794
+ {
108795
+ mediaType: "audio/aac",
108796
+ bytesPrefix: [255, 240]
108797
+ },
108798
+ {
108799
+ mediaType: "audio/aac",
108800
+ bytesPrefix: [255, 241]
108801
+ },
108802
+ {
108803
+ mediaType: "audio/aac",
108804
+ bytesPrefix: [255, 248]
108805
+ },
108806
+ {
108807
+ mediaType: "audio/aac",
108808
+ bytesPrefix: [255, 249]
108809
+ },
108392
108810
  {
108393
108811
  mediaType: "audio/mpeg",
108394
108812
  bytesPrefix: [255, 251]
@@ -108817,30 +109235,22 @@ function createSafeLookup2(lookup) {
108817
109235
  };
108818
109236
  }
108819
109237
  var safeNodeFetchPromise2;
108820
- var initialGlobalFetch4 = globalThis.fetch;
108821
- var initialGlobalFetchIsNodeDefault4 = isNodeDefaultFetch4(initialGlobalFetch4);
108822
109238
  function isNodeRuntime3() {
108823
- var _a3, _b3;
109239
+ var _a3, _b3, _c;
108824
109240
  const runtimeProcess = globalThis.process;
108825
- return ((_a3 = runtimeProcess == null ? undefined : runtimeProcess.release) == null ? undefined : _a3.name) === "node" && ((_b3 = runtimeProcess.versions) == null ? undefined : _b3.bun) == null;
109241
+ return ((_a3 = runtimeProcess == null ? undefined : runtimeProcess.release) == null ? undefined : _a3.name) === "node" && ((_b3 = runtimeProcess.versions) == null ? undefined : _b3.bun) == null && ((_c = runtimeProcess.versions) == null ? undefined : _c.deno) == null && runtimeProcess.title !== "workerd" && globalThis.EdgeRuntime == null;
108826
109242
  }
108827
109243
  async function getDefaultDownloadFetch2() {
108828
- if (!isNodeRuntime3() || !initialGlobalFetchIsNodeDefault4 || globalThis.fetch !== initialGlobalFetch4) {
109244
+ if (!isNodeRuntime3()) {
108829
109245
  return globalThis.fetch;
108830
109246
  }
108831
109247
  return safeNodeFetchPromise2 != null ? safeNodeFetchPromise2 : safeNodeFetchPromise2 = Promise.resolve().then(createSafeNodeFetch2);
108832
109248
  }
108833
- function isNodeDefaultFetch4(fetch2) {
108834
- if (typeof fetch2 !== "function") {
108835
- return false;
108836
- }
108837
- const source = Function.prototype.toString.call(fetch2);
108838
- return source.includes("internal/deps/undici") || source.includes("lazy loading of undici");
108839
- }
108840
109249
  function createSafeNodeFetch2() {
108841
- const { createRequire } = loadBuiltinModule3("node:module");
109250
+ const module = loadBuiltinModule3("node:module");
108842
109251
  const { lookup } = loadBuiltinModule3("node:dns");
108843
- const { Agent, fetch: fetch2 } = createRequire(getCurrentModulePath2())("undici");
109252
+ const nodeRequire = module.createRequire(getCurrentModulePath2());
109253
+ const { Agent, fetch: fetch2 } = nodeRequire("undici");
108844
109254
  const dispatcher = new Agent({
108845
109255
  connect: {
108846
109256
  lookup: createSafeLookup2(lookup)
@@ -108946,7 +109356,7 @@ async function fetchWithValidatedRedirects2({
108946
109356
  }
108947
109357
  const location = (_a3 = response.headers) == null ? undefined : _a3.get("location");
108948
109358
  if (REDIRECT_STATUS_CODES2.has(response.status) && location) {
108949
- await cancelResponseBody4(response);
109359
+ cancelResponseBody4(response);
108950
109360
  const nextUrl = new URL(location, currentUrl).toString();
108951
109361
  if (currentHeaders !== undefined && !isSameOrigin2(nextUrl, currentUrl)) {
108952
109362
  const userAgent = currentHeaders.get("user-agent");
@@ -110779,7 +111189,7 @@ function createProviderExecutedToolFactory2({
110779
111189
  supportsDeferredResults
110780
111190
  });
110781
111191
  }
110782
- async function resolve10(value) {
111192
+ async function resolve11(value) {
110783
111193
  if (typeof value === "function") {
110784
111194
  value = value();
110785
111195
  }
@@ -111106,246 +111516,7 @@ function withoutTrailingSlash4(url) {
111106
111516
  }
111107
111517
 
111108
111518
  // node_modules/@ai-sdk/xai/dist/index.js
111109
- var xaiFilePartProviderOptions = object({
111110
- imageDetail: _enum(["low", "high", "auto"]).optional()
111111
- });
111112
- async function convertToXaiChatMessages(prompt) {
111113
- var _a;
111114
- const messages = [];
111115
- const warnings = [];
111116
- for (const { role, content } of prompt) {
111117
- switch (role) {
111118
- case "system": {
111119
- messages.push({ role: "system", content });
111120
- break;
111121
- }
111122
- case "user": {
111123
- if (content.length === 1 && content[0].type === "text") {
111124
- messages.push({ role: "user", content: content[0].text });
111125
- break;
111126
- }
111127
- const userContent = [];
111128
- for (const part of content) {
111129
- switch (part.type) {
111130
- case "text": {
111131
- userContent.push({ type: "text", text: part.text });
111132
- break;
111133
- }
111134
- case "file": {
111135
- switch (part.data.type) {
111136
- case "reference": {
111137
- userContent.push({
111138
- type: "file",
111139
- file: {
111140
- file_id: resolveProviderReference3({
111141
- reference: part.data.reference,
111142
- provider: "xai"
111143
- })
111144
- }
111145
- });
111146
- break;
111147
- }
111148
- case "text": {
111149
- throw new UnsupportedFunctionalityError4({
111150
- functionality: "text file parts"
111151
- });
111152
- }
111153
- case "url":
111154
- case "data": {
111155
- if (getTopLevelMediaType4(part.mediaType) === "image") {
111156
- const filePartOptions = await parseProviderOptions4({
111157
- provider: "xai",
111158
- providerOptions: part.providerOptions,
111159
- schema: xaiFilePartProviderOptions
111160
- });
111161
- userContent.push({
111162
- type: "image_url",
111163
- image_url: {
111164
- url: part.data.type === "url" ? part.data.url.toString() : `data:${resolveFullMediaType4({ part })};base64,${convertToBase644(part.data.data)}`,
111165
- ...(filePartOptions == null ? undefined : filePartOptions.imageDetail) != null && {
111166
- detail: filePartOptions.imageDetail
111167
- }
111168
- }
111169
- });
111170
- } else {
111171
- throw new UnsupportedFunctionalityError4({
111172
- functionality: `file part media type ${part.mediaType}`
111173
- });
111174
- }
111175
- break;
111176
- }
111177
- }
111178
- break;
111179
- }
111180
- }
111181
- }
111182
- messages.push({ role: "user", content: userContent });
111183
- break;
111184
- }
111185
- case "assistant": {
111186
- let text = "";
111187
- const toolCalls = [];
111188
- for (const part of content) {
111189
- switch (part.type) {
111190
- case "text": {
111191
- text += part.text;
111192
- break;
111193
- }
111194
- case "tool-call": {
111195
- toolCalls.push({
111196
- id: part.toolCallId,
111197
- type: "function",
111198
- function: {
111199
- name: part.toolName,
111200
- arguments: JSON.stringify(part.input)
111201
- }
111202
- });
111203
- break;
111204
- }
111205
- }
111206
- }
111207
- messages.push({
111208
- role: "assistant",
111209
- content: text,
111210
- tool_calls: toolCalls.length > 0 ? toolCalls : undefined
111211
- });
111212
- break;
111213
- }
111214
- case "tool": {
111215
- for (const toolResponse of content) {
111216
- if (toolResponse.type === "tool-approval-response") {
111217
- continue;
111218
- }
111219
- const output = toolResponse.output;
111220
- let contentValue;
111221
- switch (output.type) {
111222
- case "text":
111223
- case "error-text":
111224
- contentValue = output.value;
111225
- break;
111226
- case "execution-denied":
111227
- contentValue = (_a = output.reason) != null ? _a : "Tool call execution denied.";
111228
- break;
111229
- case "content":
111230
- case "json":
111231
- case "error-json":
111232
- contentValue = JSON.stringify(output.value);
111233
- break;
111234
- }
111235
- messages.push({
111236
- role: "tool",
111237
- tool_call_id: toolResponse.toolCallId,
111238
- content: contentValue
111239
- });
111240
- }
111241
- break;
111242
- }
111243
- default: {
111244
- const _exhaustiveCheck = role;
111245
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
111246
- }
111247
- }
111248
- }
111249
- return { messages, warnings };
111250
- }
111251
- function convertXaiChatUsage(usage) {
111252
- var _a, _b, _c, _d;
111253
- const cacheReadTokens = (_b = (_a = usage.prompt_tokens_details) == null ? undefined : _a.cached_tokens) != null ? _b : 0;
111254
- const reasoningTokens = (_d = (_c = usage.completion_tokens_details) == null ? undefined : _c.reasoning_tokens) != null ? _d : 0;
111255
- const promptTokensIncludesCached = cacheReadTokens <= usage.prompt_tokens;
111256
- return {
111257
- inputTokens: {
111258
- total: promptTokensIncludesCached ? usage.prompt_tokens : usage.prompt_tokens + cacheReadTokens,
111259
- noCache: promptTokensIncludesCached ? usage.prompt_tokens - cacheReadTokens : usage.prompt_tokens,
111260
- cacheRead: cacheReadTokens,
111261
- cacheWrite: undefined
111262
- },
111263
- outputTokens: {
111264
- total: usage.completion_tokens + reasoningTokens,
111265
- text: usage.completion_tokens,
111266
- reasoning: reasoningTokens
111267
- },
111268
- raw: usage
111269
- };
111270
- }
111271
- function getResponseMetadata2({
111272
- id,
111273
- model,
111274
- created,
111275
- created_at
111276
- }) {
111277
- return createLanguageModelResponseMetadata4({
111278
- id,
111279
- model,
111280
- created: created != null ? created : created_at
111281
- });
111282
- }
111283
- function mapXaiFinishReason(finishReason) {
111284
- switch (finishReason) {
111285
- case "stop":
111286
- return "stop";
111287
- case "length":
111288
- return "length";
111289
- case "tool_calls":
111290
- case "function_call":
111291
- return "tool-calls";
111292
- case "content_filter":
111293
- return "content-filter";
111294
- default:
111295
- return "other";
111296
- }
111297
- }
111298
- var modelsWithoutReasoningEffort = /^grok-4\.20(-\d{4})?-(non-)?reasoning$/;
111299
- function supportsReasoningEffort(modelId) {
111300
- return !modelsWithoutReasoningEffort.test(modelId);
111301
- }
111302
- var webSourceSchema = object({
111303
- type: literal("web"),
111304
- country: string2().length(2).optional(),
111305
- excludedWebsites: array(string2()).max(5).optional(),
111306
- allowedWebsites: array(string2()).max(5).optional(),
111307
- safeSearch: boolean2().optional()
111308
- });
111309
- var xSourceSchema = object({
111310
- type: literal("x"),
111311
- excludedXHandles: array(string2()).optional(),
111312
- includedXHandles: array(string2()).optional(),
111313
- postFavoriteCount: number2().int().optional(),
111314
- postViewCount: number2().int().optional(),
111315
- xHandles: array(string2()).optional()
111316
- });
111317
- var newsSourceSchema = object({
111318
- type: literal("news"),
111319
- country: string2().length(2).optional(),
111320
- excludedWebsites: array(string2()).max(5).optional(),
111321
- safeSearch: boolean2().optional()
111322
- });
111323
- var rssSourceSchema = object({
111324
- type: literal("rss"),
111325
- links: array(string2().url()).max(1)
111326
- });
111327
- var searchSourceSchema = discriminatedUnion("type", [
111328
- webSourceSchema,
111329
- xSourceSchema,
111330
- newsSourceSchema,
111331
- rssSourceSchema
111332
- ]);
111333
- var xaiLanguageModelChatOptions = object({
111334
- reasoningEffort: _enum(["none", "low", "medium", "high", "xhigh"]).optional(),
111335
- logprobs: boolean2().optional(),
111336
- topLogprobs: number2().int().min(0).max(8).optional(),
111337
- serviceTier: _enum(["default", "priority"]).optional(),
111338
- parallel_function_calling: boolean2().optional(),
111339
- searchParameters: object({
111340
- mode: _enum(["off", "auto", "on"]),
111341
- returnCitations: boolean2().optional(),
111342
- fromDate: string2().optional(),
111343
- toDate: string2().optional(),
111344
- maxSearchResults: number2().min(1).max(50).optional(),
111345
- sources: array(searchSourceSchema).optional()
111346
- }).optional()
111347
- });
111348
- var chatCompletionsErrorSchema = object({
111519
+ var apiErrorSchema = object({
111349
111520
  error: object({
111350
111521
  message: string2(),
111351
111522
  type: string2().nullish(),
@@ -111361,7 +111532,7 @@ var speechErrorSchema = object({
111361
111532
  error: string2()
111362
111533
  });
111363
111534
  var xaiErrorDataSchema = union([
111364
- chatCompletionsErrorSchema,
111535
+ apiErrorSchema,
111365
111536
  responsesErrorSchema,
111366
111537
  speechErrorSchema
111367
111538
  ]);
@@ -111374,622 +111545,6 @@ var xaiFailedResponseHandler = createJsonErrorResponseHandler4({
111374
111545
  return data.error.message;
111375
111546
  }
111376
111547
  });
111377
- function removeAdditionalPropertiesFalse(value) {
111378
- if (Array.isArray(value)) {
111379
- return value.map(removeAdditionalPropertiesFalse);
111380
- }
111381
- if (value == null || typeof value !== "object") {
111382
- return value;
111383
- }
111384
- const result = {};
111385
- for (const [key, propertyValue] of Object.entries(value)) {
111386
- if (key === "additionalProperties" && propertyValue === false) {
111387
- continue;
111388
- }
111389
- result[key] = removeAdditionalPropertiesFalse(propertyValue);
111390
- }
111391
- return result;
111392
- }
111393
- function prepareTools7({
111394
- tools,
111395
- toolChoice
111396
- }) {
111397
- tools = (tools == null ? undefined : tools.length) ? tools : undefined;
111398
- const toolWarnings = [];
111399
- if (tools == null) {
111400
- return { tools: undefined, toolChoice: undefined, toolWarnings };
111401
- }
111402
- const xaiTools2 = [];
111403
- for (const tool of tools) {
111404
- if (tool.type === "provider") {
111405
- toolWarnings.push({
111406
- type: "unsupported",
111407
- feature: `provider-defined tool ${tool.name}`
111408
- });
111409
- } else {
111410
- xaiTools2.push({
111411
- type: "function",
111412
- function: {
111413
- name: tool.name,
111414
- description: tool.description,
111415
- parameters: removeAdditionalPropertiesFalse(tool.inputSchema),
111416
- ...tool.strict != null ? { strict: tool.strict } : {}
111417
- }
111418
- });
111419
- }
111420
- }
111421
- if (toolChoice == null) {
111422
- return { tools: xaiTools2, toolChoice: undefined, toolWarnings };
111423
- }
111424
- const type = toolChoice.type;
111425
- switch (type) {
111426
- case "auto":
111427
- case "none":
111428
- return { tools: xaiTools2, toolChoice: type, toolWarnings };
111429
- case "required":
111430
- return { tools: xaiTools2, toolChoice: "required", toolWarnings };
111431
- case "tool":
111432
- return {
111433
- tools: xaiTools2,
111434
- toolChoice: {
111435
- type: "function",
111436
- function: { name: toolChoice.toolName }
111437
- },
111438
- toolWarnings
111439
- };
111440
- default: {
111441
- const _exhaustiveCheck = type;
111442
- throw new UnsupportedFunctionalityError4({
111443
- functionality: `tool choice type: ${_exhaustiveCheck}`
111444
- });
111445
- }
111446
- }
111447
- }
111448
- var XaiChatLanguageModel = class _XaiChatLanguageModel {
111449
- constructor(modelId, config) {
111450
- this.specificationVersion = "v4";
111451
- this.supportedUrls = {
111452
- "image/*": [/^https?:\/\/.*$/]
111453
- };
111454
- this.modelId = modelId;
111455
- this.config = config;
111456
- }
111457
- static [WORKFLOW_SERIALIZE](model) {
111458
- return serializeModelOptions4({
111459
- modelId: model.modelId,
111460
- config: model.config
111461
- });
111462
- }
111463
- static [WORKFLOW_DESERIALIZE](options) {
111464
- return new _XaiChatLanguageModel(options.modelId, options.config);
111465
- }
111466
- get provider() {
111467
- return this.config.provider;
111468
- }
111469
- async getArgs({
111470
- prompt,
111471
- maxOutputTokens,
111472
- temperature,
111473
- topP,
111474
- topK,
111475
- frequencyPenalty,
111476
- presencePenalty,
111477
- stopSequences,
111478
- seed,
111479
- reasoning,
111480
- responseFormat,
111481
- providerOptions,
111482
- tools,
111483
- toolChoice
111484
- }) {
111485
- var _a, _b, _c;
111486
- const warnings = [];
111487
- const options = (_a = await parseProviderOptions4({
111488
- provider: "xai",
111489
- providerOptions,
111490
- schema: xaiLanguageModelChatOptions
111491
- })) != null ? _a : {};
111492
- if (topK != null) {
111493
- warnings.push({ type: "unsupported", feature: "topK" });
111494
- }
111495
- if (frequencyPenalty != null) {
111496
- warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
111497
- }
111498
- if (presencePenalty != null) {
111499
- warnings.push({ type: "unsupported", feature: "presencePenalty" });
111500
- }
111501
- if (stopSequences != null) {
111502
- warnings.push({ type: "unsupported", feature: "stopSequences" });
111503
- }
111504
- const { messages, warnings: messageWarnings } = await convertToXaiChatMessages(prompt);
111505
- warnings.push(...messageWarnings);
111506
- const {
111507
- tools: xaiTools2,
111508
- toolChoice: xaiToolChoice,
111509
- toolWarnings
111510
- } = prepareTools7({
111511
- tools,
111512
- toolChoice
111513
- });
111514
- warnings.push(...toolWarnings);
111515
- let reasoningEffort = options.reasoningEffort;
111516
- if (reasoningEffort == null && isCustomReasoning4(reasoning)) {
111517
- if (!supportsReasoningEffort(this.modelId)) {
111518
- warnings.push({
111519
- type: "unsupported",
111520
- feature: "reasoning",
111521
- details: `reasoning "${reasoning}" is not supported by this model.`
111522
- });
111523
- } else if (reasoning === "none") {
111524
- reasoningEffort = "none";
111525
- } else {
111526
- reasoningEffort = mapReasoningToProviderEffort4({
111527
- reasoning,
111528
- effortMap: {
111529
- minimal: "low",
111530
- low: "low",
111531
- medium: "medium",
111532
- high: "high",
111533
- xhigh: this.modelId === "grok-4.6" ? "xhigh" : "high"
111534
- },
111535
- warnings
111536
- });
111537
- }
111538
- }
111539
- const baseArgs = {
111540
- model: this.modelId,
111541
- logprobs: options.logprobs === true || options.topLogprobs != null ? true : undefined,
111542
- top_logprobs: options.topLogprobs,
111543
- max_completion_tokens: maxOutputTokens,
111544
- temperature,
111545
- top_p: topP,
111546
- seed,
111547
- reasoning_effort: reasoningEffort,
111548
- service_tier: options.serviceTier,
111549
- parallel_function_calling: options.parallel_function_calling,
111550
- response_format: (responseFormat == null ? undefined : responseFormat.type) === "json" ? responseFormat.schema != null ? {
111551
- type: "json_schema",
111552
- json_schema: {
111553
- name: (_b = responseFormat.name) != null ? _b : "response",
111554
- schema: responseFormat.schema,
111555
- strict: true
111556
- }
111557
- } : { type: "json_object" } : undefined,
111558
- search_parameters: options.searchParameters ? {
111559
- mode: options.searchParameters.mode,
111560
- return_citations: options.searchParameters.returnCitations,
111561
- from_date: options.searchParameters.fromDate,
111562
- to_date: options.searchParameters.toDate,
111563
- max_search_results: options.searchParameters.maxSearchResults,
111564
- sources: (_c = options.searchParameters.sources) == null ? undefined : _c.map((source) => {
111565
- var _a2;
111566
- return {
111567
- type: source.type,
111568
- ...source.type === "web" && {
111569
- country: source.country,
111570
- excluded_websites: source.excludedWebsites,
111571
- allowed_websites: source.allowedWebsites,
111572
- safe_search: source.safeSearch
111573
- },
111574
- ...source.type === "x" && {
111575
- excluded_x_handles: source.excludedXHandles,
111576
- included_x_handles: (_a2 = source.includedXHandles) != null ? _a2 : source.xHandles,
111577
- post_favorite_count: source.postFavoriteCount,
111578
- post_view_count: source.postViewCount
111579
- },
111580
- ...source.type === "news" && {
111581
- country: source.country,
111582
- excluded_websites: source.excludedWebsites,
111583
- safe_search: source.safeSearch
111584
- },
111585
- ...source.type === "rss" && {
111586
- links: source.links
111587
- }
111588
- };
111589
- })
111590
- } : undefined,
111591
- messages,
111592
- tools: xaiTools2,
111593
- tool_choice: xaiToolChoice
111594
- };
111595
- return {
111596
- args: baseArgs,
111597
- warnings
111598
- };
111599
- }
111600
- async doGenerate(options) {
111601
- var _a, _b, _c, _d;
111602
- const { args: body, warnings } = await this.getArgs(options);
111603
- const url = `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`;
111604
- const {
111605
- responseHeaders,
111606
- value: response,
111607
- rawValue: rawResponse
111608
- } = await postJsonToApi4({
111609
- url,
111610
- headers: combineHeaders4((_c = (_b = this.config).headers) == null ? undefined : _c.call(_b), options.headers),
111611
- body,
111612
- failedResponseHandler: xaiFailedResponseHandler,
111613
- successfulResponseHandler: createJsonResponseHandler4(xaiChatResponseSchema),
111614
- abortSignal: options.abortSignal,
111615
- fetch: this.config.fetch
111616
- });
111617
- if (response.error != null) {
111618
- throw new APICallError4({
111619
- message: response.error,
111620
- url,
111621
- requestBodyValues: body,
111622
- statusCode: 200,
111623
- responseHeaders,
111624
- responseBody: JSON.stringify(rawResponse),
111625
- isRetryable: response.code === "The service is currently unavailable"
111626
- });
111627
- }
111628
- const choice = response.choices[0];
111629
- const content = [];
111630
- if (choice.message.content != null && choice.message.content.length > 0) {
111631
- let text = choice.message.content;
111632
- const lastMessage = body.messages[body.messages.length - 1];
111633
- if ((lastMessage == null ? undefined : lastMessage.role) === "assistant" && text === lastMessage.content) {
111634
- text = "";
111635
- }
111636
- if (text.length > 0) {
111637
- content.push({ type: "text", text });
111638
- }
111639
- }
111640
- if (choice.message.reasoning_content != null && choice.message.reasoning_content.length > 0) {
111641
- content.push({
111642
- type: "reasoning",
111643
- text: choice.message.reasoning_content
111644
- });
111645
- }
111646
- if (choice.message.tool_calls != null) {
111647
- for (const toolCall of choice.message.tool_calls) {
111648
- content.push({
111649
- type: "tool-call",
111650
- toolCallId: toolCall.id,
111651
- toolName: toolCall.function.name,
111652
- input: toolCall.function.arguments
111653
- });
111654
- }
111655
- }
111656
- if (response.citations != null) {
111657
- for (const url2 of response.citations) {
111658
- content.push({
111659
- type: "source",
111660
- sourceType: "url",
111661
- id: this.config.generateId(),
111662
- url: url2
111663
- });
111664
- }
111665
- }
111666
- return {
111667
- content,
111668
- finishReason: {
111669
- unified: mapXaiFinishReason(choice.finish_reason),
111670
- raw: (_d = choice.finish_reason) != null ? _d : undefined
111671
- },
111672
- usage: response.usage ? convertXaiChatUsage(response.usage) : {
111673
- inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
111674
- outputTokens: { total: 0, text: 0, reasoning: 0 }
111675
- },
111676
- ...response.service_tier != null && {
111677
- providerMetadata: {
111678
- xai: { serviceTier: response.service_tier }
111679
- }
111680
- },
111681
- request: { body },
111682
- response: {
111683
- ...getResponseMetadata2(response),
111684
- headers: responseHeaders,
111685
- body: rawResponse
111686
- },
111687
- warnings
111688
- };
111689
- }
111690
- async doStream(options) {
111691
- var _a, _b, _c;
111692
- const { args, warnings } = await this.getArgs(options);
111693
- const body = {
111694
- ...args,
111695
- stream: true,
111696
- stream_options: {
111697
- include_usage: true
111698
- }
111699
- };
111700
- const url = `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`;
111701
- const { responseHeaders, value: response } = await postJsonToApi4({
111702
- url,
111703
- headers: combineHeaders4((_c = (_b = this.config).headers) == null ? undefined : _c.call(_b), options.headers),
111704
- body,
111705
- failedResponseHandler: xaiFailedResponseHandler,
111706
- successfulResponseHandler: async ({ response: response2 }) => {
111707
- const responseHeaders2 = extractResponseHeaders4(response2);
111708
- const contentType = response2.headers.get("content-type");
111709
- if (contentType == null ? undefined : contentType.includes("application/json")) {
111710
- const responseBody = await response2.text();
111711
- const parsedError = await safeParseJSON4({
111712
- text: responseBody,
111713
- schema: xaiStreamErrorSchema
111714
- });
111715
- if (parsedError.success) {
111716
- throw new APICallError4({
111717
- message: parsedError.value.error,
111718
- url,
111719
- requestBodyValues: body,
111720
- statusCode: 200,
111721
- responseHeaders: responseHeaders2,
111722
- responseBody,
111723
- isRetryable: parsedError.value.code === "The service is currently unavailable"
111724
- });
111725
- }
111726
- throw new APICallError4({
111727
- message: "Invalid JSON response",
111728
- url,
111729
- requestBodyValues: body,
111730
- statusCode: 200,
111731
- responseHeaders: responseHeaders2,
111732
- responseBody
111733
- });
111734
- }
111735
- return createEventSourceResponseHandler4(xaiChatChunkSchema)({
111736
- response: response2,
111737
- url,
111738
- requestBodyValues: body
111739
- });
111740
- },
111741
- abortSignal: options.abortSignal,
111742
- fetch: this.config.fetch
111743
- });
111744
- let finishReason = {
111745
- unified: "other",
111746
- raw: undefined
111747
- };
111748
- let usage = undefined;
111749
- let serviceTier = undefined;
111750
- let isFirstChunk = true;
111751
- const contentBlocks = {};
111752
- const lastReasoningDeltas = {};
111753
- let activeReasoningBlockId = undefined;
111754
- const self = this;
111755
- return {
111756
- stream: response.pipeThrough(new TransformStream({
111757
- start(controller) {
111758
- controller.enqueue({ type: "stream-start", warnings });
111759
- },
111760
- transform(chunk, controller) {
111761
- if (options.includeRawChunks) {
111762
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
111763
- }
111764
- if (!chunk.success) {
111765
- controller.enqueue({ type: "error", error: chunk.error });
111766
- return;
111767
- }
111768
- const value = chunk.value;
111769
- if (isFirstChunk) {
111770
- controller.enqueue({
111771
- type: "response-metadata",
111772
- ...getResponseMetadata2(value)
111773
- });
111774
- isFirstChunk = false;
111775
- }
111776
- if (value.citations != null) {
111777
- for (const url2 of value.citations) {
111778
- controller.enqueue({
111779
- type: "source",
111780
- sourceType: "url",
111781
- id: self.config.generateId(),
111782
- url: url2
111783
- });
111784
- }
111785
- }
111786
- if (value.usage != null) {
111787
- usage = convertXaiChatUsage(value.usage);
111788
- }
111789
- if (value.service_tier != null) {
111790
- serviceTier = value.service_tier;
111791
- }
111792
- const choice = value.choices[0];
111793
- if ((choice == null ? undefined : choice.finish_reason) != null) {
111794
- finishReason = {
111795
- unified: mapXaiFinishReason(choice.finish_reason),
111796
- raw: choice.finish_reason
111797
- };
111798
- }
111799
- if ((choice == null ? undefined : choice.delta) == null) {
111800
- return;
111801
- }
111802
- const delta = choice.delta;
111803
- const choiceIndex = choice.index;
111804
- if (delta.content != null && delta.content.length > 0) {
111805
- const textContent = delta.content;
111806
- if (activeReasoningBlockId != null && !contentBlocks[activeReasoningBlockId].ended) {
111807
- controller.enqueue({
111808
- type: "reasoning-end",
111809
- id: activeReasoningBlockId
111810
- });
111811
- contentBlocks[activeReasoningBlockId].ended = true;
111812
- activeReasoningBlockId = undefined;
111813
- }
111814
- const lastMessage = body.messages[body.messages.length - 1];
111815
- if ((lastMessage == null ? undefined : lastMessage.role) === "assistant" && textContent === lastMessage.content) {
111816
- return;
111817
- }
111818
- const blockId = `text-${value.id || choiceIndex}`;
111819
- if (contentBlocks[blockId] == null) {
111820
- contentBlocks[blockId] = { type: "text", ended: false };
111821
- controller.enqueue({
111822
- type: "text-start",
111823
- id: blockId
111824
- });
111825
- }
111826
- controller.enqueue({
111827
- type: "text-delta",
111828
- id: blockId,
111829
- delta: textContent
111830
- });
111831
- }
111832
- if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
111833
- const blockId = `reasoning-${value.id || choiceIndex}`;
111834
- if (lastReasoningDeltas[blockId] === delta.reasoning_content) {
111835
- return;
111836
- }
111837
- lastReasoningDeltas[blockId] = delta.reasoning_content;
111838
- if (contentBlocks[blockId] == null) {
111839
- contentBlocks[blockId] = { type: "reasoning", ended: false };
111840
- activeReasoningBlockId = blockId;
111841
- controller.enqueue({
111842
- type: "reasoning-start",
111843
- id: blockId
111844
- });
111845
- }
111846
- controller.enqueue({
111847
- type: "reasoning-delta",
111848
- id: blockId,
111849
- delta: delta.reasoning_content
111850
- });
111851
- }
111852
- if (delta.tool_calls != null && delta.tool_calls.length > 0) {
111853
- if (activeReasoningBlockId != null && !contentBlocks[activeReasoningBlockId].ended) {
111854
- controller.enqueue({
111855
- type: "reasoning-end",
111856
- id: activeReasoningBlockId
111857
- });
111858
- contentBlocks[activeReasoningBlockId].ended = true;
111859
- activeReasoningBlockId = undefined;
111860
- }
111861
- for (const toolCall of delta.tool_calls) {
111862
- const toolCallId = toolCall.id;
111863
- controller.enqueue({
111864
- type: "tool-input-start",
111865
- id: toolCallId,
111866
- toolName: toolCall.function.name
111867
- });
111868
- controller.enqueue({
111869
- type: "tool-input-delta",
111870
- id: toolCallId,
111871
- delta: toolCall.function.arguments
111872
- });
111873
- controller.enqueue({
111874
- type: "tool-input-end",
111875
- id: toolCallId
111876
- });
111877
- controller.enqueue({
111878
- type: "tool-call",
111879
- toolCallId,
111880
- toolName: toolCall.function.name,
111881
- input: toolCall.function.arguments
111882
- });
111883
- }
111884
- }
111885
- },
111886
- flush(controller) {
111887
- for (const [blockId, block] of Object.entries(contentBlocks)) {
111888
- if (!block.ended) {
111889
- controller.enqueue({
111890
- type: block.type === "text" ? "text-end" : "reasoning-end",
111891
- id: blockId
111892
- });
111893
- }
111894
- }
111895
- controller.enqueue({
111896
- type: "finish",
111897
- finishReason,
111898
- usage: usage != null ? usage : {
111899
- inputTokens: {
111900
- total: 0,
111901
- noCache: 0,
111902
- cacheRead: 0,
111903
- cacheWrite: 0
111904
- },
111905
- outputTokens: { total: 0, text: 0, reasoning: 0 }
111906
- },
111907
- ...serviceTier != null && {
111908
- providerMetadata: { xai: { serviceTier } }
111909
- }
111910
- });
111911
- }
111912
- })),
111913
- request: { body },
111914
- response: { headers: responseHeaders }
111915
- };
111916
- }
111917
- };
111918
- var xaiUsageSchema = object({
111919
- prompt_tokens: number2(),
111920
- completion_tokens: number2(),
111921
- total_tokens: number2(),
111922
- cost_in_usd_ticks: number2().nullish(),
111923
- prompt_tokens_details: object({
111924
- text_tokens: number2().nullish(),
111925
- audio_tokens: number2().nullish(),
111926
- image_tokens: number2().nullish(),
111927
- cached_tokens: number2().nullish()
111928
- }).catchall(json()).nullish(),
111929
- completion_tokens_details: object({
111930
- reasoning_tokens: number2().nullish(),
111931
- audio_tokens: number2().nullish(),
111932
- accepted_prediction_tokens: number2().nullish(),
111933
- rejected_prediction_tokens: number2().nullish()
111934
- }).catchall(json()).nullish()
111935
- }).catchall(json());
111936
- var xaiChatResponseSchema = object({
111937
- id: string2().nullish(),
111938
- created: number2().nullish(),
111939
- model: string2().nullish(),
111940
- choices: array(object({
111941
- message: object({
111942
- role: _enum(["assistant", "tool"]),
111943
- content: string2().nullish(),
111944
- reasoning_content: string2().nullish(),
111945
- tool_calls: array(object({
111946
- id: string2(),
111947
- type: literal("function"),
111948
- function: object({
111949
- name: string2(),
111950
- arguments: string2()
111951
- })
111952
- })).nullish()
111953
- }),
111954
- index: number2(),
111955
- finish_reason: string2().nullish()
111956
- })).nullish(),
111957
- object: literal("chat.completion").nullish(),
111958
- usage: xaiUsageSchema.nullish(),
111959
- citations: array(string2().url()).nullish(),
111960
- service_tier: string2().nullish(),
111961
- code: string2().nullish(),
111962
- error: string2().nullish()
111963
- });
111964
- var xaiChatChunkSchema = object({
111965
- id: string2().nullish(),
111966
- created: number2().nullish(),
111967
- model: string2().nullish(),
111968
- choices: array(object({
111969
- delta: object({
111970
- role: _enum(["assistant"]).optional(),
111971
- content: string2().nullish(),
111972
- reasoning_content: string2().nullish(),
111973
- tool_calls: array(object({
111974
- id: string2(),
111975
- type: literal("function"),
111976
- function: object({
111977
- name: string2(),
111978
- arguments: string2()
111979
- })
111980
- })).nullish()
111981
- }),
111982
- finish_reason: string2().nullish(),
111983
- index: number2()
111984
- })),
111985
- usage: xaiUsageSchema.nullish(),
111986
- citations: array(string2().url()).nullish(),
111987
- service_tier: string2().nullish()
111988
- });
111989
- var xaiStreamErrorSchema = object({
111990
- code: string2(),
111991
- error: string2()
111992
- });
111993
111548
  var xaiImageModelOptions = object({
111994
111549
  aspect_ratio: string2().optional(),
111995
111550
  output_format: string2().optional(),
@@ -112148,6 +111703,33 @@ var xaiImageResponseSchema = object({
112148
111703
  cost_in_usd_ticks: number2().nullish()
112149
111704
  }).nullish()
112150
111705
  });
111706
+ function getResponseMetadata2({
111707
+ id,
111708
+ model,
111709
+ created,
111710
+ created_at
111711
+ }) {
111712
+ return createLanguageModelResponseMetadata4({
111713
+ id,
111714
+ model,
111715
+ created: created != null ? created : created_at
111716
+ });
111717
+ }
111718
+ function mapXaiFinishReason(finishReason) {
111719
+ switch (finishReason) {
111720
+ case "stop":
111721
+ return "stop";
111722
+ case "length":
111723
+ return "length";
111724
+ case "tool_calls":
111725
+ case "function_call":
111726
+ return "tool-calls";
111727
+ case "content_filter":
111728
+ return "content-filter";
111729
+ default:
111730
+ return "other";
111731
+ }
111732
+ }
112151
111733
  var xaiFilesResponseSchema = lazySchema4(() => zodSchema4(object({
112152
111734
  id: string2(),
112153
111735
  object: string2().nullish(),
@@ -112163,6 +111745,13 @@ var xaiFileDeleteResponseSchema = lazySchema4(() => zodSchema4(object({
112163
111745
  object: string2().nullish(),
112164
111746
  deleted: boolean2()
112165
111747
  })));
111748
+ var modelsWithoutReasoningEffort = /^grok-4\.20(-\d{4})?-(non-)?reasoning$/;
111749
+ function supportsReasoningEffort(modelId) {
111750
+ return !modelsWithoutReasoningEffort.test(modelId);
111751
+ }
111752
+ var xaiFilePartProviderOptions = object({
111753
+ imageDetail: _enum(["low", "high", "auto"]).optional()
111754
+ });
112166
111755
  async function convertToXaiResponsesInput({
112167
111756
  prompt
112168
111757
  }) {
@@ -113136,7 +112725,7 @@ async function prepareResponsesTools2({
113136
112725
  type: "function",
113137
112726
  name: tool.name,
113138
112727
  description: tool.description,
113139
- parameters: removeAdditionalPropertiesFalse(tool.inputSchema),
112728
+ parameters: tool.inputSchema,
113140
112729
  ...tool.strict != null ? { strict: tool.strict } : {}
113141
112730
  });
113142
112731
  }
@@ -114272,6 +113861,40 @@ var xaiBatchResultSchema = object({
114272
113861
  }).nullish(),
114273
113862
  error_message: string2().nullish()
114274
113863
  });
113864
+ var xaiBatchTextResponseSchema = object({
113865
+ id: string2().nullish(),
113866
+ created: number2().nullish(),
113867
+ model: string2().nullish(),
113868
+ choices: array(object({
113869
+ message: object({
113870
+ role: _enum(["assistant", "tool"]),
113871
+ content: string2().nullish(),
113872
+ reasoning_content: string2().nullish(),
113873
+ tool_calls: array(object({
113874
+ id: string2(),
113875
+ type: literal("function"),
113876
+ function: object({
113877
+ name: string2(),
113878
+ arguments: string2()
113879
+ })
113880
+ })).nullish()
113881
+ }),
113882
+ index: number2(),
113883
+ finish_reason: string2().nullish()
113884
+ })).nullish(),
113885
+ usage: object({
113886
+ prompt_tokens: number2(),
113887
+ completion_tokens: number2(),
113888
+ total_tokens: number2(),
113889
+ cost_in_usd_ticks: number2().nullish(),
113890
+ prompt_tokens_details: object({ cached_tokens: number2().nullish() }).nullish(),
113891
+ completion_tokens_details: object({ reasoning_tokens: number2().nullish() }).nullish()
113892
+ }).nullish(),
113893
+ citations: array(string2().url()).nullish(),
113894
+ service_tier: string2().nullish(),
113895
+ code: string2().nullish(),
113896
+ error: string2().nullish()
113897
+ });
114275
113898
  var xaiBatchResultsPageSchema = lazySchema4(() => zodSchema4(object({
114276
113899
  results: array(xaiBatchResultSchema),
114277
113900
  pagination_token: string2().nullish()
@@ -114468,12 +114091,12 @@ var XaiBatch = class {
114468
114091
  if ((response == null ? undefined : response.chat_get_completion) != null) {
114469
114092
  const validation = await safeValidateTypes4({
114470
114093
  value: response.chat_get_completion,
114471
- schema: xaiChatResponseSchema
114094
+ schema: zodSchema4(xaiBatchTextResponseSchema)
114472
114095
  });
114473
114096
  if (!validation.success) {
114474
114097
  return invalidXaiBatchResult(result.batch_request_id);
114475
114098
  }
114476
- const conversion = convertXaiChatBatchResponse(validation.value);
114099
+ const conversion = convertXaiBatchTextResponse(validation.value);
114477
114100
  return conversion.success ? {
114478
114101
  type: "text",
114479
114102
  id: result.batch_request_id,
@@ -114683,7 +114306,7 @@ function invalidXaiImageBatchResult(id) {
114683
114306
  }
114684
114307
  };
114685
114308
  }
114686
- function convertXaiChatBatchResponse(response) {
114309
+ function convertXaiBatchTextResponse(response) {
114687
114310
  var _a, _b, _c, _d, _e, _f;
114688
114311
  if (response.error != null) {
114689
114312
  return {
@@ -114761,7 +114384,7 @@ function convertXaiChatBatchResponse(response) {
114761
114384
  unified: mapXaiFinishReason(lastAssistantChoice == null ? undefined : lastAssistantChoice.finish_reason),
114762
114385
  raw: (_d = lastAssistantChoice == null ? undefined : lastAssistantChoice.finish_reason) != null ? _d : undefined
114763
114386
  },
114764
- usage: response.usage ? convertXaiChatUsage(response.usage) : createNullLanguageModelUsage5(),
114387
+ usage: response.usage ? convertXaiBatchTextUsage(response.usage) : createNullLanguageModelUsage5(),
114765
114388
  response: getResponseMetadata2(response),
114766
114389
  warnings: [],
114767
114390
  ...(((_e = response.usage) == null ? undefined : _e.cost_in_usd_ticks) != null || response.service_tier != null) && {
@@ -114775,6 +114398,26 @@ function convertXaiChatBatchResponse(response) {
114775
114398
  }
114776
114399
  };
114777
114400
  }
114401
+ function convertXaiBatchTextUsage(usage) {
114402
+ var _a, _b, _c, _d;
114403
+ const cacheReadTokens = (_b = (_a = usage.prompt_tokens_details) == null ? undefined : _a.cached_tokens) != null ? _b : 0;
114404
+ const reasoningTokens = (_d = (_c = usage.completion_tokens_details) == null ? undefined : _c.reasoning_tokens) != null ? _d : 0;
114405
+ const promptTokensIncludesCached = cacheReadTokens <= usage.prompt_tokens;
114406
+ return {
114407
+ inputTokens: {
114408
+ total: promptTokensIncludesCached ? usage.prompt_tokens : usage.prompt_tokens + cacheReadTokens,
114409
+ noCache: promptTokensIncludesCached ? usage.prompt_tokens - cacheReadTokens : usage.prompt_tokens,
114410
+ cacheRead: cacheReadTokens,
114411
+ cacheWrite: undefined
114412
+ },
114413
+ outputTokens: {
114414
+ total: usage.completion_tokens + reasoningTokens,
114415
+ text: usage.completion_tokens,
114416
+ reasoning: reasoningTokens
114417
+ },
114418
+ raw: usage
114419
+ };
114420
+ }
114778
114421
  function parseXaiRealtimeServerEvent(raw) {
114779
114422
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
114780
114423
  const event = raw;
@@ -115176,7 +114819,7 @@ var xaiTools = {
115176
114819
  webSearch: webSearch2,
115177
114820
  xSearch
115178
114821
  };
115179
- var VERSION15 = "4.0.58";
114822
+ var VERSION15 = "5.0.5";
115180
114823
  var xaiFilesOptionsSchema = lazySchema4(() => zodSchema4(looseObject({
115181
114824
  teamId: string2().optional(),
115182
114825
  filePath: string2().optional(),
@@ -116005,7 +115648,7 @@ var XaiSpeechModel = class _XaiSpeechModel {
116005
115648
  const { requestBody, warnings, withTimestamps } = await this.getArgs(options);
116006
115649
  const { value, responseHeaders, rawValue } = await postJsonToApi4({
116007
115650
  url: `${this.config.baseURL}/tts`,
116008
- headers: combineHeaders4(this.config.headers ? await resolve10(this.config.headers) : undefined, options.headers),
115651
+ headers: combineHeaders4(this.config.headers ? await resolve11(this.config.headers) : undefined, options.headers),
116009
115652
  body: requestBody,
116010
115653
  failedResponseHandler: xaiFailedResponseHandler,
116011
115654
  successfulResponseHandler: withTimestamps ? createJsonResponseHandler4(xaiSpeechTimestampsResponseSchema) : createBinaryResponseHandler2(),
@@ -116467,15 +116110,6 @@ function createXai(options = {}) {
116467
116110
  })}`,
116468
116111
  ...options.headers
116469
116112
  }, `ai-sdk/xai/${VERSION15}`);
116470
- const createChatLanguageModel = (modelId) => {
116471
- return new XaiChatLanguageModel(modelId, {
116472
- provider: "xai.chat",
116473
- baseURL,
116474
- headers: getHeaders,
116475
- generateId: generateId4,
116476
- fetch: options.fetch
116477
- });
116478
- };
116479
116113
  const createResponsesLanguageModel = (modelId) => {
116480
116114
  return new XaiResponsesLanguageModel(modelId, {
116481
116115
  provider: "xai.responses",
@@ -116559,7 +116193,6 @@ function createXai(options = {}) {
116559
116193
  const provider = (modelId) => createResponsesLanguageModel(modelId);
116560
116194
  provider.specificationVersion = "v4";
116561
116195
  provider.languageModel = createResponsesLanguageModel;
116562
- provider.chat = createChatLanguageModel;
116563
116196
  provider.responses = createResponsesLanguageModel;
116564
116197
  provider.embeddingModel = (modelId) => {
116565
116198
  throw new NoSuchModelError4({ modelId, modelType: "embeddingModel" });
@@ -116876,6 +116509,55 @@ Mode: BUILD — You have full tool access. File writes and edits are automatical
116876
116509
  }
116877
116510
 
116878
116511
  // src/packages/agents/src/engine/agent-session.ts
116512
+ function translateAgentEventToLogEvent(event, context) {
116513
+ if (event.type === "tool-call") {
116514
+ return {
116515
+ schemaVersion: 1,
116516
+ sessionId: context.sessionId,
116517
+ turnId: context.turnId,
116518
+ type: "tool-start",
116519
+ timestamp: new Date().toISOString(),
116520
+ toolCallId: event.toolCall.id,
116521
+ toolName: event.toolCall.name,
116522
+ startedAt: new Date().toISOString()
116523
+ };
116524
+ }
116525
+ if (event.type === "tool-result") {
116526
+ const toolDef = defaultToolCatalog.get(event.toolResult.name);
116527
+ const summaryObj = summarizeToolResult(toolDef, event.toolResult.args, event.toolResult.result, event.toolResult.isError);
116528
+ const outputSummary = formatPlainToolSummary(summaryObj);
116529
+ const errorMessage = event.toolResult.isError ? typeof event.toolResult.result === "object" && event.toolResult.result !== null ? event.toolResult.result.message ?? JSON.stringify(event.toolResult.result) : String(event.toolResult.result) : undefined;
116530
+ const status = event.toolResult.isError ? "failed" : "completed";
116531
+ return {
116532
+ schemaVersion: 1,
116533
+ sessionId: context.sessionId,
116534
+ turnId: context.turnId,
116535
+ type: "tool-end",
116536
+ timestamp: event.toolResult.finishedAt ?? new Date().toISOString(),
116537
+ toolCallId: event.toolResult.id,
116538
+ toolName: event.toolResult.name,
116539
+ finishedAt: event.toolResult.finishedAt ?? new Date().toISOString(),
116540
+ durationMs: event.toolResult.durationMs,
116541
+ status,
116542
+ displayName: toolDef?.displayName,
116543
+ icon: toolDef?.icon,
116544
+ outputSummary,
116545
+ errorMessage
116546
+ };
116547
+ }
116548
+ return null;
116549
+ }
116550
+ function accumulateUsage(current, delta) {
116551
+ return {
116552
+ inputTokens: current.inputTokens + delta.inputTokens,
116553
+ outputTokens: current.outputTokens + delta.outputTokens,
116554
+ totalTokens: current.totalTokens + delta.totalTokens,
116555
+ reasoningTokens: delta.reasoningTokens !== undefined ? (current.reasoningTokens ?? 0) + delta.reasoningTokens : current.reasoningTokens,
116556
+ cacheReadTokens: delta.cacheReadTokens !== undefined ? (current.cacheReadTokens ?? 0) + delta.cacheReadTokens : current.cacheReadTokens,
116557
+ cacheWriteTokens: delta.cacheWriteTokens !== undefined ? (current.cacheWriteTokens ?? 0) + delta.cacheWriteTokens : current.cacheWriteTokens
116558
+ };
116559
+ }
116560
+
116879
116561
  class AgentSession {
116880
116562
  config;
116881
116563
  model;
@@ -117049,39 +116731,12 @@ class AgentSession {
117049
116731
  chatMode: mode
117050
116732
  });
117051
116733
  const wrappedOnEvent = (event) => {
117052
- if (event.type === "tool-call") {
117053
- this.sessionLogWriter?.append({
117054
- schemaVersion: 1,
117055
- sessionId: this.sessionData.id,
117056
- turnId,
117057
- type: "tool-start",
117058
- timestamp: new Date().toISOString(),
117059
- toolCallId: event.toolCall.id,
117060
- toolName: event.toolCall.name,
117061
- startedAt: new Date().toISOString()
117062
- });
117063
- } else if (event.type === "tool-result") {
117064
- const toolDef = defaultToolCatalog.get(event.toolResult.name);
117065
- const summaryObj = summarizeToolResult(toolDef, event.toolResult.args, event.toolResult.result, event.toolResult.isError);
117066
- const outputSummary = formatPlainToolSummary(summaryObj);
117067
- const errorMessage = event.toolResult.isError ? typeof event.toolResult.result === "object" && event.toolResult.result !== null ? event.toolResult.result.message ?? JSON.stringify(event.toolResult.result) : String(event.toolResult.result) : undefined;
117068
- const status = event.toolResult.isError ? "failed" : "completed";
117069
- this.sessionLogWriter?.append({
117070
- schemaVersion: 1,
117071
- sessionId: this.sessionData.id,
117072
- turnId,
117073
- type: "tool-end",
117074
- timestamp: event.toolResult.finishedAt ?? new Date().toISOString(),
117075
- toolCallId: event.toolResult.id,
117076
- toolName: event.toolResult.name,
117077
- finishedAt: event.toolResult.finishedAt ?? new Date().toISOString(),
117078
- durationMs: event.toolResult.durationMs,
117079
- status,
117080
- displayName: toolDef?.displayName,
117081
- icon: toolDef?.icon,
117082
- outputSummary,
117083
- errorMessage
117084
- });
116734
+ const logEvent = translateAgentEventToLogEvent(event, {
116735
+ sessionId: this.sessionData.id,
116736
+ turnId
116737
+ });
116738
+ if (logEvent) {
116739
+ this.sessionLogWriter?.append(logEvent);
117085
116740
  }
117086
116741
  options.onEvent?.(event);
117087
116742
  };
@@ -117114,15 +116769,7 @@ class AgentSession {
117114
116769
  this.messages.push(assistantMsg);
117115
116770
  responseMessages.push(assistantMsg);
117116
116771
  }
117117
- this.accumulatedUsage.inputTokens += summary.usage.inputTokens;
117118
- this.accumulatedUsage.outputTokens += summary.usage.outputTokens;
117119
- this.accumulatedUsage.totalTokens += summary.usage.totalTokens;
117120
- if (summary.usage.reasoningTokens) {
117121
- this.accumulatedUsage.reasoningTokens = (this.accumulatedUsage.reasoningTokens ?? 0) + summary.usage.reasoningTokens;
117122
- }
117123
- if (summary.usage.cacheReadTokens) {
117124
- this.accumulatedUsage.cacheReadTokens = (this.accumulatedUsage.cacheReadTokens ?? 0) + summary.usage.cacheReadTokens;
117125
- }
116772
+ this.accumulatedUsage = accumulateUsage(this.accumulatedUsage, summary.usage);
117126
116773
  const statusVerb = chooseTurnStatusVerb();
117127
116774
  summary.statusVerb = statusVerb;
117128
116775
  const turnMessages = [userMessage, ...responseMessages];
@@ -117161,15 +116808,7 @@ class AgentSession {
117161
116808
  const responseMessages = summary?.rawMessages ?? [];
117162
116809
  const turnMessages = [userMessage, ...responseMessages];
117163
116810
  if (summary) {
117164
- this.accumulatedUsage.inputTokens += summary.usage.inputTokens;
117165
- this.accumulatedUsage.outputTokens += summary.usage.outputTokens;
117166
- this.accumulatedUsage.totalTokens += summary.usage.totalTokens;
117167
- if (summary.usage.reasoningTokens) {
117168
- this.accumulatedUsage.reasoningTokens = (this.accumulatedUsage.reasoningTokens ?? 0) + summary.usage.reasoningTokens;
117169
- }
117170
- if (summary.usage.cacheReadTokens) {
117171
- this.accumulatedUsage.cacheReadTokens = (this.accumulatedUsage.cacheReadTokens ?? 0) + summary.usage.cacheReadTokens;
117172
- }
116811
+ this.accumulatedUsage = accumulateUsage(this.accumulatedUsage, summary.usage);
117173
116812
  summary.statusVerb = statusVerb;
117174
116813
  recordSessionTurn(this.sessionData, {
117175
116814
  id: turnId,
@@ -117353,10 +116992,7 @@ var quitCommand = {
117353
116992
  };
117354
116993
 
117355
116994
  // src/packages/agents/src/models/discovery.ts
117356
- var ANTHROPIC_MODEL_REGEX = /^claude-/i;
117357
- var OPENAI_MODEL_REGEX = /^(gpt-4|gpt-3\.5|o1|o3)/i;
117358
- var GOOGLE_MODEL_INCLUDE_REGEX = /^(gemini|gemma)-/i;
117359
- var GOOGLE_MODEL_EXCLUDE_REGEX = /(omni|antigravity|robotics|embedding|audio|tts|transcribe|live|computer|image)/i;
116995
+ var NON_CHAT_MODEL_KEYWORDS = /(embed|similarity|search-document|dall-e|imagen|veo|whisper|tts|transcribe|speech|voice|audio|image|video|moderation|rerank|robotics|live|aqa|babbage|davinci|lyria|chirp)/i;
117360
116996
  var DEFAULT_FETCH_TIMEOUT_MS = 1e4;
117361
116997
  async function fetchOpenAIModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
117362
116998
  const response = await fetch("https://api.openai.com/v1/models", {
@@ -117373,7 +117009,7 @@ async function fetchOpenAIModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
117373
117009
  if (!Array.isArray(payload.data)) {
117374
117010
  return [];
117375
117011
  }
117376
- return payload.data.filter((item) => typeof item.id === "string" && OPENAI_MODEL_REGEX.test(item.id) && !/(audio|tts|transcribe)/i.test(item.id)).map((item) => ({
117012
+ return payload.data.filter((item) => typeof item.id === "string" && !NON_CHAT_MODEL_KEYWORDS.test(item.id)).map((item) => ({
117377
117013
  provider: "openai",
117378
117014
  model_id: item.id
117379
117015
  })).sort((a, b) => a.model_id.localeCompare(b.model_id));
@@ -117393,7 +117029,7 @@ async function fetchGeminiModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
117393
117029
  if (!Array.isArray(payload.data)) {
117394
117030
  return [];
117395
117031
  }
117396
- return payload.data.map((item) => typeof item.id === "string" ? item.id.replace(/^models\//, "") : "").filter((id) => id && GOOGLE_MODEL_INCLUDE_REGEX.test(id) && !GOOGLE_MODEL_EXCLUDE_REGEX.test(id)).map((id) => ({
117032
+ return payload.data.map((item) => typeof item.id === "string" ? item.id.replace(/^models\//, "") : "").filter((id) => id && !NON_CHAT_MODEL_KEYWORDS.test(id)).map((id) => ({
117397
117033
  provider: "gemini",
117398
117034
  model_id: id
117399
117035
  })).sort((a, b) => a.model_id.localeCompare(b.model_id));
@@ -117414,13 +117050,11 @@ async function fetchAnthropicModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS
117414
117050
  if (!Array.isArray(payload.data)) {
117415
117051
  return [];
117416
117052
  }
117417
- return payload.data.filter((item) => typeof item.id === "string" && ANTHROPIC_MODEL_REGEX.test(item.id)).map((item) => ({
117053
+ return payload.data.filter((item) => typeof item.id === "string" && !NON_CHAT_MODEL_KEYWORDS.test(item.id)).map((item) => ({
117418
117054
  provider: "anthropic",
117419
117055
  model_id: item.id
117420
117056
  })).sort((a, b) => a.model_id.localeCompare(b.model_id));
117421
117057
  }
117422
- var XAI_MODEL_INCLUDE_REGEX = /^grok-/i;
117423
- var XAI_MODEL_EXCLUDE_REGEX = /(imagine-image|imagine-video|-voice-|^grok-imagine)/i;
117424
117058
  async function fetchXaiModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
117425
117059
  const response = await fetch("https://api.x.ai/v1/models", {
117426
117060
  method: "GET",
@@ -117433,7 +117067,7 @@ async function fetchXaiModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
117433
117067
  const payload = await response.json();
117434
117068
  if (!Array.isArray(payload.data))
117435
117069
  return [];
117436
- return payload.data.filter((item) => typeof item.id === "string" && XAI_MODEL_INCLUDE_REGEX.test(item.id) && !XAI_MODEL_EXCLUDE_REGEX.test(item.id)).map((item) => ({ provider: "xai", model_id: item.id })).sort((a, b) => a.model_id.localeCompare(b.model_id));
117070
+ return payload.data.filter((item) => typeof item.id === "string" && !NON_CHAT_MODEL_KEYWORDS.test(item.id)).map((item) => ({ provider: "xai", model_id: item.id })).sort((a, b) => a.model_id.localeCompare(b.model_id));
117437
117071
  }
117438
117072
  async function fetchMistralModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
117439
117073
  const response = await fetch("https://api.mistral.ai/v1/models", {
@@ -117447,9 +117081,17 @@ async function fetchMistralModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS)
117447
117081
  const payload = await response.json();
117448
117082
  if (!Array.isArray(payload.data))
117449
117083
  return [];
117450
- return payload.data.filter((item) => typeof item.id === "string" && item.capabilities?.completion_chat === true && item.archived !== true && item.TYPE !== "fine-tuned").map((item) => ({ provider: "mistral", model_id: item.id })).sort((a, b) => a.model_id.localeCompare(b.model_id));
117084
+ return payload.data.filter((item) => {
117085
+ if (typeof item.id !== "string")
117086
+ return false;
117087
+ if (item.archived === true || item.TYPE === "fine-tuned")
117088
+ return false;
117089
+ if (item.capabilities && typeof item.capabilities.completion_chat === "boolean") {
117090
+ return item.capabilities.completion_chat;
117091
+ }
117092
+ return !NON_CHAT_MODEL_KEYWORDS.test(item.id);
117093
+ }).map((item) => ({ provider: "mistral", model_id: item.id })).sort((a, b) => a.model_id.localeCompare(b.model_id));
117451
117094
  }
117452
- var DEEPSEEK_MODEL_EXCLUDE_REGEX = /(embed|rerank|moderation)/i;
117453
117095
  async function fetchDeepSeekModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
117454
117096
  const response = await fetch("https://api.deepseek.com/models", {
117455
117097
  method: "GET",
@@ -117462,7 +117104,7 @@ async function fetchDeepSeekModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS)
117462
117104
  const payload = await response.json();
117463
117105
  if (!Array.isArray(payload.data))
117464
117106
  return [];
117465
- return payload.data.filter((item) => typeof item.id === "string" && !DEEPSEEK_MODEL_EXCLUDE_REGEX.test(item.id)).map((item) => ({ provider: "deepseek", model_id: item.id })).sort((a, b) => a.model_id.localeCompare(b.model_id));
117107
+ return payload.data.filter((item) => typeof item.id === "string" && !NON_CHAT_MODEL_KEYWORDS.test(item.id)).map((item) => ({ provider: "deepseek", model_id: item.id })).sort((a, b) => a.model_id.localeCompare(b.model_id));
117466
117108
  }
117467
117109
  async function fetchOpenRouterModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_MS) {
117468
117110
  const results = [];
@@ -117479,7 +117121,12 @@ async function fetchOpenRouterModels(apiKey, timeoutMs = DEFAULT_FETCH_TIMEOUT_M
117479
117121
  const payload = await response.json();
117480
117122
  if (Array.isArray(payload.data)) {
117481
117123
  for (const item of payload.data) {
117482
- if (typeof item.id === "string" && (item.architecture?.output_modalities?.includes("text") ?? true)) {
117124
+ if (typeof item.id !== "string")
117125
+ continue;
117126
+ const hasTextModality = item.architecture?.output_modalities?.includes("text");
117127
+ if (hasTextModality === false)
117128
+ continue;
117129
+ if (!NON_CHAT_MODEL_KEYWORDS.test(item.id)) {
117483
117130
  results.push({ provider: "openrouter", model_id: item.id });
117484
117131
  }
117485
117132
  }
@@ -117931,7 +117578,7 @@ for (const cmd of builtInCommands) {
117931
117578
  }
117932
117579
 
117933
117580
  // src/app/ui/components/Header.tsx
117934
- import { homedir as homedir7 } from "node:os";
117581
+ import { homedir as homedir8 } from "node:os";
117935
117582
 
117936
117583
  // src/packages/tui/src/engine/Component.ts
117937
117584
  class Component {
@@ -118505,7 +118152,7 @@ class Header extends Component_default {
118505
118152
  formatCwd(rawPath) {
118506
118153
  if (!rawPath)
118507
118154
  return "~";
118508
- const home = homedir7();
118155
+ const home = homedir8();
118509
118156
  if (rawPath.startsWith(home)) {
118510
118157
  return `~${rawPath.slice(home.length)}`;
118511
118158
  }
@@ -120322,6 +119969,8 @@ function extractPrimaryToolParam(args) {
120322
119969
  for (const k of primaryKeys) {
120323
119970
  if (record[k] !== undefined && record[k] !== null && record[k] !== "") {
120324
119971
  const val = record[k];
119972
+ if (Array.isArray(val))
119973
+ return `${val.length} item${val.length === 1 ? "" : "s"}`;
120325
119974
  const str = typeof val === "object" ? JSON.stringify(val) : String(val);
120326
119975
  return str.split(`
120327
119976
  `)[0] ?? "";
@@ -120329,6 +119978,8 @@ function extractPrimaryToolParam(args) {
120329
119978
  }
120330
119979
  const firstVal = Object.values(record)[0];
120331
119980
  if (firstVal !== undefined && firstVal !== null && firstVal !== "") {
119981
+ if (Array.isArray(firstVal))
119982
+ return `${firstVal.length} item${firstVal.length === 1 ? "" : "s"}`;
120332
119983
  const str = typeof firstVal === "object" ? JSON.stringify(firstVal) : String(firstVal);
120333
119984
  return str.split(`
120334
119985
  `)[0] ?? "";
@@ -120481,7 +120132,7 @@ class StreamingView extends Component_default {
120481
120132
  const bullet = getStatusBullet("running", pulseFrame % 2 === 0);
120482
120133
  const toolName = activeTool.displayName ?? (activeTool.name ? activeTool.name.charAt(0).toUpperCase() + activeTool.name.slice(1) : "Tool");
120483
120134
  const targetArg = extractPrimaryToolParam(activeTool.args);
120484
- let line = `${bullet} ${toolName}`;
120135
+ let line = `${bullet} ${bold(toolName)}`;
120485
120136
  if (targetArg) {
120486
120137
  const maxArgLen = Math.max(10, maxCols - toolName.length - 8);
120487
120138
  const truncatedArg = targetArg.length > maxArgLen ? truncateMiddle(targetArg, maxArgLen) : targetArg;
@@ -120507,14 +120158,36 @@ class StreamingView extends Component_default {
120507
120158
  lines.push(`${bullet} ${bold(c.text("Thinking.."))}`);
120508
120159
  const elapsedMs = thinkingStartTime ? performance.now() - thinkingStartTime : pulseFrame * 120;
120509
120160
  let subText = "wait...";
120510
- if (elapsedMs < 2000) {
120511
- subText = pulseFrame % 16 < 8 ? "hmm.." : "wait...";
120512
- } else if (elapsedMs < 4500) {
120513
- subText = pulseFrame % 16 < 8 ? "analyzing..." : "thinking...";
120514
- } else if (elapsedMs < 8000) {
120515
- subText = "still thinking...";
120161
+ if (elapsedMs < 2500) {
120162
+ const p1 = ["wait...", "hmm...", "one sec...", "looking into it...", "checking..."];
120163
+ subText = p1[Math.floor(pulseFrame / 5) % p1.length];
120164
+ } else if (elapsedMs < 6000) {
120165
+ const p2 = [
120166
+ "analyzing...",
120167
+ "thinking...",
120168
+ "working on it...",
120169
+ "connecting the dots...",
120170
+ "figuring this out..."
120171
+ ];
120172
+ subText = p2[Math.floor(pulseFrame / 6) % p2.length];
120173
+ } else if (elapsedMs < 11000) {
120174
+ const p3 = [
120175
+ "still thinking...",
120176
+ "deep in thought...",
120177
+ "almost there...",
120178
+ "crunching details...",
120179
+ "piecing it together..."
120180
+ ];
120181
+ subText = p3[Math.floor(pulseFrame / 7) % p3.length];
120516
120182
  } else {
120517
- subText = "taking a bit time...";
120183
+ const p4 = [
120184
+ "taking a bit of time...",
120185
+ "complex one, still on it...",
120186
+ "polishing up the answer...",
120187
+ "wrapping up thoughts...",
120188
+ "finishing up..."
120189
+ ];
120190
+ subText = p4[Math.floor(pulseFrame / 8) % p4.length];
120518
120191
  }
120519
120192
  lines.push(` ${c.muted("└ ")}${c.muted(subText)}`);
120520
120193
  }
@@ -122421,6 +122094,9 @@ class PermissionQueue {
122421
122094
 
122422
122095
  // src/app/ui/utils/tool-detail.ts
122423
122096
  function renderToolDetail(detail) {
122097
+ if (detail.kind === "pre-styled") {
122098
+ return detail.text;
122099
+ }
122424
122100
  if (detail.kind === "text") {
122425
122101
  return detail.text.split(`
122426
122102
  `).map((l) => c.muted(l)).join(`
@@ -122535,7 +122211,7 @@ function formatToolStatus(options) {
122535
122211
  const cleanFirstLine = extractPrimaryToolParam(argsSummary);
122536
122212
  const maxArgLen = Math.max(10, fullTermWidth - dispName.length - 8);
122537
122213
  const truncatedArg = cleanFirstLine.length > maxArgLen ? truncateMiddle(cleanFirstLine, maxArgLen) : cleanFirstLine;
122538
- let mainLine = `${bullet} ${dispName}`;
122214
+ let mainLine = `${bullet} ${bold(dispName)}`;
122539
122215
  if (truncatedArg) {
122540
122216
  mainLine += `${c.muted("(")}${c.muted(truncatedArg)}${c.muted(")")}`;
122541
122217
  } else {
@@ -122648,12 +122324,13 @@ function renderTranscript(engine, sessionData, header) {
122648
122324
  const toolDef = defaultToolCatalog.get(toolData.toolName);
122649
122325
  const displayName = toolData.displayName ?? toolDef?.displayName;
122650
122326
  const icon = toolData.icon ?? toolDef?.icon;
122327
+ const argsSummary = toolDef && toolData.args != null ? summarizeToolArgs(toolDef, toolData.args) : toolData.argsSummary ?? "";
122651
122328
  const summary = summarizeToolResult(toolDef, toolData.args, toolData.result, toolData.status === "failed") ?? toolData.toolOutput;
122652
122329
  engine.commit("tool-result", (w) => formatToolStatus({
122653
122330
  toolName: toolData.toolName,
122654
122331
  displayName,
122655
122332
  icon,
122656
- argsSummary: toolData.argsSummary,
122333
+ argsSummary,
122657
122334
  status: toolData.status,
122658
122335
  durationMs: toolData.durationMs,
122659
122336
  error: toolData.error,
@@ -122704,7 +122381,7 @@ class UpdateCheckerService {
122704
122381
  resetTimer = null;
122705
122382
  constructor(options = {}) {
122706
122383
  this.options = options;
122707
- this.currentVersion = options.currentVersion || "0.17.0";
122384
+ this.currentVersion = options.currentVersion || package_default.version || "0.0.0";
122708
122385
  this.repo = options.repo || DEFAULT_REPO;
122709
122386
  }
122710
122387
  getState() {
@@ -123282,7 +122959,7 @@ class TUIApp {
123282
122959
  const toolName = event.toolResult.name;
123283
122960
  const displayName = toolDef?.displayName;
123284
122961
  const icon = toolDef?.icon;
123285
- const argsSummary = JSON.stringify(event.toolResult.args);
122962
+ const argsSummary = summarizeToolArgs(toolDef, event.toolResult.args);
123286
122963
  const status = event.toolResult.isError ? "failed" : "completed";
123287
122964
  const error = event.toolResult.isError ? typeof event.toolResult.result === "object" && event.toolResult.result !== null ? event.toolResult.result.message ?? JSON.stringify(event.toolResult.result) : String(event.toolResult.result) : undefined;
123288
122965
  const summary = summarizeToolResult(toolDef, event.toolResult.args, event.toolResult.result, event.toolResult.isError);
@@ -123365,7 +123042,7 @@ class TUIApp {
123365
123042
  }
123366
123043
  }
123367
123044
  // src/app/main.ts
123368
- var VERSION16 = "0.17.0";
123045
+ var VERSION16 = package_default.version;
123369
123046
  var REPO_URL = "https://github.com/sapirrior/steward";
123370
123047
  globalThis.AI_SDK_LOG_WARNINGS = false;
123371
123048
  setupGlobalErrorHandlers();