@qwen-code/qwen-code 0.18.0-preview.1 → 0.18.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 (141) hide show
  1. package/bundled/qc-helper/SKILL.md +1 -2
  2. package/bundled/qc-helper/docs/_meta.ts +1 -0
  3. package/bundled/qc-helper/docs/configuration/settings.md +20 -24
  4. package/bundled/qc-helper/docs/features/_meta.ts +0 -3
  5. package/bundled/qc-helper/docs/features/approval-mode.md +10 -14
  6. package/bundled/qc-helper/docs/features/commands.md +47 -23
  7. package/bundled/qc-helper/docs/features/followup-suggestions.md +2 -2
  8. package/bundled/qc-helper/docs/features/scheduled-tasks.md +1 -1
  9. package/bundled/qc-helper/docs/features/sub-agents.md +60 -0
  10. package/bundled/qc-helper/docs/qwen-serve-deploy-local.md +221 -0
  11. package/bundled/qc-helper/docs/qwen-serve.md +234 -24
  12. package/chunks/{agent-SXS4NQWS.js → agent-LOTJK6AH.js} +25 -19
  13. package/chunks/agent-headless-TU3EPMYU.js +50 -0
  14. package/chunks/{anthropicContentGenerator-4QBVSFSJ.js → anthropicContentGenerator-2HBRNQ3B.js} +7 -7
  15. package/chunks/{askUserQuestion-NOOLRWCJ.js → askUserQuestion-OGCMIBQM.js} +45 -3
  16. package/chunks/{ca-WRHFBIDH.js → ca-BARBRL6N.js} +48 -1
  17. package/chunks/{chunk-JMLIPZUU.js → chunk-2Y5SYSD3.js} +361 -583
  18. package/chunks/chunk-3DHXZ6EV.js +241 -0
  19. package/chunks/{chunk-AVLOK27J.js → chunk-3HTIVKZE.js} +1 -1
  20. package/chunks/{chunk-BNESGOSJ.js → chunk-55ZMG67I.js} +1 -1
  21. package/chunks/chunk-64WXLC72.js +98 -0
  22. package/chunks/{chunk-F6FLCHCS.js → chunk-6YIUGZTC.js} +1069 -211
  23. package/chunks/{chunk-C6WMLUNB.js → chunk-72LDN5PP.js} +1 -1
  24. package/chunks/{chunk-ERREX2ES.js → chunk-7BCMOPIM.js} +64 -24
  25. package/chunks/{chunk-6VFG3EUJ.js → chunk-A7B4ISQP.js} +1 -1
  26. package/chunks/{chunk-F5ORN4YO.js → chunk-B7HXHOHU.js} +1 -1
  27. package/chunks/{chunk-5RNZ2QKF.js → chunk-BIVG75CP.js} +1 -1
  28. package/chunks/{chunk-MVX64PNU.js → chunk-EYENRK4D.js} +1 -1
  29. package/chunks/{chunk-SZOEIL6S.js → chunk-H6BD2ELD.js} +1 -0
  30. package/chunks/{chunk-SCHRFI7O.js → chunk-HLPLOD42.js} +1 -1
  31. package/chunks/{chunk-R5PDRHEF.js → chunk-HR7SV7AY.js} +68 -47
  32. package/chunks/{chunk-JSYEZAYV.js → chunk-IDX6COTE.js} +2 -2
  33. package/chunks/{chunk-6KH2Q7XN.js → chunk-IWAYOW5Q.js} +17482 -11669
  34. package/chunks/chunk-J5MDQKJL.js +2230 -0
  35. package/chunks/{chunk-USE2VQ5P.js → chunk-JTQAQBTV.js} +21 -0
  36. package/chunks/{chunk-ZW7GBCRE.js → chunk-LBP46COL.js} +1014 -163
  37. package/chunks/chunk-LD2XBG6Z.js +102 -0
  38. package/chunks/{chunk-KOA52UTF.js → chunk-LEJ42GNY.js} +14 -14
  39. package/chunks/{chunk-D46KOV3C.js → chunk-M6VTDSVR.js} +1 -1
  40. package/chunks/{chunk-SHUT5MQY.js → chunk-MFBBBTNY.js} +1 -1
  41. package/chunks/{chunk-PLYZAP4W.js → chunk-OHEGWO4L.js} +101 -23
  42. package/chunks/{chunk-NQZ33PWX.js → chunk-PL3MVCWD.js} +11 -11
  43. package/chunks/chunk-QQDPRDVW.js +25 -0
  44. package/chunks/chunk-R7ODSGTK.js +159 -0
  45. package/chunks/{chunk-GBEPNWYB.js → chunk-SEGYWKIH.js} +1 -1
  46. package/chunks/chunk-SKBPNJEW.js +45 -0
  47. package/chunks/{chunk-UABFCMPA.js → chunk-SNGELLWX.js} +3 -1
  48. package/chunks/chunk-XBY7E2FX.js +605 -0
  49. package/chunks/{chunk-G763GDO6.js → chunk-XV4HCEVI.js} +36 -3
  50. package/chunks/{chunk-WFVXF3OM.js → chunk-Z2Z3GUXZ.js} +1 -0
  51. package/chunks/{chunk-BBTV54KB.js → chunk-ZTZ4DDQE.js} +2 -2
  52. package/chunks/{computer-use-CT6MU6P3.js → computer-use-3RH2DOM6.js} +25 -19
  53. package/chunks/contextCommand-K347QT6O.js +52 -0
  54. package/chunks/{cron-create-PIPMXQN4.js → cron-create-YJL3KFWI.js} +3 -3
  55. package/chunks/{cron-delete-6Y5XIDMS.js → cron-delete-WKWSJZQA.js} +3 -3
  56. package/chunks/{cron-list-A4WNRUWZ.js → cron-list-B52XEXAZ.js} +3 -3
  57. package/chunks/{de-M5RPB2NB.js → de-YGKK2BC4.js} +48 -1
  58. package/chunks/{devtools-IXE4UP72.js → devtools-FM6GJPYG.js} +1 -1
  59. package/chunks/{dist-R2SXPG74.js → dist-4LXD6L6X.js} +2 -2
  60. package/chunks/{dist-TE5QKMGR.js → dist-H6ONXVLG.js} +1 -1
  61. package/chunks/{dist-ZMQ4TXD5.js → dist-KAZ3SEBX.js} +2 -2
  62. package/chunks/{dist-BXDUQ2QY.js → dist-PK7DFCAW.js} +1 -1
  63. package/chunks/{edit-A4YK7AIB.js → edit-KU4PJGEX.js} +26 -20
  64. package/chunks/{en-UMYKQAZE.js → en-DHGYHIHX.js} +77 -2
  65. package/chunks/{enter-worktree-VNEQINLC.js → enter-worktree-PPYIDCWI.js} +25 -19
  66. package/chunks/enterPlanMode-5CZDMCB4.js +158 -0
  67. package/chunks/{exit-worktree-AVSMXC33.js → exit-worktree-UY3CGHKC.js} +25 -19
  68. package/chunks/exitPlanMode-3DN4QNSG.js +703 -0
  69. package/chunks/{fr-MPYXXXPW.js → fr-JXBKPJKQ.js} +48 -1
  70. package/chunks/{geminiContentGenerator-CR2WGARL.js → geminiContentGenerator-7A6I2RWB.js} +7 -7
  71. package/chunks/{getMachineId-bsd-F7GNPTER.js → getMachineId-bsd-4CASPIU4.js} +1 -1
  72. package/chunks/{getMachineId-darwin-T73DJL27.js → getMachineId-darwin-HPQPEMZR.js} +1 -1
  73. package/chunks/{getMachineId-linux-MKQTFPQM.js → getMachineId-linux-AUARKYHL.js} +1 -1
  74. package/chunks/{getMachineId-unsupported-MUR5KOQE.js → getMachineId-unsupported-S32ZDA2T.js} +1 -1
  75. package/chunks/{getMachineId-win-CDYFC6ZM.js → getMachineId-win-4EFLHYIJ.js} +1 -1
  76. package/chunks/{glob-5V32KOG5.js → glob-OFNQSS52.js} +25 -19
  77. package/chunks/{grep-PUTEPBR4.js → grep-6J2MSUM5.js} +28 -19
  78. package/chunks/{ja-NFZ32AB3.js → ja-TGPZSP2B.js} +48 -1
  79. package/chunks/{keychain-token-storage-UHGOCDD6.js → keychain-token-storage-6IU6ORQN.js} +3 -3
  80. package/chunks/{ls-34DLNYCD.js → ls-V3O6A5PT.js} +4 -4
  81. package/chunks/{lsp-NCDEHH3V.js → lsp-G2OCIFUA.js} +3 -3
  82. package/chunks/{monitor-EJBR5VCR.js → monitor-FKLHV423.js} +25 -19
  83. package/chunks/{notebook-edit-DZHGPP2L.js → notebook-edit-KTBYFKWG.js} +26 -20
  84. package/chunks/{openaiContentGenerator-4QNV3CHM.js → openaiContentGenerator-L5KSWQY7.js} +15 -14
  85. package/chunks/{pt-BR43FRBA.js → pt-TIBG6BIO.js} +48 -1
  86. package/chunks/{qwenContentGenerator-3XOCEMQO.js → qwenContentGenerator-PYOXLMBW.js} +27 -21
  87. package/chunks/{qwenOAuth2-KRJT35QH.js → qwenOAuth2-2KCKWDCF.js} +6 -5
  88. package/chunks/{read-file-VZ2SQQIX.js → read-file-JQVRK4NU.js} +11 -11
  89. package/chunks/ripGrep-2L4LPNAJ.js +48 -0
  90. package/chunks/{ru-DQCW2KHD.js → ru-JBCHCK4L.js} +48 -1
  91. package/chunks/{scheduler-H32DZVDV.js → scheduler-FGNXY4JQ.js} +25 -19
  92. package/chunks/send-message-SZFWNOCL.js +244 -0
  93. package/chunks/{serve-56G4B5W6.js → serve-N2IBLA3G.js} +13592 -4979
  94. package/chunks/{shell-Q77KNP4N.js → shell-PTEG6UX4.js} +25 -19
  95. package/chunks/{skill-CLWFJYBG.js → skill-X4NTK4NH.js} +64 -113
  96. package/chunks/{src-47L2LUOU.js → src-GLLQ3R5W.js} +307 -32
  97. package/chunks/{syntheticOutput-T5SWX3YF.js → syntheticOutput-IKAY5F6X.js} +4 -4
  98. package/chunks/task-create-MQICOJFV.js +19 -0
  99. package/chunks/task-list-RIHJCH32.js +151 -0
  100. package/chunks/{task-stop-3VHAQMYM.js → task-stop-FWZRFANS.js} +3 -3
  101. package/chunks/task-update-2LHPXOYM.js +408 -0
  102. package/chunks/team-create-2E4PF4KN.js +314 -0
  103. package/chunks/team-delete-DAUDQS4J.js +116 -0
  104. package/chunks/{todoWrite-EAGJGKO5.js → todoWrite-HTUACZES.js} +5 -5
  105. package/chunks/{tool-search-Q75AYDTP.js → tool-search-KTVULRES.js} +11 -11
  106. package/chunks/{web-fetch-SS6IKK6N.js → web-fetch-CZ7LLKPE.js} +5 -5
  107. package/chunks/workflow-L2ZUUDT2.js +960 -0
  108. package/chunks/{write-file-RENGC25N.js → write-file-ZEB2JDYH.js} +26 -20
  109. package/chunks/{zh-6VFXOAR5.js → zh-7H5OQC4I.js} +82 -7
  110. package/chunks/{zh-TW-IQZ4AD5M.js → zh-TW-P4IDHD3M.js} +79 -7
  111. package/cli.js +11248 -5119
  112. package/examples/agent/qwen-extension.json +1 -0
  113. package/examples/commands/qwen-extension.json +1 -0
  114. package/examples/context/qwen-extension.json +1 -0
  115. package/examples/mcp-server/qwen-extension.json +1 -0
  116. package/examples/skills/qwen-extension.json +1 -0
  117. package/examples/starter/QWEN.md +30 -0
  118. package/examples/starter/README.md +59 -0
  119. package/examples/starter/agents/diary.md +86 -0
  120. package/examples/starter/commands/writing/polish.md +13 -0
  121. package/examples/starter/example.ts +64 -0
  122. package/examples/starter/package.json +18 -0
  123. package/examples/starter/qwen-extension.json +12 -0
  124. package/examples/starter/skills/synonyms/SKILL.md +48 -0
  125. package/examples/starter/tsconfig.json +13 -0
  126. package/fzfWorker.js +1083 -0
  127. package/locales/ca.js +51 -0
  128. package/locales/de.js +51 -0
  129. package/locales/en.js +89 -2
  130. package/locales/fr.js +53 -2
  131. package/locales/ja.js +52 -2
  132. package/locales/pt.js +52 -2
  133. package/locales/ru.js +53 -2
  134. package/locales/zh-TW.js +90 -11
  135. package/locales/zh.js +94 -11
  136. package/package.json +3 -2
  137. package/bundled/qc-helper/docs/features/checkpointing.md +0 -77
  138. package/chunks/contextCommand-YODJQYIV.js +0 -46
  139. package/chunks/exitPlanMode-5SQYVROD.js +0 -229
  140. package/chunks/ripGrep-SBIZCPOL.js +0 -42
  141. package/chunks/send-message-YYF56TS7.js +0 -151
@@ -20,19 +20,19 @@ import {
20
20
  } from "./chunk-OFEVLU4C.js";
21
21
  import {
22
22
  isAnyAutoMemPath
23
- } from "./chunk-AVLOK27J.js";
23
+ } from "./chunk-3HTIVKZE.js";
24
24
  import {
25
25
  InstallationManager
26
- } from "./chunk-JSYEZAYV.js";
26
+ } from "./chunk-IDX6COTE.js";
27
27
  import {
28
28
  STRUCTURED_OUTPUT_REDACTED_ARGS
29
- } from "./chunk-5RNZ2QKF.js";
29
+ } from "./chunk-BIVG75CP.js";
30
30
  import {
31
31
  BaseDeclarativeTool,
32
32
  BaseToolInvocation,
33
33
  ToolDisplayNames,
34
34
  ToolNames
35
- } from "./chunk-G763GDO6.js";
35
+ } from "./chunk-XV4HCEVI.js";
36
36
  import {
37
37
  DEFAULT_OPENAI_BASE_URL,
38
38
  convertSchema,
@@ -40,11 +40,11 @@ import {
40
40
  runtimeDiagnostics,
41
41
  safeJsonParse,
42
42
  tokenLimit
43
- } from "./chunk-D46KOV3C.js";
43
+ } from "./chunk-M6VTDSVR.js";
44
44
  import {
45
45
  FinishReason,
46
46
  GenerateContentResponse
47
- } from "./chunk-BNESGOSJ.js";
47
+ } from "./chunk-55ZMG67I.js";
48
48
  import {
49
49
  FatalConfigError,
50
50
  Storage,
@@ -53,14 +53,14 @@ import {
53
53
  getErrorMessage,
54
54
  getErrorStatus,
55
55
  getErrorType,
56
- getSessionContext,
57
56
  isNodeError,
58
57
  isSubpaths,
59
58
  makeRelative,
60
59
  setSessionContext,
60
+ setShellTracePropagation,
61
61
  shortenPath,
62
62
  unescapePath
63
- } from "./chunk-R5PDRHEF.js";
63
+ } from "./chunk-HR7SV7AY.js";
64
64
  import {
65
65
  require_dist
66
66
  } from "./chunk-ZERZSAZL.js";
