@pensar/apex 2.4.0 → 2.5.0-canary.2512a649

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 (70) hide show
  1. package/build/agent-1wk9ejrw.js +19 -0
  2. package/build/{agent-5ejt5vpz.js → agent-cqxw0kd9.js} +24 -23
  3. package/build/agent-nhfjk81t.js +22 -0
  4. package/build/{agent-nhs1w5w0.js → agent-za6meqyw.js} +11 -10
  5. package/build/{apps-17wvz1d7.js → apps-eqncpkp8.js} +72 -31
  6. package/build/{auth-z3h9859n.js → auth-jabyx925.js} +25 -20
  7. package/build/blackboxAgent-6yg06yq2.js +22 -0
  8. package/build/blackboxPentest-9ckcgmqc.js +70 -0
  9. package/build/{cli-tkc598ey.js → cli-0drqd790.js} +633 -344
  10. package/build/cli-0nrxvm0t.js +12 -0
  11. package/build/{cli-gq40s5b3.js → cli-13bx8fdg.js} +28 -41
  12. package/build/cli-53rm0rrz.js +15 -0
  13. package/build/{cli-b1adytsy.js → cli-5s6jqck2.js} +28 -7
  14. package/build/{cli-2cbwdk78.js → cli-5xh2zw52.js} +1 -1
  15. package/build/cli-68260ckj.js +12136 -0
  16. package/build/cli-7q3ae3ft.js +6 -0
  17. package/build/{cli-72cvcqhg.js → cli-8k8wam9m.js} +1 -1
  18. package/build/{cli-mavved45.js → cli-8r0ekwvh.js} +54 -65
  19. package/build/{cli-swpbx60z.js → cli-avmhkjtv.js} +1 -1481
  20. package/build/{cli-9rhzhgx2.js → cli-dkxwnmrz.js} +1 -1
  21. package/build/{cli-0n4r54hq.js → cli-ewxfjn4c.js} +1 -1
  22. package/build/{cli-k8kc47pq.js → cli-fa5wxr8x.js} +32 -60
  23. package/build/{cli-xshasbwe.js → cli-g9xm89jx.js} +24 -45
  24. package/build/{cli-vnynf0js.js → cli-h1xcrswb.js} +10 -4
  25. package/build/cli-knd276ed.js +1485 -0
  26. package/build/{cli-repbyhkk.js → cli-nt8jrt7c.js} +2131 -1371
  27. package/build/{cli-tznv8pf1.js → cli-q8zkbvsn.js} +1 -1
  28. package/build/{cli-vq52kp7j.js → cli-qqzsm7gd.js} +23 -5
  29. package/build/{cli-32z0017y.js → cli-vazvj17j.js} +32 -56
  30. package/build/cli-w329bvm0.js +32 -0
  31. package/build/{cli-5k33webc.js → cli-ypavpbzs.js} +77 -51
  32. package/build/cli.js +661 -99
  33. package/build/{config-f1mj4nhd.js → config-bmz74x9e.js} +18 -15
  34. package/build/{doctor-ekneewa3.js → doctor-qw9mawme.js} +8 -7
  35. package/build/{fastStrike-8zka43xs.js → fastStrike-jpwx6dtk.js} +13 -11
  36. package/build/{fixes-b89s5haw.js → fixes-53r1jxkp.js} +25 -20
  37. package/build/getMachineId-bsd-xj3bn2fv.js +36 -0
  38. package/build/getMachineId-darwin-07jzjcx6.js +36 -0
  39. package/build/getMachineId-linux-ahngynxd.js +29 -0
  40. package/build/getMachineId-unsupported-vy43b44z.js +19 -0
  41. package/build/getMachineId-win-8x66cynz.js +38 -0
  42. package/build/{index-hqjdg6fg.js → index-4cknw5gy.js} +17 -11
  43. package/build/index-4fbqdgby.js +109 -0
  44. package/build/{index-mtq7kmxz.js → index-5wh7gq37.js} +4 -2
  45. package/build/{index-rbzhk712.js → index-dshvnys5.js} +10 -10
  46. package/build/{index-6d22pyxt.js → index-k8ybkkp1.js} +1785 -1228
  47. package/build/{index-4ad3sdwk.js → index-kcqbaf72.js} +4 -4
  48. package/build/{index-sf16jm0m.js → index-mxqe1y58.js} +11 -8
  49. package/build/{index-ghwf5z3v.js → index-p01t9n89.js} +3 -3
  50. package/build/{index-y5w6n3tb.js → index-xcpavpbs.js} +2 -2
  51. package/build/{issues-xx5bs4md.js → issues-xesdtrg9.js} +82 -26
  52. package/build/{logs-qtxe51w2.js → logs-83wtsyha.js} +25 -20
  53. package/build/{offesecAgent-b9e2xm6v.js → offesecAgent-efzhx1gf.js} +9 -9
  54. package/build/pentest-g1ma266m.js +30 -0
  55. package/build/{pentests-6ks3szc4.js → pentests-fcs7v2e9.js} +26 -21
  56. package/build/{targetedPentest-s1ptvq8e.js → targetedPentest-6hq0hmys.js} +17 -12
  57. package/build/{targets-sxygyj87.js → targets-qh73k68m.js} +27 -22
  58. package/build/threatModel-nqx5mr0y.js +29 -0
  59. package/build/{uninstall-tvsh81v8.js → uninstall-rab8zrm4.js} +6 -3
  60. package/build/{upload-7wdyyqmr.js → upload-kser9ga1.js} +8 -7
  61. package/build/{utils-7fwdkqk6.js → utils-7ngtwza4.js} +7 -6
  62. package/package.json +8 -2
  63. package/build/agent-mvpgvgks.js +0 -19
  64. package/build/authentication-3s97cpk4.js +0 -19
  65. package/build/blackboxAgent-gw0a1ca4.js +0 -19
  66. package/build/blackboxPentest-44333zss.js +0 -37
  67. package/build/cli-qqt4gj1w.js +0 -53
  68. package/build/main-mmjp338j.js +0 -324
  69. package/build/pentest-xtc1sjdw.js +0 -29
  70. package/build/threatModel-xsm6fwk5.js +0 -27
@@ -4,7 +4,7 @@ import {
4
4
  init_auth,
5
5
  init_constants,
6
6
  signGatewayRequest
7
- } from "./cli-0n4r54hq.js";
7
+ } from "./cli-ewxfjn4c.js";
8
8
  import {
9
9
  AISDKError,
10
10
  APICallError,
@@ -71,7 +71,6 @@ import {
71
71
  postFormDataToApi,
72
72
  postJsonToApi,
73
73
  readResponseWithSizeLimit,
74
- require_src,
75
74
  resolve,
76
75
  safeParseAsync,
77
76
  safeParseJSON,
@@ -83,15 +82,18 @@ import {
83
82
  withoutTrailingSlash,
84
83
  zodSchema,
85
84
  zod_default
86
- } from "./cli-swpbx60z.js";
85
+ } from "./cli-avmhkjtv.js";
87
86
  import {
88
87
  config,
89
88
  init_config
90
- } from "./cli-72cvcqhg.js";
89
+ } from "./cli-8k8wam9m.js";
91
90
  import {
92
91
  getCurrentVersion,
93
92
  init_installation
94
- } from "./cli-vnynf0js.js";
93
+ } from "./cli-h1xcrswb.js";
94
+ import {
95
+ require_src
96
+ } from "./cli-knd276ed.js";
95
97
  import {
96
98
  __callDispose,
97
99
  __commonJS,
@@ -6505,7 +6507,59 @@ var import_api, import_api2, __defProp, __export = (target, all) => {
6505
6507
  ...init
6506
6508
  });
6507
6509
  }
