@cydm/pie 4.8.0 → 4.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +51 -27
  2. package/dist/builtin/extensions/ask-user/index.js +4 -4
  3. package/dist/builtin/extensions/cron/index.js +906 -158
  4. package/dist/builtin/extensions/im-forward/README.md +4 -2
  5. package/dist/builtin/extensions/im-forward/index.js +6875 -3972
  6. package/dist/builtin/extensions/memory/index.js +76 -28
  7. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  8. package/dist/builtin/extensions/pie-ipc/index.js +285 -61
  9. package/dist/builtin/extensions/pie-proc/README.md +7 -7
  10. package/dist/builtin/extensions/pie-proc/index.js +493 -107
  11. package/dist/builtin/extensions/plan-mode/index.js +5 -5
  12. package/dist/builtin/extensions/subagent/index.js +8 -8
  13. package/dist/builtin/extensions/todo/index.js +4 -4
  14. package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +26 -24
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +199 -121
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chunk-HAUDUMDO.js +795 -0
  18. package/dist/builtin/skills/chrome-devtools-axi/{cli-ZE754CTH.js → cli-K7ESY3XD.js} +433 -255
  19. package/dist/builtin/skills/computer-use-axi/SKILL.md +25 -8
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +367 -65
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +2 -2
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
  23. package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-5QMS6RQC.js} +353 -287
  24. package/dist/chunks/chunk-6WKBQZWM.js +19 -0
  25. package/dist/chunks/{chunk-LAJXWOKS.js → chunk-7LICWWUE.js} +11 -9
  26. package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BQWHLYYZ.js} +4 -3
  27. package/dist/chunks/{chunk-4PR34UZF.js → chunk-BTUMBUDU.js} +159 -145
  28. package/dist/chunks/{chunk-NHV2CALB.js → chunk-FC5AN5QP.js} +409 -32
  29. package/dist/chunks/{chunk-3W3SXVPB.js → chunk-G2K4GY6N.js} +993 -371
  30. package/dist/chunks/{chunk-BLDI2GRF.js → chunk-HK3FHIAH.js} +1364 -446
  31. package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
  32. package/dist/chunks/{chunk-CGSFBWOM.js → chunk-KWK7KTSZ.js} +4 -3
  33. package/dist/chunks/chunk-OU33ROFD.js +717 -0
  34. package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-XMTRKMBG.js} +104 -22
  35. package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-3TEMOQM5.js} +1 -1
  36. package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
  37. package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-QKJ3YVDS.js} +2 -2
  38. package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-N2ZZQLTZ.js} +5 -5
  39. package/dist/chunks/{src-EGXFJ3WA.js → src-3PSR2AAX.js} +3 -3
  40. package/dist/chunks/{src-B44QWSGM.js → src-D5GN4Q5O.js} +2 -2
  41. package/dist/chunks/{src-CLE5ILN4.js → src-F5N6O2HR.js} +20 -4
  42. package/dist/chunks/{src-Q7LU27C2.js → src-TIDKYA5F.js} +31 -1
  43. package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-JAJHK44G.js} +2 -2
  44. package/dist/cli.js +4123 -2389
  45. package/models.schema.json +271 -0
  46. package/package.json +2 -2
  47. package/dist/builtin/skills/chrome-devtools-axi/chunk-Z2A5LA5A.js +0 -407
  48. package/dist/chunks/chunk-EGZ5TZRM.js +0 -1444
  49. package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