@@ -80,8 +80,9 @@ import {
80
80
  init_esm,
81
81
  isSpanContextValid,
82
82
  metrics,
83
+ propagation,
83
84
  trace
84
- } from "./chunk-WFVXF3OM.js";
85
+ } from "./chunk-Z2Z3GUXZ.js";
85
86
  import {
86
87
  __qwen_dirname,
87
88
  init_esbuild_shims
@@ -17033,7 +17034,7 @@ var require_load_balancer_child_handler = __commonJS({
17033
17034
  createSubchannel(subchannelAddress, subchannelArgs) {
17034
17035
  return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs);
17035
17036
  }
17036
- updateState(connectivityState, picker, errorMessage) {
17037
+ updateState(connectivityState, picker, errorMessage2) {
17037
17038
  var _a;
17038
17039
  if (this.calledByPendingChild()) {
17039
17040
  if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) {
@@ -17045,7 +17046,7 @@ var require_load_balancer_child_handler = __commonJS({
17045
17046
  } else if (!this.calledByCurrentChild()) {
17046
17047
  return;
17047
17048
  }
17048
- this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage);
17049
+ this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage2);
17049
17050
  }
17050
17051
  requestReresolution() {
17051
17052
  var _a;
@@ -17279,11 +17280,11 @@ var require_resolving_load_balancer = __commonJS({
17279
17280
  this.updateResolution();
17280
17281
  }
17281
17282
  }, "requestReresolution"),
17282
- updateState: /* @__PURE__ */ __name((newState, picker, errorMessage) => {
17283
+ updateState: /* @__PURE__ */ __name((newState, picker, errorMessage2) => {
17283
17284
  this.latestChildState = newState;
17284
17285
  this.latestChildPicker = picker;
17285
- this.latestChildErrorMessage = errorMessage;
17286
- this.updateState(newState, picker, errorMessage);
17286
+ this.latestChildErrorMessage = errorMessage2;
17287
+ this.updateState(newState, picker, errorMessage2);
17287
17288
  }, "updateState"),
17288
17289
  addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper),
17289
17290
  removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper)
@@ -17349,13 +17350,13 @@ var require_resolving_load_balancer = __commonJS({
17349
17350
  }
17350
17351
  this.backoffTimeout.runOnce();
17351
17352
  }
17352
- updateState(connectivityState, picker, errorMessage) {
17353
+ updateState(connectivityState, picker, errorMessage2) {
17353
17354
  trace2((0, uri_parser_1.uriToString)(this.target) + " " + connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[connectivityState]);
17354
17355
  if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) {
17355
17356
  picker = new picker_1.QueuePicker(this, picker);
17356
17357
  }
17357
17358
  this.currentState = connectivityState;
17358
- this.channelControlHelper.updateState(connectivityState, picker, errorMessage);
17359
+ this.channelControlHelper.updateState(connectivityState, picker, errorMessage2);
17359
17360
  }
17360
17361
  handleResolutionFailure(error) {
17361
17362
  if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) {
@@ -27640,13 +27641,13 @@ var require_subchannel = __commonJS({
27640
27641
  * @param newState The state to transition to
27641
27642
  * @returns True if the state changed, false otherwise
27642
27643
  */
27643
- transitionToState(oldStates, newState, errorMessage) {
27644
+ transitionToState(oldStates, newState, errorMessage2) {
27644
27645
  var _a, _b;
27645
27646
  if (oldStates.indexOf(this.connectivityState) === -1) {
27646
27647
  return false;
27647
27648
  }
27648
- if (errorMessage) {
27649
- this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage + '"');
27649
+ if (errorMessage2) {
27650
+ this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage2 + '"');
27650
27651
  } else {
27651
27652
  this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
27652
27653
  }
@@ -27687,7 +27688,7 @@ var require_subchannel = __commonJS({
27687
27688
  throw new Error(`Invalid state: unknown ConnectivityState ${newState}`);
27688
27689
  }
27689
27690
  for (const listener of this.stateListeners) {
27690
- listener(this, previousState, newState, this.keepaliveTime, errorMessage);
27691
+ listener(this, previousState, newState, this.keepaliveTime, errorMessage2);
27691
27692
  }
27692
27693
  return true;
27693
27694
  }
@@ -29256,18 +29257,18 @@ var require_transport = __commonJS({
29256
29257
  setImmediate(() => {
29257
29258
  if (!reportedError) {
29258
29259
  reportedError = true;
29259
- reject(`${errorMessage.trim()} (${(/* @__PURE__ */ new Date()).toISOString()})`);
29260
+ reject(`${errorMessage2.trim()} (${(/* @__PURE__ */ new Date()).toISOString()})`);
29260
29261
  }
29261
29262
  });
29262
29263
  }, "closeHandler");
29263
29264
  const errorHandler = /* @__PURE__ */ __name((error) => {
29264
29265
  var _a;
29265
29266
  (_a = this.session) === null || _a === void 0 ? void 0 : _a.destroy();
29266
- errorMessage = error.message;
29267
- this.trace("connection failed with error " + errorMessage);
29267
+ errorMessage2 = error.message;
29268
+ this.trace("connection failed with error " + errorMessage2);
29268
29269
  if (!reportedError) {
29269
29270
  reportedError = true;
29270
- reject(`${errorMessage} (${(/* @__PURE__ */ new Date()).toISOString()})`);
29271
+ reject(`${errorMessage2} (${(/* @__PURE__ */ new Date()).toISOString()})`);
29271
29272
  }
29272
29273
  }, "errorHandler");
29273
29274
  const sessionOptions = {
@@ -29282,7 +29283,7 @@ var require_transport = __commonJS({
29282
29283
  }
29283
29284
  const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions);
29284
29285
  this.session = session;
29285
- let errorMessage = "Failed to connect";
29286
+ let errorMessage2 = "Failed to connect";
29286
29287
  let reportedError = false;
29287
29288
  session.unref();
29288
29289
  session.once("remoteSettings", () => {
@@ -34698,8 +34699,8 @@ var require_load_balancer_pick_first = __commonJS({
34698
34699
  this.currentState = connectivity_state_1.ConnectivityState.IDLE;
34699
34700
  this.currentSubchannelIndex = 0;
34700
34701
  this.currentPick = null;
34701
- this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage) => {
34702
- this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage);
34702
+ this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage2) => {
34703
+ this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage2);
34703
34704
  };
34704
34705
  this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState();
34705
34706
  this.stickyTransientFailureMode = false;
@@ -34721,26 +34722,26 @@ var require_load_balancer_pick_first = __commonJS({
34721
34722
  var _a;
34722
34723
  if (this.currentPick) {
34723
34724
  if (this.reportHealthStatus && !this.currentPick.isHealthy()) {
34724
- const errorMessage = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`;
34725
+ const errorMessage2 = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`;
34725
34726
  this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
34726
- details: errorMessage
34727
- }), errorMessage);
34727
+ details: errorMessage2
34728
+ }), errorMessage2);
34728
34729
  } else {
34729
34730
  this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null);
34730
34731
  }
34731
34732
  } else if (((_a = this.latestAddressList) === null || _a === void 0 ? void 0 : _a.length) === 0) {
34732
- const errorMessage = `No connection established. Last error: ${this.lastError}`;
34733
+ const errorMessage2 = `No connection established. Last error: ${this.lastError}`;
34733
34734
  this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
34734
- details: errorMessage
34735
- }), errorMessage);
34735
+ details: errorMessage2
34736
+ }), errorMessage2);
34736
34737
  } else if (this.children.length === 0) {
34737
34738
  this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null);
34738
34739
  } else {
34739
34740
  if (this.stickyTransientFailureMode) {
34740
- const errorMessage = `No connection established. Last error: ${this.lastError}`;
34741
+ const errorMessage2 = `No connection established. Last error: ${this.lastError}`;
34741
34742
  this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
34742
- details: errorMessage
34743
- }), errorMessage);
34743
+ details: errorMessage2
34744
+ }), errorMessage2);
34744
34745
  } else {
34745
34746
  this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null);
34746
34747
  }
@@ -34774,7 +34775,7 @@ var require_load_balancer_pick_first = __commonJS({
34774
34775
  this.currentPick = null;
34775
34776
  }
34776
34777
  }