6508
- }, toolMetadataSchema2, uiMessagesSchema, originalGenerateId3, originalGenerateId4, defaultDownload, name21 = "AI_NoSuchProviderError", marker21, symbol21, _a21, defaultDownload2;
6510
+ }, toolMetadataSchema2, uiMessagesSchema, originalGenerateId3, originalGenerateId4, defaultDownload, wrapLanguageModel = ({
6511
+ model,
6512
+ middleware: middlewareArg,
6513
+ modelId,
6514
+ providerId
6515
+ }) => {
6516
+ return [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {
6517
+ return doWrap({ model: wrappedModel, middleware, modelId, providerId });
6518
+ }, model);
6519
+ }, doWrap = ({
6520
+ model,
6521
+ middleware: {
6522
+ transformParams,
6523
+ wrapGenerate,
6524
+ wrapStream,
6525
+ overrideProvider,
6526
+ overrideModelId,
6527
+ overrideSupportedUrls
6528
+ },
6529
+ modelId,
6530
+ providerId
6531
+ }) => {
6532
+ var _a22, _b, _c;
6533
+ async function doTransform({
6534
+ params,
6535
+ type
6536
+ }) {
6537
+ return transformParams ? await transformParams({ params, type, model }) : params;
6538
+ }
6539
+ return {
6540
+ specificationVersion: "v3",
6541
+ provider: (_a22 = providerId != null ? providerId : overrideProvider == null ? undefined : overrideProvider({ model })) != null ? _a22 : model.provider,
6542
+ modelId: (_b = modelId != null ? modelId : overrideModelId == null ? undefined : overrideModelId({ model })) != null ? _b : model.modelId,
6543
+ supportedUrls: (_c = overrideSupportedUrls == null ? undefined : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,
6544
+ async doGenerate(params) {
6545
+ const transformedParams = await doTransform({ params, type: "generate" });
6546
+ const doGenerate = async () => model.doGenerate(transformedParams);
6547
+ const doStream = async () => model.doStream(transformedParams);
6548
+ return wrapGenerate ? wrapGenerate({
6549
+ doGenerate,
6550
+ doStream,
6551
+ params: transformedParams,
6552
+ model
6553
+ }) : doGenerate();
6554
+ },
6555
+ async doStream(params) {
6556
+ const transformedParams = await doTransform({ params, type: "stream" });
6557
+ const doGenerate = async () => model.doGenerate(transformedParams);
6558
+ const doStream = async () => model.doStream(transformedParams);
6559
+ return wrapStream ? wrapStream({ doGenerate, doStream, params: transformedParams, model }) : doStream();
6560
+ }
6561
+ };
6562
+ }, name21 = "AI_NoSuchProviderError", marker21, symbol21, _a21, defaultDownload2;
6509
6563
  var init_dist4 = __esm(() => {
6510
6564
  init_dist2();
6511
6565
  init_dist2();
@@ -7678,6 +7732,59 @@ var init_dist4 = __esm(() => {
7678
7732
  defaultDownload2 = createDownload();
7679
7733
  });
7680
7734
 
7735
+ // src/core/id/id.ts
7736
+ import { randomBytes } from "node:crypto";
7737
+ function schema(prefix) {
7738
+ return zod_default.string().startsWith(prefixes[prefix]);
7739
+ }
7740
+ function descending(prefix, given) {
7741
+ return generateID(prefix, true, given);
7742
+ }
7743
+ function generateID(prefix, descending2, given) {
7744
+ if (!given) {
7745
+ return create(prefix, descending2);
7746
+ }
7747
+ if (!given.startsWith(prefixes[prefix])) {
7748
+ throw new Error(`ID ${given} does not start with ${prefixes[prefix]}`);
7749
+ }
7750
+ return given;
7751
+ }
7752
+ function randomBase62(length) {
7753
+ const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
7754
+ let result = "";
7755
+ const bytes = randomBytes(length);
7756
+ for (let i = 0;i < length; i++) {
7757
+ result += chars[bytes[i] % 62];
7758
+ }
7759
+ return result;
7760
+ }
7761
+ function create(prefix, descending2, timestamp) {
7762
+ const currentTimestamp = timestamp ?? Date.now();
7763
+ if (currentTimestamp !== lastTimestamp) {
7764
+ lastTimestamp = currentTimestamp;
7765
+ counter = 0;
7766
+ }
7767
+ counter++;
7768
+ let now2 = BigInt(currentTimestamp) * BigInt(4096) + BigInt(counter);
7769
+ now2 = descending2 ? ~now2 : now2;
7770
+ const timeBytes = Buffer.alloc(6);
7771
+ for (let i = 0;i < 6; i++) {
7772
+ timeBytes[i] = Number(now2 >> BigInt(40 - 8 * i) & BigInt(255));
7773
+ }
7774
+ return prefixes[prefix] + "_" + timeBytes.toString("hex") + randomBase62(LENGTH - 12);
7775
+ }
7776
+ var prefixes, LENGTH = 26, lastTimestamp = 0, counter = 0, newSessionId = () => descending("session"), newMessageId = () => descending("message"), newPartId = () => descending("part"), isSessionId = (s) => s.startsWith(`${prefixes.session}_`);
7777
+ var init_id = __esm(() => {
7778
+ init_zod();
7779
+ prefixes = {
7780
+ session: "ses",
7781
+ message: "msg",
7782
+ permission: "per",
7783
+ user: "usr",
7784
+ part: "prt"
7785
+ };
7786
+ });
7787
+
7681
7788
  // src/core/ai/models/anthropic.ts
7682
7789
  var ANTHROPIC_MODELS;
7683
7790
  var init_anthropic = __esm(() => {
@@ -15678,10 +15785,10 @@ function convertOpenAIResponsesUsage(usage) {
15678
15785
  function serializeToolCallArguments2(input) {
15679
15786
  return JSON.stringify(input === undefined ? {} : input);
15680
15787
  }
15681
- function isFileId(data, prefixes) {
15682
- if (!prefixes)
15788
+ function isFileId(data, prefixes2) {
15789
+ if (!prefixes2)
15683
15790
  return false;
15684
- return prefixes.some((prefix) => data.startsWith(prefix));
15791
+ return prefixes2.some((prefix) => data.startsWith(prefix));
15685
15792
  }
15686
15793
  async function convertToOpenAIResponsesInput({
15687
15794
  prompt,
@@ -21775,8 +21882,8 @@ function mapAnthropicStopReason({
21775
21882
  return "other";
21776
21883
  }
21777
21884
  }
21778
- function sanitizeJsonSchema(schema) {
21779
- return sanitizeSchema(schema);
21885
+ function sanitizeJsonSchema(schema2) {
21886
+ return sanitizeSchema(schema2);
21780
21887
  }
21781
21888
  function sanitizeDefinition(definition) {
21782
21889
  if (typeof definition === "boolean" || !isPlainObject(definition)) {
@@ -21784,46 +21891,46 @@ function sanitizeDefinition(definition) {
21784
21891
  }
21785
21892
  return sanitizeSchema(definition);
21786
21893
  }
21787
- function sanitizeSchema(schema) {
21894
+ function sanitizeSchema(schema2) {
21788
21895
  const result = {};
21789
- const schemaWithDefs = schema;
21790
- if (schema.$ref != null) {
21791
- return { $ref: schema.$ref };
21896
+ const schemaWithDefs = schema2;
21897
+ if (schema2.$ref != null) {
21898
+ return { $ref: schema2.$ref };
21792
21899
  }
21793
- if (schema.$schema != null) {
21794
- result.$schema = schema.$schema;
21900
+ if (schema2.$schema != null) {
21901
+ result.$schema = schema2.$schema;
21795
21902
  }
21796
- if (schema.$id != null) {
21797
- result.$id = schema.$id;
21903
+ if (schema2.$id != null) {
21904
+ result.$id = schema2.$id;
21798
21905
  }
21799
- if (schema.title != null) {
21800
- result.title = schema.title;
21906
+ if (schema2.title != null) {
21907
+ result.title = schema2.title;
21801
21908
  }
21802
- if (schema.description != null) {
21803
- result.description = schema.description;
21909
+ if (schema2.description != null) {
21910
+ result.description = schema2.description;
21804
21911
  }
21805
- if (schema.default !== undefined) {
21806
- result.default = schema.default;
21912
+ if (schema2.default !== undefined) {
21913
+ result.default = schema2.default;
21807
21914
  }
21808
- if (schema.const !== undefined) {
21809
- result.const = schema.const;
21915
+ if (schema2.const !== undefined) {
21916
+ result.const = schema2.const;
21810
21917
  }
21811
- if (schema.enum != null) {
21812
- result.enum = schema.enum;
21918
+ if (schema2.enum != null) {
21919
+ result.enum = schema2.enum;
21813
21920
  }
21814
- if (schema.type != null) {
21815
- result.type = schema.type;
21921
+ if (schema2.type != null) {
21922
+ result.type = schema2.type;
21816
21923
  }
21817
- if (schema.anyOf != null) {
21818
- result.anyOf = schema.anyOf.map(sanitizeDefinition);
21819
- } else if (schema.oneOf != null) {
21820
- result.anyOf = schema.oneOf.map(sanitizeDefinition);
21924
+ if (schema2.anyOf != null) {
21925
+ result.anyOf = schema2.anyOf.map(sanitizeDefinition);
21926
+ } else if (schema2.oneOf != null) {
21927
+ result.anyOf = schema2.oneOf.map(sanitizeDefinition);
21821
21928
  }
21822
- if (schema.allOf != null) {
21823
- result.allOf = schema.allOf.map(sanitizeDefinition);
21929
+ if (schema2.allOf != null) {
21930
+ result.allOf = schema2.allOf.map(sanitizeDefinition);
21824
21931
  }
21825
- if (schema.definitions != null) {
21826
- result.definitions = Object.fromEntries(Object.entries(schema.definitions).map(([name22, definition]) => [
21932
+ if (schema2.definitions != null) {
21933
+ result.definitions = Object.fromEntries(Object.entries(schema2.definitions).map(([name22, definition]) => [
21827
21934
  name22,
21828
21935
  sanitizeDefinition(definition)
21829
21936
  ]));
@@ -21835,41 +21942,41 @@ function sanitizeSchema(schema) {
21835
21942
  sanitizeDefinition(definition)
21836
21943
  ]));
21837
21944
  }
21838
- if (schema.type === "object" || schema.properties != null) {
21839
- if (schema.properties != null) {
21840
- result.properties = Object.fromEntries(Object.entries(schema.properties).map(([name22, definition]) => [
21945
+ if (schema2.type === "object" || schema2.properties != null) {
21946
+ if (schema2.properties != null) {
21947
+ result.properties = Object.fromEntries(Object.entries(schema2.properties).map(([name22, definition]) => [
21841
21948
  name22,
21842
21949
  sanitizeDefinition(definition)
21843
21950
  ]));
21844
21951
  }
21845
21952
  result.additionalProperties = false;
21846
- if (schema.required != null) {
21847
- result.required = schema.required;
21953
+ if (schema2.required != null) {
21954
+ result.required = schema2.required;
21848
21955
  }
21849
21956
  }
21850
- if (schema.items != null) {
21851
- result.items = Array.isArray(schema.items) ? schema.items.map(sanitizeDefinition) : sanitizeDefinition(schema.items);
21957
+ if (schema2.items != null) {
21958
+ result.items = Array.isArray(schema2.items) ? schema2.items.map(sanitizeDefinition) : sanitizeDefinition(schema2.items);
21852
21959
  }
21853
- if (typeof schema.format === "string" && SUPPORTED_STRING_FORMATS.has(schema.format)) {
21854
- result.format = schema.format;
21960
+ if (typeof schema2.format === "string" && SUPPORTED_STRING_FORMATS.has(schema2.format)) {
21961
+ result.format = schema2.format;
21855
21962
  }
21856
- const constraintDescription = getConstraintDescription(schema);
21963
+ const constraintDescription = getConstraintDescription(schema2);
21857
21964
  if (constraintDescription != null) {
21858
21965
  result.description = result.description == null ? constraintDescription : `${result.description}
21859
21966
  ${constraintDescription}`;
21860
21967
  }
21861
21968
  return result;
21862
21969
  }
21863
- function getConstraintDescription(schema) {
21970
+ function getConstraintDescription(schema2) {
21864
21971
  const descriptions = DESCRIPTION_CONSTRAINT_KEYS.flatMap((key) => {
21865
- const value = schema[key];
21972
+ const value = schema2[key];
21866
21973
  if (value == null || value === false) {
21867
21974
  return [];
21868
21975
  }
21869
21976
  return `${formatConstraintName(key)}: ${formatConstraintValue(value)}`;
21870
21977
  });
21871
- if (typeof schema.format === "string" && !SUPPORTED_STRING_FORMATS.has(schema.format)) {
21872
- descriptions.push(`format: ${schema.format}`);
21978
+ if (typeof schema2.format === "string" && !SUPPORTED_STRING_FORMATS.has(schema2.format)) {
21979
+ descriptions.push(`format: ${schema2.format}`);
21873
21980
  }
21874
21981
  return descriptions.length === 0 ? undefined : `${descriptions.join("; ")}.`;
21875
21982
  }
@@ -25562,8 +25669,8 @@ function convertJSONSchemaToOpenAPISchema(jsonSchema2, isRoot = true) {
25562
25669
  result.allOf = allOf.map((item) => convertJSONSchemaToOpenAPISchema(item, false));
25563
25670
  }
25564
25671
  if (anyOf) {
25565
- if (anyOf.some((schema) => typeof schema === "object" && (schema == null ? undefined : schema.type) === "null")) {
25566
- const nonNullSchemas = anyOf.filter((schema) => !(typeof schema === "object" && (schema == null ? undefined : schema.type) === "null"));
25672
+ if (anyOf.some((schema2) => typeof schema2 === "object" && (schema2 == null ? undefined : schema2.type) === "null")) {
25673
+ const nonNullSchemas = anyOf.filter((schema2) => !(typeof schema2 === "object" && (schema2 == null ? undefined : schema2.type) === "null"));
25567
25674
  if (nonNullSchemas.length === 1) {
25568
25675
  const converted = convertJSONSchemaToOpenAPISchema(nonNullSchemas[0], false);
25569
25676
  if (typeof converted === "object") {
@@ -31781,13 +31888,13 @@ function parseIntersectionDef(def, refs) {
31781
31888
  })
31782
31889
  ].filter((x) => !!x);
31783
31890
  const mergedAllOf = [];
31784
- allOf.forEach((schema) => {
31785
- if (isJsonSchema7AllOfType(schema)) {
31786
- mergedAllOf.push(...schema.allOf);
31891
+ allOf.forEach((schema2) => {
31892
+ if (isJsonSchema7AllOfType(schema2)) {
31893
+ mergedAllOf.push(...schema2.allOf);
31787
31894
  } else {
31788
- let nestedSchema = schema;
31789
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
31790
- const { additionalProperties, ...rest } = schema;
31895
+ let nestedSchema = schema2;
31896
+ if ("additionalProperties" in schema2 && schema2.additionalProperties === false) {
31897
+ const { additionalProperties, ...rest } = schema2;
31791
31898
  nestedSchema = rest;
31792
31899
  }
31793
31900
  mergedAllOf.push(nestedSchema);
@@ -31948,44 +32055,44 @@ function escapeNonAlphaNumeric(source) {
31948
32055
  }
31949
32056
  return result;
31950
32057
  }
31951
- function addFormat(schema, value, message, refs) {
32058
+ function addFormat(schema2, value, message, refs) {
31952
32059
  var _a25;
31953
- if (schema.format || ((_a25 = schema.anyOf) == null ? undefined : _a25.some((x) => x.format))) {
31954
- if (!schema.anyOf) {
31955
- schema.anyOf = [];
32060
+ if (schema2.format || ((_a25 = schema2.anyOf) == null ? undefined : _a25.some((x) => x.format))) {
32061
+ if (!schema2.anyOf) {
32062
+ schema2.anyOf = [];
31956
32063
  }
31957
- if (schema.format) {
31958
- schema.anyOf.push({
31959
- format: schema.format
32064
+ if (schema2.format) {
32065
+ schema2.anyOf.push({
32066
+ format: schema2.format
31960
32067
  });
31961
- delete schema.format;
32068
+ delete schema2.format;
31962
32069
  }
31963
- schema.anyOf.push({
32070
+ schema2.anyOf.push({
31964
32071
  format: value,
31965
32072
  ...message && refs.errorMessages && { errorMessage: { format: message } }
31966
32073
  });
31967
32074
  } else {
31968
- schema.format = value;
32075
+ schema2.format = value;
31969
32076
  }
31970
32077
  }
31971
- function addPattern(schema, regex, message, refs) {
32078
+ function addPattern(schema2, regex, message, refs) {
31972
32079
  var _a25;
31973
- if (schema.pattern || ((_a25 = schema.allOf) == null ? undefined : _a25.some((x) => x.pattern))) {
31974
- if (!schema.allOf) {
31975
- schema.allOf = [];
32080
+ if (schema2.pattern || ((_a25 = schema2.allOf) == null ? undefined : _a25.some((x) => x.pattern))) {
32081
+ if (!schema2.allOf) {
32082
+ schema2.allOf = [];
31976
32083
  }
31977
- if (schema.pattern) {
31978
- schema.allOf.push({
31979
- pattern: schema.pattern
32084
+ if (schema2.pattern) {
32085
+ schema2.allOf.push({
32086
+ pattern: schema2.pattern
31980
32087
  });
31981
- delete schema.pattern;
32088
+ delete schema2.pattern;
31982
32089
  }
31983
- schema.allOf.push({
32090
+ schema2.allOf.push({
31984
32091
  pattern: stringifyRegExpWithFlags(regex, refs),
31985
32092
  ...message && refs.errorMessages && { errorMessage: { pattern: message } }
31986
32093
  });
31987
32094
  } else {
31988
- schema.pattern = stringifyRegExpWithFlags(regex, refs);
32095
+ schema2.pattern = stringifyRegExpWithFlags(regex, refs);
31989
32096
  }
31990
32097
  }
31991
32098
  function stringifyRegExpWithFlags(regex, refs) {
@@ -32065,7 +32172,7 @@ function stringifyRegExpWithFlags(regex, refs) {
32065
32172
  }
32066
32173
  function parseRecordDef(def, refs) {
32067
32174
  var _a25, _b22, _c, _d, _e, _f;
32068
- const schema = {
32175
+ const schema2 = {
32069
32176
  type: "object",
32070
32177
  additionalProperties: (_a25 = parseDef(def.valueType._def, {
32071
32178
  ...refs,
@@ -32075,12 +32182,12 @@ function parseRecordDef(def, refs) {
32075
32182
  if (((_b22 = def.keyType) == null ? undefined : _b22._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? undefined : _c.length)) {
32076
32183
  const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
32077
32184
  return {
32078
- ...schema,
32185
+ ...schema2,
32079
32186
  propertyNames: keyType
32080
32187
  };
32081
32188
  } else if (((_d = def.keyType) == null ? undefined : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) {
32082
32189
  return {
32083
- ...schema,
32190
+ ...schema2,
32084
32191
  propertyNames: {
32085
32192
  enum: def.keyType._def.values
32086
32193
  }
@@ -32088,11 +32195,11 @@ function parseRecordDef(def, refs) {
32088
32195
  } else if (((_e = def.keyType) == null ? undefined : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? undefined : _f.length)) {
32089
32196
  const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
32090
32197
  return {
32091
- ...schema,
32198
+ ...schema2,
32092
32199
  propertyNames: keyType
32093
32200
  };
32094
32201
  }
32095
- return schema;
32202
+ return schema2;
32096
32203
  }
32097
32204
  function parseMapDef(def, refs) {
32098
32205
  if (refs.mapStrategy === "record") {
@@ -32285,9 +32392,9 @@ function decideAdditionalProperties(def, refs) {
32285
32392
  return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
32286
32393
  }
32287
32394
  }
32288
- function safeIsOptional(schema) {
32395
+ function safeIsOptional(schema2) {
32289
32396
  try {
32290
- return schema.isOptional();
32397
+ return schema2.isOptional();
32291
32398
  } catch (e) {
32292
32399
  return true;
32293
32400
  }
@@ -32300,18 +32407,18 @@ function parseSetDef(def, refs) {
32300
32407
  ...refs,
32301
32408
  currentPath: [...refs.currentPath, "items"]
32302
32409
  });
32303
- const schema = {
32410
+ const schema2 = {
32304
32411
  type: "array",
32305
32412
  uniqueItems: true,
32306
32413
  items
32307
32414
  };
32308
32415
  if (def.minSize) {
32309
- schema.minItems = def.minSize.value;
32416
+ schema2.minItems = def.minSize.value;
32310
32417
  }
32311
32418
  if (def.maxSize) {
32312
- schema.maxItems = def.maxSize.value;
32419
+ schema2.maxItems = def.maxSize.value;
32313
32420
  }
32314
- return schema;
32421
+ return schema2;
32315
32422
  }
32316
32423
  function parseTupleDef(def, refs) {
32317
32424
  if (def.rest) {
@@ -32378,12 +32485,12 @@ function parseDef(def, refs, forceResolution = false) {
32378
32485
  return jsonSchema2;
32379
32486
  }
32380
32487
  function lazySchema2(createSchema) {
32381
- let schema;
32488
+ let schema2;
32382
32489
  return () => {
32383
- if (schema == null) {
32384
- schema = createSchema();
32490
+ if (schema2 == null) {
32491
+ schema2 = createSchema();
32385
32492
  }
32386
- return schema;
32493
+ return schema2;
32387
32494
  };
32388
32495
  }
32389
32496
  function jsonSchema2(jsonSchema22, {
@@ -32404,8 +32511,8 @@ function jsonSchema2(jsonSchema22, {
32404
32511
  function isSchema(value) {
32405
32512
  return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
32406
32513
  }
32407
- function asSchema2(schema) {
32408
- return schema == null ? jsonSchema2({ properties: {}, additionalProperties: false }) : isSchema(schema) ? schema : ("~standard" in schema) ? schema["~standard"].vendor === "zod" ? zodSchema2(schema) : standardSchema(schema) : schema();
32514
+ function asSchema2(schema2) {
32515
+ return schema2 == null ? jsonSchema2({ properties: {}, additionalProperties: false }) : isSchema(schema2) ? schema2 : ("~standard" in schema2) ? schema2["~standard"].vendor === "zod" ? zodSchema2(schema2) : standardSchema(schema2) : schema2();
32409
32516
  }
32410
32517
  function standardSchema(standardSchema2) {
32411
32518
  return jsonSchema2(() => addAdditionalPropertiesToJsonSchema(standardSchema2["~standard"].jsonSchema.input({
@@ -32461,10 +32568,10 @@ function zodSchema2(zodSchema22, options) {
32461
32568
  }
32462
32569
  async function validateTypes2({
32463
32570
  value,
32464
- schema,
32571
+ schema: schema2,
32465
32572
  context: context2
32466
32573
  }) {
32467
- const result = await safeValidateTypes2({ value, schema, context: context2 });
32574
+ const result = await safeValidateTypes2({ value, schema: schema2, context: context2 });
32468
32575
  if (!result.success) {
32469
32576
  throw TypeValidationError2.wrap({ value, cause: result.error, context: context2 });
32470
32577
  }
@@ -32472,10 +32579,10 @@ async function validateTypes2({
32472
32579
  }
32473
32580
  async function safeValidateTypes2({
32474
32581
  value,
32475
- schema,
32582
+ schema: schema2,
32476
32583
  context: context2
32477
32584
  }) {
32478
- const actualSchema = asSchema2(schema);
32585
+ const actualSchema = asSchema2(schema2);
32479
32586
  try {
32480
32587
  if (actualSchema.validate == null) {
32481
32588
  return { success: true, value, rawValue: value };
@@ -32499,14 +32606,14 @@ async function safeValidateTypes2({
32499
32606
  }
32500
32607
  async function parseJSON2({
32501
32608
  text: text2,
32502
- schema
32609
+ schema: schema2
32503
32610
  }) {
32504
32611
  try {
32505
32612
  const value = secureJsonParse(text2);
32506
- if (schema == null) {
32613
+ if (schema2 == null) {
32507
32614
  return value;
32508
32615
  }
32509
- return validateTypes2({ value, schema });
32616
+ return validateTypes2({ value, schema: schema2 });
32510
32617
  } catch (error) {
32511
32618
  if (JSONParseError.isInstance(error) || TypeValidationError2.isInstance(error)) {
32512
32619
  throw error;
@@ -32516,14 +32623,14 @@ async function parseJSON2({
32516
32623
  }
32517
32624
  async function safeParseJSON2({
32518
32625
  text: text2,
32519
- schema
32626
+ schema: schema2
32520
32627
  }) {
32521
32628
  try {
32522
32629
  const value = secureJsonParse(text2);
32523
- if (schema == null) {
32630
+ if (schema2 == null) {
32524
32631
  return { success: true, value, rawValue: value };
32525
32632
  }
32526
- return await safeValidateTypes2({ value, schema });
32633
+ return await safeValidateTypes2({ value, schema: schema2 });
32527
32634
  } catch (error) {
32528
32635
  return {
32529
32636
  success: false,
@@ -32542,28 +32649,28 @@ function isParsableJson2(input) {
32542
32649
  }
32543
32650
  function parseJsonEventStream2({
32544
32651
  stream,
32545
- schema
32652
+ schema: schema2
32546
32653
  }) {
32547
32654
  return stream.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).pipeThrough(new TransformStream({
32548
32655
  async transform({ data }, controller) {
32549
32656
  if (data === "[DONE]") {
32550
32657
  return;
32551
32658
  }
32552
- controller.enqueue(await safeParseJSON2({ text: data, schema }));
32659
+ controller.enqueue(await safeParseJSON2({ text: data, schema: schema2 }));
32553
32660
  }
32554
32661
  }));
32555
32662
  }
32556
32663
  async function parseProviderOptions2({
32557
32664
  provider,
32558
32665
  providerOptions,
32559
- schema
32666
+ schema: schema2
32560
32667
  }) {
32561
32668
  if ((providerOptions == null ? undefined : providerOptions[provider]) == null) {
32562
32669
  return;
32563
32670
  }
32564
32671
  const parsedProviderOptions = await safeValidateTypes2({
32565
32672
  value: providerOptions[provider],
32566
- schema
32673
+ schema: schema2
32567
32674
  });
32568
32675
  if (!parsedProviderOptions.success) {
32569
32676
  throw new InvalidArgumentError3({
@@ -32841,21 +32948,21 @@ var btoa, atob, name24 = "AI_DownloadError", marker24, symbol24, _a24, _b15, Dow
32841
32948
  }
32842
32949
  ]))
32843
32950
  };
32844
- }, zod3ToJsonSchema = (schema, options) => {
32951
+ }, zod3ToJsonSchema = (schema2, options) => {
32845
32952
  var _a25;
32846
32953
  const refs = getRefs(options);
32847
- let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name33, schema2]) => {
32954
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name33, schema22]) => {
32848
32955
  var _a33;
32849
32956
  return {
32850
32957
  ...acc,
32851
- [name33]: (_a33 = parseDef(schema2._def, {
32958
+ [name33]: (_a33 = parseDef(schema22._def, {
32852
32959
  ...refs,
32853
32960
  currentPath: [...refs.basePath, refs.definitionPath, name33]
32854
32961
  }, true)) != null ? _a33 : parseAnyDef()
32855
32962
  };
32856
32963
  }, {}) : undefined;
32857
32964
  const name25 = typeof options === "string" ? options : (options == null ? undefined : options.nameStrategy) === "title" ? undefined : options == null ? undefined : options.name;
32858
- const main = (_a25 = parseDef(schema._def, name25 === undefined ? refs : {
32965
+ const main = (_a25 = parseDef(schema2._def, name25 === undefined ? refs : {
32859
32966
  ...refs,
32860
32967
  currentPath: [...refs.basePath, refs.definitionPath, name25]
32861
32968
  }, false)) != null ? _a25 : parseAnyDef();
@@ -33721,10 +33828,10 @@ function convertOpenAIResponsesUsage2(usage) {
33721
33828
  raw: usage
33722
33829
  };
33723
33830
  }
33724
- function isFileId2(data, prefixes) {
33725
- if (!prefixes)
33831
+ function isFileId2(data, prefixes2) {
33832
+ if (!prefixes2)
33726
33833
  return false;
33727
- return prefixes.some((prefix) => data.startsWith(prefix));
33834
+ return prefixes2.some((prefix) => data.startsWith(prefix));
33728
33835
  }
33729
33836
  async function convertToOpenAIResponsesInput2({
33730
33837
  prompt,
@@ -40985,13 +41092,13 @@ function parseIntersectionDef2(def, refs) {
40985
41092
  }))
40986
41093
  ].filter((x) => !!x);
40987
41094
  const mergedAllOf = [];
40988
- allOf.forEach((schema) => {
40989
- if (isJsonSchema7AllOfType2(schema)) {
40990
- mergedAllOf.push(...schema.allOf);
41095
+ allOf.forEach((schema2) => {
41096
+ if (isJsonSchema7AllOfType2(schema2)) {
41097
+ mergedAllOf.push(...schema2.allOf);
40991
41098
  } else {
40992
- let nestedSchema = schema;
40993
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
40994
- const _a162 = schema, { additionalProperties } = _a162, rest = __objRest(_a162, ["additionalProperties"]);
41099
+ let nestedSchema = schema2;
41100
+ if ("additionalProperties" in schema2 && schema2.additionalProperties === false) {
41101
+ const _a162 = schema2, { additionalProperties } = _a162, rest = __objRest(_a162, ["additionalProperties"]);
40995
41102
  nestedSchema = rest;
40996
41103
  }
40997
41104
  mergedAllOf.push(nestedSchema);
@@ -41152,42 +41259,42 @@ function escapeNonAlphaNumeric2(source) {
41152
41259
  }
41153
41260
  return result;
41154
41261
  }
41155
- function addFormat2(schema, value, message, refs) {
41262
+ function addFormat2(schema2, value, message, refs) {
41156
41263
  var _a222;
41157
- if (schema.format || ((_a222 = schema.anyOf) == null ? undefined : _a222.some((x) => x.format))) {
41158
- if (!schema.anyOf) {
41159
- schema.anyOf = [];
41264
+ if (schema2.format || ((_a222 = schema2.anyOf) == null ? undefined : _a222.some((x) => x.format))) {
41265
+ if (!schema2.anyOf) {
41266
+ schema2.anyOf = [];
41160
41267
  }
41161
- if (schema.format) {
41162
- schema.anyOf.push({
41163
- format: schema.format
41268
+ if (schema2.format) {
41269
+ schema2.anyOf.push({
41270
+ format: schema2.format
41164
41271
  });
41165
- delete schema.format;
41272
+ delete schema2.format;
41166
41273
  }
41167
- schema.anyOf.push(__spreadValues({
41274
+ schema2.anyOf.push(__spreadValues({
41168
41275
  format: value
41169
41276
  }, message && refs.errorMessages && { errorMessage: { format: message } }));
41170
41277
  } else {
41171
- schema.format = value;
41278
+ schema2.format = value;
41172
41279
  }
41173
41280
  }
41174
- function addPattern2(schema, regex, message, refs) {
41281
+ function addPattern2(schema2, regex, message, refs) {
41175
41282
  var _a222;
41176
- if (schema.pattern || ((_a222 = schema.allOf) == null ? undefined : _a222.some((x) => x.pattern))) {
41177
- if (!schema.allOf) {
41178
- schema.allOf = [];
41283
+ if (schema2.pattern || ((_a222 = schema2.allOf) == null ? undefined : _a222.some((x) => x.pattern))) {
41284
+ if (!schema2.allOf) {
41285
+ schema2.allOf = [];
41179
41286
  }
41180
- if (schema.pattern) {
41181
- schema.allOf.push({
41182
- pattern: schema.pattern
41287
+ if (schema2.pattern) {
41288
+ schema2.allOf.push({
41289
+ pattern: schema2.pattern
41183
41290
  });
41184
- delete schema.pattern;
41291
+ delete schema2.pattern;
41185
41292
  }
41186
- schema.allOf.push(__spreadValues({
41293
+ schema2.allOf.push(__spreadValues({
41187
41294
  pattern: stringifyRegExpWithFlags2(regex, refs)
41188
41295
  }, message && refs.errorMessages && { errorMessage: { pattern: message } }));
41189
41296
  } else {
41190
- schema.pattern = stringifyRegExpWithFlags2(regex, refs);
41297
+ schema2.pattern = stringifyRegExpWithFlags2(regex, refs);
41191
41298
  }
41192
41299
  }
41193
41300
  function stringifyRegExpWithFlags2(regex, refs) {
@@ -41267,7 +41374,7 @@ function stringifyRegExpWithFlags2(regex, refs) {
41267
41374
  }
41268
41375
  function parseRecordDef2(def, refs) {
41269
41376
  var _a222, _b222, _c, _d, _e, _f;
41270
- const schema = {
41377
+ const schema2 = {
41271
41378
  type: "object",
41272
41379
  additionalProperties: (_a222 = parseDef2(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
41273
41380
  currentPath: [...refs.currentPath, "additionalProperties"]
@@ -41275,22 +41382,22 @@ function parseRecordDef2(def, refs) {
41275
41382
  };
41276
41383
  if (((_b222 = def.keyType) == null ? undefined : _b222._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? undefined : _c.length)) {
41277
41384
  const _a162 = parseStringDef2(def.keyType._def, refs), { type } = _a162, keyType = __objRest(_a162, ["type"]);
41278
- return __spreadProps(__spreadValues({}, schema), {
41385
+ return __spreadProps(__spreadValues({}, schema2), {
41279
41386
  propertyNames: keyType
41280
41387
  });
41281
41388
  } else if (((_d = def.keyType) == null ? undefined : _d._def.typeName) === ZodFirstPartyTypeKind.ZodEnum) {
41282
- return __spreadProps(__spreadValues({}, schema), {
41389
+ return __spreadProps(__spreadValues({}, schema2), {
41283
41390
  propertyNames: {
41284
41391
  enum: def.keyType._def.values
41285
41392
  }
41286
41393
  });
41287
41394
  } else if (((_e = def.keyType) == null ? undefined : _e._def.typeName) === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? undefined : _f.length)) {
41288
41395
  const _b16 = parseBrandedDef2(def.keyType._def, refs), { type } = _b16, keyType = __objRest(_b16, ["type"]);
41289
- return __spreadProps(__spreadValues({}, schema), {
41396
+ return __spreadProps(__spreadValues({}, schema2), {
41290
41397
  propertyNames: keyType
41291
41398
  });
41292
41399
  }
41293
- return schema;
41400
+ return schema2;
41294
41401
  }
41295
41402
  function parseMapDef2(def, refs) {
41296
41403
  if (refs.mapStrategy === "record") {
@@ -41478,9 +41585,9 @@ function decideAdditionalProperties2(def, refs) {
41478
41585
  return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
41479
41586
  }
41480
41587
  }
41481
- function safeIsOptional2(schema) {
41588
+ function safeIsOptional2(schema2) {
41482
41589
  try {
41483
- return schema.isOptional();
41590
+ return schema2.isOptional();
41484
41591
  } catch (e) {
41485
41592
  return true;
41486
41593
  }
@@ -41492,18 +41599,18 @@ function parseSetDef2(def, refs) {
41492
41599
  const items = parseDef2(def.valueType._def, __spreadProps(__spreadValues({}, refs), {
41493
41600
  currentPath: [...refs.currentPath, "items"]
41494
41601
  }));
41495
- const schema = {
41602
+ const schema2 = {
41496
41603
  type: "array",
41497
41604
  uniqueItems: true,
41498
41605
  items
41499
41606
  };
41500
41607
  if (def.minSize) {
41501
- schema.minItems = def.minSize.value;
41608
+ schema2.minItems = def.minSize.value;
41502
41609
  }
41503
41610
  if (def.maxSize) {
41504
- schema.maxItems = def.maxSize.value;
41611
+ schema2.maxItems = def.maxSize.value;
41505
41612
  }
41506
- return schema;
41613
+ return schema2;
41507
41614
  }
41508
41615
  function parseTupleDef2(def, refs) {
41509
41616
  if (def.rest) {
@@ -41584,8 +41691,8 @@ function jsonSchema3(jsonSchema22, {
41584
41691
  function isSchema2(value) {
41585
41692
  return typeof value === "object" && value !== null && schemaSymbol2 in value && value[schemaSymbol2] === true && "jsonSchema" in value && "validate" in value;
41586
41693
  }
41587
- function asSchema3(schema) {
41588
- return schema == null ? jsonSchema3({ properties: {}, additionalProperties: false }) : isSchema2(schema) ? schema : ("~standard" in schema) ? schema["~standard"].vendor === "zod" ? zodSchema3(schema) : standardSchema2(schema) : schema();
41694
+ function asSchema3(schema2) {
41695
+ return schema2 == null ? jsonSchema3({ properties: {}, additionalProperties: false }) : isSchema2(schema2) ? schema2 : ("~standard" in schema2) ? schema2["~standard"].vendor === "zod" ? zodSchema3(schema2) : standardSchema2(schema2) : schema2();
41589
41696
  }
41590
41697
  function standardSchema2(standardSchema22) {
41591
41698
  return jsonSchema3(() => addAdditionalPropertiesToJsonSchema2(standardSchema22["~standard"].jsonSchema.input({
@@ -41641,10 +41748,10 @@ function zodSchema3(zodSchema22, options) {
41641
41748
  }
41642
41749
  async function validateTypes3({
41643
41750
  value,
41644
- schema,
41751
+ schema: schema2,
41645
41752
  context: context2
41646
41753
  }) {
41647
- const result = await safeValidateTypes3({ value, schema, context: context2 });
41754
+ const result = await safeValidateTypes3({ value, schema: schema2, context: context2 });
41648
41755
  if (!result.success) {
41649
41756
  throw TypeValidationError3.wrap({ value, cause: result.error, context: context2 });
41650
41757
  }
@@ -41652,10 +41759,10 @@ async function validateTypes3({
41652
41759
  }
41653
41760
  async function safeValidateTypes3({
41654
41761
  value,
41655
- schema,
41762
+ schema: schema2,
41656
41763
  context: context2
41657
41764
  }) {
41658
- const actualSchema = asSchema3(schema);
41765
+ const actualSchema = asSchema3(schema2);
41659
41766
  try {
41660
41767
  if (actualSchema.validate == null) {
41661
41768
  return { success: true, value, rawValue: value };
@@ -41679,14 +41786,14 @@ async function safeValidateTypes3({
41679
41786
  }
41680
41787
  async function parseJSON3({
41681
41788
  text: text2,
41682
- schema
41789
+ schema: schema2
41683
41790
  }) {
41684
41791
  try {
41685
41792
  const value = secureJsonParse2(text2);
41686
- if (schema == null) {
41793
+ if (schema2 == null) {
41687
41794
  return value;
41688
41795
  }
41689
- return validateTypes3({ value, schema });
41796
+ return validateTypes3({ value, schema: schema2 });
41690
41797
  } catch (error) {
41691
41798
  if (JSONParseError2.isInstance(error) || TypeValidationError3.isInstance(error)) {
41692
41799
  throw error;
@@ -41696,14 +41803,14 @@ async function parseJSON3({
41696
41803
  }
41697
41804
  async function safeParseJSON3({
41698
41805
  text: text2,
41699
- schema
41806
+ schema: schema2
41700
41807
  }) {
41701
41808
  try {
41702
41809
  const value = secureJsonParse2(text2);
41703
- if (schema == null) {
41810
+ if (schema2 == null) {
41704
41811
  return { success: true, value, rawValue: value };
41705
41812
  }
41706
- return await safeValidateTypes3({ value, schema });
41813
+ return await safeValidateTypes3({ value, schema: schema2 });
41707
41814
  } catch (error) {
41708
41815
  return {
41709
41816
  success: false,
@@ -41722,14 +41829,14 @@ function isParsableJson3(input) {
41722
41829
  }
41723
41830
  function parseJsonEventStream3({
41724
41831
  stream,
41725
- schema
41832
+ schema: schema2
41726
41833
  }) {
41727
41834
  return stream.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream2).pipeThrough(new TransformStream({
41728
41835
  async transform({ data }, controller) {
41729
41836
  if (data === "[DONE]") {
41730
41837
  return;
41731
41838
  }
41732
- controller.enqueue(await safeParseJSON3({ text: data, schema }));
41839
+ controller.enqueue(await safeParseJSON3({ text: data, schema: schema2 }));
41733
41840
  }
41734
41841
  }));
41735
41842
  }
@@ -42939,19 +43046,19 @@ var __defProp2, __defProps, __getOwnPropDescs, __getOwnPropSymbols, __hasOwnProp
42939
43046
  }
42940
43047
  ]))
42941
43048
  });
42942
- }, zod3ToJsonSchema2 = (schema, options) => {
43049
+ }, zod3ToJsonSchema2 = (schema2, options) => {
42943
43050
  var _a222;
42944
43051
  const refs = getRefs2(options);
42945
- let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name322, schema2]) => {
43052
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name322, schema22]) => {
42946
43053
  var _a322;
42947
43054
  return __spreadProps(__spreadValues({}, acc), {
42948
- [name322]: (_a322 = parseDef2(schema2._def, __spreadProps(__spreadValues({}, refs), {
43055
+ [name322]: (_a322 = parseDef2(schema22._def, __spreadProps(__spreadValues({}, refs), {
42949
43056
  currentPath: [...refs.basePath, refs.definitionPath, name322]
42950
43057
  }), true)) != null ? _a322 : parseAnyDef2()
42951
43058
  });
42952
43059
  }, {}) : undefined;
42953
43060
  const name222 = typeof options === "string" ? options : (options == null ? undefined : options.nameStrategy) === "title" ? undefined : options == null ? undefined : options.name;
42954
- const main = (_a222 = parseDef2(schema._def, name222 === undefined ? refs : __spreadProps(__spreadValues({}, refs), {
43061
+ const main = (_a222 = parseDef2(schema2._def, name222 === undefined ? refs : __spreadProps(__spreadValues({}, refs), {
42955
43062
  currentPath: [...refs.basePath, refs.definitionPath, name222]
42956
43063
  }), false)) != null ? _a222 : parseAnyDef2();
42957
43064
  const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined;
@@ -45326,77 +45433,123 @@ Error message: ${getErrorMessage4(cause)}`,
45326
45433
  });
45327
45434
  });
45328
45435
 
45329
- // src/core/id/id.ts
45330
- import { randomBytes } from "node:crypto";
45331
- function schema(prefix) {
45332
- return zod_default.string().startsWith(prefixes[prefix]);
45436
+ // src/core/observability/active-root-spans.ts
45437
+ function registerActiveRootSpan(span) {
45438
+ activeRootSpans.add(span);
45333
45439
  }
45334
- function descending(prefix, given) {
45335
- return generateID(prefix, true, given);
45336
- }
45337
- function generateID(prefix, descending2, given) {
45338
- if (!given) {
45339
- return create(prefix, descending2);
45340
- }
45341
- if (!given.startsWith(prefixes[prefix])) {
45342
- throw new Error(`ID ${given} does not start with ${prefixes[prefix]}`);
45343
- }
45344
- return given;
45440
+ function unregisterActiveRootSpan(span) {
45441
+ activeRootSpans.delete(span);
45345
45442
  }
45346
- function randomBase62(length) {
45347
- const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
45348
- let result = "";
45349
- const bytes = randomBytes(length);
45350
- for (let i = 0;i < length; i++) {
45351
- result += chars[bytes[i] % 62];
45443
+ function endAllActiveRootSpans() {
45444
+ for (const span of activeRootSpans) {
45445
+ try {
45446
+ span.end();
45447
+ } catch {}
45352
45448
  }
45353
- return result;
45449
+ activeRootSpans.clear();
45354
45450
  }
45355
- function create(prefix, descending2, timestamp) {
45356
- const currentTimestamp = timestamp ?? Date.now();
45357
- if (currentTimestamp !== lastTimestamp) {
45358
- lastTimestamp = currentTimestamp;
45359
- counter = 0;
45360
- }
45361
- counter++;
45362
- let now2 = BigInt(currentTimestamp) * BigInt(4096) + BigInt(counter);
45363
- now2 = descending2 ? ~now2 : now2;
45364
- const timeBytes = Buffer.alloc(6);
45365
- for (let i = 0;i < 6; i++) {
45366
- timeBytes[i] = Number(now2 >> BigInt(40 - 8 * i) & BigInt(255));
45367
- }
45368
- return prefixes[prefix] + "_" + timeBytes.toString("hex") + randomBase62(LENGTH - 12);
45451
+ var activeRootSpans;
45452
+ var init_active_root_spans = __esm(() => {
45453
+ activeRootSpans = new Set;
45454
+ });
45455
+
45456
+ // src/core/observability/telemetry.ts
45457
+ function createAiTelemetrySettings(input) {
45458
+ const recordPayloads = shouldRecordAiPayloads();
45459
+ const metadata = {};
45460
+ if (input.sessionId)
45461
+ metadata.sessionId = input.sessionId;
45462
+ return {
45463
+ isEnabled: true,
45464
+ recordInputs: recordPayloads,
45465
+ recordOutputs: recordPayloads,
45466
+ functionId: input.operation,
45467
+ ...Object.keys(metadata).length > 0 ? { metadata } : {}
45468
+ };
45369
45469
  }
45370
- var prefixes, LENGTH = 26, lastTimestamp = 0, counter = 0, newSessionId = () => descending("session"), newMessageId = () => descending("message"), newPartId = () => descending("part"), isSessionId = (s) => s.startsWith(`${prefixes.session}_`);
45371
- var init_id = __esm(() => {
45372
- init_zod();
45373
- prefixes = {
45374
- session: "ses",
45375
- message: "msg",
45376
- permission: "per",
45377
- user: "usr",
45378
- part: "prt"
45470
+ function describeFailure(error) {
45471
+ if (error instanceof Error)
45472
+ return error.message;
45473
+ if (typeof error === "string")
45474
+ return error;
45475
+ try {
45476
+ return JSON.stringify(error) || String(error);
45477
+ } catch {
45478
+ return String(error);
45479
+ }
45480
+ }
45481
+ function createGenerationSpanTracker() {
45482
+ const inner = import_api3.trace.getTracer("ai");
45483
+ let rootSpan = null;
45484
+ const tracer = {
45485
+ startSpan: (name27, options, context2) => {
45486
+ const span = inner.startSpan(name27, options, context2);
45487
+ if (name27 === "ai.streamText")
45488
+ rootSpan = span;
45489
+ return span;
45490
+ },
45491
+ startActiveSpan: (name27, ...rest) => {
45492
+ const callback = rest[rest.length - 1];
45493
+ const capture = (span, ...restArgs) => {
45494
+ if (name27 === "ai.streamText")
45495
+ rootSpan = span;
45496
+ return callback(span, ...restArgs);
45497
+ };
45498
+ const forwardArgs = [...rest.slice(0, -1), capture];
45499
+ return inner.startActiveSpan.call(inner, name27, ...forwardArgs);
45500
+ }
45501
+ };
45502
+ let marked = false;
45503
+ return {
45504
+ tracer,
45505
+ markFailed(error) {
45506
+ const span = rootSpan;
45507
+ if (!span || marked)
45508
+ return;
45509
+ marked = true;
45510
+ const message = describeFailure(error);
45511
+ span.recordException(error instanceof Error ? error : message);
45512
+ span.setStatus({ code: import_api3.SpanStatusCode.ERROR, message });
45513
+ }
45379
45514
  };
45515
+ }
45516
+ var import_api3;
45517
+ var init_telemetry = __esm(() => {
45518
+ init_observability();
45519
+ import_api3 = __toESM(require_src(), 1);
45380
45520
  });
45381
45521
 
45382
- // src/core/observability.ts
45522
+ // src/core/observability/index.ts
45523
+ import { AsyncLocalStorage } from "node:async_hooks";
45383
45524
  function getApexTracer() {
45384
- return import_api3.trace.getTracer("apex");
45525
+ return import_api4.trace.getTracer("apex");
45385
45526
  }
45386
45527
  function shouldRecordAiPayloads() {
45528
+ const override = aiPayloadCaptureStore.getStore();
45529
+ if (override !== undefined)
45530
+ return override;
45387
45531
  return process.env.AI_TRACE_RECORD_PAYLOADS === "true";
45388
45532
  }
45389
45533
  function withSubagentSessionBaggage(sessionId, fn) {
45390
45534
  if (!sessionId || !isSessionId(sessionId) || sessionId.includes("-")) {
45391
45535
  return fn();
45392
45536
  }
45393
- const baggage = (import_api3.propagation.getActiveBaggage() ?? import_api3.propagation.createBaggage()).setEntry(SESSION_BAGGAGE_KEY, { value: sessionId });
45394
- return import_api3.context.with(import_api3.propagation.setBaggage(import_api3.context.active(), baggage), fn);
45537
+ const baggage = (import_api4.propagation.getActiveBaggage() ?? import_api4.propagation.createBaggage()).setEntry(SESSION_BAGGAGE_KEY, { value: sessionId });
45538
+ return import_api4.context.with(import_api4.propagation.setBaggage(import_api4.context.active(), baggage), fn);
45539
+ }
45540
+ function getActiveTraceCorrelation() {
45541
+ const spanContext = import_api4.trace.getSpan(import_api4.context.active())?.spanContext();
45542
+ if (!spanContext || !import_api4.trace.isSpanContextValid(spanContext))
45543
+ return null;
45544
+ return { traceId: spanContext.traceId, spanId: spanContext.spanId };
45395
45545
  }
45396
- var import_api3, SESSION_BAGGAGE_KEY = "pensar.session.id";
45546
+ var import_api4, aiPayloadCaptureStore, SESSION_BAGGAGE_KEY = "pensar.session.id";
45397
45547
  var init_observability = __esm(() => {
45398
45548
  init_id();
45399
- import_api3 = __toESM(require_src(), 1);
45549
+ init_active_root_spans();
45550
+ init_telemetry();
45551
+ import_api4 = __toESM(require_src(), 1);
45552
+ aiPayloadCaptureStore = new AsyncLocalStorage;
45400
45553
  });
45401
45554
 
45402
45555
  // src/core/ai/caching.ts
@@ -45820,7 +45973,30 @@ var init_streamTelemetry = __esm(() => {
45820
45973
  });
45821
45974
 
45822
45975
  // src/core/ai/ai.ts
45823
- import { AsyncLocalStorage } from "node:async_hooks";
45976
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
45977
+ function isRepairFailClosedTool(toolName) {
45978
+ return REPAIR_FAIL_CLOSED_TOOLS.has(toolName);
45979
+ }
45980
+ function normalizeStepUsage(step) {
45981
+ const inputTokens = step.usage?.inputTokens ?? 0;
45982
+ const outputTokens = step.usage?.outputTokens ?? 0;
45983
+ const meta = step.providerMetadata?.anthropic;
45984
+ let cacheRead = meta?.cacheReadInputTokens ?? 0;
45985
+ let cacheWrite = meta?.cacheCreationInputTokens ?? 0;
45986
+ const details = step.usage?.inputTokenDetails;
45987
+ if (cacheRead === 0) {
45988
+ cacheRead = details?.cacheReadTokens ?? 0;
45989
+ }
45990
+ if (cacheWrite === 0) {
45991
+ cacheWrite = details?.cacheWriteTokens ?? 0;
45992
+ }
45993
+ return {
45994
+ inputTokens,
45995
+ outputTokens,
45996
+ cacheReadTokens: cacheRead,
45997
+ cacheWriteTokens: cacheWrite
45998
+ };
45999
+ }
45824
46000
  function takeStepContext() {
45825
46001
  const store = stepContextStore.getStore();
45826
46002
  if (!store)
@@ -45916,7 +46092,7 @@ function createToolExecutionGate() {
45916
46092
  }
45917
46093
  };
45918
46094
  }
45919
- function wrapStreamWithErrorHandler(originalStream, messagesContainer, opts, model, silent, rateLimitRetryCount = 0, idleResumeCount = 0) {
46095
+ function wrapStreamWithErrorHandler(originalStream, messagesContainer, opts, model, silent, rateLimitRetryCount = 0, idleResumeCount = 0, generationSpans) {
45920
46096
  let wrappedStream = null;
45921
46097
  const handler = {
45922
46098
  get(_target, prop) {
@@ -45924,6 +46100,7 @@ function wrapStreamWithErrorHandler(originalStream, messagesContainer, opts, mod
45924
46100
  if (!wrappedStream) {
45925
46101
  const toolGate = createToolExecutionGate();
45926
46102
  wrappedStream = async function* () {
46103
+ let streamError;
45927
46104
  try {
45928
46105
  for await (const chunk of withIdleTimeout(originalStream.fullStream, STREAM_IDLE_TIMEOUT_MS, toolGate.shouldEnforceIdleTimeout)) {
45929
46106
  toolGate.observe(chunk);
@@ -45936,11 +46113,22 @@ function wrapStreamWithErrorHandler(originalStream, messagesContainer, opts, mod
45936
46113
  }
45937
46114
  }
45938
46115
  if (chunk.type === "error") {
45939
- throw chunk.error;
46116
+ streamError = chunk.error;
46117
+ generationSpans?.markFailed(streamError);
46118
+ continue;
46119
+ }
46120
+ if (streamError !== undefined) {
46121
+ continue;
45940
46122
  }
45941
46123
  yield chunk;
45942
46124
  }
45943
- } catch (error) {
46125
+ if (streamError !== undefined) {
46126
+ await Promise.resolve(originalStream.response).catch(() => {});
46127
+ throw streamError;
46128
+ }
46129
+ } catch (caughtError) {
46130
+ const error = streamError !== undefined ? streamError : caughtError;
46131
+ generationSpans?.markFailed(error);
45944
46132
  const errorMessage = error instanceof Error ? error.message : String(error);
45945
46133
  const isCtxError = checkIfContextLengthError(error);
45946
46134
  if (!isCtxError && isStreamIdleTimeoutError(error) && idleResumeCount < MAX_IDLE_RESUME_RETRIES && messagesContainer.current.length > 0) {
@@ -46095,6 +46283,18 @@ function normalizeOpenAIReasoningEffort(modelId, effort) {
46095
46283
  }
46096
46284
  return DEFAULT_OPENAI_REASONING_EFFORT;
46097
46285
  }
46286
+ function buildOpenRouterProviderOptions(model) {
46287
+ if (model !== "z-ai/glm-5.2")
46288
+ return;
46289
+ return {
46290
+ openrouter: {
46291
+ provider: {
46292
+ only: ["z-ai"],
46293
+ allow_fallbacks: false
46294
+ }
46295
+ }
46296
+ };
46297
+ }
46098
46298
  function buildReasoningProviderOptions(model, opts) {
46099
46299
  const useThinking = !!opts.enableThinking && isAnthropicProvider(model) && modelSupportsAdaptiveThinking(model);
46100
46300
  const normalizedOpenAIEffort = normalizeOpenAIReasoningEffort(model, opts.openAIReasoningEffort);
@@ -46132,6 +46332,8 @@ function streamResponse(opts) {
46132
46332
  toolChoice,
46133
46333
  tools,
46134
46334
  onStepFinish: userOnStepFinish,
46335
+ languageModelMiddleware,
46336
+ usageRecorder,
46135
46337
  abortSignal,
46136
46338
  activeTools,
46137
46339
  silent,
@@ -46144,16 +46346,35 @@ function streamResponse(opts) {
46144
46346
  sessionId
46145
46347
  } = opts;
46146
46348
  const onStepFinish = async (step) => {
46349
+ const stepUsage = normalizeStepUsage(step);
46350
+ if (onCacheMetrics && (stepUsage.cacheReadTokens > 0 || stepUsage.cacheWriteTokens > 0)) {
46351
+ await onCacheMetrics({
46352
+ cacheReadInputTokens: stepUsage.cacheReadTokens,
46353
+ cacheCreationInputTokens: stepUsage.cacheWriteTokens
46354
+ });
46355
+ }
46147
46356
  await userOnStepFinish?.(step);
46148
- if (_usageCallback) {
46149
- const inp = step.usage?.inputTokens ?? 0;
46150
- const out = step.usage?.outputTokens ?? 0;
46357
+ if (usageRecorder || _usageCallback) {
46151
46358
  const stepCtx = takeStepContext();
46152
- if (inp > 0 || out > 0)
46153
- _usageCallback(model, inp, out, stepCtx);
46359
+ if (stepUsage.inputTokens > 0 || stepUsage.outputTokens > 0) {
46360
+ const usageContext = {
46361
+ ...stepCtx,
46362
+ cacheReadTokens: stepUsage.cacheReadTokens,
46363
+ cacheWriteTokens: stepUsage.cacheWriteTokens
46364
+ };
46365
+ if (usageRecorder) {
46366
+ await usageRecorder(model, stepUsage.inputTokens, stepUsage.outputTokens, usageContext);
46367
+ } else {
46368
+ await _usageCallback?.(model, stepUsage.inputTokens, stepUsage.outputTokens, usageContext);
46369
+ }
46370
+ }
46154
46371
  }
46155
46372
  };
46156
- const providerModel = getProviderModel(model, authConfig);
46373
+ const baseProviderModel = getProviderModel(model, authConfig);
46374
+ const providerModel = languageModelMiddleware ? wrapLanguageModel({
46375
+ model: baseProviderModel,
46376
+ middleware: languageModelMiddleware
46377
+ }) : baseProviderModel;
46157
46378
  const cacheBreakpoint = cacheBreakpointFor(model);
46158
46379
  const systemWithToolPolicy = applySequentialToolCallPolicy(system, tools, model);
46159
46380
  let fittedMessages = messages;
@@ -46188,14 +46409,16 @@ function streamResponse(opts) {
46188
46409
  effectiveMessages = withCachedSystemPrompt(systemWithToolPolicy, baseMessages, cacheBreakpoint);
46189
46410
  effectiveSystem = undefined;
46190
46411
  }
46191
- const providerOptions = buildReasoningProviderOptions(model, {
46412
+ const reasoningProviderOptions = buildReasoningProviderOptions(model, {
46192
46413
  enableThinking,
46193
46414
  thinkingEffort,
46194
46415
  openAIReasoningEffort
46195
46416
  });
46417
+ const openRouterProviderOptions = buildOpenRouterProviderOptions(model);
46418
+ const providerOptions = reasoningProviderOptions || openRouterProviderOptions ? { ...reasoningProviderOptions, ...openRouterProviderOptions } : undefined;
46196
46419
  let rateLimitRetryCount = 0;
46197
46420
  try {
46198
- const recordPayloads = shouldRecordAiPayloads();
46421
+ const generationSpans = createGenerationSpanTracker();
46199
46422
  const response = streamText({
46200
46423
  model: providerModel,
46201
46424
  system: effectiveSystem,
@@ -46206,11 +46429,11 @@ function streamResponse(opts) {
46206
46429
  maxRetries: 3,
46207
46430
  providerOptions,
46208
46431
  experimental_telemetry: {
46209
- isEnabled: true,
46210
- recordInputs: recordPayloads,
46211
- recordOutputs: recordPayloads,
46212
- functionId: `apex.stream.${model}`,
46213
- ...sessionId ? { metadata: { sessionId } } : {}
46432
+ ...createAiTelemetrySettings({
46433
+ operation: "apex.agent.stream",
46434
+ sessionId
46435
+ }),
46436
+ tracer: generationSpans.tracer
46214
46437
  },
46215
46438
  maxOutputTokens: getMaxOutputTokens(model),
46216
46439
  prepareStep: (opts2) => {
@@ -46227,31 +46450,9 @@ function streamResponse(opts) {
46227
46450
  if (errorMessage.toLowerCase().includes("too many tokens") || errorMessage.toLowerCase().includes("overloaded")) {
46228
46451
  rateLimitRetryCount++;
46229
46452
  await new Promise((resolve2) => setTimeout(resolve2, 1000 * rateLimitRetryCount));
46230
- if (rateLimitRetryCount < 20) {
46231
- return;
46232
- }
46233
46453
  }
46234
- throw error;
46235
46454
  },
46236
- onStepFinish: onCacheMetrics ? (stepResult) => {
46237
- const meta = stepResult.providerMetadata?.anthropic;
46238
- let cacheRead = meta?.cacheReadInputTokens ?? 0;
46239
- let cacheCreation = meta?.cacheCreationInputTokens ?? 0;
46240
- const { inputTokenDetails } = stepResult.usage;
46241
- if (cacheRead === 0) {
46242
- cacheRead = inputTokenDetails?.cacheReadTokens ?? 0;
46243
- }
46244
- if (cacheCreation === 0) {
46245
- cacheCreation = inputTokenDetails?.cacheWriteTokens ?? 0;
46246
- }
46247
- if (cacheRead > 0 || cacheCreation > 0) {
46248
- onCacheMetrics({
46249
- cacheReadInputTokens: cacheRead,
46250
- cacheCreationInputTokens: cacheCreation
46251
- });
46252
- }
46253
- onStepFinish?.(stepResult);
46254
- } : onStepFinish,
46455
+ onStepFinish,
46255
46456
  abortSignal,
46256
46457
  activeTools,
46257
46458
  experimental_repairToolCall: async ({
@@ -46265,6 +46466,12 @@ function streamResponse(opts) {
46265
46466
  const rawLen = typeof raw === "string" ? raw.length : JSON.stringify(raw).length;
46266
46467
  log.warn(`[response-debug] experimental_repairToolCall FIRED for response ` + `rawInputChars=${rawLen} error=${(error.message || String(error)).slice(0, 200)}`);
46267
46468
  }
46469
+ if (isRepairFailClosedTool(toolCall.toolName)) {
46470
+ if (!silent) {
46471
+ log.warn(`Tool-call repair disabled for security-sensitive tool "${toolCall.toolName}" — failing closed (no argument synthesis).`);
46472
+ }
46473
+ return null;
46474
+ }
46268
46475
  try {
46269
46476
  if (!silent) {
46270
46477
  log.debug(`Repairing tool call: ${toolCall.toolName}`, {
@@ -46286,7 +46493,11 @@ function streamResponse(opts) {
46286
46493
  const inputAsText = typeof rawInput === "string" ? rawInput : JSON.stringify(rawInput);
46287
46494
  const boundedInput = truncateWithMarker(inputAsText, MAX_TOOL_INPUT_CHARS);
46288
46495
  const boundedSchema = truncateWithMarker(JSON.stringify(jsonSchema4), MAX_SCHEMA_CHARS, "schema");
46289
- const { output: repairedArgs, usage: repairUsage } = await generateText({
46496
+ const {
46497
+ output: repairedArgs,
46498
+ usage: repairUsage,
46499
+ providerMetadata: repairProviderMetadata
46500
+ } = await generateText({
46290
46501
  model: providerModel,
46291
46502
  output: output_exports.object({
46292
46503
  schema: tool4.inputSchema
@@ -46304,41 +46515,47 @@ function streamResponse(opts) {
46304
46515
  ].join(`
46305
46516
  `),
46306
46517
  abortSignal,
46307
- experimental_telemetry: {
46308
- isEnabled: true,
46309
- recordInputs: recordPayloads,
46310
- recordOutputs: recordPayloads,
46311
- functionId: "apex.tool_repair",
46312
- ...sessionId ? { metadata: { sessionId } } : {}
46313
- }
46518
+ experimental_telemetry: createAiTelemetrySettings({
46519
+ operation: "apex.tool.repair",
46520
+ sessionId
46521
+ })
46314
46522
  });
46315
46523
  if (onStepFinish && repairUsage) {
46316
- onStepFinish({
46317
- text: "",
46318
- reasoning: undefined,
46319
- reasoningDetails: [],
46320
- files: [],
46321
- sources: [],
46322
- toolCalls: [],
46323
- toolResults: [],
46324
- finishReason: "stop",
46325
- usage: {
46326
- inputTokens: repairUsage.inputTokens ?? 0,
46327
- outputTokens: repairUsage.outputTokens ?? 0,
46328
- totalTokens: repairUsage.totalTokens ?? 0
46329
- },
46330
- warnings: [],
46331
- request: {},
46332
- response: {
46333
- id: "tool-repair",
46334
- timestamp: new Date,
46335
- modelId: "",
46336
- messages: []
46337
- },
46338
- providerMetadata: undefined,
46339
- stepType: "initial",
46340
- isContinued: false
46341
- });
46524
+ try {
46525
+ await onStepFinish({
46526
+ text: "",
46527
+ reasoning: undefined,
46528
+ reasoningDetails: [],
46529
+ files: [],
46530
+ sources: [],
46531
+ toolCalls: [],
46532
+ toolResults: [],
46533
+ finishReason: "stop",
46534
+ usage: {
46535
+ inputTokens: repairUsage.inputTokens ?? 0,
46536
+ outputTokens: repairUsage.outputTokens ?? 0,
46537
+ totalTokens: repairUsage.totalTokens ?? 0,
46538
+ ...repairUsage.inputTokenDetails ? { inputTokenDetails: repairUsage.inputTokenDetails } : {}
46539
+ },
46540
+ warnings: [],
46541
+ request: {},
46542
+ response: {
46543
+ id: "tool-repair",
46544
+ timestamp: new Date,
46545
+ modelId: "",
46546
+ messages: messagesContainer.current
46547
+ },
46548
+ providerMetadata: repairProviderMetadata,
46549
+ stepType: "initial",
46550
+ isContinued: false
46551
+ });
46552
+ } catch (callbackError) {
46553
+ if (!silent) {
46554
+ log.warn("Error reporting tool repair usage", {
46555
+ error: String(callbackError)
46556
+ });
46557
+ }
46558
+ }
46342
46559
  }
46343
46560
  if (repairedArgs === undefined || repairedArgs === null) {
46344
46561
  if (!silent) {
@@ -46358,7 +46575,7 @@ function streamResponse(opts) {
46358
46575
  },
46359
46576
  onFinish
46360
46577
  });
46361
- return wrapStreamWithErrorHandler(response, messagesContainer, opts, providerModel, silent);
46578
+ return wrapStreamWithErrorHandler(response, messagesContainer, opts, providerModel, silent, 0, 0, generationSpans);
46362
46579
  } catch (error) {
46363
46580
  const isContextLengthError = checkIfContextLengthError(error);
46364
46581
  const outerErrorMessage = error instanceof Error ? error.message : String(error);
@@ -46392,11 +46609,11 @@ async function generateObjectResponse(opts) {
46392
46609
  } = opts;
46393
46610
  const providerModel = getProviderModel(model, authConfig);
46394
46611
  const normalizedOpenAIEffort = normalizeOpenAIReasoningEffort(model, openAIReasoningEffort);
46612
+ const openRouterProviderOptions = buildOpenRouterProviderOptions(model);
46395
46613
  let lastError;
46396
46614
  for (let attempt = 0;attempt <= MAX_OBJECT_RATE_LIMIT_RETRIES; attempt++) {
46397
46615
  try {
46398
- const recordPayloads = shouldRecordAiPayloads();
46399
- const { output, usage } = await generateText({
46616
+ const { output, usage, providerMetadata } = await generateText({
46400
46617
  model: providerModel,
46401
46618
  output: output_exports.object({
46402
46619
  schema: schema2
@@ -46405,30 +46622,34 @@ async function generateObjectResponse(opts) {
46405
46622
  system,
46406
46623
  maxOutputTokens: maxTokens,
46407
46624
  temperature,
46408
- providerOptions: normalizedOpenAIEffort ? {
46409
- openai: {
46410
- reasoningEffort: normalizedOpenAIEffort
46411
- }
46625
+ providerOptions: normalizedOpenAIEffort || openRouterProviderOptions ? {
46626
+ ...normalizedOpenAIEffort ? {
46627
+ openai: {
46628
+ reasoningEffort: normalizedOpenAIEffort
46629
+ }
46630
+ } : {},
46631
+ ...openRouterProviderOptions
46412
46632
  } : undefined,
46413
46633
  maxRetries: 0,
46414
46634
  abortSignal,
46415
- experimental_telemetry: {
46416
- isEnabled: true,
46417
- recordInputs: recordPayloads,
46418
- recordOutputs: recordPayloads,
46419
- functionId: "apex.generate_object",
46420
- ...sessionId ? { metadata: { sessionId } } : {}
46421
- }
46635
+ experimental_telemetry: createAiTelemetrySettings({
46636
+ operation: opts.operation ?? "apex.structured.generate",
46637
+ sessionId
46638
+ })
46422
46639
  });
46423
46640
  if (onTokenUsage && usage) {
46424
46641
  onTokenUsage(usage.inputTokens ?? 0, usage.outputTokens ?? 0);
46425
46642
  }
46426
46643
  if (_usageCallback && usage) {
46427
- const inp = usage.inputTokens ?? 0;
46428
- const out = usage.outputTokens ?? 0;
46644
+ const stepUsage = normalizeStepUsage({ usage, providerMetadata });
46429
46645
  const stepCtx = takeStepContext();
46430
- if (inp > 0 || out > 0)
46431
- _usageCallback(model, inp, out, stepCtx);
46646
+ if (stepUsage.inputTokens > 0 || stepUsage.outputTokens > 0) {
46647
+ await _usageCallback(model, stepUsage.inputTokens, stepUsage.outputTokens, {
46648
+ ...stepCtx,
46649
+ cacheReadTokens: stepUsage.cacheReadTokens,
46650
+ cacheWriteTokens: stepUsage.cacheWriteTokens
46651
+ });
46652
+ }
46432
46653
  }
46433
46654
  return output;
46434
46655
  } catch (error) {
@@ -46447,7 +46668,7 @@ async function generateObjectResponse(opts) {
46447
46668
  }
46448
46669
  throw lastError;
46449
46670
  }
46450
- var log, RESPONSE_DEBUG, RESPONSE_TOOL_NAME = "response", DEFAULT_OPENAI_REASONING_EFFORT = "medium", OPENAI_REASONING_MODEL_IDS, _usageCallback = null, stepContextStore, SEQUENTIAL_TOOL_CALL_INSTRUCTION, MAX_RATE_LIMIT_RETRIES = 20, MAX_IDLE_RESUME_RETRIES = 3, STREAM_IDLE_TIMEOUT_MS, StreamIdleTimeoutError, NON_GATED_TOOLS, MAX_OBJECT_RATE_LIMIT_RETRIES = 8, ContextLengthError, ContextLengthExhaustedError, MAX_RESTART_DEPTH = 3, MAX_TOOL_INPUT_CHARS = 8000, MAX_SCHEMA_CHARS = 6000, MINIMAL_RESTART_PROMPT = "Continue the previous task. Earlier context was discarded due to repeated context-length errors.";
46671
+ var log, RESPONSE_DEBUG, RESPONSE_TOOL_NAME = "response", REPAIR_FAIL_CLOSED_TOOLS, DEFAULT_OPENAI_REASONING_EFFORT = "medium", OPENAI_REASONING_MODEL_IDS, _usageCallback = null, stepContextStore, SEQUENTIAL_TOOL_CALL_INSTRUCTION, MAX_RATE_LIMIT_RETRIES = 20, MAX_IDLE_RESUME_RETRIES = 3, STREAM_IDLE_TIMEOUT_MS, StreamIdleTimeoutError, NON_GATED_TOOLS, MAX_OBJECT_RATE_LIMIT_RETRIES = 8, ContextLengthError, ContextLengthExhaustedError, MAX_RESTART_DEPTH = 3, MAX_TOOL_INPUT_CHARS = 8000, MAX_SCHEMA_CHARS = 6000, MINIMAL_RESTART_PROMPT = "Continue the previous task. Earlier context was discarded due to repeated context-length errors.";
46451
46672
  var init_ai = __esm(() => {
46452
46673
  init_dist4();
46453
46674
  init_structured();
@@ -46460,6 +46681,9 @@ var init_ai = __esm(() => {
46460
46681
  init_utils();
46461
46682
  log = scopedLogger(() => createLogger("ai"));
46462
46683
  RESPONSE_DEBUG = process.env.RESPONSE_DEBUG === "1" || process.env.RESPONSE_DEBUG === "true";
46684
+ REPAIR_FAIL_CLOSED_TOOLS = new Set([
46685
+ "spawn_pentest_agent"
46686
+ ]);
46463
46687
  OPENAI_REASONING_MODEL_IDS = new Set([
46464
46688
  "gpt-5",
46465
46689
  "gpt-5-2025-08-07",
@@ -46479,7 +46703,7 @@ var init_ai = __esm(() => {
46479
46703
  "gpt-5.6-terra",
46480
46704
  "gpt-5.6-luna"
46481
46705
  ]);
46482
- stepContextStore = new AsyncLocalStorage;
46706
+ stepContextStore = new AsyncLocalStorage2;
46483
46707
  SEQUENTIAL_TOOL_CALL_INSTRUCTION = "CRITICAL TOOL-CALLING RULE: Emit EXACTLY ONE tool call per response. " + "Never emit more than one tool call in a single turn. After each tool call, " + "wait for its result before making the next one. Emitting multiple tool " + "calls in one turn corrupts their arguments.";
46484
46708
  STREAM_IDLE_TIMEOUT_MS = 5 * 60 * 1000;
46485
46709
  StreamIdleTimeoutError = class StreamIdleTimeoutError extends Error {
@@ -46505,9 +46729,40 @@ var init_ai = __esm(() => {
46505
46729
  };
46506
46730
  });
46507
46731
 
46732
+ // src/core/ai/model-history.ts
46733
+ function addRecentModelId(recentModelIds, modelId) {
46734
+ const nextRecentModelIds = [];
46735
+ for (const id of [modelId, ...recentModelIds]) {
46736
+ if (nextRecentModelIds.includes(id))
46737
+ continue;
46738
+ nextRecentModelIds.push(id);
46739
+ if (nextRecentModelIds.length === MAX_RECENT_MODELS)
46740
+ break;
46741
+ }
46742
+ return nextRecentModelIds;
46743
+ }
46744
+ function getRecentModels(availableModels, recentModelIds) {
46745
+ const modelsById = new Map(availableModels.map((model) => [model.id, model]));
46746
+ const seen = new Set;
46747
+ const recentModels = [];
46748
+ for (const id of recentModelIds) {
46749
+ const model = modelsById.get(id);
46750
+ if (!model || seen.has(id))
46751
+ continue;
46752
+ seen.add(id);
46753
+ recentModels.push(model);
46754
+ if (recentModels.length === MAX_RECENT_MODELS)
46755
+ break;
46756
+ }
46757
+ return recentModels;
46758
+ }
46759
+ var MAX_RECENT_MODELS = 5;
46760
+ var init_model_history = () => {};
46761
+
46508
46762
  // src/core/ai/index.ts
46509
46763
  var init_ai2 = __esm(() => {
46510
46764
  init_ai();
46765
+ init_model_history();
46511
46766
  init_models();
46512
46767
  init_utils();
46513
46768
  });
@@ -46545,7 +46800,9 @@ async function generateSessionName(opts) {
46545
46800
  maxTokens: 50,
46546
46801
  temperature: 0.7,
46547
46802
  authConfig,
46548
- abortSignal
46803
+ abortSignal,
46804
+ sessionId: opts.sessionId,
46805
+ operation: "apex.session.name"
46549
46806
  });
46550
46807
  if (!result?.name)
46551
46808
  return null;
@@ -46672,7 +46929,11 @@ function toReference(stored) {
46672
46929
  ref.customHeaderKeys = Object.keys(stored.tokens.customHeaders);
46673
46930
  }
46674
46931
  if (stored.additionalFields) {
46675
- const keys = Object.keys(stored.additionalFields);
46932
+ const authMethod = stored.additionalFields.authMethod;
46933
+ const recognized = isMobileOtpAuthMethod(authMethod);
46934
+ if (recognized)
46935
+ ref.authMethod = authMethod;
46936
+ const keys = Object.keys(stored.additionalFields).filter((key) => !(key === "authMethod" && recognized));
46676
46937
  if (keys.length > 0)
46677
46938
  ref.additionalFieldKeys = keys;
46678
46939
  }
@@ -46681,6 +46942,9 @@ function toReference(stored) {
46681
46942
  ref.context = ctx;
46682
46943
  return ref;
46683
46944
  }
46945
+ function isMobileOtpAuthMethod(value) {
46946
+ return value === "sms-passwordless" || value === "sms-mfa";
46947
+ }
46684
46948
 
46685
46949
  class CredentialManager {
46686
46950
  store = new Map;
@@ -46787,6 +47051,9 @@ class CredentialManager {
46787
47051
  if (ref.additionalFieldKeys?.length) {
46788
47052
  parts.push(` Additional secret fields: ${ref.additionalFieldKeys.join(", ")}`);
46789
47053
  }
47054
+ if (ref.authMethod) {
47055
+ parts.push(` Authentication method: ${ref.authMethod}`);
47056
+ }
46790
47057
  if (ref.context)
46791
47058
  parts.push(` Context: ${ref.context}`);
46792
47059
  return parts.join(`
@@ -47341,7 +47608,7 @@ async function create2(input) {
47341
47608
  if (normalizedConfig?.headers !== undefined) {
47342
47609
  snapshotHeaders = { ...normalizedConfig.headers };
47343
47610
  } else {
47344
- const { config: appConfig } = await import("./index-ghwf5z3v.js");
47611
+ const { config: appConfig } = await import("./index-p01t9n89.js");
47345
47612
  const cfg = await appConfig.get();
47346
47613
  snapshotHeaders = cfg.defaultHeaders ? { ...cfg.defaultHeaders } : { ...DEFAULT_HEADER_RECORD };
47347
47614
  }
@@ -47377,7 +47644,8 @@ async function create2(input) {
47377
47644
  targets: input.targets,
47378
47645
  userMessage: input.userMessage,
47379
47646
  model: input.model,
47380
- authConfig: input.authConfig
47647
+ authConfig: input.authConfig,
47648
+ sessionId: result.id
47381
47649
  }).then((aiName) => {
47382
47650
  if (aiName) {
47383
47651
  result.name = aiName;
@@ -47689,6 +47957,7 @@ var init_session = __esm(() => {
47689
47957
  prompt: zod_default.string().optional(),
47690
47958
  taskDriven: zod_default.boolean().optional(),
47691
47959
  requirePlan: zod_default.boolean().optional(),
47960
+ disableSubagents: zod_default.boolean().optional(),
47692
47961
  promptInjectionLibrarySource: zod_default.string().optional()
47693
47962
  });
47694
47963
  SessionInfoObject = zod_default.object({
@@ -47906,6 +48175,11 @@ class Logger {
47906
48175
  }
47907
48176
  }
47908
48177
  }
48178
+ const correlation = getActiveTraceCorrelation();
48179
+ if (correlation) {
48180
+ record.trace_id = correlation.traceId;
48181
+ record.span_id = correlation.spanId;
48182
+ }
47909
48183
  return safeStringify(record);
47910
48184
  }
47911
48185
  formatPretty(ts, level, msg, fields) {
@@ -47932,6 +48206,7 @@ function createLogger(scope) {
47932
48206
  var SEVERITY, VALID_LEVELS, COLORS, RESET = "\x1B[0m", DIM = "\x1B[2m", stderrSink = (line) => process.stderr.write(`${line}
47933
48207
  `), sink, logger;
47934
48208
  var init_structured = __esm(() => {
48209
+ init_observability();
47935
48210
  init_logger();
47936
48211
  SEVERITY = {
47937
48212
  DEBUG: 10,
@@ -49284,14 +49559,22 @@ async function summarizeConversation(messages, opts, model) {
49284
49559
  content: `Summarize this conversation to pass to another agent. This was the original system prompt (truncated for safety): ${systemSnippet}`
49285
49560
  }
49286
49561
  ];
49287
- const { text: summary, usage: summaryUsage } = await generateText({
49562
+ const {
49563
+ text: summary,
49564
+ usage: summaryUsage,
49565
+ providerMetadata: summaryProviderMetadata
49566
+ } = await generateText({
49288
49567
  model,
49289
49568
  system: `You are a helpful assistant that summarizes conversations to pass to another agent. Review the conversation and system prompt at the end provided by the user.`,
49290
49569
  messages: summarizedMessages,
49291
- abortSignal: opts.abortSignal
49570
+ abortSignal: opts.abortSignal,
49571
+ experimental_telemetry: createAiTelemetrySettings({
49572
+ operation: "apex.context.summarize",
49573
+ sessionId: opts.sessionId
49574
+ })
49292
49575
  });
49293
49576
  if (opts.onStepFinish && summaryUsage) {
49294
- opts.onStepFinish({
49577
+ await opts.onStepFinish({
49295
49578
  text: "",
49296
49579
  reasoning: undefined,
49297
49580
  reasoningDetails: [],
@@ -49303,16 +49586,18 @@ async function summarizeConversation(messages, opts, model) {
49303
49586
  usage: {
49304
49587
  inputTokens: summaryUsage.inputTokens ?? 0,
49305
49588
  outputTokens: summaryUsage.outputTokens ?? 0,
49306
- totalTokens: summaryUsage.totalTokens ?? 0
49589
+ totalTokens: summaryUsage.totalTokens ?? 0,
49590
+ ...summaryUsage.inputTokenDetails ? { inputTokenDetails: summaryUsage.inputTokenDetails } : {}
49307
49591
  },
49308
49592
  warnings: [],
49309
49593
  request: {},
49310
49594
  response: {
49311
49595
  id: "summarization",
49312
49596
  timestamp: new Date,
49313
- modelId: ""
49597
+ modelId: "",
49598
+ messages
49314
49599
  },
49315
- providerMetadata: undefined,
49600
+ providerMetadata: summaryProviderMetadata,
49316
49601
  stepType: "initial",
49317
49602
  isContinued: false
49318
49603
  });
@@ -49374,22 +49659,25 @@ function createSummarizationStream(messages, opts, model) {
49374
49659
  yield chunk;
49375
49660
  }
49376
49661
  }();
49662
+ const resumedForFields = resumedStreamPromise.catch(() => {
49663
+ return;
49664
+ });
49377
49665
  return {
49378
49666
  fullStream: wrappedFullStream,
49379
- text: resumedStreamPromise.then((s) => s.text),
49380
- content: resumedStreamPromise.then((s) => s.content),
49381
- reasoning: resumedStreamPromise.then((s) => s.reasoning),
49382
- reasoningText: resumedStreamPromise.then((s) => s.reasoningText),
49383
- toolCalls: resumedStreamPromise.then((s) => s.toolCalls),
49384
- toolResults: resumedStreamPromise.then((s) => s.toolResults),
49385
- usage: resumedStreamPromise.then((s) => s.usage),
49386
- finishReason: resumedStreamPromise.then((s) => s.finishReason),
49387
- warnings: resumedStreamPromise.then((s) => s.warnings),
49388
- response: resumedStreamPromise.then((s) => s.response),
49389
- files: resumedStreamPromise.then((s) => s.files),
49390
- sources: resumedStreamPromise.then((s) => s.sources),
49391
- staticToolCalls: resumedStreamPromise.then((s) => s.staticToolCalls),
49392
- dynamicToolCalls: resumedStreamPromise.then((s) => s.dynamicToolCalls),
49667
+ text: resumedForFields.then((s) => s?.text),
49668
+ content: resumedForFields.then((s) => s?.content),
49669
+ reasoning: resumedForFields.then((s) => s?.reasoning),
49670
+ reasoningText: resumedForFields.then((s) => s?.reasoningText),
49671
+ toolCalls: resumedForFields.then((s) => s?.toolCalls),
49672
+ toolResults: resumedForFields.then((s) => s?.toolResults),
49673
+ usage: resumedForFields.then((s) => s?.usage),
49674
+ finishReason: resumedForFields.then((s) => s?.finishReason),
49675
+ warnings: resumedForFields.then((s) => s?.warnings),
49676
+ response: resumedForFields.then((s) => s?.response),
49677
+ files: resumedForFields.then((s) => s?.files),
49678
+ sources: resumedForFields.then((s) => s?.sources),
49679
+ staticToolCalls: resumedForFields.then((s) => s?.staticToolCalls),
49680
+ dynamicToolCalls: resumedForFields.then((s) => s?.dynamicToolCalls),
49393
49681
  pipeTextStreamToResponse: async (response, init) => {
49394
49682
  const stream = await resumedStreamPromise;
49395
49683
  return stream.pipeTextStreamToResponse(response, init);
@@ -49416,6 +49704,7 @@ var init_utils = __esm(() => {
49416
49704
  init_auth();
49417
49705
  init_config();
49418
49706
  init_structured();
49707
+ init_observability();
49419
49708
  init_lazyLogger();
49420
49709
  init_ai();
49421
49710
  init_contextManagement();
@@ -49426,4 +49715,4 @@ var init_utils = __esm(() => {
49426
49715
  STREAMING_FETCH_TIMEOUT_MS = 35 * 60 * 1000;
49427
49716
  });
49428
49717
 
49429
- export { stepCountIs, hasToolCall, init_dist4 as init_dist, AVAILABLE_MODELS, init_models, require_tslib, scopedLogger, init_lazyLogger, buildAuthConfig, init_utils, init_ai2 as init_ai, generateRandomName, generateSessionName, init_name, CredentialManager, init_credentials, schema, descending, newSessionId, newMessageId, newPartId, init_id, RateLimiter, init_rateLimiter, NotFoundError, write2 as write, createDir, writeRaw, read2 as read, update, list, init_storage, ToolsetStateSchema, init_toolset, create2 as create, list2 as list1, normalizeMessages, sessions, init_session, writeErrorLog, routeLogsToErrorFile, init_logger, createLogger, logger, init_structured, getApexTracer, withSubagentSessionBaggage, init_observability, DEFAULT_OPENAI_REASONING_EFFORT, modelSupportsThinking, modelSupportsOpenAIReasoning, getOpenAIReasoningEfforts, streamResponse, generateObjectResponse, init_ai as init_ai1 };
49718
+ export { stepCountIs, hasToolCall, init_dist4 as init_dist, schema, descending, newSessionId, newMessageId, newPartId, init_id, registerActiveRootSpan, unregisterActiveRootSpan, endAllActiveRootSpans, init_active_root_spans, getApexTracer, shouldRecordAiPayloads, withSubagentSessionBaggage, getActiveTraceCorrelation, init_observability, addRecentModelId, getRecentModels, init_model_history, AVAILABLE_MODELS, init_models, require_tslib, scopedLogger, init_lazyLogger, buildAuthConfig, init_utils, init_ai2 as init_ai, generateRandomName, generateSessionName, init_name, CredentialManager, init_credentials, RateLimiter, init_rateLimiter, NotFoundError, write2 as write, createDir, writeRaw, read2 as read, update, list, init_storage, ToolsetStateSchema, init_toolset, create2 as create, list2 as list1, getResumeMessages, normalizeMessages, sessions, init_session, writeErrorLog, routeLogsToErrorFile, init_logger, createLogger, logger, init_structured, DEFAULT_OPENAI_REASONING_EFFORT, getContextWindow, modelSupportsThinking, modelSupportsOpenAIReasoning, getOpenAIReasoningEfforts, streamResponse, generateObjectResponse, init_ai as init_ai1 };