@@ -512,6 +512,7 @@ function registerModelsFromConfig(config) {
512
512
  provider: providerName,
513
513
  baseUrl: providerConfig.baseUrl,
514
514
  reasoning: modelDef.reasoning,
515
+ thinking: modelDef.thinking,
515
516
  input: modelDef.input,
516
517
  cost: modelDef.cost,
517
518
  contextWindow: modelDef.contextWindow,
@@ -1658,7 +1659,8 @@ function getPieFileBridge() {
1658
1659
  return CS.Pie.PieFileBridge;
1659
1660
  }
1660
1661
  async function taskToPromise(task) {
1661
- const promiseFactory = globalThis?.puer?.$promise ?? (typeof puer !== "undefined" ? puer?.$promise : void 0);
1662
+ const globalPuer = globalThis.puer;
1663
+ const promiseFactory = globalPuer?.$promise ?? (typeof puer !== "undefined" ? puer?.$promise : void 0);
1662
1664
  if (typeof promiseFactory === "function") {
1663
1665
  return await promiseFactory(task);
1664
1666
  }
@@ -1701,9 +1703,10 @@ function toJsStringArray(value) {
1701
1703
  return value.map((entry) => String(entry ?? ""));
1702
1704
  }
1703
1705
  if (value && typeof value.Length === "number") {
1706
+ const list = value;
1704
1707
  const results = [];
1705
- for (let i = 0; i < value.Length; i++) {
1706
- const entry = typeof value.get_Item === "function" ? value.get_Item(i) : value[i];
1708
+ for (let i = 0; i < list.Length; i++) {
1709
+ const entry = typeof list.get_Item === "function" ? list.get_Item(i) : list[i];
1707
1710
  results.push(String(entry ?? ""));
1708
1711
  }
1709
1712
  return results;
@@ -2116,6 +2119,7 @@ var PuerTSFileSystem = class {
2116
2119
  const normalizedPath = this.normalizePath(path);
2117
2120
  let attributes;
2118
2121
  try {
2122
+ if (typeof IO.File.GetAttributes !== "function") throw new Error("GetAttributes unavailable");
2119
2123
  attributes = Number(IO.File.GetAttributes(normalizedPath));
2120
2124
  } catch {
2121
2125
  throw new Error(`ENOENT: no such file or directory, lstat '${path}'`);
@@ -2144,6 +2148,7 @@ var PuerTSFileSystem = class {
2144
2148
  cursor = cursor ? this.normalizePath(String(IO.Path.Combine(cursor, part))) : part;
2145
2149
  let attributes;
2146
2150
  try {
2151
+ if (typeof IO.File.GetAttributes !== "function") throw new Error("GetAttributes unavailable");
2147
2152
  attributes = Number(IO.File.GetAttributes(cursor));
2148
2153
  } catch {
2149
2154
  throw new Error(`ENOENT: no such file or directory, realpath '${path}'`);
@@ -2255,11 +2260,7 @@ var PuerTSFileSystem = class {
2255
2260
  }
2256
2261
  };
2257
2262
 
2258
- // ../../packages/platform/src/http.ts
2259
- import { createRequire as createRequire2 } from "node:module";
2260
- import { fileURLToPath as fileURLToPath2 } from "node:url";
2261
- var __filename2 = fileURLToPath2(import.meta.url);
2262
- var require3 = createRequire2(__filename2);
2263
+ // ../../packages/platform/src/http-log.ts
2263
2264
  var _procEnv = typeof process !== "undefined" ? process.env : {};
2264
2265
  var DEBUG = _procEnv.PIE_DEBUG_HTTP === "1" || _procEnv.PIE_DEBUG_HTTP === "true";
2265
2266
  function logHttp(level, message, data) {
@@ -2276,6 +2277,213 @@ function logHttp(level, message, data) {
2276
2277
  logger.debug(message, context);
2277
2278
  }
2278
2279
  }
2280
+
2281
+ // ../../packages/platform/src/http.ts
2282
+ import { createRequire as createRequire2 } from "node:module";
2283
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
2284
+
2285
+ // ../../packages/platform/src/puerts-http.ts
2286
+ function scheduleNextTick(callback) {
2287
+ if (typeof setTimeout === "function") {
2288
+ setTimeout(callback, 0);
2289
+ return;
2290
+ }
2291
+ Promise.resolve().then(callback);
2292
+ }
2293
+ var PuerTSHttpClient = class {
2294
+ /** No internal re-send: each call starts exactly one bridge request. */
2295
+ transportCapabilities = { singleAttempt: true };
2296
+ async request(url, options = {}) {
2297
+ logHttp("DEBUG", `PuerTS Request started`, {
2298
+ url: url.slice(0, 100),
2299
+ method: options.method || "GET"
2300
+ });
2301
+ let legacyBridge = false;
2302
+ try {
2303
+ legacyBridge = typeof CS !== "undefined" && !!CS?.AgentBridge && typeof CS.AgentBridge.HttpPostAsyncStart === "function";
2304
+ } catch {
2305
+ legacyBridge = false;
2306
+ }
2307
+ if (legacyBridge && CS.AgentBridge) {
2308
+ const bridge = CS.AgentBridge;
2309
+ const body2 = options.body || "";
2310
+ const auth = options.headers?.Authorization || options.headers?.authorization || "";
2311
+ const authValue = auth.replace(/^Bearer\s+/i, "");
2312
+ logHttp("DEBUG", "PuerTS async HttpClient selected", { url: url.slice(0, 100) });
2313
+ const requestId = bridge.HttpPostAsyncStart(url, body2, authValue);
2314
+ logHttp("DEBUG", "PuerTS async request started", { requestId });
2315
+ const maxWait = 12e4;
2316
+ const pollInterval = 50;
2317
+ const startTime = Date.now();
2318
+ while (true) {
2319
+ if (options.signal?.aborted) {
2320
+ bridge.HttpPostAsyncCancel(requestId);
2321
+ throw new Error("Request was aborted");
2322
+ }
2323
+ const pollResult = bridge.HttpPostAsyncPoll(requestId);
2324
+ logHttp("DEBUG", "PuerTS async poll result", {
2325
+ requestId,
2326
+ pollResultType: typeof pollResult,
2327
+ length: pollResult?.length || 0
2328
+ });
2329
+ if (pollResult && pollResult.length > 0) {
2330
+ const parsed = JSON.parse(pollResult);
2331
+ logHttp("DEBUG", "PuerTS async response received", {
2332
+ requestId,
2333
+ statusCode: parsed.statusCode,
2334
+ bodyLength: parsed.body?.length || 0
2335
+ });
2336
+ return {
2337
+ status: parsed.statusCode || 200,
2338
+ statusText: parsed.status === "ok" ? "OK" : "Error",
2339
+ ok: parsed.status === "ok",
2340
+ headers: { "content-type": "application/json" },
2341
+ text() {
2342
+ return Promise.resolve(parsed.body || "");
2343
+ },
2344
+ async json() {
2345
+ return JSON.parse(parsed.body || "{}");
2346
+ },
2347
+ async *readSSELines(signal) {
2348
+ const text = parsed.body || "";
2349
+ const lines = text.split("\n");
2350
+ for (const line of lines) {
2351
+ if (signal?.aborted) throw new Error("Request was aborted");
2352
+ yield line;
2353
+ }
2354
+ }
2355
+ };
2356
+ }
2357
+ if (Date.now() - startTime > maxWait) {
2358
+ bridge.HttpPostAsyncCancel(requestId);
2359
+ throw new Error("Request timed out");
2360
+ }
2361
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
2362
+ }
2363
+ }
2364
+ if (typeof CS === "undefined" || !CS?.UnityEngine?.Networking) {
2365
+ throw new Error("HTTP client not available - not running in PuerTS environment");
2366
+ }
2367
+ const { UnityEngine } = CS;
2368
+ const method = options.method || "GET";
2369
+ const headers = options.headers || {};
2370
+ const body = options.body;
2371
+ return new Promise((resolve, reject) => {
2372
+ const request = new UnityEngine.Networking.UnityWebRequest(url, method);
2373
+ for (const [key, value] of Object.entries(headers)) {
2374
+ request.SetRequestHeader(key, value);
2375
+ }
2376
+ if (body && ["POST", "PUT", "PATCH"].includes(method.toUpperCase())) {
2377
+ const encodeUtf8 = (text) => {
2378
+ const out = [];
2379
+ for (let i = 0; i < text.length; i++) {
2380
+ let code = text.charCodeAt(i);
2381
+ if (code < 128) out.push(code);
2382
+ else {
2383
+ if (code >= 55296 && code <= 56319 && i + 1 < text.length) {
2384
+ const low = text.charCodeAt(i + 1);
2385
+ if (low >= 56320 && low <= 57343) {
2386
+ code = 65536 + (code - 55296 << 10) + (low - 56320);
2387
+ i++;
2388
+ }
2389
+ }
2390
+ if (code < 2048) out.push(192 | code >> 6, 128 | code & 63);
2391
+ else if (code < 65536) out.push(224 | code >> 12, 128 | code >> 6 & 63, 128 | code & 63);
2392
+ else out.push(240 | code >> 18, 128 | code >> 12 & 63, 128 | code >> 6 & 63, 128 | code & 63);
2393
+ }
2394
+ }
2395
+ return new Uint8Array(out);
2396
+ };
2397
+ const base64 = (bytes) => {
2398
+ let binary = "";
2399
+ const table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2400
+ for (let i = 0; i < bytes.length; i += 3) {
2401
+ const b0 = bytes[i], b1 = bytes[i + 1], b2 = bytes[i + 2];
2402
+ binary += table[b0 >> 2] + table[(b0 & 3) << 4 | (b1 ?? 0) >> 4];
2403
+ if (b1 === void 0) break;
2404
+ binary += table[(b1 & 15) << 2 | (b2 ?? 0) >> 6];
2405
+ if (b2 === void 0) break;
2406
+ binary += table[b2 & 63];
2407
+ }
2408
+ const pad = bytes.length % 3;
2409
+ return binary + (pad === 1 ? "==" : pad === 2 ? "=" : "");
2410
+ };
2411
+ const bodyBytes = CS.System.Convert.FromBase64String(base64(encodeUtf8(body)));
2412
+ request.uploadHandler = new UnityEngine.Networking.UploadHandlerRaw(bodyBytes);
2413
+ }
2414
+ request.downloadHandler = new UnityEngine.Networking.DownloadHandlerBuffer();
2415
+ let aborted = false;
2416
+ if (options.signal) {
2417
+ const onAbort = () => {
2418
+ aborted = true;
2419
+ request.Abort();
2420
+ reject(new Error("Request was aborted"));
2421
+ };
2422
+ options.signal.addEventListener("abort", onAbort, { once: true });
2423
+ }
2424
+ const asyncOp = request.SendWebRequest();
2425
+ const completed = new Promise((resolveCompleted) => {
2426
+ try {
2427
+ asyncOp.add_completed?.(() => resolveCompleted());
2428
+ } catch {
2429
+ }
2430
+ });
2431
+ const checkComplete = () => {
2432
+ if (aborted) return;
2433
+ if (asyncOp.isDone) {
2434
+ const status = request.responseCode;
2435
+ const ok = status >= 200 && status < 300;
2436
+ const responseHeaders = {};
2437
+ const headerKeys = request.GetResponseHeaderKeys?.() || [];
2438
+ for (const key of headerKeys) {
2439
+ const value = request.GetResponseHeader(key);
2440
+ if (value) responseHeaders[key] = value;
2441
+ }
2442
+ const responseText = request.downloadHandler?.text || "";
2443
+ logHttp("DEBUG", "PuerTS UnityWebRequest completed", {
2444
+ status,
2445
+ ok,
2446
+ textLength: responseText.length
2447
+ });
2448
+ resolve({
2449
+ status,
2450
+ statusText: request.error || "",
2451
+ ok,
2452
+ headers: responseHeaders,
2453
+ text() {
2454
+ return Promise.resolve(responseText);
2455
+ },
2456
+ async json() {
2457
+ return JSON.parse(responseText);
2458
+ },
2459
+ // SSE support for PuerTS - parse from complete response
2460
+ async *readSSELines(signal) {
2461
+ const text = responseText;
2462
+ const lines = text.split("\n");
2463
+ logHttp("DEBUG", "PuerTS UnityWebRequest readSSELines", {
2464
+ lines: lines.length,
2465
+ preview: text.substring(0, 100)
2466
+ });
2467
+ for (const line of lines) {
2468
+ if (signal?.aborted) {
2469
+ throw new Error("Request was aborted");
2470
+ }
2471
+ yield line;
2472
+ }
2473
+ }
2474
+ });
2475
+ } else {
2476
+ void completed.then(() => checkComplete());
2477
+ }
2478
+ };
2479
+ scheduleNextTick(checkComplete);
2480
+ });
2481
+ }
2482
+ };
2483
+
2484
+ // ../../packages/platform/src/http.ts
2485
+ var __filename2 = fileURLToPath2(import.meta.url);
2486
+ var require3 = createRequire2(__filename2);
2279
2487
  function isAbortErrorMessage(message) {
2280
2488
  return message === "Request was aborted" || message === "Operation aborted";
2281
2489
  }
@@ -2684,280 +2892,83 @@ var NodeHttpClient = class {
2684
2892
  queueHead = 0;
2685
2893
  }
2686
2894
  if (done) {
2687
- if (error) {
2688
- logFailureIfDelivered();
2689
- throw error;
2690
- }
2691
- return;
2692
- }
2693
- const waitResult = await new Promise((r) => {
2694
- waiting = r;
2695
- });
2696
- void waitResult;
2697
- }
2698
- } finally {
2699
- consumerClosed = true;
2700
- logUndeliveredFailure();
2701
- if (signal && abortHandler) {
2702
- signal.removeEventListener("abort", abortHandler);
2703
- }
2704
- if (!done && !res.destroyed) {
2705
- res.destroy();
2706
- }
2707
- }
2708
- }
2709
- };
2710
- resolve(response);
2711
- });
2712
- req.on("error", (e) => {
2713
- if (isAbortErrorMessage(e.message) && options.signal?.aborted) {
2714
- logHttp("DEBUG", `Request [${reqTag}] aborted`, {
2715
- totalTimeMs: Date.now() - requestStartTime
2716
- });
2717
- reject(e);
2718
- return;
2719
- }
2720
- logHttp("ERROR", `Request [${reqTag}] failed`, {
2721
- error: e.message,
2722
- totalTimeMs: Date.now() - requestStartTime
2723
- });
2724
- reject(e);
2725
- });
2726
- if (options.signal) {
2727
- const requestSignal = options.signal;
2728
- const onRequestAbort = () => {
2729
- logHttp("DEBUG", `Request [${reqTag}] aborted`);
2730
- req.destroy(new Error("Request was aborted"));
2731
- };
2732
- if (requestSignal.aborted) {
2733
- onRequestAbort();
2734
- } else {
2735
- requestSignal.addEventListener("abort", onRequestAbort, { once: true });
2736
- req.once("close", () => {
2737
- requestSignal.removeEventListener("abort", onRequestAbort);
2738
- });
2739
- }
2740
- }
2741
- if (!tieredStreamTimeout) {
2742
- req.on("timeout", () => {
2743
- requestTimeoutError = new Error("Request timeout");
2744
- setTimeoutKind(requestTimeoutError, "total");
2745
- logHttp("ERROR", `Request [${reqTag}] timeout`);
2746
- req.destroy(requestTimeoutError);
2747
- });
2748
- req.setTimeout(requestTimeoutMs);
2749
- } else if (tieredFirstByteTimeoutMs !== void 0) {
2750
- tieredFirstByteTimer = setTimeout(() => {
2751
- tieredFirstByteTimer = void 0;
2752
- requestTimeoutError = new Error(`Request timeout (first byte) after ${tieredFirstByteTimeoutMs}ms`);
2753
- setTimeoutKind(requestTimeoutError, "first_byte");
2754
- logHttp("WARN", `Request [${reqTag}] first byte timeout`, { firstByteTimeoutMs: tieredFirstByteTimeoutMs });
2755
- req.destroy(requestTimeoutError);
2756
- }, tieredFirstByteTimeoutMs);
2757
- tieredFirstByteTimer.unref?.();
2758
- req.once("close", clearTieredFirstByteTimer);
2759
- }
2760
- if (options.body) {
2761
- req.write(options.body);
2762
- }
2763
- req.end();
2764
- });
2765
- }
2766
- };
2767
- function scheduleNextTick(callback) {
2768
- if (typeof setTimeout === "function") {
2769
- setTimeout(callback, 0);
2770
- return;
2771
- }
2772
- Promise.resolve().then(callback);
2773
- }
2774
- var PuerTSHttpClient = class {
2775
- /** No internal re-send: each call starts exactly one bridge request. */
2776
- transportCapabilities = { singleAttempt: true };
2777
- async request(url, options = {}) {
2778
- logHttp("DEBUG", `PuerTS Request started`, {
2779
- url: url.slice(0, 100),
2780
- method: options.method || "GET"
2781
- });
2782
- let legacyBridge = false;
2783
- try {
2784
- legacyBridge = typeof CS !== "undefined" && !!CS?.AgentBridge && typeof CS.AgentBridge.HttpPostAsyncStart === "function";
2785
- } catch {
2786
- legacyBridge = false;
2787
- }
2788
- if (legacyBridge) {
2789
- const method2 = options.method || "GET";
2790
- const body2 = options.body || "";
2791
- const auth = options.headers?.Authorization || options.headers?.authorization || "";
2792
- const authValue = auth.replace(/^Bearer\s+/i, "");
2793
- logHttp("DEBUG", "PuerTS async HttpClient selected", { url: url.slice(0, 100) });
2794
- const requestId = CS.AgentBridge.HttpPostAsyncStart(url, body2, authValue);
2795
- logHttp("DEBUG", "PuerTS async request started", { requestId });
2796
- const maxWait = 12e4;
2797
- const pollInterval = 50;
2798
- const startTime = Date.now();
2799
- while (true) {
2800
- if (options.signal?.aborted) {
2801
- CS.AgentBridge.HttpPostAsyncCancel(requestId);
2802
- throw new Error("Request was aborted");
2803
- }
2804
- const pollResult = CS.AgentBridge.HttpPostAsyncPoll(requestId);
2805
- logHttp("DEBUG", "PuerTS async poll result", {
2806
- requestId,
2807
- pollResultType: typeof pollResult,
2808
- length: pollResult?.length || 0
2809
- });
2810
- if (pollResult && pollResult.length > 0) {
2811
- const parsed = JSON.parse(pollResult);
2812
- logHttp("DEBUG", "PuerTS async response received", {
2813
- requestId,
2814
- statusCode: parsed.statusCode,
2815
- bodyLength: parsed.body?.length || 0
2816
- });
2817
- return {
2818
- status: parsed.statusCode || 200,
2819
- statusText: parsed.status === "ok" ? "OK" : "Error",
2820
- ok: parsed.status === "ok",
2821
- headers: { "content-type": "application/json" },
2822
- text() {
2823
- return Promise.resolve(parsed.body || "");
2824
- },
2825
- async json() {
2826
- return JSON.parse(parsed.body || "{}");
2827
- },
2828
- async *readSSELines(signal) {
2829
- const text = parsed.body || "";
2830
- const lines = text.split("\n");
2831
- for (const line of lines) {
2832
- if (signal?.aborted) throw new Error("Request was aborted");
2833
- yield line;
2834
- }
2835
- }
2836
- };
2837
- }
2838
- if (Date.now() - startTime > maxWait) {
2839
- CS.AgentBridge.HttpPostAsyncCancel(requestId);
2840
- throw new Error("Request timed out");
2841
- }
2842
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
2843
- }
2844
- }
2845
- if (typeof CS === "undefined" || !CS?.UnityEngine?.Networking) {
2846
- throw new Error("HTTP client not available - not running in PuerTS environment");
2847
- }
2848
- const { UnityEngine } = CS;
2849
- const method = options.method || "GET";
2850
- const headers = options.headers || {};
2851
- const body = options.body;
2852
- return new Promise((resolve, reject) => {
2853
- const request = new UnityEngine.Networking.UnityWebRequest(url, method);
2854
- for (const [key, value] of Object.entries(headers)) {
2855
- request.SetRequestHeader(key, value);
2856
- }
2857
- if (body && ["POST", "PUT", "PATCH"].includes(method.toUpperCase())) {
2858
- const encodeUtf8 = (text) => {
2859
- const out = [];
2860
- for (let i = 0; i < text.length; i++) {
2861
- let code = text.charCodeAt(i);
2862
- if (code < 128) out.push(code);
2863
- else {
2864
- if (code >= 55296 && code <= 56319 && i + 1 < text.length) {
2865
- const low = text.charCodeAt(i + 1);
2866
- if (low >= 56320 && low <= 57343) {
2867
- code = 65536 + (code - 55296 << 10) + (low - 56320);
2868
- i++;
2869
- }
2870
- }
2871
- if (code < 2048) out.push(192 | code >> 6, 128 | code & 63);
2872
- else if (code < 65536) out.push(224 | code >> 12, 128 | code >> 6 & 63, 128 | code & 63);
2873
- else out.push(240 | code >> 18, 128 | code >> 12 & 63, 128 | code >> 6 & 63, 128 | code & 63);
2874
- }
2875
- }
2876
- return new Uint8Array(out);
2877
- };
2878
- const base64 = (bytes) => {
2879
- let binary = "";
2880
- const table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2881
- for (let i = 0; i < bytes.length; i += 3) {
2882
- const b0 = bytes[i], b1 = bytes[i + 1], b2 = bytes[i + 2];
2883
- binary += table[b0 >> 2] + table[(b0 & 3) << 4 | (b1 ?? 0) >> 4];
2884
- if (b1 === void 0) break;
2885
- binary += table[(b1 & 15) << 2 | (b2 ?? 0) >> 6];
2886
- if (b2 === void 0) break;
2887
- binary += table[b2 & 63];
2888
- }
2889
- const pad = bytes.length % 3;
2890
- return binary + (pad === 1 ? "==" : pad === 2 ? "=" : "");
2891
- };
2892
- const bodyBytes = CS.System.Convert.FromBase64String(base64(encodeUtf8(body)));
2893
- request.uploadHandler = new UnityEngine.Networking.UploadHandlerRaw(bodyBytes);
2894
- }
2895
- request.downloadHandler = new UnityEngine.Networking.DownloadHandlerBuffer();
2896
- let aborted = false;
2897
- if (options.signal) {
2898
- const onAbort = () => {
2899
- aborted = true;
2900
- request.Abort();
2901
- reject(new Error("Request was aborted"));
2902
- };
2903
- options.signal.addEventListener("abort", onAbort, { once: true });
2904
- }
2905
- const asyncOp = request.SendWebRequest();
2906
- const completed = new Promise((resolveCompleted) => {
2907
- try {
2908
- asyncOp.add_completed(() => resolveCompleted());
2909
- } catch {
2910
- }
2911
- });
2912
- const checkComplete = () => {
2913
- if (aborted) return;
2914
- if (asyncOp.isDone) {
2915
- const status = request.responseCode;
2916
- const ok = status >= 200 && status < 300;
2917
- const responseHeaders = {};
2918
- const headerKeys = request.GetResponseHeaderKeys?.() || [];
2919
- for (const key of headerKeys) {
2920
- const value = request.GetResponseHeader(key);
2921
- if (value) responseHeaders[key] = value;
2922
- }
2923
- const responseText = request.downloadHandler?.text || "";
2924
- logHttp("DEBUG", "PuerTS UnityWebRequest completed", {
2925
- status,
2926
- ok,
2927
- textLength: responseText.length
2928
- });
2929
- resolve({
2930
- status,
2931
- statusText: request.error || "",
2932
- ok,
2933
- headers: responseHeaders,
2934
- text() {
2935
- return Promise.resolve(responseText);
2936
- },
2937
- async json() {
2938
- return JSON.parse(responseText);
2939
- },
2940
- // SSE support for PuerTS - parse from complete response
2941
- async *readSSELines(signal) {
2942
- const text = responseText;
2943
- const lines = text.split("\n");
2944
- logHttp("DEBUG", "PuerTS UnityWebRequest readSSELines", {
2945
- lines: lines.length,
2946
- preview: text.substring(0, 100)
2947
- });
2948
- for (const line of lines) {
2949
- if (signal?.aborted) {
2950
- throw new Error("Request was aborted");
2895
+ if (error) {
2896
+ logFailureIfDelivered();
2897
+ throw error;
2898
+ }
2899
+ return;
2951
2900
  }
2952
- yield line;
2901
+ const waitResult = await new Promise((r) => {
2902
+ waiting = r;
2903
+ });
2904
+ void waitResult;
2905
+ }
2906
+ } finally {
2907
+ consumerClosed = true;
2908
+ logUndeliveredFailure();
2909
+ if (signal && abortHandler) {
2910
+ signal.removeEventListener("abort", abortHandler);
2911
+ }
2912
+ if (!done && !res.destroyed) {
2913
+ res.destroy();
2953
2914
  }
2954
2915
  }
2916
+ }
2917
+ };
2918
+ resolve(response);
2919
+ });
2920
+ req.on("error", (e) => {
2921
+ if (isAbortErrorMessage(e.message) && options.signal?.aborted) {
2922
+ logHttp("DEBUG", `Request [${reqTag}] aborted`, {
2923
+ totalTimeMs: Date.now() - requestStartTime
2955
2924
  });
2925
+ reject(e);
2926
+ return;
2927
+ }
2928
+ logHttp("ERROR", `Request [${reqTag}] failed`, {
2929
+ error: e.message,
2930
+ totalTimeMs: Date.now() - requestStartTime
2931
+ });
2932
+ reject(e);
2933
+ });
2934
+ if (options.signal) {
2935
+ const requestSignal = options.signal;
2936
+ const onRequestAbort = () => {
2937
+ logHttp("DEBUG", `Request [${reqTag}] aborted`);
2938
+ req.destroy(new Error("Request was aborted"));
2939
+ };
2940
+ if (requestSignal.aborted) {
2941
+ onRequestAbort();
2956
2942
  } else {
2957
- void completed.then(() => checkComplete());
2943
+ requestSignal.addEventListener("abort", onRequestAbort, { once: true });
2944
+ req.once("close", () => {
2945
+ requestSignal.removeEventListener("abort", onRequestAbort);
2946
+ });
2958
2947
  }
2959
- };
2960
- scheduleNextTick(checkComplete);
2948
+ }
2949
+ if (!tieredStreamTimeout) {
2950
+ req.on("timeout", () => {
2951
+ requestTimeoutError = new Error("Request timeout");
2952
+ setTimeoutKind(requestTimeoutError, "total");
2953
+ logHttp("ERROR", `Request [${reqTag}] timeout`);
2954
+ req.destroy(requestTimeoutError);
2955
+ });
2956
+ req.setTimeout(requestTimeoutMs);
2957
+ } else if (tieredFirstByteTimeoutMs !== void 0) {
2958
+ tieredFirstByteTimer = setTimeout(() => {
2959
+ tieredFirstByteTimer = void 0;
2960
+ requestTimeoutError = new Error(`Request timeout (first byte) after ${tieredFirstByteTimeoutMs}ms`);
2961
+ setTimeoutKind(requestTimeoutError, "first_byte");
2962
+ logHttp("WARN", `Request [${reqTag}] first byte timeout`, { firstByteTimeoutMs: tieredFirstByteTimeoutMs });
2963
+ req.destroy(requestTimeoutError);
2964
+ }, tieredFirstByteTimeoutMs);
2965
+ tieredFirstByteTimer.unref?.();
2966
+ req.once("close", clearTieredFirstByteTimer);
2967
+ }
2968
+ if (options.body) {
2969
+ req.write(options.body);
2970
+ }
2971
+ req.end();
2961
2972
  });
2962
2973
  }