34777
- onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage) {
34778
+ onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage2) {
34778
34779
  var _a;
34779
34780
  if ((_a = this.currentPick) === null || _a === void 0 ? void 0 : _a.realSubchannelEquals(subchannel)) {
34780
34781
  if (newState !== connectivity_state_1.ConnectivityState.READY) {
@@ -34790,8 +34791,8 @@ var require_load_balancer_pick_first = __commonJS({
34790
34791
  }
34791
34792
  if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) {
34792
34793
  child.hasReportedTransientFailure = true;
34793
- if (errorMessage) {
34794
- this.lastError = errorMessage;
34794
+ if (errorMessage2) {
34795
+ this.lastError = errorMessage2;
34795
34796
  }
34796
34797
  this.maybeEnterStickyTransientFailureMode();
34797
34798
  if (index === this.currentSubchannelIndex) {
@@ -34856,10 +34857,10 @@ var require_load_balancer_pick_first = __commonJS({
34856
34857
  clearTimeout(this.connectionDelayTimeout);
34857
34858
  this.calculateAndReportNewState();
34858
34859
  }
34859
- updateState(newState, picker, errorMessage) {
34860
+ updateState(newState, picker, errorMessage2) {
34860
34861
  trace2(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
34861
34862
  this.currentState = newState;
34862
- this.channelControlHelper.updateState(newState, picker, errorMessage);
34863
+ this.channelControlHelper.updateState(newState, picker, errorMessage2);
34863
34864
  }
34864
34865
  resetSubchannelList() {
34865
34866
  for (const child of this.children) {
@@ -34943,10 +34944,10 @@ var require_load_balancer_pick_first = __commonJS({
34943
34944
  this.options = options;
34944
34945
  this.latestState = connectivity_state_1.ConnectivityState.IDLE;
34945
34946
  const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, {
34946
- updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage) => {
34947
+ updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage2) => {
34947
34948
  this.latestState = connectivityState;
34948
34949
  this.latestPicker = picker;
34949
- channelControlHelper.updateState(connectivityState, picker, errorMessage);
34950
+ channelControlHelper.updateState(connectivityState, picker, errorMessage2);
34950
34951
  }, "updateState")
34951
34952
  });
34952
34953
  this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper);
@@ -35458,12 +35459,12 @@ var require_load_balancer_round_robin = __commonJS({
35458
35459
  this.updatesPaused = false;
35459
35460
  this.lastError = null;
35460
35461
  this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, {
35461
- updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage) => {
35462
+ updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage2) => {
35462
35463
  if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) {
35463
35464
  this.channelControlHelper.requestReresolution();
35464
35465
  }
35465
- if (errorMessage) {
35466
- this.lastError = errorMessage;
35466
+ if (errorMessage2) {
35467
+ this.lastError = errorMessage2;
35467
35468
  }
35468
35469
  this.calculateAndUpdateState();
35469
35470
  }, "updateState")
@@ -35493,10 +35494,10 @@ var require_load_balancer_round_robin = __commonJS({
35493
35494
  } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) {
35494
35495
  this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null);
35495
35496
  } else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) {
35496
- const errorMessage = `round_robin: No connection established. Last error: ${this.lastError}`;
35497
+ const errorMessage2 = `round_robin: No connection established. Last error: ${this.lastError}`;
35497
35498
  this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({
35498
- details: errorMessage
35499
- }), errorMessage);
35499
+ details: errorMessage2
35500
+ }), errorMessage2);
35500
35501
  } else {
35501
35502
  this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null);
35502
35503
  }
@@ -35506,7 +35507,7 @@ var require_load_balancer_round_robin = __commonJS({
35506
35507
  }
35507
35508
  }
35508
35509
  }
35509
- updateState(newState, picker, errorMessage) {
35510
+ updateState(newState, picker, errorMessage2) {
35510
35511
  trace2(connectivity_state_1.ConnectivityState[this.currentState] + " -> " + connectivity_state_1.ConnectivityState[newState]);
35511
35512
  if (newState === connectivity_state_1.ConnectivityState.READY) {
35512
35513
  this.currentReadyPicker = picker;
@@ -35514,7 +35515,7 @@ var require_load_balancer_round_robin = __commonJS({
35514
35515
  this.currentReadyPicker = null;
35515
35516
  }
35516
35517
  this.currentState = newState;
35517
- this.channelControlHelper.updateState(newState, picker, errorMessage);
35518
+ this.channelControlHelper.updateState(newState, picker, errorMessage2);
35518
35519
  }
35519
35520
  resetSubchannelList() {
35520
35521
  for (const child of this.children) {
@@ -35829,11 +35830,11 @@ var require_load_balancer_outlier_detection = __commonJS({
35829
35830
  mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.subchannelWrappers.push(subchannelWrapper);
35830
35831
  return subchannelWrapper;
35831
35832
  }, "createSubchannel"),
35832
- updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage) => {
35833
+ updateState: /* @__PURE__ */ __name((connectivityState, picker, errorMessage2) => {
35833
35834
  if (connectivityState === connectivity_state_1.ConnectivityState.READY) {
35834
- channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage);
35835
+ channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage2);
35835
35836
  } else {
35836
- channelControlHelper.updateState(connectivityState, picker, errorMessage);
35837
+ channelControlHelper.updateState(connectivityState, picker, errorMessage2);
35837
35838
  }
35838
35839
  }, "updateState")
35839
35840
  }));
@@ -40577,8 +40578,8 @@ var require_root2 = __commonJS({
40577
40578
  return metrics2;
40578
40579
  }();
40579
40580
  collector.logs = function() {
40580
- var logs2 = {};
40581
- logs2.v1 = function() {
40581
+ var logs3 = {};
40582
+ logs3.v1 = function() {
40582
40583
  var v1 = {};
40583
40584
  v1.LogsService = function() {
40584
40585
  function LogsService(rpcImpl, requestDelimited, responseDelimited) {
@@ -40922,7 +40923,7 @@ var require_root2 = __commonJS({
40922
40923
  }();
40923
40924
  return v1;
40924
40925
  }();
40925
- return logs2;
40926
+ return logs3;
40926
40927
  }();
40927
40928
  return collector;
40928
40929
  }();
@@ -44404,8 +44405,8 @@ var require_root2 = __commonJS({
44404
44405
  return metrics2;
44405
44406
  }();
44406
44407
  proto.logs = function() {
44407
- var logs2 = {};
44408
- logs2.v1 = function() {
44408
+ var logs3 = {};
44409
+ logs3.v1 = function() {
44409
44410
  var v1 = {};
44410
44411
  v1.LogsData = function() {
44411
44412
  function LogsData(properties) {
@@ -45347,7 +45348,7 @@ var require_root2 = __commonJS({
45347
45348
  }();
45348
45349
  return v1;
45349
45350
  }();
45350
- return logs2;
45351
+ return logs3;
45351
45352
  }();
45352
45353
  return proto;
45353
45354
  }();
@@ -48133,19 +48134,19 @@ var require_getMachineId = __commonJS({
48133
48134
  if (!getMachineIdImpl) {
48134
48135
  switch (process3.platform) {
48135
48136
  case "darwin":
48136
- getMachineIdImpl = (await import("./getMachineId-darwin-T73DJL27.js")).getMachineId;
48137
+ getMachineIdImpl = (await import("./getMachineId-darwin-HPQPEMZR.js")).getMachineId;
48137
48138
  break;
48138
48139
  case "linux":
48139
- getMachineIdImpl = (await import("./getMachineId-linux-MKQTFPQM.js")).getMachineId;
48140
+ getMachineIdImpl = (await import("./getMachineId-linux-AUARKYHL.js")).getMachineId;
48140
48141
  break;
48141
48142
  case "freebsd":
48142
- getMachineIdImpl = (await import("./getMachineId-bsd-F7GNPTER.js")).getMachineId;
48143
+ getMachineIdImpl = (await import("./getMachineId-bsd-4CASPIU4.js")).getMachineId;
48143
48144
  break;
48144
48145
  case "win32":
48145
- getMachineIdImpl = (await import("./getMachineId-win-CDYFC6ZM.js")).getMachineId;
48146
+ getMachineIdImpl = (await import("./getMachineId-win-4EFLHYIJ.js")).getMachineId;
48146
48147
  break;
48147
48148
  default:
48148
- getMachineIdImpl = (await import("./getMachineId-unsupported-MUR5KOQE.js")).getMachineId;
48149
+ getMachineIdImpl = (await import("./getMachineId-unsupported-S32ZDA2T.js")).getMachineId;
48149
48150
  break;
48150
48151
  }
48151
48152
  }
@@ -51705,8 +51706,8 @@ var require_ConsoleLogRecordExporter = __commonJS({
51705
51706
  * @param logs
51706
51707
  * @param resultCallback
51707
51708
  */
51708
- export(logs2, resultCallback) {
51709
- this._sendLogRecords(logs2, resultCallback);
51709
+ export(logs3, resultCallback) {
51710
+ this._sendLogRecords(logs3, resultCallback);
51710
51711
  }
51711
51712
  /**
51712
51713
  * Shutdown the exporter.
@@ -51823,14 +51824,14 @@ var require_InMemoryLogRecordExporter = __commonJS({
51823
51824
  * When false, exported log records will not be stored in-memory.
51824
51825
  */
51825
51826
  _stopped = false;
51826
- export(logs2, resultCallback) {
51827
+ export(logs3, resultCallback) {
51827
51828
  if (this._stopped) {
51828
51829
  return resultCallback({
51829
51830
  code: core_1.ExportResultCode.FAILED,
51830
51831
  error: new Error("Exporter has been stopped")
51831
51832
  });
51832
51833
  }
51833
- this._finishedLogRecords.push(...logs2);
51834
+ this._finishedLogRecords.push(...logs3);
51834
51835
  resultCallback({ code: core_1.ExportResultCode.SUCCESS });
51835
51836
  }
51836
51837
  shutdown() {
@@ -61211,7 +61212,12 @@ function setGeminiMdFilename(newFilename) {
61211
61212
  __name(setGeminiMdFilename, "setGeminiMdFilename");
61212
61213
  function getCurrentGeminiMdFilename() {
61213
61214
  if (Array.isArray(currentGeminiMdFilename)) {
61214
- return currentGeminiMdFilename[0];
61215
+ for (const entry of currentGeminiMdFilename) {
61216
+ if (typeof entry === "string" && entry.trim() !== "") {
61217
+ return entry.trim();
61218
+ }
61219
+ }
61220
+ return DEFAULT_CONTEXT_FILENAME;
61215
61221
  }
61216
61222
  return currentGeminiMdFilename;
61217
61223
  }
@@ -62677,12 +62683,12 @@ async function processSingleFileContent(filePath, config, offset, limit, pages)
62677
62683
  }
62678
62684
  }
62679
62685
  } catch (error) {
62680
- const errorMessage = error instanceof Error ? error.message : String(error);
62686
+ const errorMessage2 = error instanceof Error ? error.message : String(error);
62681
62687
  const displayPath = path2.relative(rootDirectory, filePath).replace(/\\/g, "/");
62682
62688
  return {
62683
- llmContent: `Error reading file ${displayPath}: ${errorMessage}`,
62684
- returnDisplay: `Error reading file ${displayPath}: ${errorMessage}`,
62685
- error: `Error reading file ${filePath}: ${errorMessage}`,
62689
+ llmContent: `Error reading file ${displayPath}: ${errorMessage2}`,
62690
+ returnDisplay: `Error reading file ${displayPath}: ${errorMessage2}`,
62691
+ error: `Error reading file ${filePath}: ${errorMessage2}`,
62686
62692
  errorType: "read_content_failure" /* READ_CONTENT_FAILURE */
62687
62693
  };
62688
62694
  }
@@ -63587,7 +63593,7 @@ __name(getProgrammingLanguage, "getProgrammingLanguage");
63587
63593
 
63588
63594
  // packages/core/src/telemetry/loggers.ts
63589
63595
  init_esbuild_shims();
63590
- var import_api_logs = __toESM(require_src2(), 1);
63596
+ var import_api_logs2 = __toESM(require_src2(), 1);
63591
63597
  init_esm2();
63592
63598
 
63593
63599
  // packages/core/src/utils/internalPromptIds.ts
@@ -63704,17 +63710,31 @@ init_esbuild_shims();
63704
63710
  import * as fs3 from "node:fs/promises";
63705
63711
  import * as path4 from "node:path";
63706
63712
  import * as crypto2 from "node:crypto";
63707
- async function truncateAndSaveToFile(content, fileName, projectTempDir, threshold, truncateLines) {
63713
+ var TOOL_OUTPUT_TRUNCATED_PREFIX = "Tool output was too large and has been truncated";
63714
+ async function truncateAndSaveToFile(content, fileName, projectTempDir, threshold, truncateLines, keep = "both") {
63715
+ if (content.length <= threshold && !Number.isFinite(truncateLines)) {
63716
+ return { content };
63717
+ }
63708
63718
  const lines = content.split("\n");
63709
63719
  if (content.length <= threshold && lines.length <= truncateLines) {
63710
63720
  return { content };
63711
63721
  }
63712
63722
  const effectiveLines = Math.min(truncateLines, lines.length);
63713
- const headCount = Math.max(Math.floor(effectiveLines / 5), 1);
63714
- const tailCount = effectiveLines - headCount;
63723
+ let headCount;
63724
+ let tailCount;
63725
+ if (keep === "head") {
63726
+ headCount = effectiveLines;
63727
+ tailCount = 0;
63728
+ } else if (keep === "tail") {
63729
+ headCount = 0;
63730
+ tailCount = effectiveLines;
63731
+ } else {
63732
+ headCount = Math.max(Math.floor(effectiveLines / 5), 1);
63733
+ tailCount = effectiveLines - headCount;
63734
+ }
63715
63735
  const separator = "\n\n---\n... [CONTENT TRUNCATED] ...\n---\n\n";
63716
63736
  const ellipsis = "...";
63717
- const headBudget = Math.floor(threshold / 5);
63737
+ const headBudget = keep === "head" ? threshold : keep === "tail" ? 0 : Math.floor(threshold / 5);
63718
63738
  const beginning = [];
63719
63739
  let headChars = 0;
63720
63740
  for (let i = 0; i < Math.min(headCount, lines.length); i++) {
@@ -63729,7 +63749,7 @@ async function truncateAndSaveToFile(content, fileName, projectTempDir, threshol
63729
63749
  beginning.push(lines[i]);
63730
63750
  headChars += lines[i].length + 1;
63731
63751
  }
63732
- const tailBudget = Math.max(threshold - headChars - separator.length, 0);
63752
+ const tailBudget = keep === "head" ? 0 : Math.max(threshold - headChars - separator.length, 0);
63733
63753
  const end = [];
63734
63754
  let tailChars = 0;
63735
63755
  const tailStart = Math.max(lines.length - tailCount, beginning.length);
@@ -63738,27 +63758,31 @@ async function truncateAndSaveToFile(content, fileName, projectTempDir, threshol
63738
63758
  if (remaining <= 0) break;
63739
63759
  if (lines[i].length + 1 > remaining) {
63740
63760
  const sliceLen = Math.max(remaining - ellipsis.length, 0);
63741
- end.unshift(ellipsis + lines[i].slice(-sliceLen));
63761
+ end.unshift(ellipsis + (sliceLen > 0 ? lines[i].slice(-sliceLen) : ""));
63742
63762
  tailChars = tailBudget;
63743
63763
  break;
63744
63764
  }
63745
63765
  end.unshift(lines[i]);
63746
63766
  tailChars += lines[i].length + 1;
63747
63767
  }
63748
- const truncatedContent = beginning.join("\n") + separator + end.join("\n");
63768
+ const truncatedContent = keep === "head" ? beginning.join("\n") + separator : keep === "tail" ? separator + end.join("\n") : beginning.join("\n") + separator + end.join("\n");
63749
63769
  const safeFileName = `${path4.basename(fileName)}.output`;
63750
63770
  const outputFile = path4.join(projectTempDir, safeFileName);
63751
- try {
63752
- await fs3.mkdir(projectTempDir, { recursive: true });
63753
- await fs3.writeFile(outputFile, content);
63754
- return {
63755
- content: `Tool output was too large and has been truncated.
63771
+ const wrappedMessage = `${TOOL_OUTPUT_TRUNCATED_PREFIX}.
63756
63772
  The full output has been saved to: ${outputFile}
63757
63773
  To read the complete output, use the ${ReadFileTool.Name} tool with the absolute file path above.
63758
63774
  The truncated output below shows the beginning and end of the content. The marker '... [CONTENT TRUNCATED] ...' indicates where content was removed.
63759
63775
 
63760
63776
  Truncated part of the output:
63761
- ${truncatedContent}`,
63777
+ ${truncatedContent}`;
63778
+ if (wrappedMessage.length >= content.length) {
63779
+ return { content };
63780
+ }
63781
+ try {
63782
+ await fs3.mkdir(projectTempDir, { recursive: true });
63783
+ await fs3.writeFile(outputFile, content, { mode: 384 });
63784
+ return {
63785
+ content: wrappedMessage,
63762
63786
  outputFile
63763
63787
  };
63764
63788
  } catch (_error) {
@@ -63769,12 +63793,16 @@ ${truncatedContent}`,
63769
63793
  }
63770
63794
  }
63771
63795
  __name(truncateAndSaveToFile, "truncateAndSaveToFile");
63772
- async function truncateToolOutput(config, toolName, content) {
63773
- const threshold = config.getTruncateToolOutputThreshold();
63774
- const lines = config.getTruncateToolOutputLines();
63796
+ async function truncateToolOutput(config, toolName, content, limits, promptId) {
63797
+ const threshold = limits?.threshold ?? config.getTruncateToolOutputThreshold();
63798
+ const lines = limits?.lines ?? config.getTruncateToolOutputLines();
63799
+ const keep = limits?.keep ?? "both";
63775
63800
  if (threshold <= 0 || lines <= 0) {
63776
63801
  return { content };
63777
63802
  }
63803
+ if (content.length <= threshold && !Number.isFinite(lines)) {
63804
+ return { content };
63805
+ }
63778
63806
  const originalLength = content.length;
63779
63807
  const fileName = `${toolName}_${crypto2.randomBytes(6).toString("hex")}`;
63780
63808
  const result = await truncateAndSaveToFile(
@@ -63782,23 +63810,65 @@ async function truncateToolOutput(config, toolName, content) {
63782
63810
  fileName,
63783
63811
  config.storage.getProjectTempDir(),
63784
63812
  threshold,
63785
- lines
63813
+ lines,
63814
+ keep
63786
63815
  );
63787
63816
  if (result.outputFile) {
63788
- logToolOutputTruncated(
63789
- config,
63790
- new ToolOutputTruncatedEvent("", {
63791
- toolName,
63792
- originalContentLength: originalLength,
63793
- truncatedContentLength: result.content.length,
63794
- threshold,
63795
- lines
63796
- })
63797
- );
63817
+ try {
63818
+ logToolOutputTruncated(
63819
+ config,
63820
+ new ToolOutputTruncatedEvent(promptId ?? "", {
63821
+ toolName,
63822
+ originalContentLength: originalLength,
63823
+ truncatedContentLength: result.content.length,
63824
+ threshold,
63825
+ lines
63826
+ })
63827
+ );
63828
+ } catch {
63829
+ }
63798
63830
  }
63799
63831
  return result;
63800
63832
  }
63801
63833
  __name(truncateToolOutput, "truncateToolOutput");
63834
+ async function truncateLlmContent(config, toolName, content, limits, promptId) {
63835
+ if (typeof content === "string") {
63836
+ if (content.trim() === "") {
63837
+ return { content: `(${toolName} completed with no output)` };
63838
+ }
63839
+ if (content.startsWith(TOOL_OUTPUT_TRUNCATED_PREFIX)) {
63840
+ return { content };
63841
+ }
63842
+ return truncateToolOutput(config, toolName, content, limits, promptId);
63843
+ }
63844
+ const parts = (Array.isArray(content) ? content : [content]).map(
63845
+ (p) => typeof p === "string" ? { text: p } : p
63846
+ );
63847
+ const textParts = parts.filter((p) => p.text !== void 0);
63848
+ const mediaParts = parts.filter((p) => p.text === void 0);
63849
+ const combined = textParts.map((p) => p.text).join("\n");
63850
+ if (combined.trim() === "" && mediaParts.length === 0) {
63851
+ return { content: `(${toolName} completed with no output)` };
63852
+ }
63853
+ if (textParts.some((p) => p.text?.startsWith(TOOL_OUTPUT_TRUNCATED_PREFIX))) {
63854
+ return { content };
63855
+ }
63856
+ const result = await truncateToolOutput(
63857
+ config,
63858
+ toolName,
63859
+ combined,
63860
+ limits,
63861
+ promptId
63862
+ );
63863
+ if (result.content === combined) {
63864
+ return { content };
63865
+ }
63866
+ return {
63867
+ content: [{ text: result.content }, ...mediaParts],
63868
+ outputFile: result.outputFile
63869
+ };
63870
+ }
63871
+ __name(truncateLlmContent, "truncateLlmContent");
63802
63872
 
63803
63873
  // packages/core/src/tools/mcp-tool.ts
63804
63874
  var debugLogger3 = createDebugLogger("MCP_TOOL");
@@ -63852,8 +63922,7 @@ var DiscoveredMCPToolInvocation = class _DiscoveredMCPToolInvocation extends Bas
63852
63922
  };
63853
63923
  return confirmationDetails;
63854
63924
  }
63855
- // Determine if the response contains tool errors
63856
- // This is needed because CallToolResults should return errors inside the response.
63925
+ // MCP spec: errors are returned inside the CallToolResult, not as exceptions.
63857
63926
  // ref: https://modelcontextprotocol.io/specification/2025-06-18/schema#calltoolresult
63858
63927
  isMCPToolError(rawResponseParts) {
63859
63928
  const functionResponse = rawResponseParts?.[0]?.functionResponse;
@@ -63965,15 +64034,15 @@ var DiscoveredMCPToolInvocation = class _DiscoveredMCPToolInvocation extends Bas
63965
64034
  callToolResult
63966
64035
  );
63967
64036
  if (this.isMCPToolError(rawResponseParts)) {
63968
- const errorMessage = `MCP tool '${this.serverToolName}' reported tool error for function call: ${safeJsonStringify({
64037
+ const errorMessage2 = `MCP tool '${this.serverToolName}' reported tool error for function call: ${safeJsonStringify({
63969
64038
  name: this.serverToolName,
63970
64039
  args: this.params
63971
64040
  })} with response: ${safeJsonStringify(rawResponseParts)}`;
63972
64041
  return {
63973
- llmContent: errorMessage,
64042
+ llmContent: errorMessage2,
63974
64043
  returnDisplay: `Error: MCP tool '${this.serverToolName}' reported an error.`,
63975
64044
  error: {
63976
- message: errorMessage,
64045
+ message: errorMessage2,
63977
64046
  type: "mcp_tool_error" /* MCP_TOOL_ERROR */
63978
64047
  }
63979
64048
  };
@@ -64026,14 +64095,14 @@ var DiscoveredMCPToolInvocation = class _DiscoveredMCPToolInvocation extends Bas
64026
64095
  });
64027
64096
  });
64028
64097
  if (this.isMCPToolError(rawResponseParts)) {
64029
- const errorMessage = `MCP tool '${this.serverToolName}' reported tool error for function call: ${safeJsonStringify(
64098
+ const errorMessage2 = `MCP tool '${this.serverToolName}' reported tool error for function call: ${safeJsonStringify(
64030
64099
  functionCalls[0]
64031
64100
  )} with response: ${safeJsonStringify(rawResponseParts)}`;
64032
64101
  return {
64033
- llmContent: errorMessage,
64102
+ llmContent: errorMessage2,
64034
64103
  returnDisplay: `Error: MCP tool '${this.serverToolName}' reported an error.`,
64035
64104
  error: {
64036
- message: errorMessage,
64105
+ message: errorMessage2,
64037
64106
  type: "mcp_tool_error" /* MCP_TOOL_ERROR */
64038
64107
  }
64039
64108
  };
@@ -64062,7 +64131,14 @@ var DiscoveredMCPToolInvocation = class _DiscoveredMCPToolInvocation extends Bas
64062
64131
  const truncated = await truncateToolOutput(
64063
64132
  this.cliConfig,
64064
64133
  `mcp__${this.serverName}__${this.serverToolName}`,
64065
- part.text
64134
+ part.text,
64135
+ // Per-tool char budget; mirrors DiscoveredMCPTool.maxOutputChars
64136
+ // (10x the global default, since MCP servers return large structured
64137
+ // output). char-only (lines: Infinity) so the global line cap can't
64138
+ // undercut the 500k char budget — many short lines (structured JSON,
64139
+ // tables) would otherwise truncate while chars remain. Consistent
64140
+ // with the shell tool's in-tool truncation.
64141
+ { threshold: 5e5, lines: Number.POSITIVE_INFINITY }
64066
64142
  );
64067
64143
  result.push({ text: truncated.content });
64068
64144
  } else {
@@ -64109,6 +64185,12 @@ var DiscoveredMCPTool = class _DiscoveredMCPTool extends BaseDeclarativeTool {
64109
64185
  static {
64110
64186
  __name(this, "DiscoveredMCPTool");
64111
64187
  }
64188
+ // MCP servers often return large structured payloads; allow 10x the global
64189
+ // budget (mirrors Claude Code's MCP `maxResultSizeChars`) before the
64190
+ // scheduler offloads. truncateTextParts uses the same ceiling per text part.
64191
+ get maxOutputChars() {
64192
+ return 5e5;
64193
+ }
64112
64194
  asFullyQualifiedTool() {
64113
64195
  return new _DiscoveredMCPTool(
64114
64196
  this.mcpTool,
@@ -64124,6 +64206,40 @@ var DiscoveredMCPTool = class _DiscoveredMCPTool extends BaseDeclarativeTool {
64124
64206
  this.annotations
64125
64207
  );
64126
64208
  }
64209
+ /**
64210
+ * Return a clone of this tool with a different `trust` value while
64211
+ * keeping every other field (including the shared underlying
64212
+ * `CallableTool` / MCP transport) identical.
64213
+ *
64214
+ * pool path: a single shared pool entry produces one
64215
+ * `DiscoveredMCPTool` snapshot; each `SessionMcpView` clones with
64216
+ * its own per-session trust before registering into its session's
64217
+ * `ToolRegistry`. Without this clone, mutating `trust` on the shared
64218
+ * instance would cross-contaminate sessions.
64219
+ *
64220
+ * Trust is the only field that legitimately varies per session;
64221
+ * everything else (transport, schema, name) is transport-level.
64222
+ */
64223
+ withTrust(trust) {
64224
+ if (trust === this.trust) return this;
64225
+ return new _DiscoveredMCPTool(
64226
+ this.mcpTool,
64227
+ this.serverName,
64228
+ this.serverToolName,
64229
+ this.description,
64230
+ this.parameterSchema,
64231
+ trust,
64232
+ // Preserve the original name (do NOT re-call generateValidName)
64233
+ // — equal-by-name is the registry's deduplication key, and a
64234
+ // different name would race-register two tools in the same
64235
+ // session.
64236
+ this.name,
64237
+ this.cliConfig,
64238
+ this.mcpClient,
64239
+ this.mcpTimeout,
64240
+ this.annotations
64241
+ );
64242
+ }
64127
64243
  createInvocation(params) {
64128
64244
  return new DiscoveredMCPToolInvocation(
64129
64245
  this.mcpTool,
@@ -66717,8 +66833,8 @@ var FileLogExporter = class extends FileExporter {
66717
66833
  static {
66718
66834
  __name(this, "FileLogExporter");
66719
66835
  }
66720
- export(logs2, resultCallback) {
66721
- const data = logs2.map((log) => this.serialize(log)).join("");
66836
+ export(logs3, resultCallback) {
66837
+ const data = logs3.map((log) => this.serialize(log)).join("");
66722
66838
  this.writeStream.write(data, (err) => {
66723
66839
  resultCallback({
66724
66840
  code: err ? import_core3.ExportResultCode.FAILED : import_core3.ExportResultCode.SUCCESS,
@@ -66925,11 +67041,7 @@ function resolveParentContext(parent) {
66925
67041
  if (parent) {
66926
67042
  return trace.setSpan(context.active(), parent.span);
66927
67043
  }
66928
- const active = context.active();
66929
- if (trace.getSpan(active)) {
66930
- return active;
66931
- }
66932
- return getSessionContext() ?? active;
67044
+ return context.active();
66933
67045
  }
66934
67046
  __name(resolveParentContext, "resolveParentContext");
66935
67047
  var NOOP_SPAN = trace.wrapSpanContext({
@@ -66945,6 +67057,11 @@ function isInNativeSubagentSpan() {
66945
67057
  return ctx !== void 0 && !ctx.ended;
66946
67058
  }
66947
67059
  __name(isInNativeSubagentSpan, "isInNativeSubagentSpan");
67060
+ function resolveSessionId(parentCtx) {
67061
+ const fromParent = parentCtx?.attributes?.["session.id"];
67062
+ return typeof fromParent === "string" && fromParent ? fromParent : getCurrentSessionId();
67063
+ }
67064
+ __name(resolveSessionId, "resolveSessionId");
66948
67065
  var activeSpans = /* @__PURE__ */ new Map();
66949
67066
  var strongSpans = /* @__PURE__ */ new Map();
66950
67067
  var interactionSequence = 0;
@@ -67059,11 +67176,10 @@ function startInteractionSpan(config, options) {
67059
67176
  "qwen-code.approval_mode": config.getApprovalMode(),
67060
67177
  "interaction.sequence": interactionSequence
67061
67178
  };
67062
- const sessionCtx = getSessionContext() ?? context.active();
67063
67179
  const span = getTracer().startSpan(
67064
67180
  SPAN_INTERACTION,
67065
67181
  { kind: SpanKind.INTERNAL, attributes },
67066
- sessionCtx
67182
+ ROOT_CONTEXT
67067
67183
  );
67068
67184
  const spanId = getSpanId(span);
67069
67185
  const spanContextObj = {
@@ -67109,13 +67225,90 @@ function endInteractionSpan(status, metadata) {
67109
67225
  interactionContext.enterWith(void 0);
67110
67226
  }
67111
67227
  __name(endInteractionSpan, "endInteractionSpan");
67228
+ async function withInteractionSpan(config, options, fn, getResultStatus) {
67229
+ if (!isTelemetrySdkInitialized()) return await fn();
67230
+ ensureCleanupInterval();
67231
+ interactionSequence++;
67232
+ const attributes = {
67233
+ "session.id": config.getSessionId(),
67234
+ "qwen-code.prompt_id": options.promptId,
67235
+ "qwen-code.message_type": options.messageType,
67236
+ "qwen-code.model": options.model,
67237
+ "qwen-code.approval_mode": config.getApprovalMode(),
67238
+ "interaction.sequence": interactionSequence
67239
+ };
67240
+ const parentContext = options.parentContext ?? ROOT_CONTEXT;
67241
+ const span = getTracer().startSpan(
67242
+ SPAN_INTERACTION,
67243
+ {
67244
+ kind: SpanKind.INTERNAL,
67245
+ attributes
67246
+ },
67247
+ parentContext
67248
+ );
67249
+ const spanId = getSpanId(span);
67250
+ const spanContextObj = {
67251
+ span,
67252
+ startTime: Date.now(),
67253
+ attributes,
67254
+ type: "interaction"
67255
+ };
67256
+ activeSpans.set(spanId, new WeakRef(spanContextObj));
67257
+ strongSpans.set(spanId, spanContextObj);
67258
+ const activeContext = trace.setSpan(parentContext, span);
67259
+ return await context.with(
67260
+ activeContext,
67261
+ async () => interactionContext.run(spanContextObj, async () => {
67262
+ let terminalStatus = "ok";
67263
+ let errorStatusSet = false;
67264
+ try {
67265
+ const result = await fn();
67266
+ terminalStatus = getResultStatus?.(result) ?? "ok";
67267
+ return result;
67268
+ } catch (error) {
67269
+ terminalStatus = "error";
67270
+ span.setStatus({
67271
+ code: SpanStatusCode.ERROR,
67272
+ message: truncateSpanError(
67273
+ error instanceof Error ? error.message : String(error)
67274
+ )
67275
+ });
67276
+ errorStatusSet = true;
67277
+ throw error;
67278
+ } finally {
67279
+ if (!spanContextObj.ended) {
67280
+ spanContextObj.ended = true;
67281
+ const duration = Date.now() - spanContextObj.startTime;
67282
+ span.setAttributes({
67283
+ "interaction.duration_ms": duration,
67284
+ "qwen-code.turn_status": terminalStatus
67285
+ });
67286
+ if (terminalStatus === "ok") {
67287
+ span.setStatus({ code: SpanStatusCode.OK });
67288
+ } else if (terminalStatus === "error" && !errorStatusSet) {
67289
+ span.setStatus({
67290
+ code: SpanStatusCode.ERROR,
67291
+ message: "interaction error"
67292
+ });
67293
+ }
67294
+ span.end();
67295
+ activeSpans.delete(spanId);
67296
+ strongSpans.delete(spanId);
67297
+ }
67298
+ }
67299
+ })
67300
+ );
67301
+ }
67302
+ __name(withInteractionSpan, "withInteractionSpan");
67112
67303
  function startLLMRequestSpan(model, promptId) {
67113
67304
  if (!isTelemetrySdkInitialized()) {
67114
67305
  return NOOP_SPAN;
67115
67306
  }
67116
67307
  const parentCtx = subagentContext.getStore() ?? interactionContext.getStore();
67117
67308
  const ctx = resolveParentContext(parentCtx);
67309
+ const sessionId = resolveSessionId(parentCtx);
67118
67310
  const attributes = {
67311
+ ...sessionId ? { "session.id": sessionId } : {},
67119
67312
  "qwen-code.model": model,
67120
67313
  "qwen-code.prompt_id": promptId,
67121
67314
  "llm_request.context": subagentContext.getStore() ? "subagent" : interactionContext.getStore() ? "interaction" : "standalone",
@@ -67191,6 +67384,30 @@ function endLLMRequestSpan(span, metadata) {
67191
67384
  endAttributes["success"] = metadata.success;
67192
67385
  if (metadata.error !== void 0)
67193
67386
  endAttributes["error"] = truncateSpanError(metadata.error);
67387
+ if (metadata.responseId !== void 0) {
67388
+ endAttributes["response_id"] = metadata.responseId;
67389
+ endAttributes["gen_ai.response.id"] = metadata.responseId;
67390
+ }
67391
+ if (metadata.finishReason !== void 0) {
67392
+ endAttributes["finish_reason"] = metadata.finishReason;
67393
+ endAttributes["gen_ai.response.finish_reasons"] = [
67394
+ metadata.finishReason
67395
+ ];
67396
+ }
67397
+ if (metadata.thoughtsTokenCount !== void 0) {
67398
+ endAttributes["thoughts_token_count"] = metadata.thoughtsTokenCount;
67399
+ endAttributes["gen_ai.usage.reasoning_tokens"] = metadata.thoughtsTokenCount;
67400
+ }
67401
+ if (metadata.subagentName !== void 0) {
67402
+ endAttributes["subagent_name"] = metadata.subagentName;
67403
+ }
67404
+ if (metadata.errorType !== void 0) {
67405
+ endAttributes["error_type"] = metadata.errorType;
67406
+ endAttributes["error.type"] = metadata.errorType;
67407
+ }
67408
+ if (metadata.errorStatusCode !== void 0) {
67409
+ endAttributes["error_status_code"] = metadata.errorStatusCode;
67410
+ }
67194
67411
  }
67195
67412
  spanCtx.span.setAttributes(endAttributes);
67196
67413
  if (metadata === void 0 || metadata.success) {
@@ -67223,7 +67440,9 @@ function startToolSpan(toolName, attrs) {
67223
67440
  }
67224
67441
  const parentCtx = subagentContext.getStore() ?? interactionContext.getStore();
67225
67442
  const ctx = resolveParentContext(parentCtx);
67443
+ const sessionId = resolveSessionId(parentCtx);
67226
67444
  const attributes = {
67445
+ ...sessionId ? { "session.id": sessionId } : {},
67227
67446
  "tool.name": toolName,
67228
67447
  ...attrs
67229
67448
  };
@@ -67310,16 +67529,22 @@ function startToolExecutionSpan() {
67310
67529
  );
67311
67530
  }
67312
67531
  const ctx = resolveParentContext(parentCtx);
67532
+ const sessionId = resolveSessionId(
67533
+ parentCtx ?? interactionContext.getStore()
67534
+ );
67313
67535
  const span = getTracer().startSpan(
67314
67536
  SPAN_TOOL_EXECUTION,
67315
- { kind: SpanKind.INTERNAL },
67537
+ {
67538
+ kind: SpanKind.INTERNAL,
67539
+ attributes: sessionId ? { "session.id": sessionId } : {}
67540
+ },
67316
67541
  ctx
67317
67542
  );
67318
67543
  const spanId = getSpanId(span);
67319
67544
  const spanContextObj = {
67320
67545
  span,
67321
67546
  startTime: Date.now(),
67322
- attributes: {},
67547
+ attributes: sessionId ? { "session.id": sessionId } : {},
67323
67548
  type: "tool.execution"
67324
67549
  };
67325
67550
  activeSpans.set(spanId, new WeakRef(spanContextObj));
@@ -68079,6 +68304,7 @@ var NOOP_PROPAGATOR = {
68079
68304
  var sdk;
68080
68305
  var telemetryInitialized = false;
68081
68306
  var telemetryShutdownPromise;
68307
+ var activeMetricReader;
68082
68308
  function isTelemetrySdkInitialized() {
68083
68309
  return telemetryInitialized;
68084
68310
  }
@@ -68121,6 +68347,27 @@ function validateUrl(url) {
68121
68347
  }
68122
68348
  }
68123
68349
  __name(validateUrl, "validateUrl");
68350
+ var SessionIdSpanProcessor = class {
68351
+ static {
68352
+ __name(this, "SessionIdSpanProcessor");
68353
+ }
68354
+ onStart(span) {
68355
+ try {
68356
+ if (span.attributes?.["session.id"]) return;
68357
+ const sessionId = getCurrentSessionId();
68358
+ if (sessionId) {
68359
+ span.setAttribute("session.id", sessionId);
68360
+ }
68361
+ } catch {
68362
+ }
68363
+ }
68364
+ onEnd(_span) {
68365
+ }
68366
+ async shutdown() {
68367
+ }
68368
+ async forceFlush() {
68369
+ }
68370
+ };
68124
68371
  function initializeTelemetry(config) {
68125
68372
  if (telemetryInitialized || !config.getTelemetryEnabled()) {
68126
68373
  return;
@@ -68190,7 +68437,7 @@ function initializeTelemetry(config) {
68190
68437
  // In interactive (TUI) mode, route bridge diagnostics to the OTEL
68191
68438
  // debug log file so they don't break out of the Ink render area
68192
68439
  // via raw stderr. In non-interactive mode, leave the default sink
68193
- // alone so CI / scripts can still see export failures on stderr
68440
+ // alone so CI / scripts can still see export failures on stderr
68194
68441
  // the canonical diagnostic channel for batch runs.
68195
68442
  //
68196
68443
  // Caveat for interactive mode: when the user has explicitly
@@ -68291,15 +68538,14 @@ function initializeTelemetry(config) {
68291
68538
  // before the detectors settle (e.g. during HttpInstrumentation span creation).
68292
68539
  autoDetectResources: false,
68293
68540
  ...textMapPropagator && { textMapPropagator },
68294
- spanProcessors: spanExporter ? [new import_sdk_trace_node.BatchSpanProcessor(spanExporter)] : [],
68541
+ spanProcessors: spanExporter ? [new SessionIdSpanProcessor(), new import_sdk_trace_node.BatchSpanProcessor(spanExporter)] : [],
68295
68542
  logRecordProcessors: logExporter ? [new import_sdk_logs.BatchLogRecordProcessor(logExporter)] : logToSpanProcessor ? [logToSpanProcessor] : [],
68296
68543
  ...metricReader && { metricReader },
68297
68544
  instrumentations: [
68298
68545
  new import_instrumentation_http.HttpInstrumentation({
68299
68546
  // OTLP HTTP exporter uses node:http (patched here, not by undici).
68300
68547
  // Without this, every OTLP upload batch creates a parasitic client
68301
- // span that itself gets exported → feedback loop. See PR #4390
68302
- // review feedback (wenshao).
68548
+ // span that itself gets exported → feedback loop.
68303
68549
  ignoreOutgoingRequestHook: /* @__PURE__ */ __name((req) => {
68304
68550
  if (otlpUrlPrefixes.length === 0) return false;
68305
68551
  const proto = req.protocol ? String(req.protocol).replace(/:$/, "") : void 0;
@@ -68339,8 +68585,12 @@ function initializeTelemetry(config) {
68339
68585
  sdk.start();
68340
68586
  debugLogger12.debug("OpenTelemetry SDK started successfully.");
68341
68587
  telemetryInitialized = true;
68588
+ activeMetricReader = metricReader;
68342
68589
  const sessionId = config.getSessionId();
68343
68590
  setSessionContext(createSessionRootContext(sessionId), sessionId);
68591
+ setShellTracePropagation(
68592
+ config.getOutboundCorrelationPropagateTraceContext()
68593
+ );
68344
68594
  initializeMetrics(config);
68345
68595
  } catch (error) {
68346
68596
  debugLogger12.error("Error starting OpenTelemetry SDK:", error);
@@ -68402,13 +68652,40 @@ async function shutdownTelemetry() {
68402
68652
  } finally {
68403
68653
  telemetryInitialized = false;
68404
68654
  sdk = void 0;
68655
+ activeMetricReader = void 0;
68405
68656
  telemetryShutdownPromise = void 0;
68406
68657
  setSessionContext(void 0);
68658
+ setShellTracePropagation(false);
68407
68659
  }
68408
68660
  })();
68409
68661
  return telemetryShutdownPromise;
68410
68662
  }
68411
68663
  __name(shutdownTelemetry, "shutdownTelemetry");
68664
+ var FORCE_FLUSH_TIMEOUT_MS = 2e3;
68665
+ async function forceFlushMetrics() {
68666
+ if (!telemetryInitialized || !activeMetricReader) return;
68667
+ const flush = activeMetricReader.forceFlush();
68668
+ flush.catch(() => {
68669
+ });
68670
+ let timer;
68671
+ const timeout = new Promise((_, reject) => {
68672
+ timer = setTimeout(
68673
+ () => reject(
68674
+ new Error(
68675
+ `forceFlushMetrics timed out after ${FORCE_FLUSH_TIMEOUT_MS}ms`
68676
+ )
68677
+ ),
68678
+ FORCE_FLUSH_TIMEOUT_MS
68679
+ );
68680
+ timer.unref?.();
68681
+ });
68682
+ try {
68683
+ await Promise.race([flush, timeout]);
68684
+ } finally {
68685
+ clearTimeout(timer);
68686
+ }
68687
+ }
68688
+ __name(forceFlushMetrics, "forceFlushMetrics");
68412
68689
 
68413
68690
  // packages/core/src/telemetry/config.ts
68414
68691
  init_esbuild_shims();
@@ -68650,26 +68927,24 @@ var createInitialMetrics = /* @__PURE__ */ __name(() => ({
68650
68927
  totalLinesRemoved: 0
68651
68928
  }
68652
68929
  }), "createInitialMetrics");
68653
- var UiTelemetryService = class extends EventEmitter {
68930
+ var UiTelemetryService = class _UiTelemetryService extends EventEmitter {
68654
68931
  static {
68655
68932
  __name(this, "UiTelemetryService");
68656
68933
  }
68934
+ static #MAX_CLOSED_SESSIONS = 1e3;
68657
68935
  #metrics = createInitialMetrics();
68936
+ #sessionMetrics = /* @__PURE__ */ new Map();
68937
+ #closedSessions = /* @__PURE__ */ new Set();
68658
68938
  #lastPromptTokenCount = 0;
68659
68939
  #lastCachedContentTokenCount = 0;
68660
- addEvent(event) {
68661
- switch (event["event.name"]) {
68662
- case EVENT_API_RESPONSE:
68663
- this.processApiResponse(event);
68664
- break;
68665
- case EVENT_API_ERROR:
68666
- this.processApiError(event);
68667
- break;
68668
- case EVENT_TOOL_CALL:
68669
- this.processToolCall(event);
68670
- break;
68671
- default:
68672
- return;
68940
+ #sessionStartTime = /* @__PURE__ */ new Date();
68941
+ addEvent(event, sessionId) {
68942
+ if (!this.#accumulateEvent(this.#metrics, event)) return;
68943
+ if (sessionId && !this.#closedSessions.has(sessionId)) {
68944
+ if (!this.#sessionMetrics.has(sessionId)) {
68945
+ this.#sessionMetrics.set(sessionId, createInitialMetrics());
68946
+ }
68947
+ this.#accumulateEvent(this.#sessionMetrics.get(sessionId), event);
68673
68948
  }
68674
68949
  this.emit("update", {
68675
68950
  metrics: this.#metrics,
@@ -68679,6 +68954,9 @@ var UiTelemetryService = class extends EventEmitter {
68679
68954
  getMetrics() {
68680
68955
  return this.#metrics;
68681
68956
  }
68957
+ getMetricsForSession(sessionId) {
68958
+ return this.#sessionMetrics.get(sessionId) ?? createInitialMetrics();
68959
+ }
68682
68960
  getLastPromptTokenCount() {
68683
68961
  return this.#lastPromptTokenCount;
68684
68962
  }
@@ -68689,6 +68967,9 @@ var UiTelemetryService = class extends EventEmitter {
68689
68967
  lastPromptTokenCount: this.#lastPromptTokenCount
68690
68968
  });
68691
68969
  }
68970
+ getSessionStartTime() {
68971
+ return this.#sessionStartTime;
68972
+ }
68692
68973
  getLastCachedContentTokenCount() {
68693
68974
  return this.#lastCachedContentTokenCount;
68694
68975
  }
@@ -68700,28 +68981,46 @@ var UiTelemetryService = class extends EventEmitter {
68700
68981
  */
68701
68982
  reset() {
68702
68983
  this.#metrics = createInitialMetrics();
68984
+ this.#sessionMetrics.clear();
68985
+ this.#closedSessions.clear();
68703
68986
  this.#lastPromptTokenCount = 0;
68704
68987
  this.#lastCachedContentTokenCount = 0;
68988
+ this.#sessionStartTime = /* @__PURE__ */ new Date();
68705
68989
  this.emit("update", {
68706
68990
  metrics: this.#metrics,
68707
68991
  lastPromptTokenCount: this.#lastPromptTokenCount
68708
68992
  });
68709
68993
  }
68710
- getOrCreateModelMetrics(modelName) {
68711
- if (!this.#metrics.models[modelName]) {
68712
- this.#metrics.models[modelName] = createInitialModelMetrics();
68994
+ resetSession(sessionId) {
68995
+ this.#sessionMetrics.set(sessionId, createInitialMetrics());
68996
+ this.#closedSessions.delete(sessionId);
68997
+ }
68998
+ removeSession(sessionId) {
68999
+ this.#sessionMetrics.delete(sessionId);
69000
+ this.#closedSessions.add(sessionId);
69001
+ if (this.#closedSessions.size > _UiTelemetryService.#MAX_CLOSED_SESSIONS) {
69002
+ const oldest = this.#closedSessions.values().next().value;
69003
+ if (oldest) this.#closedSessions.delete(oldest);
68713
69004
  }
68714
- return this.#metrics.models[modelName];
68715
69005
  }
68716
- getOrCreateSourceMetrics(modelMetrics, source) {
68717
- if (!modelMetrics.bySource[source]) {
68718
- modelMetrics.bySource[source] = createInitialModelMetricsCore();
69006
+ #accumulateEvent(metrics2, event) {
69007
+ switch (event["event.name"]) {
69008
+ case EVENT_API_RESPONSE:
69009
+ this.#accumulateApiResponse(metrics2, event);
69010
+ return true;
69011
+ case EVENT_API_ERROR:
69012
+ this.#accumulateApiError(metrics2, event);
69013
+ return true;
69014
+ case EVENT_TOOL_CALL:
69015
+ this.#accumulateToolCall(metrics2, event);
69016
+ return true;
69017
+ default:
69018
+ return false;
68719
69019
  }
68720
- return modelMetrics.bySource[source];
68721
69020
  }
68722
- processApiResponse(event) {
68723
- const modelMetrics = this.getOrCreateModelMetrics(event.model);
68724
- const sourceMetrics = this.getOrCreateSourceMetrics(
69021
+ #accumulateApiResponse(metrics2, event) {
69022
+ const modelMetrics = this.#getOrCreateModelMetrics(metrics2, event.model);
69023
+ const sourceMetrics = this.#getOrCreateSourceMetrics(
68725
69024
  modelMetrics,
68726
69025
  event.subagent_name ?? MAIN_SOURCE
68727
69026
  );
@@ -68735,9 +69034,9 @@ var UiTelemetryService = class extends EventEmitter {
68735
69034
  bucket.tokens.thoughts += event.thoughts_token_count;
68736
69035
  }
68737
69036
  }
68738
- processApiError(event) {
68739
- const modelMetrics = this.getOrCreateModelMetrics(event.model);
68740
- const sourceMetrics = this.getOrCreateSourceMetrics(
69037
+ #accumulateApiError(metrics2, event) {
69038
+ const modelMetrics = this.#getOrCreateModelMetrics(metrics2, event.model);
69039
+ const sourceMetrics = this.#getOrCreateSourceMetrics(
68741
69040
  modelMetrics,
68742
69041
  event.subagent_name ?? MAIN_SOURCE
68743
69042
  );
@@ -68747,8 +69046,8 @@ var UiTelemetryService = class extends EventEmitter {
68747
69046
  bucket.api.totalLatencyMs += event.duration_ms;
68748
69047
  }
68749
69048
  }
68750
- processToolCall(event) {
68751
- const { tools, files } = this.#metrics;
69049
+ #accumulateToolCall(metrics2, event) {
69050
+ const { tools, files } = metrics2;
68752
69051
  tools.totalCalls++;
68753
69052
  tools.totalDurationMs += event.duration_ms;
68754
69053
  if (event.success) {
@@ -68791,9 +69090,490 @@ var UiTelemetryService = class extends EventEmitter {
68791
69090
  }
68792
69091
  }
68793
69092
  }
69093
+ #getOrCreateModelMetrics(metrics2, modelName) {
69094
+ if (!metrics2.models[modelName]) {
69095
+ metrics2.models[modelName] = createInitialModelMetrics();
69096
+ }
69097
+ return metrics2.models[modelName];
69098
+ }
69099
+ #getOrCreateSourceMetrics(modelMetrics, source) {
69100
+ if (!modelMetrics.bySource[source]) {
69101
+ modelMetrics.bySource[source] = createInitialModelMetricsCore();
69102
+ }
69103
+ return modelMetrics.bySource[source];
69104
+ }
68794
69105
  };
68795
69106
  var uiTelemetryService = new UiTelemetryService();
68796
69107
 
69108
+ // packages/core/src/telemetry/daemon-tracing.ts
69109
+ init_esbuild_shims();
69110
+ init_esm();
69111
+ var import_api_logs = __toESM(require_src2(), 1);
69112
+ import { createHash as createHash3 } from "node:crypto";
69113
+ var DAEMON_TRACEPARENT_META_KEY = "qwen.telemetry.traceparent";
69114
+ var DAEMON_TRACESTATE_META_KEY = "qwen.telemetry.tracestate";
69115
+ var SPAN_DAEMON_REQUEST = "qwen-code.daemon.request";
69116
+ var SPAN_DAEMON_BRIDGE = "qwen-code.daemon.bridge";
69117
+ var EVENT_DAEMON_ERROR = "qwen-code.daemon.error";
69118
+ function errorMessage(error) {
69119
+ if (error instanceof Error) return error.message;
69120
+ return String(error);
69121
+ }
69122
+ __name(errorMessage, "errorMessage");
69123
+ function errorType(error) {
69124
+ if (error instanceof Error) return error.name || "Error";
69125
+ return typeof error;
69126
+ }
69127
+ __name(errorType, "errorType");
69128
+ var INVALID_TRACE_ID = "0".repeat(32);
69129
+ var INVALID_SPAN_ID = "0".repeat(16);
69130
+ function activeSpanContextIsValid() {
69131
+ const span = trace.getSpan(context.active());
69132
+ if (!span) return false;
69133
+ const ctx = span.spanContext();
69134
+ return ctx.traceId !== INVALID_TRACE_ID && ctx.spanId !== INVALID_SPAN_ID;
69135
+ }
69136
+ __name(activeSpanContextIsValid, "activeSpanContextIsValid");
69137
+ function stripReservedTraceMeta(meta) {
69138
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) return {};
69139
+ const record = meta;
69140
+ if (!(DAEMON_TRACEPARENT_META_KEY in record) && !(DAEMON_TRACESTATE_META_KEY in record)) {
69141
+ return { ...record };
69142
+ }
69143
+ const out = { ...record };
69144
+ delete out[DAEMON_TRACEPARENT_META_KEY];
69145
+ delete out[DAEMON_TRACESTATE_META_KEY];
69146
+ return out;
69147
+ }
69148
+ __name(stripReservedTraceMeta, "stripReservedTraceMeta");
69149
+ function hashDaemonWorkspace(workspace) {
69150
+ return createHash3("sha256").update(workspace).digest("hex").slice(0, 16);
69151
+ }
69152
+ __name(hashDaemonWorkspace, "hashDaemonWorkspace");
69153
+ async function withDaemonSpan(name, attributes, fn, options = {}) {
69154
+ if (!isTelemetrySdkInitialized()) {
69155
+ return await fn(void 0);
69156
+ }
69157
+ const autoOkOnSuccess = options.autoOkOnSuccess ?? true;
69158
+ const tracer2 = trace.getTracer(SERVICE_NAME);
69159
+ return await tracer2.startActiveSpan(
69160
+ name,
69161
+ { kind: SpanKind.INTERNAL, attributes },
69162
+ async (span) => {
69163
+ try {
69164
+ const result = await fn(span);
69165
+ if (autoOkOnSuccess) {
69166
+ span.setStatus({ code: SpanStatusCode.OK });
69167
+ }
69168
+ return result;
69169
+ } catch (error) {
69170
+ recordDaemonError(span, error);
69171
+ throw error;
69172
+ } finally {
69173
+ span.end();
69174
+ }
69175
+ }
69176
+ );
69177
+ }
69178
+ __name(withDaemonSpan, "withDaemonSpan");
69179
+ async function withDaemonRequestSpan(options, fn) {
69180
+ return await withDaemonSpan(
69181
+ SPAN_DAEMON_REQUEST,
69182
+ {
69183
+ "http.request.method": options.method,
69184
+ "http.route": options.route,
69185
+ "qwen-code.daemon.operation": "http_request",
69186
+ ...options.workspaceHash ? { "qwen-code.workspace.hash": options.workspaceHash } : {},
69187
+ ...options.sessionId ? { "session.id": options.sessionId } : {},
69188
+ ...options.clientId ? { "qwen-code.client_id": options.clientId } : {},
69189
+ ...options.permissionRequestId ? {
69190
+ "qwen-code.daemon.permission.request_id": options.permissionRequestId
69191
+ } : {}
69192
+ },
69193
+ fn,
69194
+ { autoOkOnSuccess: false }
69195
+ );
69196
+ }
69197
+ __name(withDaemonRequestSpan, "withDaemonRequestSpan");
69198
+ async function withDaemonBridgeSpan(operation, attributes, fn) {
69199
+ return await withDaemonSpan(
69200
+ SPAN_DAEMON_BRIDGE,
69201
+ {
69202
+ "qwen-code.daemon.operation": operation,
69203
+ ...attributes
69204
+ },
69205
+ async () => await fn()
69206
+ );
69207
+ }
69208
+ __name(withDaemonBridgeSpan, "withDaemonBridgeSpan");
69209
+ function recordDaemonHttpResponse(span, statusCode) {
69210
+ try {
69211
+ span?.setAttribute("http.response.status_code", statusCode);
69212
+ } catch {
69213
+ }
69214
+ }
69215
+ __name(recordDaemonHttpResponse, "recordDaemonHttpResponse");
69216
+ function addDaemonRequestAttribute(key, value) {
69217
+ try {
69218
+ trace.getSpan(context.active())?.setAttribute(key, value);
69219
+ } catch {
69220
+ }
69221
+ }
69222
+ __name(addDaemonRequestAttribute, "addDaemonRequestAttribute");
69223
+ function recordDaemonError(span, error, attributes = {}) {
69224
+ const target = span ?? trace.getSpan(context.active());
69225
+ if (!target) return;
69226
+ try {
69227
+ const message = truncateSpanError(errorMessage(error));
69228
+ target.recordException(error instanceof Error ? error : new Error(message));
69229
+ target.setAttributes({
69230
+ "error.type": errorType(error),
69231
+ "error.message": message,
69232
+ ...attributes
69233
+ });
69234
+ target.setStatus({ code: SpanStatusCode.ERROR, message });
69235
+ } catch {
69236
+ }
69237
+ }
69238
+ __name(recordDaemonError, "recordDaemonError");
69239
+ function emitDaemonLog(body, attributes = {}, options) {
69240
+ if (!isTelemetrySdkInitialized()) return;
69241
+ try {
69242
+ import_api_logs.logs.getLogger(SERVICE_NAME).emit({
69243
+ body,
69244
+ timestamp: /* @__PURE__ */ new Date(),
69245
+ attributes: {
69246
+ "event.name": options?.eventName ?? EVENT_DAEMON_ERROR,
69247
+ ...attributes
69248
+ },
69249
+ ...options?.severityNumber != null ? { severityNumber: options.severityNumber } : {}
69250
+ });
69251
+ } catch {
69252
+ }
69253
+ }
69254
+ __name(emitDaemonLog, "emitDaemonLog");
69255
+ function captureDaemonTelemetryContext() {
69256
+ return { context: context.active() };
69257
+ }
69258
+ __name(captureDaemonTelemetryContext, "captureDaemonTelemetryContext");
69259
+ async function runWithDaemonTelemetryContext(captured, fn) {
69260
+ const ctx = captured && typeof captured === "object" && "context" in captured && captured.context ? captured.context : void 0;
69261
+ if (!ctx) return await fn();
69262
+ return await context.with(ctx, fn);
69263
+ }
69264
+ __name(runWithDaemonTelemetryContext, "runWithDaemonTelemetryContext");
69265
+ function injectDaemonTraceContext(request4) {
69266
+ const currentMeta = request4._meta;
69267
+ if (!activeSpanContextIsValid()) {
69268
+ return currentMeta ? { ...request4, _meta: stripReservedTraceMeta(currentMeta) } : request4;
69269
+ }
69270
+ const nextMeta = stripReservedTraceMeta(currentMeta);
69271
+ try {
69272
+ const carrier = {};
69273
+ propagation.inject(context.active(), carrier);
69274
+ if (carrier["traceparent"]) {
69275
+ nextMeta[DAEMON_TRACEPARENT_META_KEY] = carrier["traceparent"];
69276
+ }
69277
+ if (carrier["tracestate"]) {
69278
+ nextMeta[DAEMON_TRACESTATE_META_KEY] = carrier["tracestate"];
69279
+ }
69280
+ } catch {
69281
+ }
69282
+ if (!currentMeta && !nextMeta[DAEMON_TRACEPARENT_META_KEY]) {
69283
+ return request4;
69284
+ }
69285
+ return {
69286
+ ...request4,
69287
+ _meta: nextMeta
69288
+ };
69289
+ }
69290
+ __name(injectDaemonTraceContext, "injectDaemonTraceContext");
69291
+ function extractDaemonTraceContext(source) {
69292
+ const meta = source?._meta;
69293
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
69294
+ return void 0;
69295
+ }
69296
+ const record = meta;
69297
+ const traceparent = record[DAEMON_TRACEPARENT_META_KEY];
69298
+ if (typeof traceparent !== "string" || traceparent.length === 0) {
69299
+ return void 0;
69300
+ }
69301
+ const carrier = { traceparent };
69302
+ const tracestate = record[DAEMON_TRACESTATE_META_KEY];
69303
+ if (typeof tracestate === "string" && tracestate.length > 0) {
69304
+ carrier["tracestate"] = tracestate;
69305
+ }
69306
+ const extracted = propagation.extract(ROOT_CONTEXT, carrier);
69307
+ if (trace.getSpanContext(extracted)) return extracted;
69308
+ const parts = traceparent.split("-");
69309
+ const traceId = parts[1];
69310
+ const spanId = parts[2];
69311
+ const flags = parts[3];
69312
+ if (parts[0] !== "00" || !traceId?.match(/^[0-9a-f]{32}$/) || !spanId?.match(/^[0-9a-f]{16}$/) || !flags?.match(/^[0-9a-f]{2}$/) || traceId === INVALID_TRACE_ID || spanId === INVALID_SPAN_ID) {
69313
+ return void 0;
69314
+ }
69315
+ return trace.setSpan(
69316
+ ROOT_CONTEXT,
69317
+ trace.wrapSpanContext({
69318
+ traceId,
69319
+ spanId,
69320
+ traceFlags: Number.parseInt(flags, 16),
69321
+ isRemote: true
69322
+ })
69323
+ );
69324
+ }
69325
+ __name(extractDaemonTraceContext, "extractDaemonTraceContext");
69326
+ function createDaemonBridgeTelemetry() {
69327
+ return {
69328
+ captureContext: captureDaemonTelemetryContext,
69329
+ runWithContext: runWithDaemonTelemetryContext,
69330
+ withSpan: withDaemonBridgeSpan,
69331
+ event(name, attributes) {
69332
+ if (!isTelemetrySdkInitialized()) return;
69333
+ try {
69334
+ const activeSpan = trace.getSpan(context.active());
69335
+ if (activeSpan) {
69336
+ activeSpan.addEvent(name, attributes);
69337
+ return;
69338
+ }
69339
+ const span = trace.getTracer(SERVICE_NAME).startSpan(SPAN_DAEMON_BRIDGE, {
69340
+ kind: SpanKind.INTERNAL,
69341
+ attributes: {
69342
+ "event.name": name,
69343
+ "qwen-code.daemon.operation": `event.${name}`,
69344
+ ...attributes
69345
+ }
69346
+ });
69347
+ span.addEvent(name, attributes);
69348
+ span.setStatus({ code: SpanStatusCode.OK });
69349
+ span.end();
69350
+ } catch {
69351
+ }
69352
+ },
69353
+ injectPromptContext: injectDaemonTraceContext
69354
+ };
69355
+ }
69356
+ __name(createDaemonBridgeTelemetry, "createDaemonBridgeTelemetry");
69357
+
69358
+ // packages/core/src/telemetry/daemon-metrics.ts
69359
+ init_esbuild_shims();
69360
+ init_esm();
69361
+ var DAEMON_HTTP_REQUEST_COUNT = `${SERVICE_NAME}.daemon.http.request.count`;
69362
+ var DAEMON_HTTP_REQUEST_DURATION = `${SERVICE_NAME}.daemon.http.request.duration`;
69363
+ var DAEMON_SESSION_ACTIVE = `${SERVICE_NAME}.daemon.session.active`;
69364
+ var DAEMON_SESSION_LIFECYCLE = `${SERVICE_NAME}.daemon.session.lifecycle`;
69365
+ var DAEMON_CHANNEL_LIFECYCLE = `${SERVICE_NAME}.daemon.channel.lifecycle`;
69366
+ var DAEMON_PROMPT_QUEUE_WAIT = `${SERVICE_NAME}.daemon.prompt.queue_wait`;
69367
+ var DAEMON_PROMPT_DURATION = `${SERVICE_NAME}.daemon.prompt.duration`;
69368
+ var DAEMON_BRIDGE_ERROR_COUNT = `${SERVICE_NAME}.daemon.bridge.error.count`;
69369
+ var DAEMON_CANCEL_COUNT = `${SERVICE_NAME}.daemon.cancel.count`;
69370
+ var DAEMON_SSE_ACTIVE = `${SERVICE_NAME}.daemon.sse.active`;
69371
+ var DAEMON_PROCESS_HEAP_USED = `${SERVICE_NAME}.daemon.process.heap_used`;
69372
+ var KNOWN_ERROR_TYPES = /* @__PURE__ */ new Set([
69373
+ "SessionNotFoundError",
69374
+ "WorkspaceMismatchError",
69375
+ "InvalidClientIdError",
69376
+ "SessionLimitExceededError",
69377
+ "RestoreInProgressError",
69378
+ "InvalidSessionScopeError",
69379
+ "TrustGateError",
69380
+ "WorkspaceInitConflictError",
69381
+ "WorkspaceInitPathEscapeError",
69382
+ "WorkspaceInitSymlinkError",
69383
+ "WorkspaceInitRaceError",
69384
+ "McpServerNotFoundError",
69385
+ "McpServerRestartFailedError",
69386
+ "PromptDeadlineExceededError",
69387
+ "InvalidSessionMetadataError",
69388
+ "SubscriberLimitExceededError",
69389
+ "BridgeChannelClosedError",
69390
+ "BridgeTimeoutError",
69391
+ "PermissionForbiddenError"
69392
+ ]);
69393
+ var initialized = false;
69394
+ var httpRequestCounter;
69395
+ var httpRequestDurationHistogram;
69396
+ var sessionLifecycleCounter;
69397
+ var channelLifecycleCounter;
69398
+ var promptQueueWaitHistogram;
69399
+ var promptDurationHistogram;
69400
+ var bridgeErrorCounter;
69401
+ var cancelCounter;
69402
+ function normalizeErrorType(err) {
69403
+ const name = err instanceof Error ? err.name : typeof err;
69404
+ return KNOWN_ERROR_TYPES.has(name) ? name : "unknown";
69405
+ }
69406
+ __name(normalizeErrorType, "normalizeErrorType");
69407
+ function initializeDaemonMetrics() {
69408
+ if (initialized) return;
69409
+ const meter = getMeter();
69410
+ if (!meter) return;
69411
+ httpRequestCounter = meter.createCounter(DAEMON_HTTP_REQUEST_COUNT, {
69412
+ description: "Daemon HTTP request count by route and status class.",
69413
+ valueType: ValueType.INT
69414
+ });
69415
+ httpRequestDurationHistogram = meter.createHistogram(
69416
+ DAEMON_HTTP_REQUEST_DURATION,
69417
+ {
69418
+ description: "Daemon HTTP request duration in milliseconds.",
69419
+ unit: "ms",
69420
+ valueType: ValueType.DOUBLE,
69421
+ advice: {
69422
+ explicitBucketBoundaries: [
69423
+ 1,
69424
+ 2,
69425
+ 5,
69426
+ 10,
69427
+ 25,
69428
+ 50,
69429
+ 100,
69430
+ 250,
69431
+ 500,
69432
+ 1e3,
69433
+ 2500,
69434
+ 5e3,
69435
+ 1e4,
69436
+ 3e4
69437
+ ]
69438
+ }
69439
+ }
69440
+ );
69441
+ sessionLifecycleCounter = meter.createCounter(DAEMON_SESSION_LIFECYCLE, {
69442
+ description: "Daemon session lifecycle events (spawn, close, die).",
69443
+ valueType: ValueType.INT
69444
+ });
69445
+ channelLifecycleCounter = meter.createCounter(DAEMON_CHANNEL_LIFECYCLE, {
69446
+ description: "Daemon ACP channel lifecycle events (spawn, exit).",
69447
+ valueType: ValueType.INT
69448
+ });
69449
+ promptQueueWaitHistogram = meter.createHistogram(DAEMON_PROMPT_QUEUE_WAIT, {
69450
+ description: "Time a prompt waited in the per-session FIFO queue.",
69451
+ unit: "ms",
69452
+ valueType: ValueType.DOUBLE,
69453
+ advice: {
69454
+ explicitBucketBoundaries: [
69455
+ 1,
69456
+ 5,
69457
+ 10,
69458
+ 50,
69459
+ 100,
69460
+ 500,
69461
+ 1e3,
69462
+ 5e3,
69463
+ 1e4,
69464
+ 3e4,
69465
+ 6e4
69466
+ ]
69467
+ }
69468
+ });
69469
+ promptDurationHistogram = meter.createHistogram(DAEMON_PROMPT_DURATION, {
69470
+ description: "End-to-end prompt duration from dispatch to completion.",
69471
+ unit: "ms",
69472
+ valueType: ValueType.DOUBLE,
69473
+ advice: {
69474
+ explicitBucketBoundaries: [
69475
+ 100,
69476
+ 500,
69477
+ 1e3,
69478
+ 2500,
69479
+ 5e3,
69480
+ 1e4,
69481
+ 3e4,
69482
+ 6e4,
69483
+ 12e4,
69484
+ 3e5,
69485
+ 6e5
69486
+ ]
69487
+ }
69488
+ });
69489
+ bridgeErrorCounter = meter.createCounter(DAEMON_BRIDGE_ERROR_COUNT, {
69490
+ description: "Daemon bridge error count by normalized error type.",
69491
+ valueType: ValueType.INT
69492
+ });
69493
+ cancelCounter = meter.createCounter(DAEMON_CANCEL_COUNT, {
69494
+ description: "Daemon cancel request count.",
69495
+ valueType: ValueType.INT
69496
+ });
69497
+ initialized = true;
69498
+ }
69499
+ __name(initializeDaemonMetrics, "initializeDaemonMetrics");
69500
+ var gaugesRegistered = false;
69501
+ function registerDaemonGaugeCallbacks(callbacks) {
69502
+ if (gaugesRegistered) return;
69503
+ const meter = getMeter();
69504
+ if (!meter) return;
69505
+ meter.createObservableGauge(DAEMON_SESSION_ACTIVE, {
69506
+ description: "Current number of active daemon sessions.",
69507
+ valueType: ValueType.INT
69508
+ }).addCallback((result) => {
69509
+ try {
69510
+ result.observe(callbacks.sessionCount());
69511
+ } catch {
69512
+ }
69513
+ });
69514
+ meter.createObservableGauge(DAEMON_SSE_ACTIVE, {
69515
+ description: "Current number of active SSE connections.",
69516
+ valueType: ValueType.INT
69517
+ }).addCallback((result) => {
69518
+ try {
69519
+ result.observe(callbacks.sseCount());
69520
+ } catch {
69521
+ }
69522
+ });
69523
+ meter.createObservableGauge(DAEMON_PROCESS_HEAP_USED, {
69524
+ description: "Daemon process heap memory usage in bytes.",
69525
+ unit: "bytes",
69526
+ valueType: ValueType.INT
69527
+ }).addCallback((result) => {
69528
+ try {
69529
+ result.observe(callbacks.heapUsed());
69530
+ } catch {
69531
+ }
69532
+ });
69533
+ gaugesRegistered = true;
69534
+ }
69535
+ __name(registerDaemonGaugeCallbacks, "registerDaemonGaugeCallbacks");
69536
+ function recordDaemonHttpRequest(durationMs, route, statusCode) {
69537
+ if (!initialized) return;
69538
+ const statusClass = `${Math.floor(statusCode / 100)}xx`;
69539
+ httpRequestCounter?.add(1, { route, status_class: statusClass });
69540
+ httpRequestDurationHistogram?.record(durationMs, { route });
69541
+ }
69542
+ __name(recordDaemonHttpRequest, "recordDaemonHttpRequest");
69543
+ function recordDaemonSessionLifecycle(action) {
69544
+ if (!initialized) return;
69545
+ sessionLifecycleCounter?.add(1, { action });
69546
+ }
69547
+ __name(recordDaemonSessionLifecycle, "recordDaemonSessionLifecycle");
69548
+ function recordDaemonChannelLifecycle(action, expected) {
69549
+ if (!initialized) return;
69550
+ channelLifecycleCounter?.add(1, {
69551
+ action,
69552
+ ...expected != null ? { expected } : {}
69553
+ });
69554
+ }
69555
+ __name(recordDaemonChannelLifecycle, "recordDaemonChannelLifecycle");
69556
+ function recordDaemonPromptQueueWait(durationMs) {
69557
+ if (!initialized) return;
69558
+ promptQueueWaitHistogram?.record(durationMs);
69559
+ }
69560
+ __name(recordDaemonPromptQueueWait, "recordDaemonPromptQueueWait");
69561
+ function recordDaemonPromptDuration(durationMs) {
69562
+ if (!initialized) return;
69563
+ promptDurationHistogram?.record(durationMs);
69564
+ }
69565
+ __name(recordDaemonPromptDuration, "recordDaemonPromptDuration");
69566
+ function recordDaemonBridgeError(err) {
69567
+ if (!initialized) return;
69568
+ bridgeErrorCounter?.add(1, { error_type: normalizeErrorType(err) });
69569
+ }
69570
+ __name(recordDaemonBridgeError, "recordDaemonBridgeError");
69571
+ function recordDaemonCancel() {
69572
+ if (!initialized) return;
69573
+ cancelCounter?.add(1);
69574
+ }
69575
+ __name(recordDaemonCancel, "recordDaemonCancel");
69576
+
68797
69577
  // packages/core/src/telemetry/index.ts
68798
69578
  var TelemetryTarget = /* @__PURE__ */ ((TelemetryTarget2) => {
68799
69579
  TelemetryTarget2["GCP"] = "gcp";
@@ -68847,6 +69627,7 @@ var LoggingContentGenerator = class {
68847
69627
  this.wrapped = wrapped;
68848
69628
  this.config = config;
68849
69629
  this.modalities = generatorConfig.modalities;
69630
+ this.splitToolMedia = generatorConfig.splitToolMedia;
68850
69631
  this.generatorAuthType = generatorConfig.authType;
68851
69632
  if (generatorConfig.enableOpenAILogging) {
68852
69633
  this.openaiLogger = new OpenAILogger(
@@ -68862,6 +69643,7 @@ var LoggingContentGenerator = class {
68862
69643
  openaiLogger;
68863
69644
  schemaCompliance;
68864
69645
  modalities;
69646
+ splitToolMedia;
68865
69647
  generatorAuthType;
68866
69648
  getWrapped() {
68867
69649
  return this.wrapped;
@@ -68894,8 +69676,8 @@ var LoggingContentGenerator = class {
68894
69676
  );
68895
69677
  }
68896
69678
  _logApiError(responseId, durationMs, error, model, prompt_id) {
68897
- const errorMessage = getErrorMessage(error);
68898
- const errorType = getErrorType(error);
69679
+ const errorMessage2 = getErrorMessage(error);
69680
+ const errorType2 = getErrorType(error);
68899
69681
  const errorResponseId = error?.requestID || error?.request_id || responseId;
68900
69682
  const errorStatus = getErrorStatus(error);
68901
69683
  logApiError(
@@ -68906,8 +69688,8 @@ var LoggingContentGenerator = class {
68906
69688
  durationMs,
68907
69689
  promptId: prompt_id,
68908
69690
  authType: this.generatorAuthType,
68909
- errorMessage,
68910
- errorType,
69691
+ errorMessage: errorMessage2,
69692
+ errorType: errorType2,
68911
69693
  statusCode: errorStatus,
68912
69694
  subagentName: subagentNameContext.getStore()
68913
69695
  })
@@ -69004,6 +69786,10 @@ var LoggingContentGenerator = class {
69004
69786
  outputTokens: response.usageMetadata?.candidatesTokenCount,
69005
69787
  cachedInputTokens: response.usageMetadata?.cachedContentTokenCount,
69006
69788
  durationMs: Date.now() - startTime,
69789
+ responseId: response.responseId || void 0,
69790
+ finishReason: response.candidates?.[0]?.finishReason || void 0,
69791
+ thoughtsTokenCount: response.usageMetadata?.thoughtsTokenCount,
69792
+ subagentName: subagentNameContext.getStore() || void 0,
69007
69793
  ...retrySnapshot
69008
69794
  });
69009
69795
  return response;
@@ -69014,6 +69800,9 @@ var LoggingContentGenerator = class {
69014
69800
  success: false,
69015
69801
  durationMs,
69016
69802
  error: aborted ? API_CALL_ABORTED_SPAN_STATUS_MESSAGE : API_CALL_FAILED_SPAN_STATUS_MESSAGE,
69803
+ errorType: getErrorType(error),
69804
+ errorStatusCode: getErrorStatus(error),
69805
+ subagentName: subagentNameContext.getStore() || void 0,
69017
69806
  ...retrySnapshot
69018
69807
  });
69019
69808
  await context.with(spanContext, async () => {
@@ -69084,6 +69873,9 @@ var LoggingContentGenerator = class {
69084
69873
  success: false,
69085
69874
  durationMs,
69086
69875
  error: aborted ? API_CALL_ABORTED_SPAN_STATUS_MESSAGE : API_CALL_FAILED_SPAN_STATUS_MESSAGE,
69876
+ errorType: getErrorType(error),
69877
+ errorStatusCode: getErrorStatus(error),
69878
+ subagentName: subagentNameContext.getStore() || void 0,
69087
69879
  ...retrySnapshot
69088
69880
  });
69089
69881
  try {
@@ -69139,6 +69931,9 @@ var LoggingContentGenerator = class {
69139
69931
  let firstModelVersion = "";
69140
69932
  let lastUsageMetadata;
69141
69933
  let errorOccurred = false;
69934
+ let lastFinishReason;
69935
+ let lastError;
69936
+ const subagentName = subagentNameContext.getStore();
69142
69937
  let ttftMs;
69143
69938
  let spanEndedByTimeout = false;
69144
69939
  const runInSpan = /* @__PURE__ */ __name((fn) => spanContext ? context.with(spanContext, fn) : fn(), "runInSpan");
@@ -69156,6 +69951,8 @@ var LoggingContentGenerator = class {
69156
69951
  success: false,
69157
69952
  durationMs: Date.now() - startTime,
69158
69953
  error: "Stream span timed out (idle)",
69954
+ responseId: firstResponseId || void 0,
69955
+ subagentName: subagentName || void 0,
69159
69956
  ...retrySnapshot
69160
69957
  });
69161
69958
  spanEndedByTimeout = true;
@@ -69177,6 +69974,10 @@ var LoggingContentGenerator = class {
69177
69974
  if (response.usageMetadata) {
69178
69975
  lastUsageMetadata = response.usageMetadata;
69179
69976
  }
69977
+ const candidate = response.candidates?.[0];
69978
+ if (candidate?.finishReason) {
69979
+ lastFinishReason = candidate.finishReason;
69980
+ }
69180
69981
  if (ttftMs === void 0 && hasUserVisibleContent(response)) {
69181
69982
  ttftMs = Date.now() - startTime;
69182
69983
  }
@@ -69215,6 +70016,7 @@ var LoggingContentGenerator = class {
69215
70016
  }
69216
70017
  } catch (error) {
69217
70018
  errorOccurred = true;
70019
+ lastError = error;
69218
70020
  if (!spanEndedByTimeout) {
69219
70021
  const durationMs = Date.now() - startTime;
69220
70022
  runInSpan(
@@ -69250,6 +70052,12 @@ var LoggingContentGenerator = class {
69250
70052
  ttftMs,
69251
70053
  durationMs: Date.now() - startTime,
69252
70054
  error: errorOccurred ? aborted ? API_CALL_ABORTED_SPAN_STATUS_MESSAGE : API_CALL_FAILED_SPAN_STATUS_MESSAGE : void 0,
70055
+ responseId: firstResponseId || void 0,
70056
+ finishReason: lastFinishReason,
70057
+ thoughtsTokenCount: lastUsageMetadata?.thoughtsTokenCount,
70058
+ subagentName: subagentName || void 0,
70059
+ errorType: lastError ? getErrorType(lastError) : void 0,
70060
+ errorStatusCode: lastError ? getErrorStatus(lastError) : void 0,
69253
70061
  ...retrySnapshot
69254
70062
  });
69255
70063
  }
@@ -69298,6 +70106,10 @@ var LoggingContentGenerator = class {
69298
70106
  return {
69299
70107
  model,
69300
70108
  modalities: this.modalities ?? {},
70109
+ // Mirror the pipeline default (see pipeline.ts createRequestContext) so the
70110
+ // --openai-logging fallback reconstruction reflects the same split as the
70111
+ // request actually sent. Opt out via generationConfig.splitToolMedia = false.
70112
+ splitToolMedia: this.splitToolMedia ?? true,
69301
70113
  startTime: 0
69302
70114
  };
69303
70115
  }
@@ -69672,7 +70484,18 @@ var MODALITY_PATTERNS = [
69672
70484
  // Moonshot / Kimi
69673
70485
  // -------------------
69674
70486
  [/^kimi-k2\.5/, { image: true, video: true }],
69675
- [/^kimi-/, {}]
70487
+ [/^kimi-/, {}],
70488
+ // -------------------
70489
+ // ByteDance Doubao — Seed-series and *-vision / *-vl models accept image
70490
+ // input; other Doubao models (pro / lite / text) are text-only.
70491
+ // (QwenLM/qwen-code#4876)
70492
+ // -------------------
70493
+ // seedance (text→video) and seedream (text→image) are generation models with
70494
+ // text-only input — exclude them before the multimodal Seed chat series.
70495
+ [/^doubao-seed(ance|ream)/, {}],
70496
+ [/^doubao-seed/, { image: true }],
70497
+ [/^doubao-.*(vision|vl)/, { image: true }],
70498
+ [/^doubao/, {}]
69676
70499
  ];
69677
70500
  function defaultModalities(model) {
69678
70501
  const norm = normalize(model);
@@ -71034,11 +71857,11 @@ async function createContentGenerator(generatorConfig, config, isInitialAuth) {
71034
71857
  let baseGenerator;
71035
71858
  try {
71036
71859
  if (authType === "openai" /* USE_OPENAI */) {
71037
- const { createOpenAIContentGenerator } = await import("./openaiContentGenerator-4QNV3CHM.js");
71860
+ const { createOpenAIContentGenerator } = await import("./openaiContentGenerator-L5KSWQY7.js");
71038
71861
  baseGenerator = createOpenAIContentGenerator(generatorConfig, config);
71039
71862
  } else if (authType === "qwen-oauth" /* QWEN_OAUTH */) {
71040
- const { getQwenOAuthClient: getQwenOauthClient } = await import("./qwenOAuth2-KRJT35QH.js");
71041
- const { QwenContentGenerator } = await import("./qwenContentGenerator-3XOCEMQO.js");
71863
+ const { getQwenOAuthClient: getQwenOauthClient } = await import("./qwenOAuth2-2KCKWDCF.js");
71864
+ const { QwenContentGenerator } = await import("./qwenContentGenerator-PYOXLMBW.js");
71042
71865
  try {
71043
71866
  const qwenClient = await getQwenOauthClient(
71044
71867
  config,
@@ -71056,10 +71879,10 @@ async function createContentGenerator(generatorConfig, config, isInitialAuth) {
71056
71879
  throw new Error(error instanceof Error ? error.message : String(error));
71057
71880
  }
71058
71881
  } else if (authType === "anthropic" /* USE_ANTHROPIC */) {
71059
- const { createAnthropicContentGenerator } = await import("./anthropicContentGenerator-4QBVSFSJ.js");
71882
+ const { createAnthropicContentGenerator } = await import("./anthropicContentGenerator-2HBRNQ3B.js");
71060
71883
  baseGenerator = createAnthropicContentGenerator(generatorConfig, config);
71061
71884
  } else if (authType === "gemini" /* USE_GEMINI */ || authType === "vertex-ai" /* USE_VERTEX_AI */) {
71062
- const { createGeminiContentGenerator } = await import("./geminiContentGenerator-CR2WGARL.js");
71885
+ const { createGeminiContentGenerator } = await import("./geminiContentGenerator-7A6I2RWB.js");
71063
71886
  baseGenerator = createGeminiContentGenerator(generatorConfig, config);
71064
71887
  } else {
71065
71888
  throw new Error(
@@ -71934,7 +72757,7 @@ function logStartSession(config, event) {
71934
72757
  skills: event.skills,
71935
72758
  subagents: event.subagents
71936
72759
  };
71937
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
72760
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
71938
72761
  const logRecord = {
71939
72762
  body: "CLI configuration loaded.",
71940
72763
  attributes
@@ -71958,7 +72781,7 @@ function logUserPrompt(config, event) {
71958
72781
  if (shouldLogUserPrompts(config)) {
71959
72782
  attributes["prompt"] = event.prompt;
71960
72783
  }
71961
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
72784
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
71962
72785
  const logRecord = {
71963
72786
  body: `User prompt. Length: ${event.prompt_length}.`,
71964
72787
  attributes
@@ -71975,7 +72798,7 @@ function logUserRetry(config, event) {
71975
72798
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
71976
72799
  prompt_id: event.prompt_id
71977
72800
  };
71978
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
72801
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
71979
72802
  const logRecord = {
71980
72803
  body: `User retry.`,
71981
72804
  attributes
@@ -71989,7 +72812,7 @@ function logToolCall(config, event) {
71989
72812
  "event.name": EVENT_TOOL_CALL,
71990
72813
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
71991
72814
  };
71992
- uiTelemetryService.addEvent(uiEvent);
72815
+ uiTelemetryService.addEvent(uiEvent, config.getSessionId());
71993
72816
  if (!isInternalPromptId(event.prompt_id)) {
71994
72817
  config.getChatRecordingService()?.recordUiTelemetryEvent(uiEvent);
71995
72818
  }
@@ -72008,7 +72831,7 @@ function logToolCall(config, event) {
72008
72831
  attributes["error.type"] = event.error_type;
72009
72832
  }
72010
72833
  }
72011
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
72834
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72012
72835
  const logRecord = {
72013
72836
  body: `Tool call: ${event.function_name}${event.decision ? `. Decision: ${event.decision}` : ""}. Success: ${event.success}. Duration: ${event.duration_ms}ms.`,
72014
72837
  attributes
@@ -72031,7 +72854,7 @@ function logToolOutputTruncated(config, event) {
72031
72854
  "event.name": "tool_output_truncated",
72032
72855
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72033
72856
  };
72034
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
72857
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72035
72858
  const logRecord = {
72036
72859
  body: `Tool output truncated for ${event.tool_name}.`,
72037
72860
  attributes
@@ -72061,7 +72884,7 @@ function logFileOperation(config, event) {
72061
72884
  if (event.programming_language) {
72062
72885
  attributes["programming_language"] = event.programming_language;
72063
72886
  }
72064
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
72887
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72065
72888
  const logRecord = {
72066
72889
  body: `File operation: ${event.operation}. Lines: ${event.lines}.`,
72067
72890
  attributes
@@ -72084,7 +72907,7 @@ function logApiRequest(config, event) {
72084
72907
  "event.name": EVENT_API_REQUEST,
72085
72908
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72086
72909
  };
72087
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
72910
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72088
72911
  const logRecord = {
72089
72912
  body: `API request to ${event.model}.`,
72090
72913
  attributes
@@ -72101,7 +72924,7 @@ function logFlashFallback(config, event) {
72101
72924
  "event.name": EVENT_FLASH_FALLBACK,
72102
72925
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72103
72926
  };
72104
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
72927
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72105
72928
  const logRecord = {
72106
72929
  body: `Switching to flash as Fallback.`,
72107
72930
  attributes
@@ -72118,7 +72941,7 @@ function logRipgrepFallback(config, event) {
72118
72941
  "event.name": EVENT_RIPGREP_FALLBACK,
72119
72942
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72120
72943
  };
72121
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
72944
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72122
72945
  const logRecord = {
72123
72946
  body: `Switching to grep as fallback.`,
72124
72947
  attributes
@@ -72132,7 +72955,7 @@ function logApiError(config, event) {
72132
72955
  "event.name": EVENT_API_ERROR,
72133
72956
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72134
72957
  };
72135
- uiTelemetryService.addEvent(uiEvent);
72958
+ uiTelemetryService.addEvent(uiEvent, config.getSessionId());
72136
72959
  if (!isInternalPromptId(event.prompt_id)) {
72137
72960
  config.getChatRecordingService()?.recordUiTelemetryEvent(uiEvent);
72138
72961
  }
@@ -72153,7 +72976,7 @@ function logApiError(config, event) {
72153
72976
  if (typeof event.status_code === "number") {
72154
72977
  attributes[SemanticAttributes.HTTP_STATUS_CODE] = event.status_code;
72155
72978
  }
72156
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
72979
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72157
72980
  const logRecord = {
72158
72981
  body: `API error for ${event.model}. Error: ${event.error_message}. Duration: ${event.duration_ms}ms.`,
72159
72982
  attributes
@@ -72172,7 +72995,7 @@ function logApiCancel(config, event) {
72172
72995
  "event.name": EVENT_API_CANCEL,
72173
72996
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72174
72997
  };
72175
- uiTelemetryService.addEvent(uiEvent);
72998
+ uiTelemetryService.addEvent(uiEvent, config.getSessionId());
72176
72999
  QwenLogger.getInstance(config)?.logApiCancelEvent(event);
72177
73000
  if (!isTelemetrySdkInitialized()) return;
72178
73001
  const attributes = {
@@ -72182,7 +73005,7 @@ function logApiCancel(config, event) {
72182
73005
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString(),
72183
73006
  model_name: event.model
72184
73007
  };
72185
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73008
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72186
73009
  const logRecord = {
72187
73010
  body: `API request cancelled for ${event.model}.`,
72188
73011
  attributes
@@ -72196,7 +73019,7 @@ function logApiResponse(config, event) {
72196
73019
  "event.name": EVENT_API_RESPONSE,
72197
73020
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72198
73021
  };
72199
- uiTelemetryService.addEvent(uiEvent);
73022
+ uiTelemetryService.addEvent(uiEvent, config.getSessionId());
72200
73023
  if (!isInternalPromptId(event.prompt_id)) {
72201
73024
  config.getChatRecordingService()?.recordUiTelemetryEvent(uiEvent);
72202
73025
  }
@@ -72216,7 +73039,7 @@ function logApiResponse(config, event) {
72216
73039
  attributes[SemanticAttributes.HTTP_STATUS_CODE] = event.status_code;
72217
73040
  }
72218
73041
  }
72219
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73042
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72220
73043
  const logRecord = {
72221
73044
  body: `API response from ${event.model}. Status: ${event.status_code || "N/A"}. Duration: ${event.duration_ms}ms.`,
72222
73045
  attributes
@@ -72251,7 +73074,7 @@ function logLoopDetected(config, event) {
72251
73074
  ...getCommonAttributes(config),
72252
73075
  ...event
72253
73076
  };
72254
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73077
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72255
73078
  const logRecord = {
72256
73079
  body: `Loop detected. Type: ${event.loop_type}.`,
72257
73080
  attributes
@@ -72271,7 +73094,7 @@ function logNextSpeakerCheck(config, event) {
72271
73094
  ...event,
72272
73095
  "event.name": EVENT_NEXT_SPEAKER_CHECK
72273
73096
  };
72274
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73097
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72275
73098
  const logRecord = {
72276
73099
  body: `Next speaker check.`,
72277
73100
  attributes
@@ -72287,7 +73110,7 @@ function logSlashCommand(config, event) {
72287
73110
  ...event,
72288
73111
  "event.name": EVENT_SLASH_COMMAND
72289
73112
  };
72290
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73113
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72291
73114
  const logRecord = {
72292
73115
  body: `Slash command: ${event.command}.`,
72293
73116
  attributes
@@ -72303,7 +73126,7 @@ function logIdeConnection(config, event) {
72303
73126
  ...event,
72304
73127
  "event.name": EVENT_IDE_CONNECTION
72305
73128
  };
72306
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73129
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72307
73130
  const logRecord = {
72308
73131
  body: `Ide connection. Type: ${event.connection_type}.`,
72309
73132
  attributes
@@ -72319,7 +73142,7 @@ function logConversationFinishedEvent(config, event) {
72319
73142
  ...event,
72320
73143
  "event.name": EVENT_CONVERSATION_FINISHED
72321
73144
  };
72322
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73145
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72323
73146
  const logRecord = {
72324
73147
  body: `Conversation finished.`,
72325
73148
  attributes
@@ -72334,7 +73157,7 @@ function logChatCompression(config, event) {
72334
73157
  ...event,
72335
73158
  "event.name": EVENT_CHAT_COMPRESSION
72336
73159
  };
72337
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73160
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72338
73161
  const logRecord = {
72339
73162
  body: `Chat compression (Saved ${event.tokens_before - event.tokens_after} tokens)`,
72340
73163
  attributes
@@ -72353,7 +73176,7 @@ function logKittySequenceOverflow(config, event) {
72353
73176
  ...getCommonAttributes(config),
72354
73177
  ...event
72355
73178
  };
72356
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73179
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72357
73180
  const logRecord = {
72358
73181
  body: `Kitty sequence buffer overflow: ${event.sequence_length} bytes`,
72359
73182
  attributes
@@ -72369,7 +73192,7 @@ function logContentRetry(config, event) {
72369
73192
  ...event,
72370
73193
  "event.name": EVENT_CONTENT_RETRY
72371
73194
  };
72372
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73195
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72373
73196
  const logRecord = {
72374
73197
  body: `Content retry attempt ${event.attempt_number} due to ${event.error_type}.`,
72375
73198
  attributes
@@ -72386,7 +73209,7 @@ function logContentRetryFailure(config, event) {
72386
73209
  ...event,
72387
73210
  "event.name": EVENT_CONTENT_RETRY_FAILURE
72388
73211
  };
72389
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73212
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72390
73213
  const logRecord = {
72391
73214
  body: `All content retries failed after ${event.total_attempts} attempts.`,
72392
73215
  attributes
@@ -72403,7 +73226,7 @@ function logApiRetry(config, event) {
72403
73226
  ...event,
72404
73227
  "event.name": EVENT_API_RETRY
72405
73228
  };
72406
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73229
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72407
73230
  const logRecord = {
72408
73231
  body: `API retry attempt ${event.attempt_number} for ${event.model} (status ${event.status_code ?? "unknown"}).`,
72409
73232
  attributes
@@ -72421,7 +73244,7 @@ function logSubagentExecution(config, event) {
72421
73244
  "event.name": EVENT_SUBAGENT_EXECUTION,
72422
73245
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72423
73246
  };
72424
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73247
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72425
73248
  const logRecord = {
72426
73249
  body: `Subagent execution: ${event.subagent_name}.`,
72427
73250
  attributes
@@ -72443,7 +73266,7 @@ function logModelSlashCommand(config, event) {
72443
73266
  ...event,
72444
73267
  "event.name": EVENT_MODEL_SLASH_COMMAND
72445
73268
  };
72446
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73269
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72447
73270
  const logRecord = {
72448
73271
  body: `Model slash command. Model: ${event.model_name}`,
72449
73272
  attributes
@@ -72469,7 +73292,7 @@ function logExtensionInstallEvent(config, event) {
72469
73292
  extension_source: event.extension_source,
72470
73293
  status: event.status
72471
73294
  };
72472
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73295
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72473
73296
  const logRecord = {
72474
73297
  body: `Installed extension ${event.extension_name}`,
72475
73298
  attributes
@@ -72486,7 +73309,7 @@ function logExtensionUninstall(config, event) {
72486
73309
  "event.name": EVENT_EXTENSION_UNINSTALL,
72487
73310
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72488
73311
  };
72489
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73312
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72490
73313
  const logRecord = {
72491
73314
  body: `Uninstalled extension ${event.extension_name}`,
72492
73315
  attributes
@@ -72507,7 +73330,7 @@ async function logExtensionUpdateEvent(config, event) {
72507
73330
  extension_version: event.extension_version,
72508
73331
  extension_source: event.extension_source
72509
73332
  };
72510
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73333
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72511
73334
  const logRecord = {
72512
73335
  body: `Updated extension ${event.extension_name} from ${event.extension_previous_version} to ${event.extension_version}`,
72513
73336
  attributes
@@ -72524,7 +73347,7 @@ function logExtensionEnable(config, event) {
72524
73347
  "event.name": EVENT_EXTENSION_ENABLE,
72525
73348
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72526
73349
  };
72527
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73350
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72528
73351
  const logRecord = {
72529
73352
  body: `Enabled extension ${event.extension_name}`,
72530
73353
  attributes
@@ -72541,7 +73364,7 @@ function logExtensionDisable(config, event) {
72541
73364
  "event.name": EVENT_EXTENSION_DISABLE,
72542
73365
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72543
73366
  };
72544
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73367
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72545
73368
  const logRecord = {
72546
73369
  body: `Disabled extension ${event.extension_name}`,
72547
73370
  attributes
@@ -72564,7 +73387,7 @@ function logAuth(config, event) {
72564
73387
  if (event.error_message) {
72565
73388
  attributes["error.message"] = event.error_message;
72566
73389
  }
72567
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73390
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72568
73391
  const logRecord = {
72569
73392
  body: `Auth event: ${event.action_type} ${event.status} for ${event.auth_type}`,
72570
73393
  attributes
@@ -72581,7 +73404,7 @@ function logSkillLaunch(config, event) {
72581
73404
  "event.name": EVENT_SKILL_LAUNCH,
72582
73405
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72583
73406
  };
72584
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73407
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72585
73408
  const logRecord = {
72586
73409
  body: `Skill launch: ${event.skill_name}. Success: ${event.success}.`,
72587
73410
  attributes
@@ -72595,7 +73418,7 @@ function logUserFeedback(config, event) {
72595
73418
  "event.name": EVENT_USER_FEEDBACK,
72596
73419
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72597
73420
  };
72598
- uiTelemetryService.addEvent(uiEvent);
73421
+ uiTelemetryService.addEvent(uiEvent, config.getSessionId());
72599
73422
  config.getChatRecordingService()?.recordUiTelemetryEvent(uiEvent);
72600
73423
  QwenLogger.getInstance(config)?.logUserFeedbackEvent(event);
72601
73424
  if (!isTelemetrySdkInitialized()) return;
@@ -72605,7 +73428,7 @@ function logUserFeedback(config, event) {
72605
73428
  "event.name": EVENT_USER_FEEDBACK,
72606
73429
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72607
73430
  };
72608
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73431
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72609
73432
  const logRecord = {
72610
73433
  body: `User feedback: Rating ${event.rating} for session ${event.session_id}.`,
72611
73434
  attributes
@@ -72623,7 +73446,7 @@ function logArenaSessionStarted(config, event) {
72623
73446
  "event.name": EVENT_ARENA_SESSION_STARTED,
72624
73447
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72625
73448
  };
72626
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73449
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72627
73450
  const logRecord = {
72628
73451
  body: `Arena session started. Agents: ${event.model_ids.length}.`,
72629
73452
  attributes
@@ -72641,7 +73464,7 @@ function logArenaAgentCompleted(config, event) {
72641
73464
  "event.name": EVENT_ARENA_AGENT_COMPLETED,
72642
73465
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72643
73466
  };
72644
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73467
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72645
73468
  const logRecord = {
72646
73469
  body: `Arena agent ${event.agent_model_id} ${event.status}. Duration: ${event.duration_ms}ms. Tokens: ${event.total_tokens}.`,
72647
73470
  attributes
@@ -72666,7 +73489,7 @@ function logArenaSessionEnded(config, event) {
72666
73489
  "event.name": EVENT_ARENA_SESSION_ENDED,
72667
73490
  "event.timestamp": (/* @__PURE__ */ new Date()).toISOString()
72668
73491
  };
72669
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73492
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72670
73493
  const logRecord = {
72671
73494
  body: `Arena session ended: ${event.status}.${event.winner_model_id ? ` Winner: ${event.winner_model_id}.` : ""}`,
72672
73495
  attributes
@@ -72716,7 +73539,7 @@ function logPromptSuggestion(config, event) {
72716
73539
  if (event.reason) {
72717
73540
  attributes["reason"] = event.reason;
72718
73541
  }
72719
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73542
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72720
73543
  const logRecord = {
72721
73544
  body: `Prompt suggestion: ${event.outcome}.`,
72722
73545
  attributes
@@ -72740,7 +73563,7 @@ function logSpeculation(config, event) {
72740
73563
  if (event.boundary_type) {
72741
73564
  attributes["boundary_type"] = event.boundary_type;
72742
73565
  }
72743
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73566
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72744
73567
  const logRecord = {
72745
73568
  body: `Speculation: ${event.outcome}.`,
72746
73569
  attributes
@@ -72763,7 +73586,7 @@ function logMemoryExtract(config, event) {
72763
73586
  if (event.skipped_reason) {
72764
73587
  attributes["skipped_reason"] = event.skipped_reason;
72765
73588
  }
72766
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73589
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72767
73590
  logger.emit({
72768
73591
  body: `Memory extract: ${event.status}. Patches: ${event.patches_count}. Topics: ${event.touched_topics || "none"}.`,
72769
73592
  attributes
@@ -72788,7 +73611,7 @@ function logMemoryDream(config, event) {
72788
73611
  touched_topics: event.touched_topics,
72789
73612
  duration_ms: event.duration_ms
72790
73613
  };
72791
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73614
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72792
73615
  logger.emit({
72793
73616
  body: `Memory dream: ${event.status}. Deduped: ${event.deduped_entries}. Topics: ${event.touched_topics || "none"}.`,
72794
73617
  attributes
@@ -72812,7 +73635,7 @@ function logMemoryRecall(config, event) {
72812
73635
  strategy: event.strategy,
72813
73636
  duration_ms: event.duration_ms
72814
73637
  };
72815
- const logger = import_api_logs.logs.getLogger(SERVICE_NAME);
73638
+ const logger = import_api_logs2.logs.getLogger(SERVICE_NAME);
72816
73639
  logger.emit({
72817
73640
  body: `Memory recall: strategy=${event.strategy}. Selected ${event.docs_selected}/${event.docs_scanned} docs.`,
72818
73641
  attributes
@@ -73073,6 +73896,13 @@ var ReadFileTool = class _ReadFileTool extends BaseDeclarativeTool {
73073
73896
  __name(this, "ReadFileTool");
73074
73897
  }
73075
73898
  static Name = ToolNames.READ_FILE;
73899
+ // Self-managed: ReadFile controls its own size via line-based paging
73900
+ // (offset/limit, default 2000 lines), so it is exempt from the scheduler's
73901
+ // char-based truncation. Oversized reads are bounded by the per-message
73902
+ // batch budget instead.
73903
+ get maxOutputChars() {
73904
+ return Number.POSITIVE_INFINITY;
73905
+ }
73076
73906
  validateToolParamValues(params) {
73077
73907
  const filePath = unescapePath(params.file_path.trim());
73078
73908
  params.file_path = filePath;
@@ -73231,6 +74061,7 @@ export {
73231
74061
  truncateSpanError,
73232
74062
  startInteractionSpan,
73233
74063
  endInteractionSpan,
74064
+ withInteractionSpan,
73234
74065
  startLLMRequestSpan,
73235
74066
  endLLMRequestSpan,
73236
74067
  startToolSpan,
@@ -73251,6 +74082,7 @@ export {
73251
74082
  initializeTelemetry,
73252
74083
  refreshSessionContext,
73253
74084
  shutdownTelemetry,
74085
+ forceFlushMetrics,
73254
74086
  logStartSession,
73255
74087
  logUserPrompt,
73256
74088
  logUserRetry,
@@ -73296,7 +74128,9 @@ export {
73296
74128
  memoryAge,
73297
74129
  memoryFreshnessText,
73298
74130
  ReadFileTool,
74131
+ TOOL_OUTPUT_TRUNCATED_PREFIX,
73299
74132
  truncateToolOutput,
74133
+ truncateLlmContent,
73300
74134
  DiscoveredMCPTool,
73301
74135
  generateValidName,
73302
74136
  StartSessionEvent,
@@ -73355,6 +74189,30 @@ export {
73355
74189
  parseBooleanEnvFlag,
73356
74190
  parseTelemetryTargetValue,
73357
74191
  resolveTelemetrySettings,
74192
+ DAEMON_TRACEPARENT_META_KEY,
74193
+ DAEMON_TRACESTATE_META_KEY,
74194
+ hashDaemonWorkspace,
74195
+ withDaemonSpan,
74196
+ withDaemonRequestSpan,
74197
+ withDaemonBridgeSpan,
74198
+ recordDaemonHttpResponse,
74199
+ addDaemonRequestAttribute,
74200
+ recordDaemonError,
74201
+ emitDaemonLog,
74202
+ captureDaemonTelemetryContext,
74203
+ runWithDaemonTelemetryContext,
74204
+ injectDaemonTraceContext,
74205
+ extractDaemonTraceContext,
74206
+ createDaemonBridgeTelemetry,
74207
+ initializeDaemonMetrics,
74208
+ registerDaemonGaugeCallbacks,
74209
+ recordDaemonHttpRequest,
74210
+ recordDaemonSessionLifecycle,
74211
+ recordDaemonChannelLifecycle,
74212
+ recordDaemonPromptQueueWait,
74213
+ recordDaemonPromptDuration,
74214
+ recordDaemonBridgeError,
74215
+ recordDaemonCancel,
73358
74216
  TelemetryTarget,
73359
74217
  DEFAULT_TELEMETRY_TARGET,
73360
74218
  DEFAULT_OTLP_ENDPOINT,