2963
2974
  };
@@ -3738,6 +3749,28 @@ function deletePuertsDirectoryByEnumeration(path, recursive) {
3738
3749
 
3739
3750
  // ../../packages/platform/src/websocket-node.ts
3740
3751
  import { createRequire as createRequire5 } from "node:module";
3752
+
3753
+ // ../../packages/platform/src/websocket-types.ts
3754
+ var WebSocketTransportError = class extends Error {
3755
+ kind;
3756
+ /** HTTP status of a refused handshake, when the transport reports one. */
3757
+ status;
3758
+ /** Close code carried by the failure, when one exists. */
3759
+ closeCode;
3760
+ /** True ONLY when the failure rejected synchronously BEFORE handing any bytes
3761
+ * to the underlying socket (zero submission / zero billing ambiguity). */
3762
+ preflight;
3763
+ constructor(kind, message, details = {}) {
3764
+ super(`[websocket:${kind}] ${message}`);
3765
+ this.name = "WebSocketTransportError";
3766
+ this.kind = kind;
3767
+ if (details.status !== void 0) this.status = details.status;
3768
+ if (details.closeCode !== void 0) this.closeCode = details.closeCode;
3769
+ if (details.preflight !== void 0) this.preflight = details.preflight;
3770
+ }
3771
+ };
3772
+
3773
+ // ../../packages/platform/src/websocket-node.ts
3741
3774
  var require5 = createRequire5(import.meta.url);
3742
3775
  var failure = (kind, message) => new WebSocketTransportError(kind, message);
3743
3776
  var NodeWebSocketClient = class {
@@ -3862,7 +3895,7 @@ var NodeConnection = class {
3862
3895
  async send(message, options) {
3863
3896
  const bytes = Buffer.byteLength(message);
3864
3897
  if (bytes > (this.options.maxMessageBytes ?? 32 * 1024 * 1024) || this.pendingBytes + bytes > (this.options.maxBufferedBytes ?? 32 * 1024 * 1024) || this.pendingMessages >= (this.options.maxBufferedMessages ?? 256)) {
3865
- throw failure("overflow", "Outgoing WebSocket buffer exceeded");
3898
+ throw new WebSocketTransportError("overflow", "Outgoing WebSocket buffer exceeded", { preflight: true });
3866
3899
  }
3867
3900
  const signal = options?.signal;
3868
3901
  if (signal?.aborted) {
@@ -3934,20 +3967,6 @@ var NodeConnection = class {
3934
3967
  };
3935
3968
 
3936
3969
  // ../../packages/platform/src/websocket.ts
3937
- var WebSocketTransportError = class extends Error {
3938
- kind;
3939
- /** HTTP status of a refused handshake, when the transport reports one. */
3940
- status;
3941
- /** Close code carried by the failure, when one exists. */
3942
- closeCode;
3943
- constructor(kind, message, details = {}) {
3944
- super(`[websocket:${kind}] ${message}`);
3945
- this.name = "WebSocketTransportError";
3946
- this.kind = kind;
3947
- if (details.status !== void 0) this.status = details.status;
3948
- if (details.closeCode !== void 0) this.closeCode = details.closeCode;
3949
- }
3950
- };
3951
3970
  var webSocketClientInstance;
3952
3971
  function getNodeWebSocketClient() {
3953
3972
  return detectPlatform() === "node" ? new NodeWebSocketClient() : void 0;
@@ -4027,6 +4046,531 @@ function parseStreamingJson(partialJson) {
4027
4046
  }
4028
4047
  }
4029
4048
 
4049
+ // ../../packages/ai/src/thinking.ts
4050
+ var ALL_THINKING_LEVELS = [
4051
+ "off",
4052
+ "minimal",
4053
+ "low",
4054
+ "medium",
4055
+ "high",
4056
+ "xhigh",
4057
+ "max"
4058
+ ];
4059
+ var PORTABLE_THINKING_LEVELS = [
4060
+ "off",
4061
+ "minimal",
4062
+ "low",
4063
+ "medium",
4064
+ "high",
4065
+ "xhigh"
4066
+ ];
4067
+ var ACTIVE_THINKING_LEVELS = [
4068
+ "minimal",
4069
+ "low",
4070
+ "medium",
4071
+ "high",
4072
+ "xhigh",
4073
+ "max"
4074
+ ];
4075
+ var LEVEL_RANK = {
4076
+ off: 0,
4077
+ minimal: 1,
4078
+ low: 2,
4079
+ medium: 3,
4080
+ high: 4,
4081
+ xhigh: 5,
4082
+ max: 6
4083
+ };
4084
+ var DEFAULT_THINKING_BUDGETS = {
4085
+ minimal: 1024,
4086
+ low: 2048,
4087
+ medium: 8192,
4088
+ high: 16384,
4089
+ xhigh: 16384,
4090
+ max: 16384
4091
+ };
4092
+ var ALL_LEVEL_SET = new Set(ALL_THINKING_LEVELS);
4093
+ var PORTABLE_LEVEL_SET = new Set(PORTABLE_THINKING_LEVELS);
4094
+ var ACTIVE_LEVEL_SET = new Set(ACTIVE_THINKING_LEVELS);
4095
+ function isThinkingSelectionLevel(value) {
4096
+ return typeof value === "string" && ALL_LEVEL_SET.has(value);
4097
+ }
4098
+ function isPortableThinkingLevel(value) {
4099
+ return typeof value === "string" && PORTABLE_LEVEL_SET.has(value);
4100
+ }
4101
+ function isActiveThinkingLevel(value) {
4102
+ return typeof value === "string" && ACTIVE_LEVEL_SET.has(value);
4103
+ }
4104
+ function isThinkingModeCompatibleWithApi(api, mode) {
4105
+ if (mode === "none") return true;
4106
+ if (api === "anthropic-messages") return mode === "adaptive" || mode === "budget";
4107
+ if (api === "openai-responses" || api === "openai-completions") return mode === "effort";
4108
+ return true;
4109
+ }
4110
+ function isDisableWireCompatibleWithApi(api, disableWire) {
4111
+ if (disableWire === "omit") return true;
4112
+ if (disableWire === "disabled") return api === "anthropic-messages";
4113
+ if (disableWire === "none") return api === "openai-responses" || api === "openai-completions";
4114
+ return true;
4115
+ }
4116
+ function normalizeAdaptiveEffort(effort) {
4117
+ if (effort === "minimal") return "low";
4118
+ if (effort === "xhigh") return "high";
4119
+ return effort;
4120
+ }
4121
+ function canonicalizeLevels(levels, fallback) {
4122
+ if (!Array.isArray(levels) || levels.length === 0) {
4123
+ return [...fallback];
4124
+ }
4125
+ const unique = /* @__PURE__ */ new Set();
4126
+ for (const entry of levels) {
4127
+ if (isThinkingSelectionLevel(entry)) unique.add(entry);
4128
+ }
4129
+ if (unique.size === 0) return ["off"];
4130
+ return Array.from(unique).sort((a, b) => LEVEL_RANK[a] - LEVEL_RANK[b]);
4131
+ }
4132
+ function defaultLevelsForMode(api, mode) {
4133
+ if (mode === "adaptive") return ["off", "low", "medium", "high", "max"];
4134
+ if (mode === "budget") return ["off", "minimal", "low", "medium", "high"];
4135
+ if (mode === "effort") {
4136
+ return api === "openai-responses" ? ["off", "minimal", "low", "medium", "high", "xhigh"] : ["off", "minimal", "low", "medium", "high"];
4137
+ }
4138
+ return ["off"];
4139
+ }
4140
+ function isForcedNoneEffort(model) {
4141
+ return model.api === "openai-completions" && model.compat?.forcedReasoningEffort === "none";
4142
+ }
4143
+ function positiveFiniteNumber(value) {
4144
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
4145
+ }
4146
+ function getModelThinkingCapabilities(model) {
4147
+ if (!model) {
4148
+ return {
4149
+ mode: "none",
4150
+ configurable: false,
4151
+ reasoningCapable: false,
4152
+ wireConfigurable: false,
4153
+ supportedLevels: ["off"],
4154
+ disableWire: "omit"
4155
+ };
4156
+ }
4157
+ const forcedNone = isForcedNoneEffort(model);
4158
+ if (forcedNone) {
4159
+ return {
4160
+ mode: "none",
4161
+ configurable: false,
4162
+ reasoningCapable: false,
4163
+ wireConfigurable: false,
4164
+ supportedLevels: ["off"],
4165
+ disableWire: "none"
4166
+ };
4167
+ }
4168
+ if (model.thinking) {
4169
+ const declared = model.thinking;
4170
+ const mode = declared.mode;
4171
+ if (mode === "none" || !isThinkingModeCompatibleWithApi(model.api, mode)) {
4172
+ const disableWire2 = declared.disableWire && isDisableWireCompatibleWithApi(model.api, declared.disableWire) ? declared.disableWire : "omit";
4173
+ return {
4174
+ mode: "none",
4175
+ configurable: false,
4176
+ reasoningCapable: Boolean(model.reasoning),
4177
+ wireConfigurable: false,
4178
+ supportedLevels: model.reasoning ? [] : ["off"],
4179
+ disableWire: disableWire2,
4180
+ outputAllowance: declared.outputAllowance
4181
+ };
4182
+ }
4183
+ const compatEffortExplicitlyOff = (model.api === "openai-completions" || model.api === "openai-responses") && model.compat?.supportsReasoningEffort === false;
4184
+ const wireConfigurable = mode === "effort" ? !compatEffortExplicitlyOff : true;
4185
+ const supportedLevels = wireConfigurable ? canonicalizeLevels(declared.supportedLevels, defaultLevelsForMode(model.api, mode)) : [];
4186
+ const configurable = wireConfigurable && supportedLevels.length > 1;
4187
+ const defaultLevel = declared.defaultLevel && supportedLevels.includes(declared.defaultLevel) ? declared.defaultLevel : void 0;
4188
+ const disableWire = declared.disableWire && isDisableWireCompatibleWithApi(model.api, declared.disableWire) ? declared.disableWire : "omit";
4189
+ return {
4190
+ mode: wireConfigurable ? mode : "none",
4191
+ configurable,
4192
+ reasoningCapable: true,
4193
+ wireConfigurable,
4194
+ supportedLevels,
4195
+ ...defaultLevel ? { defaultLevel } : {},
4196
+ disableWire,
4197
+ ...declared.effortMap ? { effortMap: declared.effortMap } : {},
4198
+ ...declared.budgets ? { budgets: declared.budgets } : {},
4199
+ ...declared.minBudgetTokens !== void 0 ? { minBudgetTokens: declared.minBudgetTokens } : mode === "budget" && model.api === "anthropic-messages" ? { minBudgetTokens: 1024 } : {},
4200
+ ...declared.maxBudgetTokens !== void 0 ? { maxBudgetTokens: declared.maxBudgetTokens } : {},
4201
+ ...declared.outputAllowance ? { outputAllowance: declared.outputAllowance } : {}
4202
+ };
4203
+ }
4204
+ if (!model.reasoning) {
4205
+ return {
4206
+ mode: "none",
4207
+ configurable: false,
4208
+ reasoningCapable: false,
4209
+ wireConfigurable: false,
4210
+ supportedLevels: ["off"],
4211
+ disableWire: "omit"
4212
+ };
4213
+ }
4214
+ if (model.api === "anthropic-messages") {
4215
+ return {
4216
+ mode: "budget",
4217
+ configurable: true,
4218
+ reasoningCapable: true,
4219
+ wireConfigurable: true,
4220
+ supportedLevels: ["off", "minimal", "low", "medium", "high"],
4221
+ disableWire: "omit",
4222
+ minBudgetTokens: 1024
4223
+ };
4224
+ }
4225
+ if (model.api === "openai-responses") {
4226
+ const supportsEffort = model.compat?.supportsReasoningEffort ?? true;
4227
+ if (supportsEffort) {
4228
+ return {
4229
+ mode: "effort",
4230
+ configurable: true,
4231
+ reasoningCapable: true,
4232
+ wireConfigurable: true,
4233
+ supportedLevels: ["off", "minimal", "low", "medium", "high", "xhigh"],
4234
+ disableWire: "omit"
4235
+ };
4236
+ }
4237
+ return {
4238
+ mode: "none",
4239
+ configurable: false,
4240
+ reasoningCapable: true,
4241
+ wireConfigurable: false,
4242
+ supportedLevels: [],
4243
+ disableWire: "omit"
4244
+ };
4245
+ }
4246
+ if (model.api === "openai-completions") {
4247
+ const supportsEffort = model.compat?.supportsReasoningEffort ?? false;
4248
+ if (supportsEffort) {
4249
+ return {
4250
+ mode: "effort",
4251
+ configurable: true,
4252
+ reasoningCapable: true,
4253
+ wireConfigurable: true,
4254
+ supportedLevels: ["off", "minimal", "low", "medium", "high"],
4255
+ disableWire: "omit"
4256
+ };
4257
+ }
4258
+ return {
4259
+ mode: "none",
4260
+ configurable: false,
4261
+ reasoningCapable: true,
4262
+ wireConfigurable: false,
4263
+ supportedLevels: [],
4264
+ disableWire: "omit"
4265
+ };
4266
+ }
4267
+ return {
4268
+ mode: "effort",
4269
+ configurable: true,
4270
+ reasoningCapable: true,
4271
+ wireConfigurable: true,
4272
+ supportedLevels: ["off", "minimal", "low", "medium", "high"],
4273
+ disableWire: "omit"
4274
+ };
4275
+ }
4276
+ function getSupportedThinkingLevels(model) {
4277
+ return [...getModelThinkingCapabilities(model).supportedLevels];
4278
+ }
4279
+ function clampToSupportedLevels(requested, supported) {
4280
+ if (supported.includes(requested)) {
4281
+ return { effective: requested, clamped: false };
4282
+ }
4283
+ if (supported.length === 0) {
4284
+ return { effective: "off", clamped: requested !== "off", reason: "model exposes no configurable levels" };
4285
+ }
4286
+ if (requested === "off") {
4287
+ return {
4288
+ effective: supported[0],
4289
+ clamped: true,
4290
+ reason: `model cannot disable thinking; clamped to "${supported[0]}"`
4291
+ };
4292
+ }
4293
+ const activeSupported = supported.filter((level) => level !== "off");
4294
+ if (activeSupported.length === 0) {
4295
+ return {
4296
+ effective: "off",
4297
+ clamped: true,
4298
+ reason: "model does not support thinking"
4299
+ };
4300
+ }
4301
+ const reqRank = LEVEL_RANK[requested];
4302
+ let candidate;
4303
+ for (const level of activeSupported) {
4304
+ if (LEVEL_RANK[level] <= reqRank) {
4305
+ candidate = level;
4306
+ }
4307
+ }
4308
+ const effective = candidate ?? activeSupported[0];
4309
+ return {
4310
+ effective,
4311
+ clamped: true,
4312
+ reason: `clamped "${requested}" to "${effective}" for this model`
4313
+ };
4314
+ }
4315
+ function resolveBudgetTokensForLevel(cap, level, customBudgets) {
4316
+ const customVal = positiveFiniteNumber(customBudgets?.[level]);
4317
+ const modelVal = positiveFiniteNumber(cap.budgets?.[level]);
4318
+ let budget;
4319
+ if (customVal !== void 0) {
4320
+ budget = customVal;
4321
+ } else if (modelVal !== void 0) {
4322
+ budget = modelVal;
4323
+ } else if (level === "xhigh" || level === "max") {
4324
+ const customHigh = positiveFiniteNumber(customBudgets?.high);
4325
+ const modelHigh = positiveFiniteNumber(cap.budgets?.high);
4326
+ budget = customHigh ?? modelHigh ?? DEFAULT_THINKING_BUDGETS[level];
4327
+ } else {
4328
+ budget = DEFAULT_THINKING_BUDGETS[level];
4329
+ }
4330
+ if (budget === 0) return 0;
4331
+ const minBudget = positiveFiniteNumber(cap.minBudgetTokens);
4332
+ if (minBudget !== void 0 && budget < minBudget) {
4333
+ budget = minBudget;
4334
+ }
4335
+ const maxBudget = positiveFiniteNumber(cap.maxBudgetTokens);
4336
+ if (maxBudget !== void 0 && budget > maxBudget) {
4337
+ budget = maxBudget;
4338
+ }
4339
+ return Math.floor(budget);
4340
+ }
4341
+ function resolveOutputAllowance(model, level, customBudgets) {
4342
+ const cap = getModelThinkingCapabilities(model);
4343
+ const customVal = positiveFiniteNumber(customBudgets?.[level]);
4344
+ if (customVal !== void 0) return Math.floor(customVal);
4345
+ const modelAllowance = positiveFiniteNumber(cap.outputAllowance?.[level]);
4346
+ if (modelAllowance !== void 0) return Math.floor(modelAllowance);
4347
+ const modelBudget = positiveFiniteNumber(cap.budgets?.[level]);
4348
+ if (modelBudget !== void 0) return Math.floor(modelBudget);
4349
+ if (level === "xhigh" || level === "max") {
4350
+ const fallbackHigh = positiveFiniteNumber(customBudgets?.high) ?? positiveFiniteNumber(cap.outputAllowance?.high) ?? positiveFiniteNumber(cap.budgets?.high);
4351
+ if (fallbackHigh !== void 0) return Math.floor(fallbackHigh);
4352
+ }
4353
+ return DEFAULT_THINKING_BUDGETS[level];
4354
+ }
4355
+ function buildDisableWire(cap, model) {
4356
+ if (cap.disableWire === "disabled") {
4357
+ return model?.api === "anthropic-messages" ? { kind: "anthropic_disabled" } : { kind: "omit" };
4358
+ }
4359
+ if (cap.disableWire === "none") {
4360
+ return { kind: "effort", effort: "none" };
4361
+ }
4362
+ return { kind: "omit" };
4363
+ }
4364
+ function resolveThinkingSelection(model, requestedInput, options) {
4365
+ const cap = getModelThinkingCapabilities(model);
4366
+ const requested = isThinkingSelectionLevel(requestedInput) ? requestedInput : cap.defaultLevel ?? "off";
4367
+ if (model && isForcedNoneEffort(model)) {
4368
+ return {
4369
+ requested,
4370
+ effective: "off",
4371
+ clamped: requested !== "off",
4372
+ supportedLevels: ["off"],
4373
+ configurable: false,
4374
+ reasoningCapable: false,
4375
+ wireConfigurable: false,
4376
+ mode: "none",
4377
+ wire: { kind: "effort", effort: "none" },
4378
+ ...requested !== "off" ? { reason: "model forces reasoning_effort=none" } : {}
4379
+ };
4380
+ }
4381
+ if (!cap.reasoningCapable) {
4382
+ return {
4383
+ requested,
4384
+ effective: "off",
4385
+ clamped: requested !== "off",
4386
+ supportedLevels: ["off"],
4387
+ configurable: false,
4388
+ reasoningCapable: false,
4389
+ wireConfigurable: false,
4390
+ mode: "none",
4391
+ wire: buildDisableWire(cap, model),
4392
+ ...requested !== "off" ? { reason: "model does not support thinking" } : {}
4393
+ };
4394
+ }
4395
+ if (!cap.wireConfigurable) {
4396
+ return {
4397
+ requested,
4398
+ effective: requested,
4399
+ clamped: false,
4400
+ supportedLevels: [],
4401
+ configurable: false,
4402
+ reasoningCapable: true,
4403
+ wireConfigurable: false,
4404
+ mode: "none",
4405
+ wire: { kind: "omit" },
4406
+ reason: "model uses built-in reasoning; wire effort is not configurable"
4407
+ };
4408
+ }
4409
+ const { effective, clamped, reason } = clampToSupportedLevels(requested, cap.supportedLevels);
4410
+ if (effective === "off") {
4411
+ return {
4412
+ requested,
4413
+ effective,
4414
+ clamped,
4415
+ supportedLevels: [...cap.supportedLevels],
4416
+ configurable: cap.configurable,
4417
+ reasoningCapable: cap.reasoningCapable,
4418
+ wireConfigurable: cap.wireConfigurable,
4419
+ mode: cap.mode,
4420
+ wire: buildDisableWire(cap, model),
4421
+ ...reason ? { reason } : {}
4422
+ };
4423
+ }
4424
+ let wire;
4425
+ if (cap.mode === "adaptive") {
4426
+ const mappedEffort = normalizeAdaptiveEffort(cap.effortMap?.[effective] ?? effective);
4427
+ wire = mappedEffort === "none" ? buildDisableWire(cap, model) : { kind: "anthropic_adaptive", effort: mappedEffort };
4428
+ } else if (cap.mode === "budget") {
4429
+ const budgetTokens = resolveBudgetTokensForLevel(cap, effective, options?.customBudgets);
4430
+ wire = budgetTokens > 0 ? { kind: "anthropic_budget", budgetTokens } : { kind: "omit" };
4431
+ } else {
4432
+ const mappedEffort = cap.effortMap?.[effective] ?? effective;
4433
+ wire = { kind: "effort", effort: mappedEffort };
4434
+ }
4435
+ return {
4436
+ requested,
4437
+ effective,
4438
+ clamped,
4439
+ supportedLevels: [...cap.supportedLevels],
4440
+ configurable: cap.configurable,
4441
+ reasoningCapable: cap.reasoningCapable,
4442
+ wireConfigurable: cap.wireConfigurable,
4443
+ mode: cap.mode,
4444
+ wire,
4445
+ ...reason ? { reason } : {}
4446
+ };
4447
+ }
4448
+ function validateExplicitThinkingSelection(model, rawLevel) {
4449
+ const cap = getModelThinkingCapabilities(model);
4450
+ const modelLabel = model ? `${model.provider}/${model.id}` : "current model";
4451
+ if (!isThinkingSelectionLevel(rawLevel)) {
4452
+ const allowed = cap.wireConfigurable ? cap.supportedLevels : cap.reasoningCapable ? [...PORTABLE_THINKING_LEVELS] : ["off"];
4453
+ return {
4454
+ ok: false,
4455
+ error: `Unsupported thinking level "${rawLevel}". Supported: ${allowed.join(", ")}`,
4456
+ supportedLevels: allowed
4457
+ };
4458
+ }
4459
+ if (cap.wireConfigurable) {
4460
+ if (!cap.supportedLevels.includes(rawLevel)) {
4461
+ return {
4462
+ ok: false,
4463
+ error: `Model "${modelLabel}" does not support thinking level "${rawLevel}". Supported: ${cap.supportedLevels.join(", ")}`,
4464
+ supportedLevels: [...cap.supportedLevels]
4465
+ };
4466
+ }
4467
+ return {
4468
+ ok: true,
4469
+ level: rawLevel,
4470
+ resolved: resolveThinkingSelection(model, rawLevel)
4471
+ };
4472
+ }
4473
+ if (!cap.reasoningCapable) {
4474
+ if (rawLevel !== "off") {
4475
+ return {
4476
+ ok: false,
4477
+ error: `Model "${modelLabel}" does not support thinking. Supported: off`,
4478
+ supportedLevels: ["off"]
4479
+ };
4480
+ }
4481
+ return {
4482
+ ok: true,
4483
+ level: "off",
4484
+ resolved: resolveThinkingSelection(model, "off")
4485
+ };
4486
+ }
4487
+ if (rawLevel === "max") {
4488
+ return {
4489
+ ok: false,
4490
+ error: `Model "${modelLabel}" does not support native thinking level "max".`,
4491
+ supportedLevels: [...PORTABLE_THINKING_LEVELS]
4492
+ };
4493
+ }
4494
+ return {
4495
+ ok: true,
4496
+ level: rawLevel,
4497
+ resolved: resolveThinkingSelection(model, rawLevel)
4498
+ };
4499
+ }
4500
+ function formatBudgetShort(tokens) {
4501
+ if (tokens < 1e3) return `${tokens} tokens`;
4502
+ const k = tokens / 1e3;
4503
+ return Number.isInteger(k) ? `~${k}k tokens` : `~${k.toFixed(1)}k tokens`;
4504
+ }
4505
+ function describeThinkingLevel(model, level) {
4506
+ const cap = getModelThinkingCapabilities(model);
4507
+ if (level === "off") {
4508
+ if (!cap.reasoningCapable) return "Thinking not supported by this model";
4509
+ if (!cap.wireConfigurable) return "Hide thinking trace (model reasoning is built-in)";
4510
+ if (cap.disableWire === "disabled") return "Explicitly disable thinking";
4511
+ if (cap.disableWire === "none") return "Disable reasoning effort (effort=none)";
4512
+ return "Omit thinking request (model default)";
4513
+ }
4514
+ if (!cap.reasoningCapable) {
4515
+ return "Not supported by this model (effective: off)";
4516
+ }
4517
+ if (!cap.wireConfigurable) {
4518
+ return "Built-in model reasoning (wire effort not configurable; guides output allowance)";
4519
+ }
4520
+ if (cap.mode === "adaptive") {
4521
+ const wireEffort2 = normalizeAdaptiveEffort(cap.effortMap?.[level] ?? level);
4522
+ const mappedSuffix = wireEffort2 !== level ? ` (wire effort=${wireEffort2})` : ` (adaptive effort=${wireEffort2})`;
4523
+ switch (level) {
4524
+ case "minimal":
4525
+ return `Minimal adaptive reasoning${mappedSuffix}`;
4526
+ case "low":
4527
+ return `Light adaptive reasoning${mappedSuffix}`;
4528
+ case "medium":
4529
+ return `Moderate adaptive reasoning${mappedSuffix}`;
4530
+ case "high":
4531
+ return `Deep adaptive reasoning${mappedSuffix}`;
4532
+ case "xhigh":
4533
+ return `Extra-high adaptive reasoning${mappedSuffix}`;
4534
+ case "max":
4535
+ return `Maximum adaptive reasoning${mappedSuffix}`;
4536
+ }
4537
+ }
4538
+ if (cap.mode === "budget") {
4539
+ const budget = resolveBudgetTokensForLevel(cap, level);
4540
+ const budgetLabel = budget > 0 ? `budget ${formatBudgetShort(budget)}` : "budget omitted";
4541
+ switch (level) {
4542
+ case "minimal":
4543
+ return `Very brief reasoning (${budgetLabel})`;
4544
+ case "low":
4545
+ return `Light reasoning (${budgetLabel})`;
4546
+ case "medium":
4547
+ return `Moderate reasoning (${budgetLabel})`;
4548
+ case "high":
4549
+ return `Deep reasoning (${budgetLabel})`;
4550
+ case "xhigh":
4551
+ return `Extra-high reasoning (${budgetLabel})`;
4552
+ case "max":
4553
+ return `Maximum reasoning (${budgetLabel})`;
4554
+ }
4555
+ }
4556
+ const wireEffort = cap.effortMap?.[level] ?? level;
4557
+ const effortLabel = wireEffort !== level ? `effort=${wireEffort}, mapped from ${level}` : `effort=${wireEffort}`;
4558
+ switch (level) {
4559
+ case "minimal":
4560
+ return `Very brief reasoning (${effortLabel})`;
4561
+ case "low":
4562
+ return `Light reasoning (${effortLabel})`;
4563
+ case "medium":
4564
+ return `Moderate reasoning (${effortLabel})`;
4565
+ case "high":
4566
+ return `Deep reasoning (${effortLabel})`;
4567
+ case "xhigh":
4568
+ return `Extra-high reasoning (${effortLabel})`;
4569
+ case "max":
4570
+ return `Maximum reasoning (${effortLabel})`;
4571
+ }
4572
+ }
4573
+
4030
4574
  // ../../packages/ai/src/providers/simple-options.ts
4031
4575
  var DEFAULT_MAX_TOKENS = 32e3;
4032
4576
  function positiveFiniteOrInfinity(value) {
@@ -4056,26 +4600,13 @@ function buildBaseOptions(model, options, apiKey) {
4056
4600
  metadata: options?.metadata
4057
4601
  };
4058
4602
  }
4059
- function clampReasoning(effort) {
4060
- return effort === "xhigh" ? "high" : effort;
4603
+ function adjustMaxTokensForOutputAllowance(baseMaxTokens, modelMaxTokens, allowance) {
4604
+ const safeAllowance = typeof allowance === "number" && Number.isFinite(allowance) && allowance > 0 ? Math.floor(allowance) : 0;
4605
+ const outputCap = positiveFiniteOrInfinity(modelMaxTokens);
4606
+ return Math.min(baseMaxTokens + safeAllowance, outputCap);
4061
4607
  }
4062
- function adjustMaxTokensForThinking(baseMaxTokens, modelMaxTokens, reasoningLevel, customBudgets) {
4063
- const defaultBudgets = {
4064
- minimal: 1024,
4065
- low: 2048,
4066
- medium: 8192,
4067
- high: 16384
4068
- };
4069
- const budgets = { ...defaultBudgets };
4070
- if (customBudgets) {
4071
- for (const key of Object.keys(defaultBudgets)) {
4072
- const value = customBudgets[key];
4073
- if (typeof value === "number" && Number.isFinite(value) && value >= 0) budgets[key] = value;
4074
- }
4075
- }
4076
- const minOutputTokens = 1024;
4077
- const level = clampReasoning(reasoningLevel);
4078
- let thinkingBudget = budgets[level] ?? defaultBudgets[level] ?? 0;
4608
+ function adjustMaxTokensForBudget(baseMaxTokens, modelMaxTokens, desiredBudget, minOutputTokens = 1024) {
4609
+ let thinkingBudget = typeof desiredBudget === "number" && Number.isFinite(desiredBudget) && desiredBudget > 0 ? Math.floor(desiredBudget) : 0;
4079
4610
  const outputCap = positiveFiniteOrInfinity(modelMaxTokens);
4080
4611
  const maxTokens = Math.min(baseMaxTokens + thinkingBudget, outputCap);
4081
4612
  if (maxTokens <= thinkingBudget) {
@@ -4307,9 +4838,12 @@ function buildOpenAIChatCompletionsPayload(model, context, options, compat) {
4307
4838
  if (options?.temperature !== void 0) params.temperature = options.temperature;
4308
4839
  if (context.tools) params.tools = convertTools(context.tools, compat);
4309
4840
  if (options?.toolChoice) params.tool_choice = options.toolChoice;
4841
+ const thinkingCapable = model.thinking ? model.thinking.mode !== "none" : Boolean(model.reasoning);
4842
+ const allowsEffort = model.thinking?.mode === "effort" ? model.compat?.supportsReasoningEffort !== false : Boolean(thinkingCapable && compat.supportsReasoningEffort);
4843
+ const allowsNoneWire = model.thinking?.disableWire === "none";
4310
4844
  if (model.compat?.forcedReasoningEffort) {
4311
4845
  params.reasoning_effort = model.compat.forcedReasoningEffort;
4312
- } else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
4846
+ } else if (options?.reasoningEffort && (allowsEffort || options.reasoningEffort === "none" && allowsNoneWire)) {
4313
4847
  params.reasoning_effort = options.reasoningEffort;
4314
4848
  }
4315
4849
  return params;
@@ -5429,13 +5963,14 @@ function formatOpenAIStreamError(error) {
5429
5963
  if (!error || typeof error !== "object") {
5430
5964
  return typeof error === "string" ? error : "OpenAI-compatible stream returned an error";
5431
5965
  }
5432
- const message = typeof error.message === "string" && error.message.length > 0 ? error.message : "OpenAI-compatible stream returned an error";
5966
+ const record = error;
5967
+ const message = typeof record.message === "string" && record.message.length > 0 ? record.message : "OpenAI-compatible stream returned an error";
5433
5968
  const metadata = [];
5434
- if (typeof error.type === "string" && error.type.length > 0) {
5435
- metadata.push(`type=${error.type}`);
5969
+ if (typeof record.type === "string" && record.type.length > 0) {
5970
+ metadata.push(`type=${record.type}`);
5436
5971
  }
5437
- if (typeof error.code === "string" && error.code.length > 0) {
5438
- metadata.push(`code=${error.code}`);
5972
+ if (typeof record.code === "string" && record.code.length > 0) {
5973
+ metadata.push(`code=${record.code}`);
5439
5974
  }
5440
5975
  return metadata.length > 0 ? `${message} (${metadata.join(", ")})` : message;
5441
5976
  }
@@ -5586,7 +6121,7 @@ var streamOpenAICompletions = (model, context, options) => {
5586
6121
  };
5587
6122
  const resolveToolCallEntry = (toolCall, toolCallCount) => {
5588
6123
  const id = typeof toolCall.id === "string" && toolCall.id.length > 0 ? toolCall.id : "";
5589
- if (Number.isInteger(toolCall.index) && toolCall.index >= 0) {
6124
+ if (typeof toolCall.index === "number" && Number.isInteger(toolCall.index) && toolCall.index >= 0) {
5590
6125
  let entry = toolCallsByIndex.get(toolCall.index);
5591
6126
  if (entry && id && entry.block.id && entry.block.id !== id) {
5592
6127
  throw createProtocolError(`OpenAI-compatible stream changed tool call id at index ${toolCall.index} from "${entry.block.id}" to "${id}".`);
@@ -5726,7 +6261,8 @@ var streamOpenAICompletions = (model, context, options) => {
5726
6261
  ];
5727
6262
  let foundReasoningField = null;
5728
6263
  for (const field of reasoningFields) {
5729
- if (choice.delta[field] !== null && choice.delta[field] !== void 0 && choice.delta[field].length > 0) {
6264
+ const value = choice.delta[field];
6265
+ if (typeof value === "string" && value.length > 0) {
5730
6266
  foundReasoningField = field;
5731
6267
  break;
5732
6268
  }
@@ -5747,7 +6283,7 @@ var streamOpenAICompletions = (model, context, options) => {
5747
6283
  });
5748
6284
  }
5749
6285
  if (currentBlock.type === "thinking") {
5750
- const delta = choice.delta[foundReasoningField];
6286
+ const delta = choice.delta[foundReasoningField] ?? "";
5751
6287
  currentBlock.thinking += delta;
5752
6288
  stream2.push({
5753
6289
  type: "thinking_delta",
@@ -5914,10 +6450,16 @@ var streamSimpleOpenAICompletions = (model, context, options) => {
5914
6450
  throw new Error(`No API key for provider: ${model.provider}`);
5915
6451
  }
5916
6452
  const base = buildBaseOptions(model, options, apiKey);
5917
- const reasoningEffort = clampReasoning(options?.reasoning);
5918
- const needsThinkingAllowance = Boolean(model.reasoning) && options?.reasoning !== void 0;
5919
- const adjusted = needsThinkingAllowance ? adjustMaxTokensForThinking(base.maxTokens || 0, model.maxTokens, options.reasoning, options?.thinkingBudgets) : void 0;
5920
- let maxTokens = adjusted ? adjusted.maxTokens : base.maxTokens;
6453
+ const resolved = resolveThinkingSelection(model, options?.reasoning ?? "off", {
6454
+ customBudgets: options?.thinkingBudgets
6455
+ });
6456
+ const reasoningEffort = resolved.wire.kind === "effort" ? resolved.wire.effort : void 0;
6457
+ const needsThinkingAllowance = resolved.reasoningCapable && resolved.effective !== "off";
6458
+ let maxTokens = needsThinkingAllowance ? adjustMaxTokensForOutputAllowance(
6459
+ base.maxTokens || 0,
6460
+ model.maxTokens,
6461
+ resolveOutputAllowance(model, resolved.effective, options?.thinkingBudgets)
6462
+ ) : base.maxTokens;
5921
6463
  if (maxTokens === void 0) {
5922
6464
  maxTokens = DEFAULT_MAX_TOKENS;
5923
6465
  }
@@ -6236,11 +6778,33 @@ var streamAnthropic = (model, context, options) => {
6236
6778
  if (context.tools?.length) {
6237
6779
  params.tools = convertTools2(context.tools);
6238
6780
  }
6239
- if (options?.thinkingEnabled && model.reasoning) {
6240
- params.thinking = {
6241
- type: "enabled",
6242
- budget_tokens: options.thinkingBudgetTokens || 1024
6243
- };
6781
+ const modelThinkingCapable = model.thinking ? model.thinking.mode !== "none" : Boolean(model.reasoning);
6782
+ if (options?.thinkingMode === "disabled") {
6783
+ params.thinking = { type: "disabled" };
6784
+ } else if (options?.thinkingMode === "adaptive" && modelThinkingCapable) {
6785
+ params.thinking = { type: "adaptive" };
6786
+ if (options.outputEffort && options.outputEffort !== "none") {
6787
+ params.output_config = { effort: options.outputEffort };
6788
+ }
6789
+ } else if ((options?.thinkingMode === "enabled" || options?.thinkingEnabled) && modelThinkingCapable) {
6790
+ const minBudget = model.thinking?.minBudgetTokens ?? 1024;
6791
+ const maxBudget = model.thinking?.maxBudgetTokens;
6792
+ const rawBudget = options?.thinkingBudgetTokens;
6793
+ if (rawBudget === void 0) {
6794
+ params.thinking = {
6795
+ type: "enabled",
6796
+ budget_tokens: minBudget
6797
+ };
6798
+ } else if (Number.isFinite(rawBudget) && rawBudget > 0) {
6799
+ let budget = Math.max(minBudget, Math.floor(rawBudget));
6800
+ if (maxBudget !== void 0 && Number.isFinite(maxBudget) && maxBudget >= minBudget) {
6801
+ budget = Math.min(budget, Math.floor(maxBudget));
6802
+ }
6803
+ params.thinking = {
6804
+ type: "enabled",
6805
+ budget_tokens: budget
6806
+ };
6807
+ }
6244
6808
  }
6245
6809
  if (options?.toolChoice) {
6246
6810
  if (typeof options.toolChoice === "string") {
@@ -6253,7 +6817,10 @@ var streamAnthropic = (model, context, options) => {
6253
6817
  applyCacheBreakpoints(params, options?.cacheRetention);
6254
6818
  }
6255
6819
  options?.onPayload?.(params);
6256
- const anthropicStream = client.messages.stream({ ...params, stream: true }, { signal: options?.signal });
6820
+ const anthropicStream = client.messages.stream(
6821
+ { ...params, stream: true },
6822
+ { signal: options?.signal }
6823
+ );
6257
6824
  stream2.push({ type: "start", partial: output });
6258
6825
  const blocks = output.content;
6259
6826
  let hasReportedInputUsage = false;
@@ -6315,7 +6882,7 @@ var streamAnthropic = (model, context, options) => {
6315
6882
  const index = blocks.findIndex((b) => b.index === event.index);
6316
6883
  const block = blocks[index];
6317
6884
  if (block?.type === "toolCall") {
6318
- block.partialJson += event.delta.partial_json;
6885
+ block.partialJson = (block.partialJson ?? "") + event.delta.partial_json;
6319
6886
  block.arguments = parseStreamingJson(block.partialJson);
6320
6887
  stream2.push({
6321
6888
  type: "toolcall_delta",
@@ -6392,16 +6959,47 @@ var streamSimpleAnthropic = (model, context, options) => {
6392
6959
  throw new Error(`No API key for provider: ${model.provider}`);
6393
6960
  }
6394
6961
  const base = buildBaseOptions(model, options, apiKey);
6395
- if (!options?.reasoning) {
6396
- return streamAnthropic(model, context, { ...base, thinkingEnabled: false });
6397
- }
6398
- const adjusted = adjustMaxTokensForThinking(base.maxTokens || 0, model.maxTokens, options.reasoning, options.thinkingBudgets);
6399
- return streamAnthropic(model, context, {
6400
- ...base,
6401
- maxTokens: adjusted.maxTokens,
6402
- thinkingEnabled: true,
6403
- thinkingBudgetTokens: adjusted.thinkingBudget
6962
+ const resolved = resolveThinkingSelection(model, options?.reasoning ?? "off", {
6963
+ customBudgets: options?.thinkingBudgets
6404
6964
  });
6965
+ if (resolved.wire.kind === "anthropic_disabled") {
6966
+ return streamAnthropic(model, context, {
6967
+ ...base,
6968
+ thinkingEnabled: false,
6969
+ thinkingMode: "disabled"
6970
+ });
6971
+ }
6972
+ if (resolved.wire.kind === "anthropic_adaptive") {
6973
+ const effectiveLevel = resolved.effective;
6974
+ const allowance = resolveOutputAllowance(model, effectiveLevel, options?.thinkingBudgets);
6975
+ const maxTokens = adjustMaxTokensForOutputAllowance(base.maxTokens || 0, model.maxTokens, allowance);
6976
+ return streamAnthropic(model, context, {
6977
+ ...base,
6978
+ maxTokens,
6979
+ thinkingEnabled: true,
6980
+ thinkingMode: "adaptive",
6981
+ outputEffort: resolved.wire.effort
6982
+ });
6983
+ }
6984
+ if (resolved.wire.kind === "anthropic_budget") {
6985
+ const minBudget = model.thinking?.minBudgetTokens ?? 1024;
6986
+ const adjusted = adjustMaxTokensForBudget(base.maxTokens || 0, model.maxTokens, resolved.wire.budgetTokens, minBudget);
6987
+ if (adjusted.thinkingBudget < minBudget) {
6988
+ return streamAnthropic(model, context, {
6989
+ ...base,
6990
+ maxTokens: adjusted.maxTokens,
6991
+ thinkingEnabled: false
6992
+ });
6993
+ }
6994
+ return streamAnthropic(model, context, {
6995
+ ...base,
6996
+ maxTokens: adjusted.maxTokens,
6997
+ thinkingEnabled: true,
6998
+ thinkingMode: "enabled",
6999
+ thinkingBudgetTokens: adjusted.thinkingBudget
7000
+ });
7001
+ }
7002
+ return streamAnthropic(model, context, { ...base, thinkingEnabled: false });
6405
7003
  };
6406
7004
 
6407
7005
  // ../../packages/ai/src/providers/responses/responses-compat.ts
@@ -6574,14 +7172,16 @@ function buildResponsesRequest(model, context, options, compat = getResponsesCom
6574
7172
  }
6575
7173
  if (options?.temperature !== void 0) params.temperature = options.temperature;
6576
7174
  if (options?.topP !== void 0) params.top_p = options.topP;
6577
- if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
7175
+ const thinkingCapable = model.thinking ? model.thinking.mode !== "none" : Boolean(model.reasoning);
7176
+ const allowsNoneWire = model.thinking?.disableWire === "none";
7177
+ if (options?.reasoningEffort && (thinkingCapable || options.reasoningEffort === "none" && allowsNoneWire) && compat.supportsReasoningEffort) {
6578
7178
  params.reasoning = { effort: options.reasoningEffort };
6579
7179
  }
6580
- if (model.reasoning && compat.supportsReasoningSummary && compat.reasoningSummary !== "none") {
7180
+ if (thinkingCapable && options?.reasoningEffort !== "none" && compat.supportsReasoningSummary && compat.reasoningSummary !== "none") {
6581
7181
  params.reasoning = params.reasoning ?? {};
6582
7182
  params.reasoning.summary = compat.reasoningSummary;
6583
7183
  }
6584
- if (compat.supportsEncryptedReasoning && model.reasoning) {
7184
+ if (compat.supportsEncryptedReasoning && thinkingCapable && options?.reasoningEffort !== "none") {
6585
7185
  params.include = ["reasoning.encrypted_content"];
6586
7186
  }
6587
7187
  if (context.tools && context.tools.length > 0) {
@@ -7474,7 +8074,17 @@ function streamResponsesWS(model, context, options) {
7474
8074
  });
7475
8075
  lifecycle("submission_attempted", { submissionAttempted: true });
7476
8076
  armPhaseTimer("first_response", budgets.firstResponseTimeoutMs);
7477
- await transportIO(() => activeConnection.send(body, { signal: requestAbort.signal }));
8077
+ try {
8078
+ await transportIO(() => activeConnection.send(body, { signal: requestAbort.signal }));
8079
+ } catch (error) {
8080
+ if (error instanceof WebSocketTransportError && error.kind === "overflow" && error.preflight === true && options?.transport === "auto" && !options?.signal?.aborted && !state.abort.signal.aborted && !timedOut) {
8081
+ sent = false;
8082
+ delete reducer.message.remoteFailure;
8083
+ await runSSEFallback();
8084
+ return;
8085
+ }
8086
+ throw error;
8087
+ }
7478
8088
  let started = false;
7479
8089
  let responseId;
7480
8090
  const receiveIterator = activeConnection.receive(requestAbort.signal)[Symbol.asyncIterator]();
@@ -7651,26 +8261,22 @@ var streamSimpleResponses = (model, context, options) => {
7651
8261
  throw new Error(`No API key for provider: ${model.provider}`);
7652
8262
  }
7653
8263
  const base = buildBaseOptions(model, options, apiKey);
7654
- const needsThinkingAllowance = Boolean(model.reasoning) && options?.reasoning !== void 0;
8264
+ const resolved = resolveThinkingSelection(model, options?.reasoning ?? "off", {
8265
+ customBudgets: options?.thinkingBudgets
8266
+ });
8267
+ const needsThinkingAllowance = resolved.reasoningCapable && resolved.effective !== "off";
7655
8268
  let maxTokens = base.maxTokens;
7656
8269
  if (needsThinkingAllowance) {
7657
- const adjusted = adjustMaxTokensForThinking(
7658
- base.maxTokens || 0,
7659
- model.maxTokens,
7660
- options.reasoning,
7661
- options?.thinkingBudgets
7662
- );
7663
- maxTokens = adjusted.maxTokens;
8270
+ const allowance = resolveOutputAllowance(model, resolved.effective, options?.thinkingBudgets);
8271
+ maxTokens = adjustMaxTokensForOutputAllowance(base.maxTokens || 0, model.maxTokens, allowance);
7664
8272
  }
7665
8273
  if (maxTokens === void 0) {
7666
8274
  maxTokens = DEFAULT_MAX_TOKENS;
7667
8275
  }
7668
- const reasoningEffort = model.reasoning ? options?.reasoning : void 0;
8276
+ const reasoningEffort = resolved.wire.kind === "effort" ? resolved.wire.effort : void 0;
7669
8277
  return streamResponses(model, context, {
7670
8278
  ...base,
7671
8279
  maxTokens,
7672
- // Responses accepts the full effort vocabulary verified in the SDK
7673
- // ("none" excluded from Pie's ThinkingLevel); pass through unchanged.
7674
8280
  reasoningEffort
7675
8281
  });
7676
8282
  };
@@ -11104,7 +11710,7 @@ function buildLengthHint(error, args, path) {
11104
11710
  const direction = error.type === ValueErrorType.StringMaxLength ? "trim to at most the limit" : "extend to at least the minimum";
11105
11711
  let value = args;
11106
11712
  for (const segment of path.split("/").filter(Boolean)) {
11107
- value = value?.[segment];
11713
+ value = value !== null && typeof value === "object" ? value[segment] : void 0;
11108
11714
  }
11109
11715
  if (typeof value !== "string") return "";
11110
11716
  return `(got length ${value.length} \u2014 ${direction} and retry)`;
@@ -11127,22 +11733,23 @@ function resolveSchemaNode(schema, path) {
11127
11733
  let node = schema;
11128
11734
  for (const segment of path.split("/").filter(Boolean)) {
11129
11735
  if (!node || typeof node !== "object") return void 0;
11736
+ const record = node;
11130
11737
  if (/^\d+$/.test(segment)) {
11131
- node = node.items;
11132
- } else if (node.properties && segment in node.properties) {
11133
- node = node.properties[segment];
11134
- } else if (node.additionalProperties && typeof node.additionalProperties === "object") {
11135
- node = node.additionalProperties;
11738
+ node = record.items;
11739
+ } else if (record.properties && segment in record.properties) {
11740
+ node = record.properties[segment];
11741
+ } else if (record.additionalProperties && typeof record.additionalProperties === "object") {
11742
+ node = record.additionalProperties;
11136
11743
  } else {
11137
11744
  return void 0;
11138
11745
  }
11139
11746
  }
11140
- return node;
11747
+ return node && typeof node === "object" ? node : void 0;
11141
11748
  }
11142
11749
  function receivedKeysAt(args, path) {
11143
11750
  let target = args;
11144
11751
  for (const segment of path.split("/").filter(Boolean)) {
11145
- target = target?.[segment];
11752
+ target = target !== null && typeof target === "object" ? target[segment] : void 0;
11146
11753
  }
11147
11754
  if (target && typeof target === "object" && !Array.isArray(target)) {
11148
11755
  return Object.keys(target);
@@ -11168,15 +11775,6 @@ registerApiProvider({
11168
11775
  });
11169
11776
 
11170
11777
  export {
11171
- hashText,
11172
- detectPlatform,
11173
- createLogger,
11174
- setLogger,
11175
- getLogger,
11176
- getPlatformConfig,
11177
- FileSystemGateway,
11178
- getFileSystemGateway,
11179
- getFileSystem,
11180
11778
  format_exports,
11181
11779
  type_exports,
11182
11780
  ExtendsUndefinedCheck,
@@ -11205,7 +11803,31 @@ export {
11205
11803
  EventStream,
11206
11804
  AssistantMessageEventStream,
11207
11805
  createAssistantMessageEventStream,
11806
+ hashText,
11807
+ detectPlatform,
11808
+ createLogger,
11809
+ setLogger,
11810
+ getLogger,
11811
+ getPlatformConfig,
11812
+ FileSystemGateway,
11813
+ getFileSystemGateway,
11814
+ getFileSystem,
11208
11815
  parseStreamingJson,
11816
+ ALL_THINKING_LEVELS,
11817
+ PORTABLE_THINKING_LEVELS,
11818
+ ACTIVE_THINKING_LEVELS,
11819
+ DEFAULT_THINKING_BUDGETS,
11820
+ isThinkingSelectionLevel,
11821
+ isPortableThinkingLevel,
11822
+ isActiveThinkingLevel,
11823
+ isThinkingModeCompatibleWithApi,
11824
+ isDisableWireCompatibleWithApi,
11825
+ getModelThinkingCapabilities,
11826
+ getSupportedThinkingLevels,
11827
+ resolveOutputAllowance,
11828
+ resolveThinkingSelection,
11829
+ validateExplicitThinkingSelection,
11830
+ describeThinkingLevel,
11209
11831
  NO_CACHE_CAPABILITY,
11210
11832
  ANTHROPIC_PROMPT_CACHE_CAPABILITY,
11211
11833
  getModelCacheCapability,