nolo-cli 0.219.0 → 0.221.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 (201) hide show
  1. package/{_executeModel-WW57SJN4.js → _executeModel-WZKT6XEU.js} +74 -74
  2. package/{action-CK64LS6S.js → action-GDZDXPMB.js} +7 -7
  3. package/{addContentAction-EQXMFNPR.js → addContentAction-7RO4AMRI.js} +12 -12
  4. package/{addDialogAgentAction-RSDZDASD.js → addDialogAgentAction-EVYBGTXB.js} +14 -14
  5. package/{agentDeleteCommand-X2VWEKUA.js → agentDeleteCommand-PZWRHNXY.js} +114 -115
  6. package/{agentEmailCommands-6IE773VW.js → agentEmailCommands-QTKMEICX.js} +115 -116
  7. package/{agentFavoriteCommands-2LKGKSUD.js → agentFavoriteCommands-7LOP3HUD.js} +5 -5
  8. package/{agentGrantCommands-QQV4N4JW.js → agentGrantCommands-L6O2HVJI.js} +5 -5
  9. package/{agentListCommands-5UNM7CGG.js → agentListCommands-GUGMORTK.js} +84 -70
  10. package/{agentMachineCommands-EVWFKK6Q.js → agentMachineCommands-7QGICJLM.js} +56 -55
  11. package/{agentProviderCommands-ZCH37KAL.js → agentProviderCommands-STI3DQ6A.js} +6 -6
  12. package/{agentPullCommand-XN6ZPBUW.js → agentPullCommand-KHV4EELF.js} +5 -5
  13. package/{agentRecordCommands-DX2WE6BH.js → agentRecordCommands-SLLADS5C.js} +102 -103
  14. package/{agentRunCommand-KGOT2AFB.js → agentRunCommand-OFQLOF5Y.js} +113 -112
  15. package/{agentRunControl-QDFW5P2T.js → agentRunControl-MBG4U6SL.js} +20 -14
  16. package/{agentRuntimeLocal-SD7U2EGY.js → agentRuntimeLocal-TU4LA353.js} +39 -39
  17. package/{agentSlice-ACZGTZVW.js → agentSlice-L4SBGWTB.js} +16 -16
  18. package/{appDeleteCommands-NE3NQQJL.js → appDeleteCommands-JWP3XPUA.js} +50 -49
  19. package/{appDeployCommands-2BAHY522.js → appDeployCommands-6E4TQCWI.js} +50 -49
  20. package/{appDeployStatusCommands-JTW6LZNC.js → appDeployStatusCommands-ALU4SADG.js} +50 -49
  21. package/{appGetCommands-WKFEJO6A.js → appGetCommands-JEY4L6L4.js} +50 -49
  22. package/{appListCommands-HNAZZLFX.js → appListCommands-PCAVHU7M.js} +50 -49
  23. package/{authCommand-4FDPL7WG.js → authCommand-CGRIIOOV.js} +26 -23
  24. package/{authCommands-GAJ3NIXO.js → authCommands-55OGQGCR.js} +9 -6
  25. package/{builtinSkillRegistry-PXH7EGQB.js → builtinSkillRegistry-BAE2LDXF.js} +4 -4
  26. package/{chromeOpsCommands-YKX2QX3A.js → chromeOpsCommands-WAA45NCS.js} +6 -6
  27. package/{chunk-OB6DVWPF.js → chunk-262R3XNN.js} +16 -2
  28. package/{chunk-5OZC7R7Y.js → chunk-2MCB7CD7.js} +13 -12
  29. package/{chunk-IWH5SOU4.js → chunk-2NPD3FTX.js} +3 -3
  30. package/{chunk-OGHP3CTL.js → chunk-2X7WFDT6.js} +1 -1
  31. package/{chunk-XI2BWJM5.js → chunk-324FWHUA.js} +20 -3
  32. package/{chunk-JWXITTQB.js → chunk-3P54D2E4.js} +1 -1
  33. package/{chunk-EGXPAWLG.js → chunk-3U44JB3O.js} +1 -1
  34. package/{chunk-YL3EFYL3.js → chunk-4D4QD7FT.js} +3 -1
  35. package/{chunk-EUCFKKDM.js → chunk-4I2MXV5Q.js} +38 -10
  36. package/{chunk-C4WTX5TU.js → chunk-4ZGPHFLE.js} +2 -2
  37. package/{chunk-MOMR7NMG.js → chunk-547ENH5T.js} +1 -1
  38. package/chunk-5ZUOVCKT.js +32 -0
  39. package/{chunk-TRWT3EE3.js → chunk-62HXNQVV.js} +1 -1
  40. package/{chunk-KOXKKHFE.js → chunk-6QHKRARD.js} +2 -2
  41. package/{chunk-YGMBIXCF.js → chunk-6XRPBZRS.js} +4 -2
  42. package/{chunk-JC5XLWZK.js → chunk-7JGMNKKG.js} +19 -15
  43. package/{chunk-FRSBYNWI.js → chunk-AGYPUBFW.js} +31 -205
  44. package/{chunk-UYOICCYG.js → chunk-ALAES342.js} +59 -88
  45. package/{chunk-VREDDN25.js → chunk-ATEKLSLR.js} +1 -1
  46. package/{chunk-6NKA6RKF.js → chunk-AUAJTAFM.js} +8 -8
  47. package/chunk-BIDSIRTS.js +307 -0
  48. package/chunk-BIWI5M4E.js +62 -0
  49. package/{chunk-L5I543VB.js → chunk-BNMPUQW6.js} +1 -1
  50. package/{chunk-BGGHA5DV.js → chunk-BP5ZJ6B4.js} +1 -1
  51. package/{chunk-Q6HOUF4O.js → chunk-CBUZ6DKA.js} +3 -3
  52. package/{chunk-LE6LGAJE.js → chunk-CD3RU7XL.js} +17 -2
  53. package/{chunk-AVHRSJUH.js → chunk-CMMI3DAT.js} +13 -13
  54. package/{chunk-H7R3365N.js → chunk-CYWNWA77.js} +5 -5
  55. package/{chunk-6D7NVU66.js → chunk-D6YNCNM6.js} +17 -14
  56. package/{chunk-6RQFZCKH.js → chunk-DBUR22G5.js} +6 -6
  57. package/{chunk-MKQ2UTTX.js → chunk-DDC6P6EH.js} +22 -19
  58. package/{chunk-PVZY6P3S.js → chunk-DEA37IUY.js} +2 -2
  59. package/{chunk-QLFCTYRH.js → chunk-DGYCDA6W.js} +3 -3
  60. package/{chunk-SRL56PI2.js → chunk-DUUDXSLX.js} +21 -7
  61. package/{chunk-KFHREHUQ.js → chunk-DXWGFL2Z.js} +89 -1
  62. package/{chunk-PFJNLBRU.js → chunk-EEOOBRA7.js} +6 -6
  63. package/{chunk-KN3HEZIQ.js → chunk-EVGU5P4U.js} +1 -1
  64. package/{chunk-O2CYENYJ.js → chunk-EXJK7TQO.js} +2113 -1090
  65. package/{chunk-CXDPIPZ4.js → chunk-F6Z6ZCUV.js} +2 -2
  66. package/{chunk-EOWLBDY6.js → chunk-FJSNBZXR.js} +1 -1
  67. package/{chunk-GNHMRBYZ.js → chunk-G7IUT2V3.js} +4 -3
  68. package/{chunk-7WPAI5JJ.js → chunk-GACR7H6T.js} +14 -14
  69. package/{chunk-65XXHYZ5.js → chunk-GOCSSER3.js} +3 -3
  70. package/{chunk-4NMHE7CX.js → chunk-GPOV42YM.js} +14 -14
  71. package/{chunk-SASHAZ67.js → chunk-GUXZK7SE.js} +2 -2
  72. package/{chunk-F3TQURKK.js → chunk-GYS5FUYR.js} +19 -19
  73. package/{chunk-VHPAA6MT.js → chunk-H6L2NFHY.js} +6 -6
  74. package/{chunk-G2EJ7NL4.js → chunk-HBRDSQ3M.js} +2 -2
  75. package/{chunk-OOF7XDZF.js → chunk-HHFGE2WF.js} +6 -6
  76. package/{chunk-DJSTBAOU.js → chunk-HSSBDZLD.js} +4 -4
  77. package/{chunk-GIABSSWQ.js → chunk-HYLRQDEE.js} +4 -4
  78. package/{chunk-N3J4VDGV.js → chunk-IAAIUH64.js} +15 -15
  79. package/{chunk-UJKTI5PG.js → chunk-ILHQ2AXT.js} +0 -1
  80. package/{chunk-T3O6BLYU.js → chunk-IXG6YXQM.js} +147 -115
  81. package/{chunk-TVFRV3UQ.js → chunk-JUSHVFNF.js} +238 -185
  82. package/{chunk-QWYFFHCJ.js → chunk-K67C2JUC.js} +10 -10
  83. package/{chunk-HCJFGH6Y.js → chunk-L32W3PRP.js} +46 -16
  84. package/{chunk-2KTUDBG7.js → chunk-M4SFKP5L.js} +1 -1
  85. package/{chunk-KAVGK4ES.js → chunk-MDZWUD3R.js} +18 -18
  86. package/{chunk-OXKUPBAQ.js → chunk-NHY322ZU.js} +151 -10
  87. package/{chunk-UMRI2IRY.js → chunk-OBIC6EG7.js} +6 -6
  88. package/{chunk-VALBGPM6.js → chunk-OBSEKCVK.js} +17 -20
  89. package/{chunk-SYQR7FQS.js → chunk-OG6MQOQG.js} +96 -28
  90. package/{chunk-AMEOV5VZ.js → chunk-OOJNQK6V.js} +33 -33
  91. package/{chunk-K5FNYHZC.js → chunk-OWKNSIXL.js} +149 -54
  92. package/{chunk-XFJ4ZPFC.js → chunk-OYU2MA5S.js} +25 -25
  93. package/{chunk-CKT6QUE2.js → chunk-Q3IVPFVO.js} +1 -1
  94. package/{chunk-AFHOCBSP.js → chunk-QBZCGP34.js} +1 -1
  95. package/{chunk-2ZKFCIJJ.js → chunk-QCB42576.js} +1 -1
  96. package/{chunk-HOCHUZQ7.js → chunk-QJTZ76CP.js} +24 -6
  97. package/{chunk-XWGDCWXY.js → chunk-QRGDJA4B.js} +9 -9
  98. package/{chunk-4A2JIXR2.js → chunk-QYB23WUH.js} +1 -1
  99. package/{chunk-FVZW66K4.js → chunk-R3NEQZ53.js} +288 -95
  100. package/{chunk-2VUZSVAS.js → chunk-R6Z5S5GA.js} +7 -7
  101. package/{chunk-MK2Q7ZJD.js → chunk-R7XWZDOH.js} +58 -24
  102. package/{chunk-GGKNJ42M.js → chunk-RBPUNSG5.js} +2 -2
  103. package/{chunk-GVGOEMNV.js → chunk-RG2DGNL6.js} +3 -3
  104. package/{chunk-2OLYKYNY.js → chunk-RTHFJZ6M.js} +8 -8
  105. package/{chunk-C4VAR65S.js → chunk-RYOLWYBK.js} +120 -116
  106. package/{chunk-D726I5AZ.js → chunk-S6FDXXZV.js} +2 -2
  107. package/{chunk-JVRQ6YVK.js → chunk-S6K5F3KP.js} +1 -1
  108. package/{chunk-7UH3DGV6.js → chunk-SMJEXX2S.js} +7 -7
  109. package/{chunk-IWQAOW2X.js → chunk-SRCCSTIM.js} +8 -8
  110. package/{chunk-KO63FPG3.js → chunk-STJ6LSQE.js} +750 -2523
  111. package/{chunk-Q7WP5RPC.js → chunk-TGNIKIHR.js} +5 -5
  112. package/{chunk-AK5O76CC.js → chunk-TI2EPRHE.js} +2 -2
  113. package/{chunk-5R63B62U.js → chunk-TSPMLCWI.js} +7 -7
  114. package/{chunk-QVBXJNZ2.js → chunk-TUSTONB3.js} +1 -1
  115. package/{chunk-3ESU44FG.js → chunk-UE2EVEYS.js} +3 -3
  116. package/{chunk-S7SB7L2I.js → chunk-UWAIJOF2.js} +19 -19
  117. package/{chunk-KEN3N2TN.js → chunk-VMJVAJ6W.js} +13 -10
  118. package/{chunk-SOF4OWDM.js → chunk-VS276URX.js} +0 -2
  119. package/{chunk-N7HVLYOY.js → chunk-VSYTM22R.js} +3 -3
  120. package/{chunk-FIYSMXHY.js → chunk-WWTSEBDF.js} +1 -1
  121. package/{chunk-E2BESSAW.js → chunk-X4O7FJF5.js} +2 -0
  122. package/{chunk-3N4ASIP6.js → chunk-XJPLSAPJ.js} +11 -11
  123. package/{chunk-J6T25AJ6.js → chunk-XSW4EXQV.js} +82 -18
  124. package/{chunk-DVQH4BTR.js → chunk-YKY4OVOX.js} +14 -10
  125. package/{chunk-5RKUPJYL.js → chunk-ZH3KXFHS.js} +11 -3
  126. package/chunk-ZOHO6MOF.js +376 -0
  127. package/{chunk-652XYZGP.js → chunk-ZXF6D3I6.js} +13 -6
  128. package/{cliAgentConfigHelpers-PO3MVDME.js → cliAgentConfigHelpers-BTRHMPW2.js} +12 -12
  129. package/{cliEnvHelpers-VPSJ4XWC.js → cliEnvHelpers-CNMP3RDX.js} +1 -1
  130. package/{cliExecutor-4MAX3PZL.js → cliExecutor-K6FDZTQ2.js} +3 -1
  131. package/{cliLocalAgentRecordReader-Z7CH4K4R.js → cliLocalAgentRecordReader-M3F76NIP.js} +45 -45
  132. package/{commandRegistry-SDSYBKMC.js → commandRegistry-ZLWHQVAI.js} +93 -93
  133. package/{contentThunks-G3TRPEAU.js → contentThunks-4ZX2TO7C.js} +36 -35
  134. package/{cooldownCommands-X7P5M2V5.js → cooldownCommands-YB5H5BBK.js} +4 -4
  135. package/{createAgentAutomationAction-KHA4MXUJ.js → createAgentAutomationAction-L4CYUZJG.js} +36 -35
  136. package/{createDialogAction-KWSBNAPJ.js → createDialogAction-QTU2R2Q3.js} +37 -36
  137. package/{createPageAction-HXKJ7OFG.js → createPageAction-F3GJTHW2.js} +37 -36
  138. package/{db-CS4ZJQKV.js → db-M7FU2GNK.js} +9 -6
  139. package/{dbSlice-ZJPDIFER.js → dbSlice-XRUZOGSU.js} +11 -11
  140. package/{deleteFile-Q3YDB4ML.js → deleteFile-6URDHYRB.js} +7 -7
  141. package/{dialogCommands-6KQEBHSG.js → dialogCommands-NRLCOPJR.js} +52 -52
  142. package/{dialogNotifyCommand-WIZFFEY3.js → dialogNotifyCommand-SHGPCU22.js} +13 -13
  143. package/{dialogSlice-HXPKFGRL.js → dialogSlice-P2S4LXQD.js} +34 -33
  144. package/{dialogUsageCommand-HTVPR2CX.js → dialogUsageCommand-W2WCSGKF.js} +1 -1
  145. package/{docCreateCommands-XZOLWBRC.js → docCreateCommands-YJRDA3RX.js} +48 -47
  146. package/{docDeleteCommands-ZSO4LGWE.js → docDeleteCommands-A5QIHZNF.js} +50 -49
  147. package/{docReadCommands-TTMXCDER.js → docReadCommands-CF2LTMYH.js} +48 -47
  148. package/{docStore-A2B3GH33.js → docStore-6O7NYL6A.js} +12 -12
  149. package/{docUpdateCommands-PRG6WOXL.js → docUpdateCommands-QRKV4ZXE.js} +48 -47
  150. package/fetchMessages-TQEUZD7H.js +1 -1
  151. package/{getPricing-YH3VMSVU.js → getPricing-LF5C4XSI.js} +5 -5
  152. package/{handleSendMessageAction-NWYG3Q72.js → handleSendMessageAction-7IHLR37A.js} +65 -65
  153. package/{hostCredentialCreate-WS6D3EHT.js → hostCredentialCreate-VNCQUAFT.js} +102 -103
  154. package/index.js +56 -18
  155. package/keys-RWF7UCB4.js +1 -1
  156. package/{localDialogRead-SVTPA5GY.js → localDialogRead-CCOCVGAP.js} +1 -1
  157. package/{localRecall-2J6QPOK2.js → localRecall-BDYKXB46.js} +3 -1
  158. package/{localRuntimeAdapter-TFYOA6YE.js → localRuntimeAdapter-FOWVNMIK.js} +109 -110
  159. package/{machineCommands-WFWV25IR.js → machineCommands-ZGC3J4JB.js} +111 -112
  160. package/{machineWsRunDispatch-ZGXC3F2R.js → machineWsRunDispatch-KK5U4M3G.js} +100 -101
  161. package/{memberThunks-JRYNONYV.js → memberThunks-7Y3OYSJQ.js} +15 -15
  162. package/{memoryCommands-5WC3T66U.js → memoryCommands-BC6REPQB.js} +4 -4
  163. package/{models-CXINDUJA.js → models-H5NNZRLH.js} +2 -2
  164. package/{overlay-THLKYIWY.js → overlay-BBQZXGYI.js} +5 -3
  165. package/package.json +1 -1
  166. package/{projectArchive-ULJDLUA6.js → projectArchive-7ZDYBXAX.js} +42 -41
  167. package/{providerPresetApply-SHT2SUVB.js → providerPresetApply-WHAMP2D5.js} +6 -6
  168. package/{providerRegistry-TA7EGCVZ.js → providerRegistry-ZI2KORJ7.js} +6 -6
  169. package/{read-Q7GOHGNP.js → read-TYMBGEXO.js} +8 -8
  170. package/{readDocTool-Z5OQ6422.js → readDocTool-SKQVHBLO.js} +1 -1
  171. package/{readlineWorkspace-LTCV2BFW.js → readlineWorkspace-YHT4SX2C.js} +3946 -4393
  172. package/{removeDialogAgentAction-U3F2MNAY.js → removeDialogAgentAction-F5QE2O2B.js} +16 -16
  173. package/{runAgentClientLoop-BVIEQUB3.js → runAgentClientLoop-H4ED5V3K.js} +71 -67
  174. package/{runtimeDoctorCommands-I47JN4HS.js → runtimeDoctorCommands-RRKPBGVO.js} +14 -14
  175. package/{secretCommands-LJXOOYA7.js → secretCommands-KZWBZIYS.js} +4 -4
  176. package/{setDialogExtraReferencesAction-G3WSJ7EM.js → setDialogExtraReferencesAction-72L27ERM.js} +13 -13
  177. package/{setPrimaryDialogAgentAction-6FHAHZBB.js → setPrimaryDialogAgentAction-GJJDUSGJ.js} +16 -16
  178. package/{settingThunks-AXTBX3Q5.js → settingThunks-ZRGWVGZD.js} +15 -15
  179. package/{skillDiscovery-B5V23AXP.js → skillDiscovery-I37M5KJC.js} +3 -3
  180. package/{spaceCommands-IB6FKWIC.js → spaceCommands-MEH3HJBC.js} +53 -52
  181. package/{store-JRVN62NM.js → store-Z53ICFL3.js} +3 -1
  182. package/{streamAgentChatTurn-DNYFHBJM.js → streamAgentChatTurn-ZXPOXU33.js} +89 -128
  183. package/{switchDialogAgentAction-UOFIAGPL.js → switchDialogAgentAction-IIJBPND3.js} +14 -14
  184. package/{tableCommands-HITDSLHS.js → tableCommands-FTAOCBTX.js} +11 -11
  185. package/{tools-JVOJ5HC4.js → tools-2MRWA2PP.js} +58 -58
  186. package/tuiRestart-2IL37YIB.js +41 -0
  187. package/{tuiSummaryLlmCaller-7LWYTHLM.js → tuiSummaryLlmCaller-W2QN4VAC.js} +18 -18
  188. package/{updateCommands-RJVCRSBP.js → updateCommands-CPATDG6J.js} +8 -6
  189. package/{updateDialogTitleAction-Q57BOSXG.js → updateDialogTitleAction-RZ3KZSGQ.js} +36 -35
  190. package/{usageCommand-RVKHEPLU.js → usageCommand-2BF74MKF.js} +2 -2
  191. package/{usageRebuildCommand-GRAFOZF2.js → usageRebuildCommand-UHB55BQM.js} +3 -3
  192. package/{windowsSelfUpdate-KERHIAB4.js → windowsSelfUpdate-ZFD6J5HF.js} +2 -2
  193. package/chunk-2THCNKE4.js +0 -147
  194. package/chunk-KEPOVMF4.js +0 -91
  195. package/{accountResolver-EK2S4PWF.js → accountResolver-QETKNC7T.js} +3 -3
  196. package/{chunk-AGP3YSEC.js → chunk-4N6G2CKP.js} +3 -3
  197. package/{chunk-BLVSFYQ3.js → chunk-LISC7BD4.js} +3 -3
  198. package/{chunk-SNBZZPYH.js → chunk-OQHIVPG4.js} +3 -3
  199. package/{chunk-47ITIXO7.js → chunk-USGHJSGO.js} +3 -3
  200. package/{offlineMarxistsAgentCommand-4IC3Y4C6.js → offlineMarxistsAgentCommand-XVXUE6G5.js} +3 -3
  201. package/{workloadLifecycle-O2I3NZ2Q.js → workloadLifecycle-HFJIN5IZ.js} +8 -8
@@ -1,24 +1,22 @@
1
1
  import {
2
- parsePositiveFiniteNumberOrFallback
3
- } from "./chunk-Y5GCAMGP.js";
2
+ findPotentialSecrets
3
+ } from "./chunk-6QDYSCPW.js";
4
+ import {
5
+ applyMemoryInterpreterMutation,
6
+ deriveStateResident,
7
+ resolvePureVNextRuntime,
8
+ touchMemoryItemsInDb
9
+ } from "./chunk-ZOHO6MOF.js";
4
10
  import {
5
11
  getReadableCliDb
6
12
  } from "./chunk-YFLVRVYK.js";
7
13
  import {
8
14
  INSTABOX_RUN_CONFIG_ENV,
9
- attachLocalCommandObservations,
10
15
  buildLocalRunEnv,
11
- captureLocalRunBase,
12
- collectHostTaskPlannedWorkspace,
13
- collectHostTaskWorkspace,
14
16
  createCliLocalRuntimeAdapter,
15
- createHostAuthorExecution,
16
17
  detectCurrentMachineId,
17
- formatLocalRunSummary,
18
18
  getOrCreateSharedStore,
19
19
  hashInstaboxDeliveryManifest,
20
- hostTaskEventsRoot,
21
- inspectLocalRunWorkspace,
22
20
  isCliProviderAgentConfig,
23
21
  isDockerRuntimeKey,
24
22
  isFullstackCodingAgentRef,
@@ -26,38 +24,18 @@ import {
26
24
  isLiveAgentRunObservation,
27
25
  isMachineBoundLocalhostCustomProvider,
28
26
  isSubtaskRun,
29
- matchesHostReviewDispatch,
30
- observeLocalCommandResult,
27
+ normalizeCliRunImages,
31
28
  parseAgentRunArgs,
32
29
  parseAgentRunEvent,
33
30
  readFlagValue,
34
- readHostTask,
35
- readHostTaskAcceptancePlan,
36
- redactSecrets,
37
31
  resolveAuthToken as resolveAuthToken2,
38
32
  resolveBoundMachineId,
39
33
  resolveFileWriteGateEnabled,
40
34
  resolveRawAgentInput,
41
35
  resolveServerUrl,
42
- safeAskText,
43
- settleHostReviewsForScope,
44
- shouldPrintLocalRunSummary,
45
- unknownLocalRunAcceptance,
46
- unknownTaskCompletion,
47
36
  validateInstaboxWorkspaceSelection,
48
- withHostReviewDispatch,
49
- withholdIfSecretLike,
50
- wrapLocalCommandWorkspaceObservation,
51
37
  writeUsage
52
- } from "./chunk-KO63FPG3.js";
53
- import {
54
- clearCredentialAvailability,
55
- readEffectiveCredentialEntry
56
- } from "./chunk-FIYSMXHY.js";
57
- import {
58
- readDbRecord,
59
- resolveAgentRecordFromHybridStore
60
- } from "./chunk-6D7NVU66.js";
38
+ } from "./chunk-STJ6LSQE.js";
61
39
  import {
62
40
  boxGlyphs,
63
41
  displayWidth,
@@ -65,30 +43,32 @@ import {
65
43
  stripAnsi,
66
44
  tokenizeAnsiLine,
67
45
  visibleWidth
68
- } from "./chunk-J6T25AJ6.js";
46
+ } from "./chunk-XSW4EXQV.js";
47
+ import {
48
+ clearCredentialAvailability,
49
+ readEffectiveCredentialEntry
50
+ } from "./chunk-WWTSEBDF.js";
51
+ import {
52
+ CliProviderQuotaError
53
+ } from "./chunk-R7XWZDOH.js";
54
+ import {
55
+ resolveMachineId
56
+ } from "./chunk-S73EPYNC.js";
69
57
  import {
70
- _appendEntityBatch,
71
- _appendEvidenceBatch,
72
- _appendRelationBatch,
73
- _appendRetiredStateBatch,
74
- _appendStateBatch,
75
- getMemoryEntityVNext,
76
- getMemoryEvidenceVNext,
77
58
  getMemoryEvidenceVNextStrict,
78
- getMemoryStateVNext,
79
- listMemoryStatesForEntityVNext,
80
59
  loadMemoryVNextCatalog,
81
60
  putMemoryEvidenceVNext
82
- } from "./chunk-XI2BWJM5.js";
61
+ } from "./chunk-324FWHUA.js";
83
62
  import {
84
63
  rankMemoryCandidates,
85
64
  recallMemoryVNextLocal
86
- } from "./chunk-YL3EFYL3.js";
65
+ } from "./chunk-4D4QD7FT.js";
87
66
  import {
88
67
  DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET,
89
68
  EXPLICIT_REMEMBER_PREFIX_REGEX,
90
- buildMemoryOverlay
91
- } from "./chunk-EUCFKKDM.js";
69
+ buildMemoryOverlay,
70
+ emptyMemoryInjectionObservation
71
+ } from "./chunk-4I2MXV5Q.js";
92
72
  import {
93
73
  buildLegacyMemoryEvidence,
94
74
  resolveLegacyMemoryPrincipal
@@ -96,26 +76,17 @@ import {
96
76
  import {
97
77
  isBuiltinNoloAgentRef,
98
78
  resolveLocalUserId
99
- } from "./chunk-OOF7XDZF.js";
100
- import {
101
- CliProviderQuotaError
102
- } from "./chunk-MK2Q7ZJD.js";
103
- import {
104
- resolveMachineId
105
- } from "./chunk-S73EPYNC.js";
79
+ } from "./chunk-HHFGE2WF.js";
106
80
  import {
107
81
  extractGoogleValidationLink
108
82
  } from "./chunk-BMQ2MJUK.js";
109
83
  import {
110
84
  resolveCliLocalRuntimeKeyCapability
111
- } from "./chunk-T3O6BLYU.js";
112
- import {
113
- isTransientFetchError
114
- } from "./chunk-KFHREHUQ.js";
85
+ } from "./chunk-IXG6YXQM.js";
115
86
  import {
116
87
  parseUiCard,
117
88
  uiCardFallback
118
- } from "./chunk-3N4ASIP6.js";
89
+ } from "./chunk-XJPLSAPJ.js";
119
90
  import {
120
91
  isGatewayHttpStatus
121
92
  } from "./chunk-NF64D32W.js";
@@ -125,7 +96,7 @@ import {
125
96
  loadMemoryCandidatesFromDb,
126
97
  loadOwnerItemsFromDb,
127
98
  resolveAgentMemoryPolicy
128
- } from "./chunk-7UH3DGV6.js";
99
+ } from "./chunk-SMJEXX2S.js";
129
100
  import {
130
101
  API_REPORTED_COST_MULTIPLIER,
131
102
  estimateMessagesTokens,
@@ -135,7 +106,17 @@ import {
135
106
  resolveAgentContextWindow,
136
107
  resolveOccupancy,
137
108
  resolveOccupancyWindow
138
- } from "./chunk-FVZW66K4.js";
109
+ } from "./chunk-R3NEQZ53.js";
110
+ import {
111
+ parsePositiveFiniteNumberOrFallback
112
+ } from "./chunk-Y5GCAMGP.js";
113
+ import {
114
+ readDbRecord,
115
+ resolveAgentRecordFromHybridStore
116
+ } from "./chunk-D6YNCNM6.js";
117
+ import {
118
+ isTransientFetchError
119
+ } from "./chunk-DXWGFL2Z.js";
139
120
  import {
140
121
  isCliAuthorityBrokerProtocolError,
141
122
  isCliAuthorityBrokerTimeoutError,
@@ -144,19 +125,55 @@ import {
144
125
  import {
145
126
  getDefaultCliLocalRuntimeDb
146
127
  } from "./chunk-N5Z2V73W.js";
128
+ import {
129
+ awaitLocalWriterChild,
130
+ createRunActivityTracker,
131
+ createShellApprovalChild,
132
+ getRunResultHeaderMeta,
133
+ isHistoryIntegrityFailure,
134
+ popSingleQueueMessage,
135
+ readRunRecord,
136
+ recordRunResultHeaderMeta,
137
+ recordRunStartup,
138
+ registerLocalForegroundWriter,
139
+ reportRunProcessIdentity,
140
+ resolveResultServerMeta,
141
+ resolveRunQueuePath,
142
+ resolveRunsDir,
143
+ serverOriginForDialog,
144
+ settleRunTerminalAuthoritatively,
145
+ spawnLocalBackgroundRun,
146
+ transitionRunToTerminal
147
+ } from "./chunk-OWKNSIXL.js";
148
+ import {
149
+ formatAgentListCard,
150
+ formatFinishedRunCard,
151
+ formatIdentityRow,
152
+ formatListRunsCard,
153
+ formatNotFoundRunCard,
154
+ formatStatusRunCard,
155
+ formatStopRunCard,
156
+ getAgentRunStatusIcon,
157
+ isAgentRunTerminalStatus
158
+ } from "./chunk-OOJNQK6V.js";
147
159
  import {
148
160
  isLocalCliAgentKey
149
161
  } from "./chunk-BR3GT6MR.js";
162
+ import {
163
+ buildSkillDiscoveryContextLayer
164
+ } from "./chunk-Q3IVPFVO.js";
150
165
  import {
151
166
  LOCAL_AGENT_CONFIG_MISSING_CODE,
152
167
  LOCAL_TURN_ABORTED_CODE,
153
- evaluateTaskExecutionContract,
154
168
  markCliUserBatchPhase,
155
169
  readActionGate
156
- } from "./chunk-TVFRV3UQ.js";
170
+ } from "./chunk-JUSHVFNF.js";
157
171
  import {
158
172
  resolveAgentRuntimeConfigFromRecord
159
- } from "./chunk-SASHAZ67.js";
173
+ } from "./chunk-GUXZK7SE.js";
174
+ import {
175
+ resolveAgentImageInputSupport
176
+ } from "./chunk-DUUDXSLX.js";
160
177
  import {
161
178
  createThinkParserState,
162
179
  flushThinkParser,
@@ -168,18 +185,18 @@ import {
168
185
  isQuotaExhaustedText,
169
186
  resolveAvailabilityAction,
170
187
  resolveCredentialKeyWithFallback
171
- } from "./chunk-HOCHUZQ7.js";
188
+ } from "./chunk-QJTZ76CP.js";
172
189
  import {
173
190
  ATTACHMENT_PART_TYPE,
174
191
  ATTACHMENT_PART_VERSION,
175
192
  describeAttachmentForModel,
176
193
  normalizeAttachmentPart
177
- } from "./chunk-XWGDCWXY.js";
194
+ } from "./chunk-QRGDJA4B.js";
178
195
  import {
179
196
  findCodexOAuthPinnedContextWindow,
180
197
  normalizeUsage,
181
198
  readCacheReadInputTokensOrNull
182
- } from "./chunk-HCJFGH6Y.js";
199
+ } from "./chunk-L32W3PRP.js";
183
200
  import {
184
201
  isOAuthApiKeyRef
185
202
  } from "./chunk-UKZX3NHN.js";
@@ -189,13 +206,17 @@ import {
189
206
  import {
190
207
  normalizeRuntimeToolPolicyOverride,
191
208
  resolveEffectiveRuntimeToolPolicy
192
- } from "./chunk-47ITIXO7.js";
209
+ } from "./chunk-USGHJSGO.js";
193
210
  import {
194
211
  compactWhitespace
195
212
  } from "./chunk-DWLEOOGR.js";
196
213
  import {
197
- isAntigravityOAuthAgent
198
- } from "./chunk-JC5XLWZK.js";
214
+ QUOTA_ERROR_PATTERNS,
215
+ isQuotaExhaustedError
216
+ } from "./chunk-EWQ3HGNZ.js";
217
+ import {
218
+ estimateTokenCount
219
+ } from "./chunk-PSCNXBYA.js";
199
220
  import {
200
221
  parseExternalSkillMarkdown,
201
222
  parseSkillDocProtocol
@@ -205,19 +226,13 @@ import {
205
226
  BUILTIN_NOLO_AGENT_NAME,
206
227
  builtinAgentCatalogEntryById,
207
228
  parseBuiltinPlatformAgentId
208
- } from "./chunk-UJKTI5PG.js";
229
+ } from "./chunk-ILHQ2AXT.js";
209
230
  import {
210
231
  parsePublicAgentId
211
232
  } from "./chunk-M2EJHDJP.js";
212
- import {
213
- createMemoryKey
214
- } from "./chunk-SYTHYBMI.js";
215
233
  import {
216
234
  ulid
217
235
  } from "./chunk-OJKUU3LP.js";
218
- import {
219
- buildSkillDiscoveryContextLayer
220
- } from "./chunk-CKT6QUE2.js";
221
236
  import {
222
237
  buildAgentsMdLayer,
223
238
  buildAgentsMdLayerHeader,
@@ -225,55 +240,35 @@ import {
225
240
  buildMemoryUseGuidanceLayer,
226
241
  partitionScopedBlocks,
227
242
  renderTurnContextBlocksWithScope
228
- } from "./chunk-JWXITTQB.js";
243
+ } from "./chunk-3P54D2E4.js";
229
244
  import {
230
245
  exitCliFromWatchdog,
231
246
  getLogger,
232
247
  normalizeError
233
- } from "./chunk-YGMBIXCF.js";
248
+ } from "./chunk-6XRPBZRS.js";
249
+ import {
250
+ RuntimeProtocolMismatchError,
251
+ RuntimeVersionMismatchError,
252
+ resolveAuthToken,
253
+ validateAgentRunProtocol
254
+ } from "./chunk-BIDSIRTS.js";
255
+ import {
256
+ readPipeText,
257
+ spawnProcess
258
+ } from "./chunk-4O22PGNQ.js";
234
259
  import {
235
260
  agentRunCardLabels,
236
261
  getCliLocale,
237
262
  t,
238
263
  toolLabel,
239
264
  toolLabelVariants
240
- } from "./chunk-OB6DVWPF.js";
241
- import {
242
- awaitLocalWriterChild,
243
- createRunActivityTracker,
244
- createShellApprovalChild,
245
- getRunResultHeaderMeta,
246
- isHistoryIntegrityFailure,
247
- popSingleQueueMessage,
248
- readRunRecord,
249
- recordRunResultHeaderMeta,
250
- registerLocalForegroundWriter,
251
- reportRunProcessIdentity,
252
- resolveResultServerMeta,
253
- resolveRunQueuePath,
254
- resolveRunsDir,
255
- serverOriginForDialog,
256
- settleRunTerminalAuthoritatively,
257
- spawnLocalBackgroundRun
258
- } from "./chunk-K5FNYHZC.js";
259
- import {
260
- formatAgentListCard,
261
- formatFinishedRunCard,
262
- formatIdentityRow,
263
- formatListRunsCard,
264
- formatNotFoundRunCard,
265
- formatStatusRunCard,
266
- formatStopRunCard,
267
- getAgentRunStatusIcon,
268
- isAgentRunTerminalStatus
269
- } from "./chunk-AMEOV5VZ.js";
265
+ } from "./chunk-262R3XNN.js";
270
266
  import {
271
- QUOTA_ERROR_PATTERNS,
272
- isQuotaExhaustedError
273
- } from "./chunk-EWQ3HGNZ.js";
267
+ isAntigravityOAuthAgent
268
+ } from "./chunk-7JGMNKKG.js";
274
269
  import {
275
270
  resolveClientVersion
276
- } from "./chunk-2OLYKYNY.js";
271
+ } from "./chunk-RTHFJZ6M.js";
277
272
  import {
278
273
  toErrorMessage
279
274
  } from "./chunk-HNMXYYJR.js";
@@ -282,29 +277,384 @@ import {
282
277
  } from "./chunk-3EUW3WEO.js";
283
278
  import {
284
279
  findModelConfig
285
- } from "./chunk-LE6LGAJE.js";
280
+ } from "./chunk-CD3RU7XL.js";
281
+ import {
282
+ asOptionalTrimmedString
283
+ } from "./chunk-G3SUCT4W.js";
286
284
  import {
287
285
  CLIENT_VERSION_TOO_OLD_CODE,
288
286
  NOLO_CLIENT_VERSION_HEADER,
289
287
  buildClientVersionUpgradeMessage
290
- } from "./chunk-VALBGPM6.js";
288
+ } from "./chunk-OBSEKCVK.js";
291
289
  import {
292
290
  asTrimmedLowercaseString
293
291
  } from "./chunk-QSJ3HFEF.js";
294
- import {
295
- resolveAuthToken
296
- } from "./chunk-2THCNKE4.js";
297
- import {
298
- asOptionalTrimmedString
299
- } from "./chunk-G3SUCT4W.js";
300
292
 
301
293
  // packages/cli/agentRunCommand.ts
294
+ import { createHash as createHash3 } from "node:crypto";
295
+
296
+ // packages/cli/agentRunLocalWorkspace.ts
302
297
  import { createHash } from "node:crypto";
298
+ import { constants } from "node:fs";
299
+ import { lstat, open } from "node:fs/promises";
300
+ import { resolve } from "node:path";
301
+ function unknownLocalRunAcceptance(cwd, base) {
302
+ return {
303
+ schemaVersion: 1,
304
+ source: "local-runtime",
305
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
306
+ cwd,
307
+ base,
308
+ deliveryHead: null,
309
+ workspace: { status: "unknown", fingerprint: null, changedPaths: null, atomic: false },
310
+ checks: { status: "unknown", reason: "No version-bound command execution evidence collected" },
311
+ review: { status: "unknown" }
312
+ };
313
+ }
314
+ async function runGitForLocalSummary(args, deps = {}) {
315
+ const spawn = deps.spawnProcess ?? spawnProcess;
316
+ const read = deps.readPipeText ?? readPipeText;
317
+ const proc = spawn({
318
+ cmd: ["git", ...args.gitArgs],
319
+ cwd: args.cwd,
320
+ stdout: "pipe",
321
+ stderr: "pipe"
322
+ });
323
+ const [stdout, stderr, exitCode] = await Promise.all([
324
+ read(proc.stdout),
325
+ read(proc.stderr),
326
+ proc.exited
327
+ ]);
328
+ if (exitCode !== 0) {
329
+ throw new Error((stderr || stdout || `git ${args.gitArgs.join(" ")} failed`).trim());
330
+ }
331
+ return args.gitArgs.includes("-z") || args.gitArgs.includes("--binary") ? stdout : stdout.trim();
332
+ }
333
+ async function inspectLocalRunWorkspace(cwd, deps = {}, acceptanceBase) {
334
+ if (acceptanceBase !== void 0) {
335
+ const acceptance = unknownLocalRunAcceptance(cwd, acceptanceBase);
336
+ const sample = acceptanceBase === null ? null : await captureBoundedWorkspace(cwd, {
337
+ spawn: deps.spawnProcess,
338
+ signal: deps.signal,
339
+ limits: deps.sampleLimits,
340
+ base: acceptanceBase
341
+ });
342
+ if (sample) {
343
+ acceptance.deliveryHead = sample.head;
344
+ acceptance.workspace = {
345
+ status: "observed",
346
+ fingerprint: sample.fingerprint,
347
+ changedPaths: sample.changedPaths,
348
+ atomic: false
349
+ };
350
+ }
351
+ return {
352
+ cwd,
353
+ clean: sample ? sample.status.trim() === "" : false,
354
+ status: sample?.status ?? "workspace inspection unavailable (unknown)",
355
+ acceptance,
356
+ ...sample?.commit ? { commit: sample.commit } : {}
357
+ };
358
+ }
359
+ const run = (gitArgs) => runGitForLocalSummary({ cwd, gitArgs }, deps);
360
+ const status = await run(["status", "--short"]);
361
+ const rawCommit = await run(["log", "-1", "--format=%h%x00%s"]).catch(() => "");
362
+ const [hash, subject] = rawCommit.split("\0");
363
+ return {
364
+ cwd,
365
+ clean: status.trim() === "",
366
+ status,
367
+ ...hash ? { commit: { hash, subject: subject ?? "" } } : {}
368
+ };
369
+ }
370
+ function shouldPrintLocalRunSummary(args) {
371
+ return Boolean(args.localRuntimeCwd && args.parsed.runtimeMode === "local");
372
+ }
373
+ function formatLocalRunSummary(args) {
374
+ return [
375
+ "",
376
+ "[nolo] local run summary",
377
+ `workspace: ${args.inspection.cwd}`,
378
+ ...args.dialogId ? [`dialog: ${args.dialogId}`] : [],
379
+ ...args.inspection.commit ? [`commit: ${args.inspection.commit.hash} ${args.inspection.commit.subject}`] : [],
380
+ `dirty: ${args.inspection.clean ? "clean" : "dirty"}`,
381
+ ...!args.inspection.clean && args.inspection.status.trim() ? [`status:
382
+ ${args.inspection.status.trim()}`] : [],
383
+ ""
384
+ ].join("\n");
385
+ }
386
+ async function captureLocalRunBase(cwd, options = {}) {
387
+ if (options.signal?.aborted) return null;
388
+ const controller = new AbortController();
389
+ const abort = () => controller.abort();
390
+ options.signal?.addEventListener("abort", abort, { once: true });
391
+ const timer = setTimeout(abort, options.timeoutMs ?? 2e3);
392
+ let child;
393
+ let bytesRead = 0;
394
+ let onAbort;
395
+ const stop = () => {
396
+ child?.kill();
397
+ child?.stdout?.destroy();
398
+ child?.stderr?.destroy();
399
+ };
400
+ controller.signal.addEventListener("abort", stop, { once: true });
401
+ const work = async () => {
402
+ child = (options.spawn ?? spawnProcess)({
403
+ cmd: ["git", "rev-parse", "HEAD"],
404
+ cwd,
405
+ stdin: "ignore",
406
+ stdout: "pipe",
407
+ stderr: "pipe",
408
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" }
409
+ });
410
+ const read = async (stream) => {
411
+ const chunks = [];
412
+ if (stream) for await (const chunk of stream) {
413
+ if (controller.signal.aborted) throw new Error("base capture cancelled");
414
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
415
+ bytesRead += bytes.length;
416
+ if (bytesRead > (options.outputBytes ?? 4096)) {
417
+ controller.abort();
418
+ throw new Error("base output budget");
419
+ }
420
+ chunks.push(bytes);
421
+ }
422
+ return Buffer.concat(chunks).toString("utf8").trim();
423
+ };
424
+ const [head, , code] = await Promise.all([read(child.stdout), read(child.stderr), child.exited]);
425
+ if (controller.signal.aborted || code !== 0 || !/^[a-f0-9]{40,64}$/.test(head)) return null;
426
+ return head;
427
+ };
428
+ try {
429
+ return await Promise.race([work(), new Promise((resolve5) => {
430
+ onAbort = () => resolve5(null);
431
+ controller.signal.addEventListener("abort", onAbort, { once: true });
432
+ if (controller.signal.aborted) resolve5(null);
433
+ })]);
434
+ } catch {
435
+ return null;
436
+ } finally {
437
+ controller.abort();
438
+ clearTimeout(timer);
439
+ options.signal?.removeEventListener("abort", abort);
440
+ controller.signal.removeEventListener("abort", stop);
441
+ if (onAbort) controller.signal.removeEventListener("abort", onAbort);
442
+ }
443
+ }
444
+ function observeLocalCommandResult(event, cwd) {
445
+ if (event.type !== "tool-result" || event.toolName !== "execShell") return;
446
+ const meta = event.metadata;
447
+ if (!meta || meta.executionState !== "synchronous-complete" || meta.detached === true || meta.aborted === true || typeof meta.command !== "string" || typeof meta.timedOut !== "boolean" || !meta.timedOut && (typeof meta.exitCode !== "number" || !Number.isInteger(meta.exitCode))) return;
448
+ return {
449
+ commandFingerprint: `sha256:${createHash("sha256").update(meta.command).digest("hex")}`,
450
+ cwd,
451
+ cwdSource: "configured-workspace",
452
+ exitCode: meta.timedOut ? "timeout" : meta.exitCode,
453
+ // Settlement replaces this with the containing result-file JSON pointer.
454
+ evidence: "runtime-tool-result",
455
+ versionBinding: "unknown",
456
+ source: "execShell-tool-result",
457
+ toolCallId: event.toolCallId,
458
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString()
459
+ };
460
+ }
461
+ function attachLocalCommandObservations(acceptance, observations, resultReference) {
462
+ if (!observations.length) return;
463
+ const existing = acceptance.checks.observations ?? [];
464
+ acceptance.checks.observations = [...existing, ...observations.map((observation, index) => ({
465
+ ...observation,
466
+ evidence: `${resultReference}#/acceptance/checks/observations/${existing.length + index}`
467
+ }))];
468
+ acceptance.checks.reason = "Command exits observed; execution cwd is configured only and execution-time version stability is unproven";
469
+ }
470
+ var COMMAND_WORKSPACE_SAMPLE_LIMITS = {
471
+ timeoutMs: 2e3,
472
+ gitOutputBytes: 1024 * 1024,
473
+ files: 128,
474
+ fileBytes: 1024 * 1024,
475
+ totalFileBytes: 4 * 1024 * 1024,
476
+ concurrentSamples: 1
477
+ };
478
+ var activeCommandWorkspaceSamples = 0;
479
+ async function captureBoundedWorkspace(cwd, options = {}) {
480
+ if (options.signal?.aborted || activeCommandWorkspaceSamples >= COMMAND_WORKSPACE_SAMPLE_LIMITS.concurrentSamples) return null;
481
+ activeCommandWorkspaceSamples++;
482
+ const limits = { ...COMMAND_WORKSPACE_SAMPLE_LIMITS, ...options.limits };
483
+ const controller = new AbortController();
484
+ const abort = () => controller.abort();
485
+ options.signal?.addEventListener("abort", abort, { once: true });
486
+ const timer = setTimeout(abort, limits.timeoutMs);
487
+ let outputBytes = 0;
488
+ let fileBytes = 0;
489
+ const check = () => {
490
+ if (controller.signal.aborted) throw new Error("sample cancelled");
491
+ };
492
+ const git = async (args) => {
493
+ check();
494
+ const child = (options.spawn ?? spawnProcess)({
495
+ cmd: ["git", ...args],
496
+ cwd,
497
+ stdin: "ignore",
498
+ stdout: "pipe",
499
+ stderr: "pipe",
500
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" }
501
+ });
502
+ const stop = () => {
503
+ child.kill();
504
+ child.stdout?.destroy();
505
+ child.stderr?.destroy();
506
+ };
507
+ controller.signal.addEventListener("abort", stop, { once: true });
508
+ const read = async (stream) => {
509
+ const chunks = [];
510
+ if (stream) for await (const chunk of stream) {
511
+ check();
512
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
513
+ outputBytes += bytes.length;
514
+ if (outputBytes > limits.gitOutputBytes) {
515
+ controller.abort();
516
+ throw new Error("git output budget");
517
+ }
518
+ chunks.push(bytes);
519
+ }
520
+ return Buffer.concat(chunks);
521
+ };
522
+ try {
523
+ const [stdout, , code] = await Promise.all([read(child.stdout), read(child.stderr), child.exited]);
524
+ check();
525
+ if (code !== 0) throw new Error("git inspection failed");
526
+ return stdout;
527
+ } finally {
528
+ controller.signal.removeEventListener("abort", stop);
529
+ stop();
530
+ }
531
+ };
532
+ const work = async () => {
533
+ const head = await git(["rev-parse", "HEAD"]);
534
+ const root = (await git(["rev-parse", "--show-toplevel"])).toString("utf8").trim();
535
+ const digest = createHash("sha256").update(head);
536
+ const summary = options.base !== void 0 ? (await git(["log", "-1", "--format=%h%x00%s"])).toString("utf8").trim() : "";
537
+ const paths = options.base !== void 0 ? (await git(["-C", root, "diff", "--name-only", "-z", options.base, "--"])).toString("utf8").split("\0").filter(Boolean) : [];
538
+ if (paths.length > limits.files) throw new Error("base changed file count budget");
539
+ const status = await git(["-C", root, "status", "--porcelain=v1", "-z", "--untracked-files=all"]);
540
+ if (status.toString("utf8").split("\0").filter(Boolean).length > limits.files) throw new Error("changed file count budget");
541
+ digest.update(status);
542
+ for (const args of [
543
+ ["diff", "--no-ext-diff", "--no-textconv", "--binary", "HEAD", "--"],
544
+ ["diff", "--cached", "--no-ext-diff", "--no-textconv", "--binary", "HEAD", "--"]
545
+ ]) digest.update(await git(["-C", root, ...args]));
546
+ const names = (await git(["-C", root, "ls-files", "--others", "--exclude-standard", "-z"])).toString("utf8").split("\0").filter(Boolean).sort();
547
+ if (names.length > limits.files) throw new Error("file count budget");
548
+ for (const name of names) {
549
+ check();
550
+ const path2 = resolve(root, name);
551
+ const stat = await lstat(path2);
552
+ check();
553
+ if (!stat.isFile() || stat.size > limits.fileBytes || fileBytes + stat.size > limits.totalFileBytes) throw new Error("file budget");
554
+ digest.update(JSON.stringify([name, stat.mode, stat.size]));
555
+ if (stat.size === 0) {
556
+ const after2 = await lstat(path2);
557
+ check();
558
+ if (!after2.isFile() || after2.size !== 0 || after2.ino !== stat.ino || after2.mtimeMs !== stat.mtimeMs) throw new Error("racing empty file");
559
+ continue;
560
+ }
561
+ let readBytes = 0;
562
+ const file = await open(path2, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
563
+ try {
564
+ check();
565
+ const opened = await file.stat();
566
+ check();
567
+ if (!opened.isFile() || opened.ino !== stat.ino || opened.size !== stat.size) throw new Error("racing open");
568
+ const stream = file.createReadStream({
569
+ autoClose: false,
570
+ highWaterMark: Math.min(32 * 1024, stat.size),
571
+ end: stat.size - 1,
572
+ signal: controller.signal
573
+ });
574
+ try {
575
+ for await (const chunk of stream) {
576
+ check();
577
+ const bytes = chunk;
578
+ readBytes += bytes.length;
579
+ fileBytes += bytes.length;
580
+ if (readBytes > limits.fileBytes || fileBytes > limits.totalFileBytes) throw new Error("read budget");
581
+ digest.update(bytes);
582
+ }
583
+ } finally {
584
+ stream.destroy();
585
+ }
586
+ } finally {
587
+ await file.close();
588
+ }
589
+ const after = await lstat(path2);
590
+ check();
591
+ if (readBytes !== stat.size || after.size !== stat.size || after.mtimeMs !== stat.mtimeMs || after.ino !== stat.ino || !after.isFile()) throw new Error("racing file");
592
+ }
593
+ check();
594
+ const [hash, subject] = summary.split("\0");
595
+ return {
596
+ fingerprint: `sha256:${digest.digest("hex")}`,
597
+ head: head.toString("utf8").trim(),
598
+ status: status.toString("utf8").replace(/\0/g, "\n"),
599
+ changedPaths: [.../* @__PURE__ */ new Set([...paths, ...names])].sort(),
600
+ ...hash ? { commit: { hash, subject: subject ?? "" } } : {}
601
+ };
602
+ };
603
+ let onAbort;
604
+ try {
605
+ const pending = work().finally(() => {
606
+ activeCommandWorkspaceSamples--;
607
+ });
608
+ return await Promise.race([pending, new Promise((resolve5) => {
609
+ onAbort = () => resolve5(null);
610
+ controller.signal.addEventListener("abort", onAbort, { once: true });
611
+ if (controller.signal.aborted) resolve5(null);
612
+ })]);
613
+ } catch {
614
+ return null;
615
+ } finally {
616
+ controller.abort();
617
+ clearTimeout(timer);
618
+ options.signal?.removeEventListener("abort", abort);
619
+ if (onAbort) controller.signal.removeEventListener("abort", onAbort);
620
+ }
621
+ }
622
+ async function captureCommandWorkspaceFingerprint(cwd, options = {}) {
623
+ return (await captureBoundedWorkspace(cwd, options))?.fingerprint ?? null;
624
+ }
625
+ function wrapLocalCommandWorkspaceObservation(adapter, cwd, bindings, capture = captureCommandWorkspaceFingerprint, signal) {
626
+ const safeCapture = (callSignal) => capture(cwd, { signal: signal ?? callSignal }).catch(() => null);
627
+ return {
628
+ ...adapter,
629
+ async executeTool(call, options) {
630
+ if (call.name !== "execShell") return adapter.executeTool.call(adapter, call, options);
631
+ try {
632
+ if (JSON.parse(call.arguments).background === true) return adapter.executeTool.call(adapter, call, options);
633
+ } catch {
634
+ }
635
+ const before = await safeCapture(options?.abortSignal);
636
+ const result = await adapter.executeTool.call(adapter, call, options);
637
+ if (result.metadata?.executionState === "synchronous-complete" && result.metadata.detached !== true && result.metadata.aborted !== true) {
638
+ const after = await safeCapture(options?.abortSignal);
639
+ bindings.set(call.id, {
640
+ versionBinding: !before || !after ? "unknown" : before === after ? "observed-unchanged" : "stale",
641
+ executionWorkspace: {
642
+ before,
643
+ after,
644
+ atomic: false,
645
+ limitation: "ABA and external concurrent writes are not excluded"
646
+ }
647
+ });
648
+ }
649
+ return result;
650
+ }
651
+ };
652
+ }
303
653
 
304
654
  // packages/cli/client/instaboxRunConfigWrite.ts
305
655
  import { randomUUID } from "node:crypto";
306
656
  import { lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
307
- import { isAbsolute, join, normalize, resolve } from "node:path";
657
+ import { isAbsolute, join, normalize, resolve as resolve2 } from "node:path";
308
658
  var InstaboxRunConfigWriteError = class extends Error {
309
659
  code;
310
660
  constructor(code, message) {
@@ -341,7 +691,7 @@ function writeInstaboxRunConfig(options) {
341
691
  if (!rawPath) {
342
692
  fail("missing_manifest_path", 'workspaceMode \u4E3A "snapshot" \u65F6\u5FC5\u987B\u63D0\u4F9B manifest \u6587\u4EF6\u8DEF\u5F84');
343
693
  }
344
- const resolvedManifestPath = resolve(rawPath);
694
+ const resolvedManifestPath = resolve2(rawPath);
345
695
  let rawText = "";
346
696
  try {
347
697
  const reader = options.readTextFile ?? ((p) => readFileSync(p, "utf8"));
@@ -411,7 +761,7 @@ function writeInstaboxRunConfig(options) {
411
761
  config.manifestSha256 = manifestSha256;
412
762
  }
413
763
  const runsDir = options.runsDir ?? resolveRunsDir(env);
414
- const normalizedRunsDir = normalize(resolve(runsDir));
764
+ const normalizedRunsDir = normalize(resolve2(runsDir));
415
765
  try {
416
766
  mkdirSync(normalizedRunsDir, { recursive: true, mode: 448 });
417
767
  } catch (err) {
@@ -516,78 +866,6 @@ function resolveCliBatchIdentity(options) {
516
866
  return { batchId, messageIds };
517
867
  }
518
868
 
519
- // packages/cli/client/agentRun.ts
520
- import { resolve as resolveHostReviewPath } from "node:path";
521
-
522
- // packages/cli/client/hostTaskBinding.ts
523
- import { resolve as resolve2 } from "node:path";
524
- function bindHostTask(args) {
525
- let latest;
526
- let completion;
527
- function load() {
528
- if (!args.reference) return void 0;
529
- if (resolve2(args.reference.workspace) !== resolve2(args.workspace) || args.reference.dialogId !== args.dialogId) {
530
- return { authorization: "unknown", reason: "scope_mismatch" };
531
- }
532
- return readHostTask(hostTaskEventsRoot(args.env), args.reference);
533
- }
534
- latest = load();
535
- const contract = args.completionEvidenceProvider && latest && latest.authorization !== "unknown" ? latest.contract : void 0;
536
- const adapter = !args.reference ? args.adapter : {
537
- ...args.adapter,
538
- // Re-read authority before each protected action. A review-only binding owns
539
- // typed review tools, not ordinary chat tools or their existing permission gates.
540
- // Explicit completion tasks retain their all-tool stop semantics; unknown scope
541
- // fails closed. Already running tools are not cancelled by this entry guard.
542
- executeTool: async (call, opts) => {
543
- latest = load();
544
- const authorization = latest?.authorization ?? "unknown";
545
- const protectedTool = call.name === "requestTaskReview" || call.name === "recordTaskReviewDecision";
546
- if (authorization !== "active" && (args.completionEvidenceProvider || protectedTool || authorization === "unknown")) {
547
- const code = authorization === "paused" ? "authorization_paused" : authorization === "revoked" ? "authorization_revoked" : "authorization_unknown";
548
- throw Object.assign(new Error(`host task authority ${authorization}: tool "${call.name}" was not executed`), { code });
549
- }
550
- return args.adapter.executeTool(call, opts);
551
- },
552
- saveTurn: async (input) => {
553
- latest = load();
554
- const stopped = args.signal?.aborted || input.result.businessCompletion?.reasons.includes("stopped");
555
- if (args.completionEvidenceProvider) {
556
- const snapshot = latest && latest.authorization !== "unknown" ? latest.contract : void 0;
557
- let evidence;
558
- try {
559
- evidence = snapshot ? await args.completionEvidenceProvider(snapshot) : void 0;
560
- } catch {
561
- }
562
- latest = load();
563
- const current = latest && latest.authorization !== "unknown" ? latest.contract : void 0;
564
- completion = !current || !evidence || evidence.taskId !== current.taskId ? stopped ? { taskId: args.reference.taskId, status: "blocked", reasons: ["stopped"] } : unknownTaskCompletion(args.reference.taskId) : evaluateTaskExecutionContract({ ...evidence, authorization: current.authorization }, {
565
- stopped,
566
- executionFailed: input.result.error === true || !!input.result.runtimeProviderFailure || !!input.result.emptyAssistantFallbackReason,
567
- budgetExhausted: input.result.businessCompletion?.reasons.includes("budget_exhausted")
568
- });
569
- }
570
- const result = { ...input.result };
571
- delete result.businessCompletion;
572
- if (completion) result.businessCompletion = completion;
573
- try {
574
- return await args.adapter.saveTurn({ ...input, result });
575
- } catch (error) {
576
- if (args.completionEvidenceProvider) completion = { taskId: args.reference.taskId, status: "blocked", reasons: ["execution_failed"] };
577
- throw error;
578
- }
579
- }
580
- };
581
- return {
582
- adapter,
583
- contract,
584
- result: () => args.reference ? {
585
- taskAuthorization: latest?.authorization ?? "unknown",
586
- ...args.completionEvidenceProvider ? { businessCompletion: completion ?? unknownTaskCompletion(args.reference.taskId) } : {}
587
- } : {}
588
- };
589
- }
590
-
591
869
  // packages/agent-runtime/modelLayerOverride.ts
592
870
  var MODEL_LAYER_KEYS = [
593
871
  "provider",
@@ -2648,8 +2926,8 @@ function stripHtmlTags(s) {
2648
2926
  }
2649
2927
  return out;
2650
2928
  }
2651
- function unwrap(s, open, close) {
2652
- return s.length >= open.length + close.length && s.startsWith(open) && s.endsWith(close) ? s.slice(open.length, s.length - close.length) : null;
2929
+ function unwrap(s, open2, close) {
2930
+ return s.length >= open2.length + close.length && s.startsWith(open2) && s.endsWith(close) ? s.slice(open2.length, s.length - close.length) : null;
2653
2931
  }
2654
2932
  function cleanLabel(raw) {
2655
2933
  const trimmed = stripHtmlTags(raw.trim()).trim();
@@ -2659,11 +2937,11 @@ function cleanLabel(raw) {
2659
2937
  }
2660
2938
  function displayGenerics(s) {
2661
2939
  let out = "";
2662
- let open = false;
2940
+ let open2 = false;
2663
2941
  for (const c of s) {
2664
2942
  if (c === "~") {
2665
- out += open ? ">" : "<";
2666
- open = !open;
2943
+ out += open2 ? ">" : "<";
2944
+ open2 = !open2;
2667
2945
  } else {
2668
2946
  out += c;
2669
2947
  }
@@ -4744,15 +5022,15 @@ function parseClass(src) {
4744
5022
  }
4745
5023
  if (first === "class") {
4746
5024
  const rest = st.slice("class".length).trim();
4747
- const open = rest.endsWith("{");
4748
- let name = open ? rest.slice(0, -1).trim() : rest;
5025
+ const open2 = rest.endsWith("{");
5026
+ let name = open2 ? rest.slice(0, -1).trim() : rest;
4749
5027
  let label = null;
4750
5028
  const labeled = /^(\S+?)\[(.+)\](:::\S+)?$/.exec(name);
4751
5029
  if (labeled) {
4752
5030
  name = labeled[1] + (labeled[3] ?? "");
4753
5031
  label = nonEmpty(cleanLabel(labeled[2]));
4754
5032
  }
4755
- if (!open && /\s/.test(name)) {
5033
+ if (!open2 && /\s/.test(name)) {
4756
5034
  const assign = parseClassAssign(name);
4757
5035
  if (assign)
4758
5036
  classAssignments.push(assign);
@@ -4760,7 +5038,7 @@ function parseClass(src) {
4760
5038
  graph.drop(st);
4761
5039
  } else if (name === "" || /\s/.test(name)) {
4762
5040
  graph.drop(st);
4763
- if (open)
5041
+ if (open2)
4764
5042
  curClass = "skip";
4765
5043
  } else {
4766
5044
  const idx = declare(name);
@@ -4771,7 +5049,7 @@ function parseClass(src) {
4771
5049
  if (title)
4772
5050
  title[title.length - 1] = label;
4773
5051
  }
4774
- if (open)
5052
+ if (open2)
4775
5053
  curClass = idx ?? "skip";
4776
5054
  }
4777
5055
  } else if (st.startsWith("<<")) {
@@ -4956,15 +5234,15 @@ function parseEr(src) {
4956
5234
  });
4957
5235
  }
4958
5236
  } else {
4959
- const open = st.endsWith("{");
4960
- const decl = open ? st.slice(0, -1).trim() : st;
5237
+ const open2 = st.endsWith("{");
5238
+ const decl = open2 ? st.slice(0, -1).trim() : st;
4961
5239
  if (decl === "" || erTokens(decl).length !== 1) {
4962
5240
  graph.drop(st);
4963
- if (open)
5241
+ if (open2)
4964
5242
  curEntity = "skip";
4965
5243
  } else {
4966
5244
  const idx = erEntity(graph, decl);
4967
- if (open)
5245
+ if (open2)
4968
5246
  curEntity = idx ?? "skip";
4969
5247
  }
4970
5248
  }
@@ -4976,14 +5254,14 @@ function parseEr(src) {
4976
5254
  return graph.nodes.length === 0 ? null : graph;
4977
5255
  }
4978
5256
  function erEntity(graph, token) {
4979
- const open = token.startsWith('"') ? -1 : token.indexOf("[");
5257
+ const open2 = token.startsWith('"') ? -1 : token.indexOf("[");
4980
5258
  let idx;
4981
- if (open !== -1) {
4982
- const id = token.slice(0, open);
5259
+ if (open2 !== -1) {
5260
+ const id = token.slice(0, open2);
4983
5261
  if (!token.endsWith("]")) {
4984
5262
  graph.warnings.push(`entity "${id}": alias is missing its closing \`]\``);
4985
5263
  }
4986
- const label = cleanLabel(token.slice(open + 1).replace(/\]+$/, ""));
5264
+ const label = cleanLabel(token.slice(open2 + 1).replace(/\]+$/, ""));
4987
5265
  if (id === "" || label === "")
4988
5266
  return null;
4989
5267
  idx = graph.nodeLabel(id, label);
@@ -5165,10 +5443,10 @@ function parseSubgraphDecl(rest) {
5165
5443
  return [label, decodeHtmlEntities(label)];
5166
5444
  }
5167
5445
  }
5168
- const open = rest.indexOf("[");
5169
- if (open !== -1) {
5170
- const id = rest.slice(0, open).trim();
5171
- const label = cleanLabel(rest.slice(open + 1).replace(/\]+$/, "").trim());
5446
+ const open2 = rest.indexOf("[");
5447
+ if (open2 !== -1) {
5448
+ const id = rest.slice(0, open2).trim();
5449
+ const label = cleanLabel(rest.slice(open2 + 1).replace(/\]+$/, "").trim());
5172
5450
  if (id !== "" && label !== "")
5173
5451
  return [id, label];
5174
5452
  }
@@ -5729,10 +6007,10 @@ var SHAPES = [
5729
6007
  ["(", ")"]
5730
6008
  ];
5731
6009
  function nodeText(body) {
5732
- for (const [open, close] of SHAPES) {
5733
- const at = body.indexOf(open);
5734
- if (at !== -1 && body.endsWith(close) && body.length > at + open.length + close.length - 1) {
5735
- return cleanLabel(body.slice(at + open.length, body.length - close.length));
6010
+ for (const [open2, close] of SHAPES) {
6011
+ const at = body.indexOf(open2);
6012
+ if (at !== -1 && body.endsWith(close) && body.length > at + open2.length + close.length - 1) {
6013
+ return cleanLabel(body.slice(at + open2.length, body.length - close.length));
5736
6014
  }
5737
6015
  }
5738
6016
  return cleanLabel(body);
@@ -6306,9 +6584,9 @@ function parseState(src) {
6306
6584
  inNote = true;
6307
6585
  } else if (first === "state") {
6308
6586
  const rest = st.slice(firstWord(st).length).trim();
6309
- const open = rest.endsWith("{");
6310
- const body = open ? rest.slice(0, -1).trim() : rest;
6311
- if (!open) {
6587
+ const open2 = rest.endsWith("{");
6588
+ const body = open2 ? rest.slice(0, -1).trim() : rest;
6589
+ if (!open2) {
6312
6590
  if (parseStateDecl(body, graph) === null)
6313
6591
  graph.drop(st);
6314
6592
  } else {
@@ -8140,7 +8418,7 @@ function normalizeListLine(line) {
8140
8418
  }
8141
8419
  return line;
8142
8420
  }
8143
- var TOOL_TREE_HEADER_RE = /^•\s+(.+?)\s+\((\d+)\) · (.*?) ✓$/;
8421
+ var TOOL_TREE_HEADER_RE = /^(?:▸|•)\s+(.+?)\s+\((\d+)\) · (.*?) ✓$/;
8144
8422
  var TOOL_SINGLE_RE = /^▸\s+(.+?)(?:\s+·\s+(.*?))?(?:\s{2}(✓|✗|!)(?:\s+(.*))?)$/;
8145
8423
  function plainToolLine(line) {
8146
8424
  return stripAnsi(line);
@@ -8186,23 +8464,40 @@ function statusColorSeq(marker, brightness) {
8186
8464
  if (marker === "\u2717") return colorSeq("danger", brightness);
8187
8465
  return colorSeq("warning", brightness);
8188
8466
  }
8467
+ function styleToolDetailSegments(detail, muted, chrome) {
8468
+ const metaMatch = detail.match(/^(.*?)(\s+·\s+(?:\d+\s+(?:lines?|bytes?\s+written|replacements?|matches?)(?:\s+·\s+truncated)?|truncated))$/);
8469
+ if (!metaMatch) {
8470
+ return `${muted}${detail}${STYLE.reset}`;
8471
+ }
8472
+ return `${muted}${metaMatch[1]}${STYLE.reset}${chrome}${STYLE.dim}${metaMatch[2]}${STYLE.reset}`;
8473
+ }
8189
8474
  function styleTuiToolLine(line, brightness) {
8190
8475
  const plain = plainToolLine(line);
8191
8476
  const chrome = colorSeq("chrome", brightness);
8192
8477
  const muted = colorSeq("muted", brightness);
8478
+ const info = colorSeq("info", brightness);
8479
+ const danger = colorSeq("danger", brightness);
8193
8480
  const header = toolTreeHeaderMatch(plain);
8194
8481
  if (header) {
8195
- return `${chrome}\u2022${STYLE.reset} ${STYLE.bold}${muted}${header[1]}${STYLE.reset} ${chrome}${STYLE.dim}(${header[2]})${STYLE.reset} ${chrome}\xB7 ${header[3]}${STYLE.reset} ${statusColorSeq("\u2713", brightness)}\u2713${STYLE.reset}`;
8482
+ const glyph = plain.startsWith("\u2022") ? "\u2022" : "\u25B8";
8483
+ return `${chrome}${glyph}${STYLE.reset} ${STYLE.bold}${info}${header[1]}${STYLE.reset} ${chrome}${STYLE.dim}(${header[2]})${STYLE.reset} ${chrome}\xB7${STYLE.reset} ${muted}${header[3]}${STYLE.reset} ${statusColorSeq("\u2713", brightness)}\u2713${STYLE.reset}`;
8196
8484
  }
8197
8485
  const single = plain.match(TOOL_SINGLE_RE);
8198
8486
  if (single) {
8199
8487
  const [, label, detail, marker, statusDetail] = single;
8200
- let rendered = `${chrome}\u25B8${STYLE.reset} ${STYLE.bold}${muted}${label}${STYLE.reset}`;
8201
- if (detail) rendered += ` ${chrome}\xB7 ${detail}${STYLE.reset}`;
8488
+ const isError = marker === "\u2717";
8489
+ const labelColor = isError ? danger : info;
8490
+ let rendered = `${chrome}\u25B8${STYLE.reset} ${STYLE.bold}${labelColor}${label}${STYLE.reset}`;
8491
+ if (detail) {
8492
+ rendered += ` ${chrome}\xB7${STYLE.reset} ${styleToolDetailSegments(detail, muted, chrome)}`;
8493
+ }
8202
8494
  rendered += ` ${statusColorSeq(marker, brightness)}${marker}${STYLE.reset}`;
8203
8495
  if (statusDetail) {
8204
- const metaSeq = marker === "\u2713" ? chrome : statusColorSeq(marker, brightness);
8205
- rendered += ` ${metaSeq}${STYLE.dim}${statusDetail}${STYLE.reset}`;
8496
+ if (isError) {
8497
+ rendered += ` ${danger}${statusDetail}${STYLE.reset}`;
8498
+ } else {
8499
+ rendered += ` ${chrome}${STYLE.dim}${statusDetail}${STYLE.reset}`;
8500
+ }
8206
8501
  }
8207
8502
  return rendered;
8208
8503
  }
@@ -8733,6 +9028,9 @@ function formatAssistantTextForCli(text) {
8733
9028
  return text.replace(/\u003cthink\u003e[\s\S]*?\u003c\/think\u003e\s*/gi, "").replace(/\n{3,}/g, "\n\n").trim();
8734
9029
  }
8735
9030
 
9031
+ // packages/cli/client/toolOutput.ts
9032
+ import { createHash as createHash2 } from "node:crypto";
9033
+
8736
9034
  // packages/cli/tui/tuiLayout.ts
8737
9035
  var DEFAULT_TERMINAL_ROWS = 24;
8738
9036
  var DEFAULT_TERMINAL_COLUMNS = 80;
@@ -8764,25 +9062,982 @@ function resolveHistoryViewportHeight(terminalRows, composerRows, foregroundRese
8764
9062
  return Math.max(0, rows - composer - reserved);
8765
9063
  }
8766
9064
 
8767
- // node_modules/diff/libesm/diff/base.js
8768
- var Diff = class {
8769
- diff(oldStr, newStr, options = {}) {
8770
- let callback;
8771
- if (typeof options === "function") {
8772
- callback = options;
8773
- options = {};
8774
- } else if ("callback" in options) {
8775
- callback = options.callback;
9065
+ // packages/core/redactSecrets.ts
9066
+ var REDACTED = "\u27E8redacted\u27E9";
9067
+ function redactSecrets(text) {
9068
+ return text.replace(/\b(?:sk|pk)-[A-Za-z0-9_-]{10,}/g, REDACTED).replace(
9069
+ /\b(Authorization:\s*Basic\s+)[A-Za-z0-9._~+/=-]{8,}/gi,
9070
+ `$1${REDACTED}`
9071
+ ).replace(/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{12,}/gi, `$1${REDACTED}`).replace(
9072
+ /(^|\s)((?:--[a-z0-9-]*(?:token|key|secret|password|credential)[a-z0-9-]*)(?:[^\S\r\n]*=[^\S\r\n]*|[^\S\r\n]+))(?:"(?:\\[^\r\n]|[^"\\\r\n]){8,}(?:"|(?=[\r\n]|$))|'(?:\\[^\r\n]|[^'\\\r\n]){8,}(?:'|(?=[\r\n]|$))|[^\s"']{8,})/gi,
9073
+ `$1$2${REDACTED}`
9074
+ ).replace(
9075
+ /(^|[^\w-])((?:[A-Z0-9]+_)*(?:API[_-]?KEY|APIKEY|ACCESS[_-]?TOKEN|AUTH[_-]?TOKEN|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|KEY)\s*[=:]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n]){8,}(?:"|(?=[\r\n]|$))|'(?:\\[^\r\n]|[^'\\\r\n]){8,}(?:'|(?=[\r\n]|$))|[^\s"',;]{8,})/g,
9076
+ `$1$2${REDACTED}`
9077
+ ).replace(
9078
+ /\b((?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|token|secret|password|passwd|credential)s?\s*[=:]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n]){8,}(?:"|(?=[\r\n]|$))|'(?:\\[^\r\n]|[^'\\\r\n]){8,}(?:'|(?=[\r\n]|$))|[^\s"',;]{8,})/gi,
9079
+ `$1${REDACTED}`
9080
+ );
9081
+ }
9082
+
9083
+ // packages/cli/tui/redactSecrets.ts
9084
+ var NORMAL_GIST_SECRET_PATTERNS = [
9085
+ /\bbearer\s+[A-Za-z0-9._~+/=-]{8,}/i,
9086
+ /\bsk-(?:ant-)?(?:api)?[0-9a-zA-Z-]{10,}/,
9087
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{10,}/,
9088
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}/
9089
+ ];
9090
+ function withholdIfSecretLike(gist) {
9091
+ if (!gist) return "";
9092
+ if (findPotentialSecrets(gist).length > 0) return "";
9093
+ if (NORMAL_GIST_SECRET_PATTERNS.some((pattern) => pattern.test(gist))) return "";
9094
+ return gist;
9095
+ }
9096
+
9097
+ // packages/core/shellCommandGist.ts
9098
+ function shellWords(text, validationOnly = false) {
9099
+ const words2 = [];
9100
+ let word = "", started = false;
9101
+ let quote;
9102
+ for (let i = 0; i < text.length; i++) {
9103
+ const ch = text[i];
9104
+ if (ch === "\\" && quote !== "'") {
9105
+ const next = text[++i];
9106
+ if (next === void 0) return null;
9107
+ word += next;
9108
+ started = true;
9109
+ continue;
9110
+ }
9111
+ if (ch === "$" && quote !== "'" || ch === "`" && quote !== "'") return null;
9112
+ if (quote) {
9113
+ if (ch === quote) quote = void 0;
9114
+ else word += ch;
9115
+ continue;
9116
+ }
9117
+ if (ch === "'" || ch === '"') {
9118
+ quote = ch;
9119
+ started = true;
9120
+ continue;
9121
+ }
9122
+ if (validationOnly && (ch === "|" || ch === "~")) {
9123
+ word += ch;
9124
+ started = true;
9125
+ continue;
9126
+ }
9127
+ if (/[<> &|;(){}*?\[\]#~]/.test(ch) && !/\s/.test(ch)) return null;
9128
+ if (/\s/.test(ch)) {
9129
+ if (started) words2.push(word);
9130
+ word = "";
9131
+ started = false;
9132
+ } else {
9133
+ word += ch;
9134
+ started = true;
8776
9135
  }
8777
- const oldString = this.castInput(oldStr, options);
8778
- const newString = this.castInput(newStr, options);
8779
- const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
8780
- const newTokens = this.removeEmpty(this.tokenize(newString, options));
8781
- return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
8782
9136
  }
8783
- diffWithOptionsObj(oldTokens, newTokens, options, callback) {
8784
- var _a;
8785
- const done = (value) => {
9137
+ if (quote) return null;
9138
+ if (started) words2.push(word);
9139
+ return words2;
9140
+ }
9141
+ function isSafeGitTarget(token) {
9142
+ if (!token || token.startsWith("-")) return false;
9143
+ if (/:\/\/|@/.test(token)) return false;
9144
+ return true;
9145
+ }
9146
+ function clipShortText(text, maxLen = 24) {
9147
+ const oneLine = text.replace(/\s+/g, " ").trim();
9148
+ if (!oneLine) return "";
9149
+ return oneLine.length <= maxLen ? oneLine : `${oneLine.slice(0, maxLen - 1)}\u2026`;
9150
+ }
9151
+ function parseGit(rest) {
9152
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9153
+ if (!tokens2) return null;
9154
+ let i = 0, context;
9155
+ while (tokens2[i]?.startsWith("-")) {
9156
+ const option = tokens2[i++];
9157
+ if (["-C", "-c", "--git-dir", "--work-tree"].includes(option)) {
9158
+ const value = tokens2[i++];
9159
+ if (!value || value.startsWith("-")) return null;
9160
+ if (option === "-C") context = value;
9161
+ } else if (!/^(--git-dir|--work-tree)=.+/.test(option) && !["--no-pager", "--no-optional-locks", "--literal-pathspecs"].includes(option)) return null;
9162
+ }
9163
+ const sub = tokens2[i++];
9164
+ const args = tokens2.slice(i);
9165
+ const result = (action, object, readOnly) => ({ action, object, context, readOnly });
9166
+ if (sub === "worktree") {
9167
+ const operation = args.shift();
9168
+ const operands = [];
9169
+ let end = false;
9170
+ for (let j = 0; j < args.length; j++) {
9171
+ const token = args[j];
9172
+ if (!end && token === "--") {
9173
+ end = true;
9174
+ continue;
9175
+ }
9176
+ if (!end && token.startsWith("-")) {
9177
+ if (operation === "add" && ["-b", "-B", "--reason"].includes(token)) {
9178
+ if (!args[++j] || args[j].startsWith("-")) return null;
9179
+ } else if (!(operation === "add" && ["--detach", "--checkout", "--no-checkout", "--lock"].includes(token)) && !(operation === "list" && ["--porcelain", "-v", "--verbose", "-z"].includes(token)) && !(operation === "remove" && ["-f", "--force"].includes(token))) return null;
9180
+ } else operands.push(token);
9181
+ }
9182
+ if (operation === "list" && !operands.length) return result("\u5217\u51FA\u5DE5\u4F5C\u533A", void 0, true);
9183
+ if (operation === "add" && operands.length >= 1 && operands.length <= 2) return result("\u521B\u5EFA\u5DE5\u4F5C\u533A", operands[0], false);
9184
+ if (operation === "remove" && operands.length === 1) return result("\u79FB\u9664\u5DE5\u4F5C\u533A", operands[0], false);
9185
+ return null;
9186
+ }
9187
+ if (sub === "branch") {
9188
+ let mode = "create", end = false;
9189
+ const operands = [];
9190
+ for (const token of args) {
9191
+ if (!end && token === "--") {
9192
+ end = true;
9193
+ continue;
9194
+ }
9195
+ if (!end && token.startsWith("-")) {
9196
+ if (["-d", "-D", "--delete"].includes(token) && mode === "create") mode = "delete";
9197
+ else if (["--list", "-a", "--all", "-r", "--remotes", "-v", "-vv", "--show-current"].includes(token) && mode === "create") mode = "list";
9198
+ else return null;
9199
+ } else operands.push(token);
9200
+ }
9201
+ if (mode === "delete" && operands.length === 1) return result("\u5220\u9664\u5206\u652F", operands[0], false);
9202
+ if (mode === "list" || !args.length) return result("\u5217\u51FA\u5206\u652F", void 0, true);
9203
+ if (mode === "create" && operands.length >= 1 && operands.length <= 2) return result("\u521B\u5EFA\u5206\u652F", operands[0], false);
9204
+ return null;
9205
+ }
9206
+ if (sub === "checkout" && args.some((t2) => t2 === "." || t2 === "--" || t2.includes("/"))) return null;
9207
+ const nonFlagArgs = (list) => {
9208
+ const out = [];
9209
+ for (let j = 0; j < list.length; j++) {
9210
+ const tok = list[j];
9211
+ if (tok === "--") {
9212
+ out.push(...list.slice(j + 1));
9213
+ break;
9214
+ }
9215
+ if (tok.startsWith("-")) {
9216
+ if (["-m", "-F", "-b", "-B", "-n", "--max-count", "--format", "--pretty", "--since", "--until", "--author", "-U"].includes(tok)) j++;
9217
+ continue;
9218
+ }
9219
+ out.push(tok);
9220
+ }
9221
+ return out;
9222
+ };
9223
+ switch (sub) {
9224
+ case "status":
9225
+ return result("\u67E5\u72B6\u6001", void 0, true);
9226
+ case "log":
9227
+ return result("\u67E5\u5386\u53F2", void 0, true);
9228
+ case "rev-list":
9229
+ return result("\u7EDF\u8BA1\u63D0\u4EA4", void 0, true);
9230
+ case "merge-base":
9231
+ return result("\u67E5\u5171\u540C\u7956\u5148", void 0, true);
9232
+ case "rev-parse":
9233
+ return result("\u67E5\u4ED3\u5E93\u4FE1\u606F", void 0, true);
9234
+ case "show": {
9235
+ const target = nonFlagArgs(args)[0];
9236
+ return result("\u770B\u63D0\u4EA4", isSafeGitTarget(target) ? clipShortText(target, 20) : void 0, true);
9237
+ }
9238
+ case "diff": {
9239
+ const target = nonFlagArgs(args).find(isSafeGitTarget);
9240
+ return result("\u770B\u5DEE\u5F02", target ? baseName(target) ?? clipShortText(target, 20) : void 0, true);
9241
+ }
9242
+ case "tag": {
9243
+ const hasMutating = args.some((t2) => ["-d", "--delete", "-a", "-s", "-f", "--force"].includes(t2)) || nonFlagArgs(args).length > 0;
9244
+ return hasMutating ? result("\u7BA1\u6807\u7B7E", void 0, false) : result("\u67E5\u6807\u7B7E", void 0, true);
9245
+ }
9246
+ case "add": {
9247
+ if (args.some((t2) => t2 === "-A" || t2 === "--all" || t2 === ".")) return result("\u6682\u5B58\u5168\u90E8\u4FEE\u6539", void 0, false);
9248
+ const files = nonFlagArgs(args).filter(isSafeGitTarget);
9249
+ if (files.length === 1) return result("\u6682\u5B58", baseName(files[0]) ?? files[0], false);
9250
+ if (files.length > 1) return result("\u6682\u5B58", `${files.length} \u9879`, false);
9251
+ return result("\u6682\u5B58\u4FEE\u6539", void 0, false);
9252
+ }
9253
+ case "commit":
9254
+ return result("\u63D0\u4EA4", void 0, false);
9255
+ case "merge": {
9256
+ const branch = nonFlagArgs(args).find(isSafeGitTarget);
9257
+ return result("\u5408\u5E76", branch ? clipShortText(branch, 28) : void 0, false);
9258
+ }
9259
+ case "checkout":
9260
+ case "switch": {
9261
+ const branch = nonFlagArgs(args).find(isSafeGitTarget);
9262
+ return result("\u5207\u6362\u5206\u652F", branch ? clipShortText(branch, 28) : void 0, false);
9263
+ }
9264
+ case "push": {
9265
+ const parts = nonFlagArgs(args).filter(isSafeGitTarget);
9266
+ const target = parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0];
9267
+ return result("\u63A8\u9001", target ? clipShortText(target, 28) : void 0, false);
9268
+ }
9269
+ case "pull": {
9270
+ const parts = nonFlagArgs(args).filter(isSafeGitTarget);
9271
+ const target = parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0];
9272
+ return result("\u62C9\u53D6", target ? clipShortText(target, 28) : void 0, false);
9273
+ }
9274
+ case "fetch": {
9275
+ const remote = nonFlagArgs(args).find(isSafeGitTarget);
9276
+ return result("\u83B7\u53D6\u8FDC\u7AEF", remote ? clipShortText(remote, 24) : void 0, true);
9277
+ }
9278
+ case "stash": {
9279
+ const op = nonFlagArgs(args)[0];
9280
+ return op === "list" ? result("\u67E5\u8D2E\u85CF", void 0, true) : result("\u6682\u5B58", void 0, false);
9281
+ }
9282
+ case "reset":
9283
+ return result("\u91CD\u7F6E", void 0, false);
9284
+ case "restore":
9285
+ return result("\u6062\u590D\u6587\u4EF6", void 0, false);
9286
+ default:
9287
+ return null;
9288
+ }
9289
+ }
9290
+ function baseName(path2) {
9291
+ const cleaned = path2.replace(/^['"]|['"]$/g, "").replace(/\/+$/, "");
9292
+ if (!cleaned || cleaned === "." || cleaned === "..") return void 0;
9293
+ const parts = cleaned.split("/").filter(Boolean);
9294
+ const base = parts.pop();
9295
+ return base || void 0;
9296
+ }
9297
+ function splitSegments(command) {
9298
+ const segments = [];
9299
+ let current = "";
9300
+ let quote = null;
9301
+ let hasFallback = false;
9302
+ for (let i = 0; i < command.length; i++) {
9303
+ const ch = command[i];
9304
+ const next = command[i + 1];
9305
+ if (quote) {
9306
+ if (ch === "\\" && next && quote === '"') {
9307
+ current += ch + next;
9308
+ i++;
9309
+ continue;
9310
+ }
9311
+ current += ch;
9312
+ if (ch === quote) quote = null;
9313
+ continue;
9314
+ }
9315
+ if (ch === '"' || ch === "'") {
9316
+ quote = ch;
9317
+ current += ch;
9318
+ continue;
9319
+ }
9320
+ if (ch === "\\" && next) {
9321
+ current += ch + next;
9322
+ i++;
9323
+ continue;
9324
+ }
9325
+ if (ch === "&" && next === "&") {
9326
+ const trimmed = current.trim();
9327
+ if (trimmed) segments.push(trimmed);
9328
+ current = "";
9329
+ i++;
9330
+ continue;
9331
+ }
9332
+ if (ch === "|" && next === "|") {
9333
+ hasFallback = true;
9334
+ current = "";
9335
+ i++;
9336
+ continue;
9337
+ }
9338
+ if (ch === ";") {
9339
+ const trimmed = current.trim();
9340
+ if (trimmed) segments.push(trimmed);
9341
+ current = "";
9342
+ continue;
9343
+ }
9344
+ current += ch;
9345
+ }
9346
+ const tail = current.trim();
9347
+ if (tail) segments.push(tail);
9348
+ return { segments, hasFallback };
9349
+ }
9350
+ function stripEnvAssignments(segment) {
9351
+ let rest = segment.trimStart();
9352
+ if (/^export\s+[A-Za-z_][A-Za-z0-9_]*=/.test(rest)) {
9353
+ rest = rest.replace(/^export\s+/, "");
9354
+ }
9355
+ while (/^[A-Za-z_][A-Za-z0-9_]*=(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\S*)\s*/.test(rest)) {
9356
+ const next = rest.replace(/^[A-Za-z_][A-Za-z0-9_]*=(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\S*)\s*/, "");
9357
+ if (next === rest) break;
9358
+ rest = next;
9359
+ }
9360
+ return rest;
9361
+ }
9362
+ function firstVerbToken(segment) {
9363
+ let rest = stripEnvAssignments(segment).trim();
9364
+ const wrappers = /* @__PURE__ */ new Set(["sudo", "env", "command", "time", "nohup", "exec"]);
9365
+ let guard = 0;
9366
+ while (guard++ < 6) {
9367
+ const before = rest;
9368
+ rest = stripEnvAssignments(rest).trim();
9369
+ const m = rest.match(/^(\S+)\s*(.*)$/s);
9370
+ if (!m) return { verb: "", rest: "" };
9371
+ const [, word, restAfter] = m;
9372
+ const base = word.replace(/^.*\//, "");
9373
+ if (wrappers.has(base) && restAfter.trim()) {
9374
+ rest = restAfter.trim();
9375
+ continue;
9376
+ }
9377
+ if (base === "timeout" && restAfter.trim()) {
9378
+ const tokens2 = shellWords(restAfter.trim());
9379
+ if (!tokens2 || tokens2.length < 2) return { verb: "timeout", rest: restAfter.trim() };
9380
+ let idx = 0;
9381
+ while (idx < tokens2.length && tokens2[idx].startsWith("-")) {
9382
+ const opt = tokens2[idx++];
9383
+ if (["-k", "-s", "--kill-after", "--signal"].includes(opt)) idx++;
9384
+ }
9385
+ if (idx < tokens2.length && /^\d+(?:\.\d+)?[smhd]?$/i.test(tokens2[idx])) idx++;
9386
+ if (idx < tokens2.length) {
9387
+ const inner = tokens2.slice(idx).map((q) => /\s/.test(q) ? JSON.stringify(q) : q).join(" ");
9388
+ rest = inner;
9389
+ continue;
9390
+ }
9391
+ }
9392
+ if (before !== rest && !rest) return { verb: "", rest: "" };
9393
+ return { verb: base, rest: restAfter.trim() };
9394
+ }
9395
+ return { verb: "", rest };
9396
+ }
9397
+ function extractSafeSearchTarget(rest) {
9398
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9399
+ if (!tokens2) return void 0;
9400
+ const valuedOpts = /* @__PURE__ */ new Set(["-e", "-f", "-g", "--glob", "-t", "--type", "-T", "--type-not", "-A", "-B", "-C", "-m", "--max-count", "--max-filesize", "--color", "--sort"]);
9401
+ let hasExtendedRegex = false;
9402
+ let pattern;
9403
+ for (let i = 0; i < tokens2.length; i++) {
9404
+ const tok = tokens2[i];
9405
+ if (tok === "--") {
9406
+ pattern = tokens2[i + 1];
9407
+ break;
9408
+ }
9409
+ if (tok.startsWith("-")) {
9410
+ if (tok === "-E" || tok === "-P" || tok === "--extended-regexp") hasExtendedRegex = true;
9411
+ if (valuedOpts.has(tok)) {
9412
+ if (tok === "-e" && !pattern && tokens2[i + 1]) pattern = tokens2[i + 1];
9413
+ i++;
9414
+ }
9415
+ continue;
9416
+ }
9417
+ pattern = tok;
9418
+ break;
9419
+ }
9420
+ if (!pattern || hasExtendedRegex || /[|[\]^$()*+?\\]/.test(pattern)) return void 0;
9421
+ return clipShortText(pattern, 22);
9422
+ }
9423
+ function parseSed(rest) {
9424
+ const rawTokens = shellWords(rest.split(/\s+\|\s+/)[0]);
9425
+ if (!rawTokens) return null;
9426
+ let quiet = false;
9427
+ let inPlace = false;
9428
+ const scripts = [];
9429
+ const positional = [];
9430
+ for (let i = 0; i < rawTokens.length; i++) {
9431
+ const tok = rawTokens[i];
9432
+ if (tok === "--") {
9433
+ positional.push(...rawTokens.slice(i + 1));
9434
+ break;
9435
+ }
9436
+ if (tok.startsWith("-") && tok.length > 1) {
9437
+ if (tok === "--quiet" || tok === "--silent") {
9438
+ quiet = true;
9439
+ continue;
9440
+ }
9441
+ if (tok === "--in-place" || tok.startsWith("--in-place=")) {
9442
+ inPlace = true;
9443
+ continue;
9444
+ }
9445
+ if (tok === "--regexp-extended") continue;
9446
+ if (tok.startsWith("--expression=")) {
9447
+ scripts.push(tok.slice("--expression=".length));
9448
+ continue;
9449
+ }
9450
+ if (tok === "--expression") {
9451
+ if (rawTokens[i + 1] === void 0) return null;
9452
+ scripts.push(rawTokens[++i]);
9453
+ continue;
9454
+ }
9455
+ if (tok.startsWith("--")) return null;
9456
+ for (let c = 1; c < tok.length; c++) {
9457
+ const flag = tok[c];
9458
+ if (flag === "n") {
9459
+ quiet = true;
9460
+ continue;
9461
+ }
9462
+ if (flag === "r" || flag === "E") continue;
9463
+ if (flag === "i") {
9464
+ inPlace = true;
9465
+ if (c === tok.length - 1 && rawTokens[i + 1] === "") i++;
9466
+ break;
9467
+ }
9468
+ if (flag === "e") {
9469
+ if (c + 1 < tok.length) {
9470
+ scripts.push(tok.slice(c + 1));
9471
+ } else {
9472
+ if (rawTokens[i + 1] === void 0) return null;
9473
+ scripts.push(rawTokens[++i]);
9474
+ }
9475
+ break;
9476
+ }
9477
+ return null;
9478
+ }
9479
+ continue;
9480
+ }
9481
+ positional.push(tok);
9482
+ }
9483
+ const isSedScript = (tok) => /^(?:\d+|\$)(?:,\s*(?:\d+|\$))?[pdq=!]?$/.test(tok) || /^s[|/#]/.test(tok) || /^\/.*\/[pd=!]?$/.test(tok) || /^\d+[ew]/.test(tok);
9484
+ for (const tok of positional) {
9485
+ if (isSedScript(tok)) scripts.push(tok);
9486
+ }
9487
+ const files = positional.filter((t2) => !isSedScript(t2));
9488
+ if (scripts.length === 0 && files.length >= 2) {
9489
+ scripts.push(files.shift());
9490
+ }
9491
+ const fileToken = files[files.length - 1];
9492
+ const target = fileToken ? baseName(fileToken) : void 0;
9493
+ if (inPlace) {
9494
+ const isSafeSub = (part) => {
9495
+ if (part.length < 4 || part[0] !== "s") return false;
9496
+ const delim = part[1];
9497
+ if (delim !== "|" && delim !== "/" && delim !== "#") return false;
9498
+ let delimsSeen = 1;
9499
+ let idx = 2;
9500
+ for (; idx < part.length && delimsSeen < 3; idx++) {
9501
+ const ch = part[idx];
9502
+ if (ch === "\\" && idx + 1 < part.length) {
9503
+ idx++;
9504
+ continue;
9505
+ }
9506
+ if (ch === delim) delimsSeen++;
9507
+ }
9508
+ if (delimsSeen !== 3) return false;
9509
+ return /^[gipI]*$/.test(part.slice(idx));
9510
+ };
9511
+ const allSafe = scripts.every((s) => {
9512
+ const parts = s.split(";").map((p) => p.trim()).filter(Boolean);
9513
+ return parts.length > 0 && parts.every(isSafeSub);
9514
+ });
9515
+ if (!allSafe) return null;
9516
+ const replaceCount = (rest.match(/s[|/#][^|/#]*[|/#][^|/#]*[|/#]/g) ?? []).length;
9517
+ return {
9518
+ verb: "\u7F16\u8F91",
9519
+ target,
9520
+ count: replaceCount > 1 ? replaceCount : void 0,
9521
+ unit: "\u5904\u66FF\u6362",
9522
+ readOnly: false
9523
+ };
9524
+ }
9525
+ if (quiet) {
9526
+ const isStrictReadOnlyPrint = (s) => /^(?:\d+|\$)(?:\s*,\s*(?:\d+|\$))?\s*p$/.test(s.trim());
9527
+ if (scripts.length === 0 || !scripts.every(isStrictReadOnlyPrint)) {
9528
+ return null;
9529
+ }
9530
+ return { verb: "\u67E5\u770B", target, readOnly: true };
9531
+ }
9532
+ return { verb: "\u5904\u7406\u6587\u672C", target, readOnly: false };
9533
+ }
9534
+ function parseNolo(rest) {
9535
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9536
+ if (!tokens2 || tokens2.length === 0) return null;
9537
+ const sub = tokens2[0];
9538
+ const action = tokens2[1];
9539
+ const nonFlag = tokens2.slice(2).filter((t2) => !t2.startsWith("-"));
9540
+ if (sub === "browser" || sub === "chrome") {
9541
+ const map = {
9542
+ status: ["\u67E5\u6D4F\u89C8\u5668\u72B6\u6001", true],
9543
+ "list-tabs": ["\u5217\u6D4F\u89C8\u5668\u6807\u7B7E", true],
9544
+ "read-page": ["\u6D4F\u89C8\u5668\u8BFB\u9875\u9762", true],
9545
+ "read-network": ["\u67E5\u6D4F\u89C8\u5668\u8BF7\u6C42", true],
9546
+ screenshot: ["\u6D4F\u89C8\u5668\u622A\u56FE", true],
9547
+ "open-tab": ["\u6D4F\u89C8\u5668\u5F00\u6807\u7B7E", false],
9548
+ click: ["\u6D4F\u89C8\u5668\u70B9\u51FB", false],
9549
+ type: ["\u6D4F\u89C8\u5668\u8F93\u5165", false],
9550
+ press: ["\u6D4F\u89C8\u5668\u6309\u952E", false]
9551
+ };
9552
+ if (action && map[action]) return { verb: map[action][0], readOnly: map[action][1] };
9553
+ return { verb: "\u6D4F\u89C8\u5668\u64CD\u4F5C", readOnly: false };
9554
+ }
9555
+ if (sub === "agent") {
9556
+ if (action === "list" || action === "providers" || action === "models") return { verb: action === "list" ? "\u5217\u667A\u80FD\u4F53" : "\u5217\u6A21\u578B\u901A\u9053", readOnly: true };
9557
+ if (action === "read") return { verb: "\u8BFB\u667A\u80FD\u4F53", target: nonFlag[0] ? clipShortText(nonFlag[0], 24) : void 0, readOnly: true };
9558
+ if (action === "create") return { verb: "\u521B\u5EFA\u667A\u80FD\u4F53", target: nonFlag[0] ? clipShortText(nonFlag[0], 24) : void 0, readOnly: false };
9559
+ if (action === "delete") return { verb: "\u5220\u9664\u667A\u80FD\u4F53", target: nonFlag[0] ? clipShortText(nonFlag[0], 24) : void 0, readOnly: false };
9560
+ return { verb: "\u7BA1\u7406\u667A\u80FD\u4F53", readOnly: false };
9561
+ }
9562
+ if (sub === "dialog") {
9563
+ if (action === "list") return { verb: "\u5217\u5BF9\u8BDD", readOnly: true };
9564
+ if (action === "read") return { verb: "\u8BFB\u5BF9\u8BDD", target: nonFlag[0] ? clipShortText(nonFlag[0], 20) : void 0, readOnly: true };
9565
+ if (action === "status") return { verb: "\u67E5\u5BF9\u8BDD\u72B6\u6001", readOnly: true };
9566
+ if (action === "search") return { verb: "\u641C\u5BF9\u8BDD", readOnly: true };
9567
+ return { verb: "\u7BA1\u5BF9\u8BDD", readOnly: false };
9568
+ }
9569
+ if (sub === "secret") {
9570
+ if (action === "list") return { verb: "\u5217\u51ED\u636E", readOnly: true };
9571
+ if (action === "run") return { verb: "\u5E26\u51ED\u636E\u6267\u884C", readOnly: false };
9572
+ return { verb: "\u7BA1\u51ED\u636E", readOnly: false };
9573
+ }
9574
+ if (sub === "ci") return { verb: "\u67E5 CI \u72B6\u6001", readOnly: true };
9575
+ return null;
9576
+ }
9577
+ function classifySegment(segment) {
9578
+ const { verb, rest } = firstVerbToken(segment);
9579
+ if (!verb) return null;
9580
+ switch (verb) {
9581
+ case "cd":
9582
+ return { verb: "\u8FDB\u5165\u76EE\u5F55", target: baseName(rest), readOnly: true };
9583
+ case "mkdir":
9584
+ return { verb: "\u5EFA\u76EE\u5F55", target: baseName(rest.replace(/^-\S+\s+/, "")), readOnly: false };
9585
+ case "cp":
9586
+ return { verb: "\u590D\u5236", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
9587
+ case "mv":
9588
+ return { verb: "\u79FB\u52A8", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
9589
+ case "rm":
9590
+ return { verb: "\u5220\u9664", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
9591
+ case "touch":
9592
+ return { verb: "\u521B\u5EFA\u6587\u4EF6", target: baseName(rest), readOnly: false };
9593
+ case "cat": {
9594
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9595
+ const file = tokens2?.find((t2) => !t2.startsWith("-"));
9596
+ return { verb: "\u8BFB\u53D6", target: baseName(file ?? rest.split(/\s+/)[0] ?? ""), readOnly: true };
9597
+ }
9598
+ case "ls": {
9599
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9600
+ const dir = tokens2?.find((t2) => !t2.startsWith("-"));
9601
+ return { verb: "\u5217\u51FA\u76EE\u5F55", target: dir ? baseName(dir) : void 0, readOnly: true };
9602
+ }
9603
+ case "grep":
9604
+ case "rg":
9605
+ return { verb: "\u641C\u7D22", target: extractSafeSearchTarget(rest), readOnly: true };
9606
+ case "chmod":
9607
+ return { verb: "\u6539\u6743\u9650", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
9608
+ case "chown":
9609
+ return { verb: "\u6539\u5C5E\u4E3B", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
9610
+ case "tar":
9611
+ case "unzip":
9612
+ return { verb: "\u89E3\u538B", readOnly: false };
9613
+ case "git": {
9614
+ const parsed = parseGit(rest);
9615
+ return parsed ? { verb: parsed.action, target: parsed.object, readOnly: parsed.readOnly } : null;
9616
+ }
9617
+ case "sed":
9618
+ return parseSed(rest);
9619
+ case "nolo":
9620
+ return parseNolo(rest);
9621
+ case "gh": {
9622
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9623
+ if (!tokens2?.length) return null;
9624
+ const sub = tokens2[0];
9625
+ const op = tokens2[1];
9626
+ const isRead = ["view", "list", "status", "checks", "diff"].includes(op ?? "");
9627
+ if (sub === "pr") return { verb: isRead ? "\u67E5 PR" : "\u64CD\u4F5C PR", readOnly: isRead };
9628
+ if (sub === "run") return { verb: isRead ? "\u67E5 CI \u8FD0\u884C" : "\u64CD\u4F5C CI \u8FD0\u884C", readOnly: isRead };
9629
+ if (sub === "issue") return { verb: isRead ? "\u67E5 Issue" : "\u64CD\u4F5C Issue", readOnly: isRead };
9630
+ if (sub === "api") return { verb: "\u8C03 GitHub API", readOnly: false };
9631
+ return null;
9632
+ }
9633
+ case "ps":
9634
+ return { verb: "\u67E5\u8FDB\u7A0B", readOnly: true };
9635
+ case "sha256sum": {
9636
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9637
+ const file = tokens2?.find((t2) => !t2.startsWith("-"));
9638
+ return { verb: "\u7B97\u6821\u9A8C\u548C", target: file ? baseName(file) : void 0, readOnly: true };
9639
+ }
9640
+ case "dnf":
9641
+ case "yum": {
9642
+ const sub = rest.split(/\s+/)[0] ?? "";
9643
+ if (sub === "install") return { verb: "\u88C5\u8F6F\u4EF6\u5305", readOnly: false };
9644
+ if (sub === "remove" || sub === "erase") return { verb: "\u5378\u8F7D\u8F6F\u4EF6\u5305", readOnly: false };
9645
+ if (sub === "update" || sub === "upgrade") return { verb: "\u66F4\u65B0\u7CFB\u7EDF", readOnly: false };
9646
+ if (sub === "search") return { verb: "\u641C\u7D22\u8F6F\u4EF6\u5305", readOnly: true };
9647
+ if (sub === "list") return { verb: "\u5217\u51FA\u8F6F\u4EF6\u5305", readOnly: true };
9648
+ if (sub === "history") return { verb: "\u67E5\u5B89\u88C5\u5386\u53F2", readOnly: true };
9649
+ return null;
9650
+ }
9651
+ case "rpm":
9652
+ case "pacman":
9653
+ case "apt":
9654
+ case "apt-get":
9655
+ return { verb: "\u7BA1\u8F6F\u4EF6\u5305", readOnly: false };
9656
+ case "systemctl":
9657
+ case "journalctl": {
9658
+ const tokens2 = rest.split(/\s+/).filter((t2) => t2 && !t2.startsWith("-"));
9659
+ const sub = tokens2[0] ?? "";
9660
+ if (verb === "journalctl") return { verb: "\u67E5\u65E5\u5FD7", readOnly: true };
9661
+ const sysVerbs = {
9662
+ start: ["\u542F\u52A8\u670D\u52A1", false],
9663
+ stop: ["\u505C\u6B62\u670D\u52A1", false],
9664
+ restart: ["\u91CD\u542F\u670D\u52A1", false],
9665
+ status: ["\u67E5\u670D\u52A1\u72B6\u6001", true],
9666
+ enable: ["\u542F\u7528\u670D\u52A1", false],
9667
+ disable: ["\u505C\u7528\u670D\u52A1", false],
9668
+ "daemon-reload": ["\u91CD\u8F7D\u670D\u52A1\u914D\u7F6E", false],
9669
+ "list-units": ["\u5217\u670D\u52A1", true],
9670
+ "list-unit-files": ["\u5217\u670D\u52A1", true],
9671
+ is: ["\u67E5\u670D\u52A1\u72B6\u6001", true],
9672
+ cat: ["\u770B\u670D\u52A1\u5B9A\u4E49", true]
9673
+ };
9674
+ const mapped = sysVerbs[sub];
9675
+ return mapped ? { verb: mapped[0], readOnly: mapped[1] } : null;
9676
+ }
9677
+ case "awk":
9678
+ return { verb: "\u5904\u7406\u6587\u672C", readOnly: true };
9679
+ case "find": {
9680
+ if (/(?:^|\s)(?:-delete|-exec|-execdir|-ok|-okdir)(?:\s|$)/.test(rest)) return null;
9681
+ return { verb: "\u67E5\u627E\u6587\u4EF6", readOnly: true };
9682
+ }
9683
+ case "curl":
9684
+ case "wget":
9685
+ return { verb: "\u4E0B\u8F7D", readOnly: false };
9686
+ case "bun":
9687
+ case "npm":
9688
+ case "pnpm":
9689
+ case "yarn": {
9690
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]) ?? rest.split(/\s+/).filter(Boolean);
9691
+ const sub = tokens2[0] ?? "";
9692
+ if (sub === "test") {
9693
+ const target = tokens2.slice(1).find((t2) => !t2.startsWith("-"));
9694
+ return { verb: "\u8DD1\u6D4B\u8BD5", target: target ? baseName(target) : void 0, readOnly: false };
9695
+ }
9696
+ if (sub === "install" || sub === "i" || sub === "add") return { verb: "\u88C5\u4F9D\u8D56", readOnly: false };
9697
+ if (sub === "run") {
9698
+ const script = tokens2[1];
9699
+ return { verb: "\u8DD1\u811A\u672C", target: script, readOnly: false };
9700
+ }
9701
+ if (sub === "build") return { verb: "\u6784\u5EFA", readOnly: false };
9702
+ if (sub === "x" || sub === "exec") {
9703
+ return { verb: "\u6267\u884C", target: tokens2[1], readOnly: false };
9704
+ }
9705
+ if (verb === "bun" && (sub === "-e" || sub === "-p" || sub === "--inline-heredoc" || tokens2.includes("--inline-heredoc"))) {
9706
+ return { verb: "\u6267\u884C\u5185\u8054\u811A\u672C (Bun)", readOnly: false };
9707
+ }
9708
+ const scriptFile = tokens2.find((t2) => !t2.startsWith("-") && (/\.(?:ts|tsx|js|mjs|mts|cjs)$/i.test(t2) || t2.includes("/")));
9709
+ if (scriptFile) {
9710
+ return { verb: "\u8FD0\u884C\u811A\u672C", target: baseName(scriptFile), readOnly: false };
9711
+ }
9712
+ return null;
9713
+ }
9714
+ case "python":
9715
+ case "python3": {
9716
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]) ?? [];
9717
+ if (tokens2.includes("--inline-heredoc") || /(?:^|\s)-[A-Za-z]*c(?:\s|$)/.test(rest)) {
9718
+ return { verb: "\u6267\u884C\u5185\u8054\u811A\u672C (Python)", readOnly: false };
9719
+ }
9720
+ const script = rest.split(/\s+/).find((t2) => t2 && !t2.startsWith("-"));
9721
+ return { verb: "\u6267\u884C\u811A\u672C", target: baseName(script ?? ""), readOnly: false };
9722
+ }
9723
+ case "node": {
9724
+ if (/(?:^|\s)-[A-Za-z]*e(?:\s|$)/.test(rest)) return null;
9725
+ const script = rest.split(/\s+/).find((t2) => t2 && !t2.startsWith("-"));
9726
+ return { verb: "\u6267\u884C\u811A\u672C", target: baseName(script ?? ""), readOnly: false };
9727
+ }
9728
+ case "bash":
9729
+ case "sh":
9730
+ case "zsh": {
9731
+ if (/(?:^|\s)-[A-Za-z]*[ce](?:\s|$)/.test(rest)) return null;
9732
+ const script = rest.split(/\s+/).find((t2) => t2 && !t2.startsWith("-"));
9733
+ return { verb: "\u6267\u884C\u811A\u672C", target: baseName(script ?? ""), readOnly: false };
9734
+ }
9735
+ case "echo":
9736
+ case "printf":
9737
+ return { verb: "\u8F93\u51FA", readOnly: true };
9738
+ case "head":
9739
+ case "tail":
9740
+ case "wc":
9741
+ case "sort":
9742
+ case "uniq": {
9743
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9744
+ let file;
9745
+ if (tokens2) {
9746
+ for (let i = 0; i < tokens2.length; i++) {
9747
+ const tok = tokens2[i];
9748
+ if (tok === "-n" || tok === "-c") {
9749
+ i++;
9750
+ continue;
9751
+ }
9752
+ if (tok.startsWith("-")) continue;
9753
+ file = tok;
9754
+ break;
9755
+ }
9756
+ }
9757
+ return file ? { verb: "\u67E5\u770B", target: baseName(file), readOnly: true } : { verb: "\u67E5\u770B\u8F93\u51FA", readOnly: true };
9758
+ }
9759
+ default:
9760
+ return null;
9761
+ }
9762
+ }
9763
+ function summarizeActions(actions) {
9764
+ const cds = actions.filter((a) => a.verb === "\u8FDB\u5165\u76EE\u5F55");
9765
+ const body = actions.filter((a) => a.verb !== "\u8FDB\u5165\u76EE\u5F55");
9766
+ const merged = [];
9767
+ for (const action of body) {
9768
+ const last = merged[merged.length - 1];
9769
+ if (last && last.verb === action.verb && last.target === action.target) {
9770
+ last.count = (last.count ?? 1) + (action.count ?? 1);
9771
+ continue;
9772
+ }
9773
+ merged.push({ ...action });
9774
+ }
9775
+ const renderOne = (a) => {
9776
+ if (a.count && a.count > 1) {
9777
+ const suffix = a.unit ?? (a.verb === "\u590D\u5236" || a.verb === "\u79FB\u52A8" || a.verb === "\u5220\u9664" ? "\u4E2A\u6587\u4EF6" : "\u9879");
9778
+ const head = a.unit && a.target ? `${a.verb} ${a.target}` : a.verb;
9779
+ return `${head} ${a.count} ${suffix}`;
9780
+ }
9781
+ return a.target ? `${a.verb} ${a.target}` : a.verb;
9782
+ };
9783
+ const parts = merged.map(renderOne);
9784
+ const cdPart = cds.length > 0 && cds[0].target ? `\u8FDB\u5165 ${cds[0].target}` : "";
9785
+ const joined = parts.length > 0 ? parts.join("\u3001") : "";
9786
+ if (cdPart && joined) return `${cdPart}\uFF1A${joined}`;
9787
+ return cdPart || joined;
9788
+ }
9789
+ var PIPELINE_FILTER_COMMANDS = /* @__PURE__ */ new Set([
9790
+ "head",
9791
+ "tail",
9792
+ "cat",
9793
+ "wc",
9794
+ "sort",
9795
+ "uniq",
9796
+ "cut",
9797
+ "tr",
9798
+ "nl",
9799
+ "column",
9800
+ "grep",
9801
+ "rg",
9802
+ "ag",
9803
+ "ack",
9804
+ "jq",
9805
+ "less",
9806
+ "more",
9807
+ "bat",
9808
+ "awk",
9809
+ "sed"
9810
+ ]);
9811
+ function hasNonFilterPipeline(command) {
9812
+ let quote = null;
9813
+ for (let i = 0; i < command.length; i++) {
9814
+ const ch = command[i];
9815
+ const next = command[i + 1];
9816
+ if (quote) {
9817
+ if (ch === "\\" && next && quote === '"') {
9818
+ i++;
9819
+ continue;
9820
+ }
9821
+ if (ch === quote) quote = null;
9822
+ continue;
9823
+ }
9824
+ if (ch === '"' || ch === "'") {
9825
+ quote = ch;
9826
+ continue;
9827
+ }
9828
+ if (ch === "\\" && next) {
9829
+ i++;
9830
+ continue;
9831
+ }
9832
+ if (ch === "|" && next !== "|" && command[i - 1] !== "|") {
9833
+ const afterPipe = command.slice(i + 1).trimStart();
9834
+ const m = afterPipe.match(/^(\S+)\s*(.*)$/s);
9835
+ if (!m) return true;
9836
+ let word = m[1].replace(/^.*\//, "");
9837
+ let restAfter = m[2];
9838
+ let guard = 0;
9839
+ while (guard++ < 4) {
9840
+ if (word === "sudo") {
9841
+ const opt = restAfter.match(/^(?:-\S+\s+)*(\S+)\s*(.*)$/s);
9842
+ if (!opt) return true;
9843
+ word = opt[1].replace(/^.*\//, "");
9844
+ restAfter = opt[2];
9845
+ continue;
9846
+ }
9847
+ if (word === "env" || word === "xargs") {
9848
+ const nxt = restAfter.match(/^(?:[A-Za-z_]\w*=\S*\s+|-\S+\s+)*(\S+)\s*(.*)$/s);
9849
+ if (!nxt) return true;
9850
+ word = nxt[1].replace(/^.*\//, "");
9851
+ restAfter = nxt[2];
9852
+ continue;
9853
+ }
9854
+ break;
9855
+ }
9856
+ if (!PIPELINE_FILTER_COMMANDS.has(word)) return true;
9857
+ }
9858
+ }
9859
+ return false;
9860
+ }
9861
+ function collapseSafeHeredocs(command) {
9862
+ const lines = command.split(/\r?\n/);
9863
+ const out = [];
9864
+ for (let i = 0; i < lines.length; i++) {
9865
+ const line = lines[i];
9866
+ const trimmed = line.trim();
9867
+ if (!trimmed) continue;
9868
+ const hd = trimmed.match(/^(.*?)\s*<<-?\s*'([A-Za-z0-9_]+)'\s*$/);
9869
+ if (hd) {
9870
+ const head = hd[1].trim();
9871
+ const tag = hd[2];
9872
+ let end = -1;
9873
+ for (let j = i + 1; j < lines.length; j++) {
9874
+ if (lines[j].trim() === tag) {
9875
+ end = j;
9876
+ break;
9877
+ }
9878
+ }
9879
+ if (end === -1) return null;
9880
+ out.push(`${head} --inline-heredoc`);
9881
+ i = end;
9882
+ continue;
9883
+ }
9884
+ out.push(trimmed);
9885
+ }
9886
+ return out.join("\n");
9887
+ }
9888
+ function normalizeTopLevelNewlines(command) {
9889
+ let out = "";
9890
+ let quote = null;
9891
+ for (let i = 0; i < command.length; i++) {
9892
+ const ch = command[i];
9893
+ const next = command[i + 1];
9894
+ if (quote) {
9895
+ if (ch === "\\" && next && quote === '"') {
9896
+ out += ch + next;
9897
+ i++;
9898
+ continue;
9899
+ }
9900
+ if (ch === quote) quote = null;
9901
+ out += ch === "\n" ? " " : ch;
9902
+ continue;
9903
+ }
9904
+ if (ch === '"' || ch === "'") {
9905
+ quote = ch;
9906
+ out += ch;
9907
+ continue;
9908
+ }
9909
+ if (ch === "\\" && next) {
9910
+ out += ch + next;
9911
+ i++;
9912
+ continue;
9913
+ }
9914
+ if (ch === "\n") {
9915
+ if (!out.endsWith("&& ") && out.trim().length > 0) out += " && ";
9916
+ continue;
9917
+ }
9918
+ out += ch;
9919
+ }
9920
+ return out.replace(/(?:\s*&&\s*)+$/, "").trim();
9921
+ }
9922
+ function summarizeShellCommand(command) {
9923
+ const collapsed = collapseSafeHeredocs(command);
9924
+ if (collapsed === null) return null;
9925
+ const normalized = normalizeTopLevelNewlines(collapsed);
9926
+ if (!normalized) return null;
9927
+ if (hasNonFilterPipeline(normalized)) return null;
9928
+ const { segments, hasFallback } = splitSegments(normalized);
9929
+ if (segments.length === 0) return null;
9930
+ if (hasFallback) return null;
9931
+ if (segments.some((segment) => !shellWords(segment, true))) return null;
9932
+ const actions = [];
9933
+ for (const segment of segments) {
9934
+ const action = classifySegment(segment);
9935
+ if (!action) return null;
9936
+ actions.push(action);
9937
+ }
9938
+ const summary = summarizeActions(actions);
9939
+ if (!summary) return null;
9940
+ const readOnly = actions.every((a) => a.readOnly === true);
9941
+ const single = segments.length === 1 ? firstVerbToken(segments[0]) : void 0;
9942
+ const git = single?.verb === "git" ? parseGit(single.rest) : null;
9943
+ const singleAction = segments.length === 1 && !actions[0]?.count ? { action: actions[0].verb, ...actions[0].target ? { object: actions[0].target } : {} } : {};
9944
+ return { summary, foldedSegments: segments.length, readOnly, ...singleAction, ...git ?? {} };
9945
+ }
9946
+
9947
+ // packages/core/toolActivityPresentation.ts
9948
+ var families = {
9949
+ readFile: ["read", "\u8BFB\u53D6", ["path"], true],
9950
+ read_file: ["read", "\u8BFB\u53D6", ["path"], true],
9951
+ readWorkspaceFile: ["read", "\u8BFB\u53D6", ["path"], true],
9952
+ writeFile: ["write", "\u5199\u5165", ["path"], false],
9953
+ editFile: ["edit", "\u4FEE\u6539", ["path"], false],
9954
+ globFiles: ["find", "\u67E5\u627E\u6587\u4EF6", ["pattern", "path"], true],
9955
+ search: ["search", "\u641C\u7D22", ["query", "pattern"], true],
9956
+ grep: ["search", "\u641C\u7D22", ["pattern", "query"], true],
9957
+ loadSkill: ["skill", "\u52A0\u8F7D\u6280\u80FD", ["name", "slug"], true]
9958
+ };
9959
+ var shellTools = /* @__PURE__ */ new Set(["execShell", "exec_shell", "runCommand", "launchProcess"]);
9960
+ function projectToolActivity(input, translate) {
9961
+ const text = (...keys) => {
9962
+ for (const key of keys) {
9963
+ const value = input.args?.[key];
9964
+ if (typeof value === "string" && value.length) return value;
9965
+ }
9966
+ return void 0;
9967
+ };
9968
+ let action = input.toolName, object, summary, readOnly = false;
9969
+ let confidence = "raw-fallback";
9970
+ let context = text("cwd");
9971
+ if (shellTools.has(input.toolName)) {
9972
+ object = text("command", "cmd");
9973
+ const gist = object ? summarizeShellCommand(object) : null;
9974
+ action = gist?.action ?? gist?.summary ?? "\u547D\u4EE4";
9975
+ if (gist) {
9976
+ object = gist.object;
9977
+ context = context ?? gist.context;
9978
+ summary = gist.summary;
9979
+ readOnly = gist.readOnly === true;
9980
+ confidence = "recognized";
9981
+ }
9982
+ if (!gist || gist.action) action = translate?.(gist?.action ? `toolActivity.shell.${gist.action}` : "toolActivity.shell", action) ?? action;
9983
+ } else {
9984
+ const family = families[input.toolName];
9985
+ if (family) {
9986
+ action = translate?.(`toolActivity.${family[0]}`, family[1]) ?? family[1];
9987
+ object = text(...family[2]);
9988
+ readOnly = family[3];
9989
+ confidence = "recognized";
9990
+ } else object = text("path", "query", "command", "url", "name");
9991
+ }
9992
+ return { key: input.key, action, object, context, ...summary ? { summary } : {}, readOnly, confidence, state: input.state, attention: input.attention, standalone: input.mode !== "ordinary" || input.attention.length > 0 || ["failed", "cancelled", "repairing"].includes(input.state), scopeKey: input.scopeKey, batchKey: input.batchKey, evidenceKey: input.evidenceKey };
9993
+ }
9994
+ function canCoalesceToolActivities(previous, next) {
9995
+ return !previous.standalone && !next.standalone && previous.attention.length === 0 && next.attention.length === 0 && !!previous.scopeKey && previous.scopeKey === next.scopeKey && !!previous.batchKey && previous.batchKey === next.batchKey;
9996
+ }
9997
+
9998
+ // packages/cli/tui/askTextSanitize.ts
9999
+ var ASK_SECRET_PLACEHOLDER = "\u27E8redacted\u27E9";
10000
+ var C0_C1_CONTROL_REGEX = /[\x00-\x1f\x7f-\x9f]/g;
10001
+ function toText(value) {
10002
+ return typeof value === "string" ? value : String(value ?? "");
10003
+ }
10004
+ function cleanAskText(value) {
10005
+ return stripAnsi(toText(value)).replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").replace(C0_C1_CONTROL_REGEX, "").replace(/\s+/g, " ").trim();
10006
+ }
10007
+ function safeAskText(value, max) {
10008
+ const cleaned = redactSecrets(cleanAskText(value));
10009
+ if (!cleaned) return "";
10010
+ const guarded = withholdIfSecretLike(cleaned) || ASK_SECRET_PLACEHOLDER;
10011
+ return max === void 0 ? guarded : clipCompactText(guarded, max, "\u2026");
10012
+ }
10013
+ function safeApprovalMultilineText(value) {
10014
+ const lines = stripAnsi(String(value ?? "")).replace(/\r\n?|\u2028|\u2029/g, "\n").split("\n");
10015
+ return lines.map((line) => {
10016
+ const cleaned = line.replace(/\t/g, " ").replace(C0_C1_CONTROL_REGEX, "");
10017
+ const redacted = redactSecrets(cleaned);
10018
+ return redacted ? withholdIfSecretLike(redacted) || ASK_SECRET_PLACEHOLDER : "";
10019
+ }).join("\n");
10020
+ }
10021
+
10022
+ // node_modules/diff/libesm/diff/base.js
10023
+ var Diff = class {
10024
+ diff(oldStr, newStr, options = {}) {
10025
+ let callback;
10026
+ if (typeof options === "function") {
10027
+ callback = options;
10028
+ options = {};
10029
+ } else if ("callback" in options) {
10030
+ callback = options.callback;
10031
+ }
10032
+ const oldString = this.castInput(oldStr, options);
10033
+ const newString = this.castInput(newStr, options);
10034
+ const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
10035
+ const newTokens = this.removeEmpty(this.tokenize(newString, options));
10036
+ return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
10037
+ }
10038
+ diffWithOptionsObj(oldTokens, newTokens, options, callback) {
10039
+ var _a;
10040
+ const done = (value) => {
8786
10041
  value = this.postProcess(value, options);
8787
10042
  if (callback) {
8788
10043
  setTimeout(function() {
@@ -9086,14 +10341,6 @@ function formatSearchItemQuery(query, path2, customHomedir) {
9086
10341
  if (!text) return "search";
9087
10342
  return text.length > 80 ? `${text.slice(0, 79)}\u2026` : text;
9088
10343
  }
9089
- function formatRunItemCommand(command, exitCode, timedOut) {
9090
- let text = compactWhitespace(command || "");
9091
- if (!text) text = "command";
9092
- text = text.length > 80 ? `${text.slice(0, 79)}\u2026` : text;
9093
- if (timedOut) return `${text} (timed out)`;
9094
- if (typeof exitCode === "number" && exitCode !== 0) return `${text} (exit ${exitCode})`;
9095
- return text;
9096
- }
9097
10344
  function formatFetchItemUrl(url) {
9098
10345
  const text = (url || "").trim();
9099
10346
  if (!text) return "webpage";
@@ -9111,10 +10358,20 @@ function isRunToolName(name) {
9111
10358
  return name === "execShell" || name === "runCommand" || name === "launchProcess";
9112
10359
  }
9113
10360
  function isFailedToolResult(event) {
9114
- const exitCode = event.metadata?.exitCode;
9115
- if (event.metadata?.actionGate) return false;
10361
+ if (event.type === "tool-error") return true;
10362
+ const metadata = event.metadata ?? {};
10363
+ if (metadata.actionGate) return false;
10364
+ const exitCode = metadata.exitCode;
9116
10365
  if (typeof exitCode === "number" && exitCode !== 0) return true;
9117
- return Boolean(event.metadata?.timedOut);
10366
+ if (Boolean(metadata.timedOut) || Boolean(metadata.failed) || Boolean(event.metadata?.failed)) return true;
10367
+ if (metadata.success === false) return true;
10368
+ if (typeof metadata.error === "string" && metadata.error.trim().length > 0) return true;
10369
+ if (typeof metadata.errorMessage === "string" && metadata.errorMessage.trim().length > 0) return true;
10370
+ if (typeof event.content === "string") {
10371
+ const trimmed = event.content.trim();
10372
+ if (/^\[工具\s*"[^"]+"\s*执行失败:\s*[^\]]+\]$/.test(trimmed)) return true;
10373
+ }
10374
+ return false;
9118
10375
  }
9119
10376
  function parseUiAskChoiceForCli(event) {
9120
10377
  if (event.toolName !== "ask_user" && !event.metadata?.uiAskChoice) {
@@ -9154,9 +10411,9 @@ function formatUiAskChoiceBlock(event, colorEnabled) {
9154
10411
  lines.push("");
9155
10412
  const questionText = safeAskText(parsed.question, 200);
9156
10413
  if (colorEnabled) {
9157
- lines.push(`${themeText("\u2753 ", "info", true)}${styleCliText(questionText, "cyan", true)}`);
10414
+ lines.push(`${themeText("? ", "info", true)}${styleCliText(questionText, "cyan", true)}`);
9158
10415
  } else {
9159
- lines.push(`\u2753 ${questionText}`);
10416
+ lines.push(`? ${questionText}`);
9160
10417
  }
9161
10418
  if (parsed.resolved) {
9162
10419
  if (parsed.cancelled) {
@@ -9577,6 +10834,7 @@ function snippetLinesWithKind(snippet, kind, maxWidth = resolveEditSnippetMaxWid
9577
10834
  return lines.slice(0, EDIT_SNIPPET_MAX_LINES).map((line) => buildEditLine(kind, line, maxWidth));
9578
10835
  }
9579
10836
  function truncateByDisplayWidth(line, maxWidth) {
10837
+ if (maxWidth <= 0) return "";
9580
10838
  if (displayWidth(line) <= maxWidth) return line;
9581
10839
  let width = 0;
9582
10840
  let kept = "";
@@ -9703,7 +10961,7 @@ function memoryToolGist(toolName, metadata) {
9703
10961
  function normalToolGistRaw(event) {
9704
10962
  const metadata = event.metadata ?? {};
9705
10963
  const toolName = event.toolName || "";
9706
- if (toolName === "readFile") {
10964
+ if (toolName === "readFile" || toolName === "writeFile" || toolName === "editFile") {
9707
10965
  const path3 = typeof metadata.path === "string" ? metadata.path : typeof metadata.filePath === "string" ? metadata.filePath : "";
9708
10966
  if (path3) return gistClip(formatReadItemPath(path3, metadata), 52);
9709
10967
  }
@@ -9719,6 +10977,8 @@ function normalToolGistRaw(event) {
9719
10977
  if (isRunToolName(toolName)) {
9720
10978
  const command2 = typeof metadata.command === "string" ? metadata.command : "";
9721
10979
  if (command2) {
10980
+ const gist = summarizeShellCommand(command2);
10981
+ if (gist) return truncateByDisplayWidth(redactSecrets(gist.summary), normalRunGistMaxWidth());
9722
10982
  return commandFullGist(command2, normalRunGistMaxWidth());
9723
10983
  }
9724
10984
  }
@@ -9727,7 +10987,11 @@ function normalToolGistRaw(event) {
9727
10987
  const path2 = typeof metadata.path === "string" ? metadata.path : "";
9728
10988
  if (path2) return pathBasenameGist(path2);
9729
10989
  const command = typeof metadata.command === "string" ? metadata.command : "";
9730
- if (command) return commandFullGist(command, normalRunGistMaxWidth());
10990
+ if (command) {
10991
+ const gist = summarizeShellCommand(command);
10992
+ if (gist) return truncateByDisplayWidth(redactSecrets(gist.summary), normalRunGistMaxWidth());
10993
+ return commandFullGist(command, normalRunGistMaxWidth());
10994
+ }
9731
10995
  const query = typeof metadata.query === "string" ? metadata.query : "";
9732
10996
  if (query) return clipCompactText(query, 64, "\u2026");
9733
10997
  return "";
@@ -9740,6 +11004,21 @@ function formatNormalToolDuration(elapsedMs) {
9740
11004
  if (elapsedMs < 1e3) return `${Math.round(elapsedMs)}ms`;
9741
11005
  return `${(elapsedMs / 1e3).toFixed(1)}s`;
9742
11006
  }
11007
+ function normalResultSummary(event) {
11008
+ const m = event.metadata ?? {};
11009
+ const count = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
11010
+ if (event.toolName === "readFile" && count(m.startLine) && count(m.endLine))
11011
+ return `${Math.max(0, m.endLine - m.startLine + 1)} lines${m.truncated ? " \xB7 truncated" : ""}`;
11012
+ if (event.toolName === "writeFile" && count(m.bytes)) return `${m.bytes} bytes written`;
11013
+ if (event.toolName === "editFile" && count(m.replacements)) return `${m.replacements} replacements`;
11014
+ if (event.toolName === "searchText" && count(m.matchCount)) return `${m.matchCount} matches${m.truncated ? " \xB7 truncated" : ""}`;
11015
+ return "";
11016
+ }
11017
+ function fitNormalLine(head, tail, budget) {
11018
+ const status = budget === 1 ? tail.trimStart().slice(0, 1) : truncateByDisplayWidth(tail.trimStart(), budget);
11019
+ const room = Math.max(0, budget - displayWidth(status) - 2);
11020
+ return room ? `${truncateByDisplayWidth(head, room)} ${status}` : status;
11021
+ }
9743
11022
  function formatNormalToolLine(event, pending, colorEnabled, opts) {
9744
11023
  if (event.type === "tool-call") return "";
9745
11024
  const toolName = event.toolName || pending?.toolName || "tool";
@@ -9760,27 +11039,38 @@ function formatNormalToolLine(event, pending, colorEnabled, opts) {
9760
11039
  return formatShowInteractionBlock(event, colorEnabled);
9761
11040
  }
9762
11041
  const label = toolLabel(toolName);
9763
- if (readActionGate(event.metadata?.actionGate)) {
9764
- return formatToolTraceLine(`\u25B8 ${label} ! ${t("toolNeedsAction")}`, colorEnabled, "error");
9765
- }
9766
- if (event.type === "tool-error") {
9767
- return formatToolTraceLine(`\u25B8 ${label} \u2717 ${toolFailureReason(event) || t("toolFailed")}`, colorEnabled, "error");
9768
- }
9769
- if (event.metadata?.timedOut) {
9770
- return formatToolTraceLine(`\u25B8 ${label} \u2717 ${t("toolTimedOut")}`, colorEnabled, "error");
9771
- }
9772
- if (isFailedToolResult(event)) {
9773
- return formatToolTraceLine(`\u25B8 ${label} \u2717 ${toolFailureReason(event) || t("toolFailed")}`, colorEnabled, "error");
9774
- }
9775
- const gist = normalToolGist(event);
11042
+ const cols = typeof process !== "undefined" && typeof process.stdout?.columns === "number" && process.stdout.columns > 0 ? process.stdout.columns : 80;
11043
+ const totalBudget = Math.max(1, resolveHistoryLayoutGeometry(cols).contentWidth - displayWidth("\u25C8 "));
11044
+ if (readActionGate(event.metadata?.actionGate) || event.metadata?.permissionRequest) {
11045
+ const gist2 = opts?.tuiTrees ? normalToolGist(event) : "";
11046
+ const title = gist2 ? `${label} \xB7 ${gist2}` : label;
11047
+ return formatToolTraceLine(fitNormalLine(`\u25B8 ${title}`, `! ${t("toolNeedsAction")}`, totalBudget), colorEnabled, "error");
11048
+ }
11049
+ if (event.type === "tool-error" || event.metadata?.timedOut || isFailedToolResult(event)) {
11050
+ const reason = event.metadata?.timedOut ? t("toolTimedOut") : toolFailureReason(event) || t("toolFailed");
11051
+ const gist2 = opts?.tuiTrees ? normalToolGist(event) : "";
11052
+ const title = gist2 ? `${label} \xB7 ${gist2}` : label;
11053
+ return formatToolTraceLine(fitNormalLine(`\u25B8 ${title}`, `\u2717 ${reason}`, totalBudget), colorEnabled, "error");
11054
+ }
11055
+ const resultSummary = normalResultSummary(event);
11056
+ const gist = [normalToolGist(event), resultSummary].filter(Boolean).join(" \xB7 ");
9776
11057
  const hint = editFileResultHint(event);
9777
11058
  const statsInline = hint?.inline ? ` ${hint.inline}` : "";
9778
11059
  const durationInline = formatNormalToolDuration(event.elapsedMs);
9779
11060
  const tail = durationInline ? ` \u2713 ${durationInline}` : " \u2713";
9780
- const mainLine = formatToolTraceLine(
9781
- gist ? `\u25B8 ${label} \xB7 ${gist}${statsInline}${tail}` : `\u25B8 ${label}${statsInline}${tail}`,
9782
- colorEnabled
9783
- );
11061
+ let fittedGist = gist;
11062
+ if (gist) {
11063
+ const prefix = `\u25B8 ${label} \xB7 `;
11064
+ const suffix = `${statsInline}${tail}`;
11065
+ const prefixWidth = displayWidth(prefix);
11066
+ const suffixWidth = displayWidth(suffix);
11067
+ const maxGistWidth = Math.max(0, totalBudget - prefixWidth - suffixWidth);
11068
+ if (displayWidth(gist) > maxGistWidth) {
11069
+ fittedGist = maxGistWidth > 0 ? truncateByDisplayWidth(gist, maxGistWidth) : "";
11070
+ }
11071
+ }
11072
+ const lineContent = fittedGist ? `\u25B8 ${label} \xB7 ${fittedGist}${statsInline}${tail}` : `\u25B8 ${label}${statsInline}${tail}`;
11073
+ const mainLine = formatToolTraceLine(fitNormalLine(lineContent.slice(0, -tail.length), tail, totalBudget), colorEnabled);
9784
11074
  if (hint?.detail?.length) {
9785
11075
  const filePath = typeof event.metadata?.path === "string" ? event.metadata.path : void 0;
9786
11076
  return `${mainLine}${formatEditDetailBlock(hint.detail, colorEnabled, filePath)}`;
@@ -9871,33 +11161,43 @@ var TUI_TREE_TOOLS = {
9871
11161
  Search: ["exa_search"],
9872
11162
  Fetch: ["fetchWebpage"]
9873
11163
  };
11164
+ function toolDetails(event, line) {
11165
+ const command = event.metadata?.command;
11166
+ return isRunToolName(event.toolName) && typeof command === "string" ? `${line}${safeApprovalMultilineText(command)}
11167
+ ` : line;
11168
+ }
9874
11169
  function createToolEventFormatter(colorEnabled = resolveCliColorEnabled(), opts = {}) {
9875
11170
  const pending = /* @__PURE__ */ new Map();
11171
+ let scope = 0;
9876
11172
  let tree = null;
9877
11173
  const treeKind = (name) => Object.keys(TUI_TREE_TOOLS).find((kind) => TUI_TREE_TOOLS[kind].includes(name)) ?? null;
9878
- const treeLine = (kind, items, fallback) => {
11174
+ const treeLine = (kind, items, fallback, details) => {
9879
11175
  const label = kind === "Run" ? toolLabel("execShell") : kind === "Read" ? toolLabel("readFile") : kind === "Fetch" ? toolLabel("fetchWebpage") : toolLabel("exa_search");
9880
11176
  const header = `${label} (${items.length}) \xB7 `;
9881
11177
  const columns = resolveHistoryLayoutGeometry(process.stdout.columns).contentWidth - displayWidth("\u25C8 ");
11178
+ const budget = Math.max(1, columns);
9882
11179
  let shown = 1;
9883
11180
  for (let count = 2; count <= items.length; count++) {
9884
- const omitted2 = items.length - count;
9885
- const suffix = omitted2 ? `, \u2026 +${omitted2}` : "";
9886
- if (displayWidth(`\u2022 ${header}${items.slice(0, count).join(", ")}${suffix} \u2713`) > columns) break;
11181
+ const suffix = count < items.length ? ", \u2026" : "";
11182
+ if (displayWidth(`\u25B8 ${header}${items.slice(0, count).join(", ")}${suffix} \u2713`) > budget) break;
9887
11183
  shown = count;
9888
11184
  }
9889
- const omitted = items.length - shown;
11185
+ const summary = fitNormalLine(`${header}${items.slice(0, shown).join(", ")}${shown < items.length ? ", \u2026" : ""}`, "\u2713", Math.max(1, budget - 2));
9890
11186
  const payload = {
9891
11187
  kind,
9892
- summary: `${header}${items.slice(0, shown).join(", ")}${omitted ? `, \u2026 +${omitted}` : ""} \u2713`,
9893
- fallback
11188
+ summary,
11189
+ fallback,
11190
+ details,
11191
+ previousRow: tree?.lastRow
9894
11192
  };
11193
+ if (tree) tree.lastRow = `\u25B8 ${summary}`;
9895
11194
  return `${TUI_TREE_MARKER}${JSON.stringify(payload)}${TUI_TREE_END}
9896
11195
  `;
9897
11196
  };
9898
11197
  const formatTreeEvent = (event, call) => {
11198
+ if (event.type === "tool-error") tree = null;
9899
11199
  if (!opts.tuiTrees || event.type !== "tool-result") return null;
9900
- if (isFailedToolResult(event) || event.metadata?.failed || event.metadata?.timedOut || readActionGate(event.metadata?.actionGate)) {
11200
+ if (isFailedToolResult(event) || event.metadata?.failed || event.metadata?.timedOut || readActionGate(event.metadata?.actionGate) || event.metadata?.permissionRequest) {
9901
11201
  tree = null;
9902
11202
  return null;
9903
11203
  }
@@ -9907,20 +11207,40 @@ function createToolEventFormatter(colorEnabled = resolveCliColorEnabled(), opts
9907
11207
  tree = null;
9908
11208
  return null;
9909
11209
  }
11210
+ const activity = projectToolActivity({
11211
+ key: event.toolCallId,
11212
+ toolName: name,
11213
+ args: event.metadata,
11214
+ state: "success",
11215
+ attention: [],
11216
+ mode: "ordinary",
11217
+ // Formatter lifecycle/reset is the real assistant-output boundary;
11218
+ // round comes from the execution stream, never from adjacent rows.
11219
+ scopeKey: `assistant:${scope}`,
11220
+ batchKey: Number.isInteger(event.round) && event.round >= 0 ? `round:${event.round}` : void 0,
11221
+ evidenceKey: event.toolCallId
11222
+ });
9910
11223
  let item = "";
9911
11224
  const m = event.metadata ?? {};
9912
11225
  if (kind === "Run") {
9913
- const command = typeof m.command === "string" ? m.command : "";
9914
- item = command ? formatRunItemCommand(command, typeof m.exitCode === "number" ? m.exitCode : void 0, Boolean(m.timedOut)) : "command";
11226
+ item = activity.summary ?? (activity.confidence === "raw-fallback" ? clipCompactText(redactSecrets(activity.object ?? ""), 56, "\u2026") : [activity.action, activity.object].filter(Boolean).join(" "));
9915
11227
  }
9916
11228
  if (kind === "Read") item = formatReadItemPath(typeof m.path === "string" ? m.path : typeof m.filePath === "string" ? m.filePath : "file", m);
9917
11229
  if (kind === "Search") item = formatSearchItemQuery(typeof m.query === "string" ? m.query : typeof m.pattern === "string" ? m.pattern : "search", typeof m.path === "string" ? m.path : void 0);
9918
11230
  if (kind === "Fetch") item = formatFetchItemUrl(typeof m.url === "string" ? m.url : "webpage");
9919
- item = withholdIfSecretLike(item) || toolLabel(name);
9920
- if (tree?.kind !== kind) tree = { kind, items: [] };
11231
+ item = safeAskText(item) || toolLabel(name);
11232
+ if (tree?.kind !== kind || !canCoalesceToolActivities(tree.activity, activity)) tree = { kind, items: [], activity };
9921
11233
  tree.items.push(item);
9922
- if (tree.items.length < 2) return formatNormalToolLine(event, call, colorEnabled, opts);
9923
- return treeLine(kind, tree.items, formatNormalToolLine(event, call, colorEnabled, opts));
11234
+ if (tree.items.length < 2) {
11235
+ const line2 = formatNormalToolLine(event, call, colorEnabled, opts);
11236
+ tree.lastRow = stripAnsi(line2).trimEnd();
11237
+ const rawCommand = typeof m.command === "string" ? m.command : "";
11238
+ const runIdentity = kind === "Run" && activity.readOnly && rawCommand ? createHash2("sha256").update(rawCommand).digest("hex").slice(0, 16) : void 0;
11239
+ return `${TUI_TREE_MARKER}${JSON.stringify({ kind, summary: stripAnsi(line2).trimEnd().replace(/^▸ /, ""), fallback: line2, details: toolDetails(event, line2), appendOnly: true, ...runIdentity ? { readOnly: true, runIdentity } : {} })}${TUI_TREE_END}
11240
+ `;
11241
+ }
11242
+ const line = formatNormalToolLine(event, call, colorEnabled, opts);
11243
+ return treeLine(kind, tree.items, line, toolDetails(event, line));
9924
11244
  };
9925
11245
  const format = (event) => {
9926
11246
  if (event.type === "tool-call") {
@@ -9934,10 +11254,16 @@ function createToolEventFormatter(colorEnabled = resolveCliColorEnabled(), opts
9934
11254
  pending.delete(event.toolCallId);
9935
11255
  const treeOutput = formatTreeEvent(event, call);
9936
11256
  if (treeOutput !== null) return treeOutput;
9937
- return formatNormalToolLine(event, call, colorEnabled, opts);
11257
+ const line = formatNormalToolLine(event, call, colorEnabled, opts);
11258
+ if (opts.tuiTrees && line && isRunToolName(event.toolName)) {
11259
+ return `${TUI_TREE_MARKER}${JSON.stringify({ kind: "Run", summary: "", fallback: line, details: toolDetails(event, line), appendOnly: true })}${TUI_TREE_END}
11260
+ `;
11261
+ }
11262
+ return line;
9938
11263
  };
9939
11264
  format.reset = () => {
9940
11265
  tree = null;
11266
+ scope++;
9941
11267
  };
9942
11268
  format.consume = (event) => {
9943
11269
  if (event.type === "tool-call") {
@@ -10185,10 +11511,6 @@ function shouldPromoteTuiNarration(text) {
10185
11511
  if (text.length >= TUI_PROGRESS_BUFFER_LIMIT) return true;
10186
11512
  return /(^|\n)\s*(?:#{1,3}\s|```|[-*+]\s|\d+[.)]\s)/.test(text);
10187
11513
  }
10188
- function narrationActivityLabel(text) {
10189
- const oneLine = stripAnsi(text).replace(/[`*_#>]/g, "").replace(/\s+/g, " ").trim();
10190
- return truncateThinkingHint(oneLine, 60);
10191
- }
10192
11514
  function createCliTurnOutput(params) {
10193
11515
  const { options } = params;
10194
11516
  const workingLabel = params.workingLabel ?? `${options.agentName} -> working`;
@@ -10201,12 +11523,7 @@ function createCliTurnOutput(params) {
10201
11523
  const assistantLabelManaged = options.output.assistantLabelManaged === true;
10202
11524
  const showThinking = !assistantLabelManaged && options.showThinking !== false;
10203
11525
  const hidesRoutineTuiToolDetail = (event) => {
10204
- if (!assistantLabelManaged || event.toolName !== "editFile") return false;
10205
- if (event.type === "tool-error") return false;
10206
- if (readActionGate(event.metadata?.actionGate)) return false;
10207
- if (event.metadata?.timedOut || event.metadata?.failed || event.metadata?.error) return false;
10208
- if (typeof event.metadata?.exitCode === "number" && event.metadata.exitCode !== 0) return false;
10209
- return true;
11526
+ return false;
10210
11527
  };
10211
11528
  let streamedAssistantText = false;
10212
11529
  let everStreamedAnyText = false;
@@ -10280,11 +11597,6 @@ function createCliTurnOutput(params) {
10280
11597
  streamedAssistantText = true;
10281
11598
  options.activityReporter?.(null);
10282
11599
  };
10283
- const dropPendingTuiProgress = () => {
10284
- pendingTuiNarration = "";
10285
- tuiNarrationPromoted = false;
10286
- options.activityReporter?.(null);
10287
- };
10288
11600
  const writeVisibleAssistantChunk = (chunk) => {
10289
11601
  if (!chunk) return;
10290
11602
  if (!assistantLabelManaged) formatToolEvent.reset?.();
@@ -10303,6 +11615,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10303
11615
  }
10304
11616
  printedAssistantLabel = true;
10305
11617
  }
11618
+ if (assistantLabelManaged) options.activityReporter?.(t("generatingReply"));
10306
11619
  everStreamedAnyText = true;
10307
11620
  if (assistantLabelManaged) {
10308
11621
  if (tuiNarrationPromoted) {
@@ -10314,8 +11627,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10314
11627
  if (shouldPromoteTuiNarration(pendingTuiNarration)) {
10315
11628
  flushPendingTuiNarration();
10316
11629
  } else {
10317
- const label = narrationActivityLabel(pendingTuiNarration);
10318
- if (label) options.activityReporter?.(label);
11630
+ options.activityReporter?.(t("generatingReply"));
10319
11631
  }
10320
11632
  return;
10321
11633
  }
@@ -10336,7 +11648,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10336
11648
  }
10337
11649
  if (event.type === "tool-call") {
10338
11650
  if (assistantLabelManaged && pendingTuiNarration) {
10339
- dropPendingTuiProgress();
11651
+ flushPendingTuiNarration();
10340
11652
  }
10341
11653
  renderWriter.flush();
10342
11654
  if (!hidesRoutineTuiToolDetail(event)) {
@@ -10377,12 +11689,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10377
11689
  /**
10378
11690
  * Terminal cleanup for abort/error paths that never reach `finish()`.
10379
11691
  *
10380
- * A user abort discards the transient TUI progress buffer: the user stopped
10381
- * on purpose and the dock already showed that text as activity. A genuine
10382
- * failure must not swallow prose that never got the chance to be *proven*
10383
- * durable (only a following tool call proves "progress"), so it promotes the
10384
- * pending buffer and flushes what was already promoted — otherwise a short
10385
- * final answer followed by a transport error disappears from the transcript.
11692
+ * Preserve original prose on both abort and transport failure.
10386
11693
  */
10387
11694
  cancel(cleanup) {
10388
11695
  if (assistantLabelManaged && cleanup?.preservePendingNarration) {
@@ -10392,7 +11699,8 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10392
11699
  options.output.write("\n");
10393
11700
  }
10394
11701
  }
10395
- dropPendingTuiProgress();
11702
+ flushPendingTuiNarration();
11703
+ renderWriter.flush();
10396
11704
  },
10397
11705
  pushText(chunk) {
10398
11706
  writeVisibleAssistantChunk(chunk);
@@ -10969,57 +12277,9 @@ function isBalanceExhaustedError(error) {
10969
12277
  return matchesBalanceError(message);
10970
12278
  }
10971
12279
 
10972
- // packages/cli/client/hostTaskWorkspaceAssessment.ts
10973
- import { resolve as resolve3 } from "node:path";
10974
- var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
10975
- var present = (value) => typeof value === "string" && value.trim().length > 0;
10976
- function resolveCurrentHostTaskReference(input) {
10977
- const ref = input.reference;
10978
- if (!ref || !present(ref.taskId) || !present(ref.workspace) || !present(ref.dialogId) || ref.dialogId !== input.dialogId || resolve3(ref.workspace) !== resolve3(input.workspace) || readHostTask(hostTaskEventsRoot(input.env), ref).authorization === "unknown") return void 0;
10979
- return structuredClone(ref);
10980
- }
10981
- async function assessHostTaskWorkspace(input) {
10982
- const ref = resolveCurrentHostTaskReference(input);
10983
- if (!ref) return void 0;
10984
- const root = hostTaskEventsRoot(input.env);
10985
- const blocked = (reason, businessReason = "invalid_contract") => ({
10986
- exitCode: 1,
10987
- hostTaskWorkspaceBlocker: reason,
10988
- businessCompletion: { taskId: ref.taskId, status: "blocked", reasons: [businessReason] }
10989
- });
10990
- const fresh = await collectHostTaskWorkspace(ref, input.env);
10991
- const plan = readHostTaskAcceptancePlan(ref, input.env);
10992
- let planned;
10993
- if (plan) {
10994
- try {
10995
- planned = { status: "ready", context: await collectHostTaskPlannedWorkspace(ref, input.env) };
10996
- } catch {
10997
- planned = { status: "blocked", reason: "task_planned_workspace_unavailable" };
10998
- }
10999
- }
11000
- const authority = readHostTask(root, ref).authorization;
11001
- if (authority === "paused" || authority === "revoked") return blocked(`authorization_${authority}`, `authorization_${authority}`);
11002
- if (authority !== "active") return blocked("task_authority_unavailable");
11003
- const supplied = object(input.evidence);
11004
- if (supplied?.status === "blocked") return blocked(present(supplied.reason) ? supplied.reason : "workspace_blocked");
11005
- if (fresh.status === "blocked") return blocked(fresh.reason);
11006
- if (planned?.status === "blocked") return blocked(planned.reason);
11007
- if (planned?.status === "ready" && planned.context.baseline !== fresh.context.baseline) {
11008
- return blocked("task_plan_baseline_mismatch");
11009
- }
11010
- const context = object(supplied?.context);
11011
- const scope = object(context?.scope);
11012
- if (supplied?.status !== "ready" || !context || !scope || scope.taskId !== ref.taskId || scope.dialogId !== ref.dialogId || scope.taskInstanceId !== ref.taskInstanceId || !present(scope.workspace) || resolve3(scope.workspace) !== resolve3(ref.workspace)) return blocked("workspace_evidence_mismatch");
11013
- const matches = (canonical) => context.baseline === canonical.baseline && context.revision === canonical.revision && Array.isArray(context.taskPaths) && context.taskPaths.length === canonical.taskPaths.length && context.taskPaths.every((path2, index) => path2 === canonical.taskPaths[index]);
11014
- if (!matches(fresh.context) && !(planned?.status === "ready" && matches(planned.context))) {
11015
- return blocked("workspace_evidence_mismatch");
11016
- }
11017
- return void 0;
11018
- }
11019
-
11020
12280
  // packages/cli/client/agentRun.ts
11021
12281
  async function loadRunLocalAgentTurn() {
11022
- const { runLocalAgentTurn } = await import("./agentRuntimeLocal-SD7U2EGY.js");
12282
+ const { runLocalAgentTurn } = await import("./agentRuntimeLocal-TU4LA353.js");
11023
12283
  return runLocalAgentTurn;
11024
12284
  }
11025
12285
  var stripDebugNoise = (s) => s.replace(/\s*raw="[\s\S]*"/g, "").replace(/\s*raw=\S+/g, "").replace(/\s*headers=\[[^\]]*\]/g, "").replace(/\s*headers=\S+/g, "").trim();
@@ -11451,9 +12711,9 @@ function isStandaloneResetSentence(text, index) {
11451
12711
  var RATE_LIMIT_DETAIL_MAX_CHARS = 140;
11452
12712
  var UPSTREAM_TAG_MAX_CHARS = 64;
11453
12713
  function findJsonObjectEnd(text, from) {
11454
- const open = text[from];
11455
- if (open !== "{" && open !== "[") return -1;
11456
- const close = open === "{" ? "}" : "]";
12714
+ const open2 = text[from];
12715
+ if (open2 !== "{" && open2 !== "[") return -1;
12716
+ const close = open2 === "{" ? "}" : "]";
11457
12717
  let depth = 0;
11458
12718
  let inString = false;
11459
12719
  let escaped = false;
@@ -11466,7 +12726,7 @@ function findJsonObjectEnd(text, from) {
11466
12726
  continue;
11467
12727
  }
11468
12728
  if (ch === '"') inString = true;
11469
- else if (ch === open) depth += 1;
12729
+ else if (ch === open2) depth += 1;
11470
12730
  else if (ch === close) {
11471
12731
  depth -= 1;
11472
12732
  if (depth === 0) return i + 1;
@@ -11814,6 +13074,10 @@ function describeLocalRunFailure(message, rawError) {
11814
13074
  }
11815
13075
  if (isMissingBatchReceiptFailure(message)) {
11816
13076
  return `[nolo] ${describeMissingBatchReceipt()}.
13077
+ `;
13078
+ }
13079
+ if (/\bimage_model_unsupported\b/.test(message)) {
13080
+ return `[nolo] ${message}. ${NO_FALLBACK} Check the selected model's image capability or use a model known to support images.
11817
13081
  `;
11818
13082
  }
11819
13083
  const cls = classifyLocalRunError(message);
@@ -12163,6 +13427,17 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12163
13427
  options.modelOverride
12164
13428
  ) : resolvedBaseAdapter;
12165
13429
  if (adapter2) adapter2 = applyEphemeralIfRequested(options, adapter2);
13430
+ if (adapter2 && options.imageUrls?.length) {
13431
+ const imageAdapter = adapter2;
13432
+ adapter2 = { ...imageAdapter, loadAgentConfig: async (agentRef) => {
13433
+ const config = await imageAdapter.loadAgentConfig(agentRef);
13434
+ if (!config) return config;
13435
+ if (!resolveAgentImageInputSupport({ ...config, hasVision: config.hasVision ?? false })) {
13436
+ throw new Error("image_model_unsupported: child model image capability is unsupported or unknown");
13437
+ }
13438
+ return config;
13439
+ } };
13440
+ }
12166
13441
  return adapter2;
12167
13442
  })();
12168
13443
  if (!baseAdapter) {
@@ -12189,12 +13464,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12189
13464
  } : void 0;
12190
13465
  const currentDialogId = options.continueDialogId ?? ulid2();
12191
13466
  const freshDialog = options.freshDialog ?? !options.continueDialogId;
12192
- options = { ...options, hostTaskRef: resolveCurrentHostTaskReference({
12193
- reference: options.hostTaskRef,
12194
- workspace: options.localRuntimeCwd ?? process.cwd(),
12195
- dialogId: currentDialogId,
12196
- env: options.env
12197
- }) };
12198
13467
  const turnId = `turn-${ulid2()}`;
12199
13468
  const runtimeContextWithOwnership = {
12200
13469
  ...runtimeContext ?? {},
@@ -12202,80 +13471,8 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12202
13471
  turnId,
12203
13472
  getProcessCausalDepth: options.getProcessCausalDepth
12204
13473
  };
12205
- const installReviewHost = baseAdapter.installTaskReviewHost;
12206
- if (options.hostTaskRef && installReviewHost) {
12207
- const scope = structuredClone(options.hostTaskRef);
12208
- const authorExecutionId = createHostAuthorExecution(options.env, scope, turnId);
12209
- installReviewHost({ scope, authorExecutionId, authorize: async () => {
12210
- if (!scope.taskId?.trim() || !scope.workspace?.trim() || !scope.dialogId?.trim() || scope.dialogId !== currentDialogId || resolveHostReviewPath(scope.workspace) !== resolveHostReviewPath(options.localRuntimeCwd ?? process.cwd())) throw new Error("task_review_host_scope_mismatch");
12211
- } });
12212
- }
12213
- let reviewContext;
12214
- const requestedReview = options.hostReviewDispatch;
12215
- if (requestedReview && options.hostTaskRef && requestedReview.scope.taskId === options.hostTaskRef.taskId && requestedReview.scope.dialogId === currentDialogId && resolveHostReviewPath(requestedReview.scope.workspace) === resolveHostReviewPath(options.hostTaskRef.workspace)) {
12216
- reviewContext = { ...requestedReview, authorExecutionId: createHostAuthorExecution(options.env, options.hostTaskRef, turnId) };
12217
- }
12218
13474
  const commandVersionBindings = /* @__PURE__ */ new Map();
12219
13475
  const commandAdapter = !options.runtimeKey || options.runtimeKey === "local" ? wrapLocalCommandWorkspaceObservation(baseAdapter, options.localRuntimeCwd ?? process.cwd(), commandVersionBindings, void 0, options.abortSignal) : baseAdapter;
12220
- const reviewAdapter = {
12221
- ...commandAdapter,
12222
- executeTool: async (call, opts) => {
12223
- let args = {};
12224
- try {
12225
- args = typeof call.arguments === "string" ? JSON.parse(call.arguments) : call.arguments ?? {};
12226
- } catch {
12227
- }
12228
- const matched = call.name === "startAgentRun" && matchesHostReviewDispatch(reviewContext, call, args);
12229
- const result = await withHostReviewDispatch(matched ? reviewContext : void 0, () => commandAdapter.executeTool(call, opts));
12230
- return result;
12231
- }
12232
- };
12233
- const completionEvidenceProvider = options.hostTaskRef ? options.hostTaskCompletionEvidenceProvider : void 0;
12234
- let hostTask = bindHostTask({
12235
- adapter: reviewAdapter,
12236
- reference: options.hostTaskRef,
12237
- workspace: options.localRuntimeCwd ?? process.cwd(),
12238
- dialogId: currentDialogId,
12239
- env: options.env,
12240
- signal: options.abortSignal,
12241
- completionEvidenceProvider
12242
- });
12243
- if (options.hostTaskRef && options.hostTaskWorkspaceEvidence !== void 0 && readHostTask(hostTaskEventsRoot(options.env), options.hostTaskRef).authorization === "active") {
12244
- const blocker = await assessHostTaskWorkspace({
12245
- reference: options.hostTaskRef,
12246
- workspace: options.localRuntimeCwd ?? process.cwd(),
12247
- dialogId: currentDialogId,
12248
- env: options.env,
12249
- evidence: options.hostTaskWorkspaceEvidence
12250
- });
12251
- if (blocker) {
12252
- options.output.write(`[auto-review] blocked: ${blocker.hostTaskWorkspaceBlocker}
12253
- `);
12254
- try {
12255
- const saved = await reviewAdapter.saveTurn({
12256
- agentKey: options.agentKey,
12257
- messages: [{ role: "user", content: options.message }],
12258
- continueDialogId: currentDialogId,
12259
- runtimeContext: runtimeContextWithOwnership,
12260
- result: {
12261
- model: "host-workspace-assessment",
12262
- content: "",
12263
- error: true,
12264
- businessCompletion: blocker.businessCompletion
12265
- }
12266
- });
12267
- return {
12268
- ...blocker,
12269
- hostTaskRef: options.hostTaskRef,
12270
- dialogId: saved.dialogId,
12271
- taskAuthorization: readHostTask(hostTaskEventsRoot(options.env), options.hostTaskRef).authorization
12272
- };
12273
- } catch (localError) {
12274
- return { ...blocker, hostTaskRef: options.hostTaskRef, localError };
12275
- }
12276
- }
12277
- }
12278
- let usedReviewTool = false;
12279
13476
  let batchProviderStarted = false;
12280
13477
  let mainProviderStarted = false;
12281
13478
  let refusalModel = "";
@@ -12298,9 +13495,9 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12298
13495
  }
12299
13496
  };
12300
13497
  const adapter = {
12301
- ...hostTask.adapter,
13498
+ ...commandAdapter,
12302
13499
  resolveProvider: async (...args) => {
12303
- const provider = await hostTask.adapter.resolveProvider(...args);
13500
+ const provider = await commandAdapter.resolveProvider(...args);
12304
13501
  const isTextOnly = Boolean(args[1]?.textOnly);
12305
13502
  if (!isTextOnly) refusalModel = provider.model;
12306
13503
  return {
@@ -12317,26 +13514,8 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12317
13514
  }
12318
13515
  };
12319
13516
  },
12320
- executeTool: async (call, opts) => {
12321
- const protectedReview = call.name === "requestTaskReview" || call.name === "recordTaskReviewDecision";
12322
- if (!protectedReview) return reviewAdapter.executeTool(call, opts);
12323
- usedReviewTool = true;
12324
- if (options.hostTaskRef?.taskInstanceId) {
12325
- const authorize = baseAdapter.authorizeAccountTask;
12326
- if (!authorize) throw new Error("task_review_account_authorization_unavailable");
12327
- await authorize(options.hostTaskRef);
12328
- }
12329
- if (!options.hostTaskRef && ["requestTaskReview", "recordTaskReviewDecision"].includes(call.name)) {
12330
- const admit = baseAdapter.admitAccountReviewTurn;
12331
- if (!admit) throw new Error("task_review_account_admission_unavailable");
12332
- const reference = await admit(currentDialogId, turnId);
12333
- options = { ...options, hostTaskRef: reference };
12334
- hostTask = bindHostTask({ adapter: reviewAdapter, reference, workspace: options.localRuntimeCwd ?? process.cwd(), dialogId: currentDialogId, env: options.env, signal: options.abortSignal });
12335
- }
12336
- return hostTask.adapter.executeTool(call, opts);
12337
- },
13517
+ // 工具执行直接走 ...commandAdapter 展开(无需再写一行透传)。
12338
13518
  saveTurn: async (input) => {
12339
- if (usedReviewTool && options.hostTaskRef) await settleHostReviewsForScope(options.hostTaskRef, options.env, options.hostReviewContentAcceptance);
12340
13519
  const completeBatch = Boolean(batchIdentity && batchProviderStarted && !input.result.error);
12341
13520
  const injectedBatches = options.drainInjectedBatches ?? [];
12342
13521
  const injectedMessageIds = new Set(injectedBatches.flatMap((batch) => batch.messageIds));
@@ -12345,8 +13524,11 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12345
13524
  ...!input.result.error ? injectedBatches.map((batch) => batch.batchId) : []
12346
13525
  ];
12347
13526
  try {
12348
- const saved = await hostTask.adapter.saveTurn({
13527
+ const saved = await commandAdapter.saveTurn({
12349
13528
  ...input,
13529
+ // Receipt-backed user rows are excluded below to avoid duplicate persistence.
13530
+ // Keep their explicit identities for post-sync native memory capture.
13531
+ ...{ cliCaptureUserMessageIds: input.messages.filter((message) => message.role === "user").map((message) => message.cliMessageId).filter((id) => typeof id === "string") },
12350
13532
  messages: input.messages.filter((message) => {
12351
13533
  const cliMessageId = message.cliMessageId;
12352
13534
  if (!cliMessageId) return true;
@@ -12393,7 +13575,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12393
13575
  const runLocalAgentTurn = await loadRunLocalAgentTurn();
12394
13576
  const result = await runLocalAgentTurn({
12395
13577
  adapter,
12396
- ...hostTask.contract ? { taskExecutionContract: hostTask.contract } : {},
12397
13578
  agentRef: options.agentKey,
12398
13579
  userLanguage: options.userLanguage ?? options.env.NOLO_LANG ?? null,
12399
13580
  input: buildUserInputContent(messageForLocal, options.imageUrls),
@@ -12486,8 +13667,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12486
13667
  mainProviderAttempted: mainProviderStarted,
12487
13668
  exitCode: 0,
12488
13669
  stopReason: result.stopReason,
12489
- ...hostTask.result(),
12490
- ...options.hostTaskRef ? { hostTaskRef: options.hostTaskRef } : {},
12491
13670
  dialogId: result.dialogId,
12492
13671
  ...typeof result.content === "string" && result.content.trim() ? { finalText: result.content } : {},
12493
13672
  ...result.title !== void 0 ? { title: result.title } : {},
@@ -12525,10 +13704,8 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12525
13704
  const pendingToolName = error?.pendingToolName;
12526
13705
  return retainCommandObservations({
12527
13706
  exitCode: 0,
12528
- ...hostTask.result(),
12529
13707
  savedTurnPersisted: turnPersisted,
12530
13708
  mainProviderAttempted: mainProviderStarted,
12531
- ...options.hostTaskRef ? { hostTaskRef: options.hostTaskRef } : {},
12532
13709
  streamInterrupted: true,
12533
13710
  ...savedDialogId ? { dialogId: savedDialogId } : {},
12534
13711
  ...pendingToolName ? { pendingToolName } : {},
@@ -12574,7 +13751,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12574
13751
  }
12575
13752
  return retainCommandObservations({
12576
13753
  exitCode: 1,
12577
- ...hostTask.result(),
12578
13754
  localError: error,
12579
13755
  savedTurnPersisted: persisted,
12580
13756
  mainProviderAttempted: mainProviderStarted,
@@ -12642,7 +13818,6 @@ function foldLocalResultForTui(localResult) {
12642
13818
  const folded = {
12643
13819
  exitCode: localResult.exitCode,
12644
13820
  ...projectLocalTurnFacts(localResult),
12645
- ...localResult.hostTaskRef ? { hostTaskRef: localResult.hostTaskRef } : {},
12646
13821
  ...localResult.dialogId ? { dialogId: localResult.dialogId } : {},
12647
13822
  title: localResult.title,
12648
13823
  ...localResult.titlePatchPromise ? { titlePatchPromise: localResult.titlePatchPromise } : {},
@@ -12986,7 +14161,7 @@ function buildHostEnvironmentLayer(options) {
12986
14161
 
12987
14162
  // packages/agent-runtime/agentsMd.ts
12988
14163
  import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
12989
- import { resolve as resolve4 } from "node:path";
14164
+ import { resolve as resolve3 } from "node:path";
12990
14165
  var AGENTS_MD_MAX_BYTES = 8192;
12991
14166
  var AGENTS_MD_MARKER_RESERVE_BYTES = 512;
12992
14167
  var AGENTS_MD_CANDIDATES = ["AGENTS.md", "CLAUDE.md"];
@@ -13187,7 +14362,7 @@ ${entry.line}`;
13187
14362
  };
13188
14363
  function readAgentsMdLayerFromDisk(cwd) {
13189
14364
  for (const name of AGENTS_MD_CANDIDATES) {
13190
- const filePath = resolve4(cwd, name);
14365
+ const filePath = resolve3(cwd, name);
13191
14366
  if (!existsSync2(filePath)) continue;
13192
14367
  try {
13193
14368
  const raw = readFileSync3(filePath, "utf8");
@@ -13329,16 +14504,16 @@ function runDoDCommands(commands, cwd, deps = {}) {
13329
14504
 
13330
14505
  // packages/cli/agentRunPrompts.ts
13331
14506
  import { existsSync as existsSync3, readFileSync as readFileSync4, readdirSync, statSync as statSync2 } from "node:fs";
13332
- import { dirname, extname, isAbsolute as isAbsolute2, join as join2, relative as relativePath, resolve as resolve5, sep } from "node:path";
14507
+ import { dirname, extname, isAbsolute as isAbsolute2, join as join2, relative as relativePath, resolve as resolve4, sep } from "node:path";
13333
14508
  function workflowRefToCandidatePath(cwd, ref) {
13334
14509
  const normalized = ref.trim();
13335
14510
  if (!normalized) return "";
13336
14511
  if (normalized.endsWith(".md") || normalized.includes("/") || normalized.includes("\\")) {
13337
- const directPath = resolve5(cwd, normalized);
14512
+ const directPath = resolve4(cwd, normalized);
13338
14513
  if (existsSync3(directPath)) return directPath;
13339
14514
  }
13340
14515
  const fileName = normalized.replace(/[^a-zA-Z0-9一-鿿]+/g, "-").replace(/^-+|-+$/g, "");
13341
- return resolve5(cwd, "docs", "workflows", `${fileName}.md`);
14516
+ return resolve4(cwd, "docs", "workflows", `${fileName}.md`);
13342
14517
  }
13343
14518
  var SKILL_SEARCH_DIRS = [
13344
14519
  ".agents/skills"
@@ -13347,15 +14522,15 @@ function skillRefToCandidatePath(cwd, ref) {
13347
14522
  const normalized = ref.trim();
13348
14523
  if (!normalized) return "";
13349
14524
  if (normalized.endsWith(".md") || normalized.includes("/") || normalized.includes("\\")) {
13350
- const directPath = resolve5(cwd, normalized);
14525
+ const directPath = resolve4(cwd, normalized);
13351
14526
  if (existsSync3(directPath)) return directPath;
13352
14527
  }
13353
14528
  const fileName = normalized.replace(/[^a-zA-Z0-9一-鿿]+/g, "-").replace(/^-+|-+$/g, "");
13354
14529
  for (const dir of SKILL_SEARCH_DIRS) {
13355
- const skillMdPath = resolve5(cwd, dir, fileName, "SKILL.md");
14530
+ const skillMdPath = resolve4(cwd, dir, fileName, "SKILL.md");
13356
14531
  if (existsSync3(skillMdPath)) return skillMdPath;
13357
14532
  }
13358
- return resolve5(cwd, ".agents", "skills", fileName, "SKILL.md");
14533
+ return resolve4(cwd, ".agents", "skills", fileName, "SKILL.md");
13359
14534
  }
13360
14535
  async function resolveWorkflowReference(ref, cwd = process.cwd()) {
13361
14536
  const path2 = workflowRefToCandidatePath(cwd, ref);
@@ -13372,11 +14547,11 @@ async function resolveWorkflowReference(ref, cwd = process.cwd()) {
13372
14547
  }
13373
14548
  function inlineRelativeRefs(body, skillDir) {
13374
14549
  const refPattern = /\[([^\]]+)\]\((\.\/[^)]+|[^)]+\/[^)]+)\)/g;
13375
- const normalizedSkillDir = resolve5(skillDir) + sep;
14550
+ const normalizedSkillDir = resolve4(skillDir) + sep;
13376
14551
  return body.replace(refPattern, (match, label, relPath) => {
13377
14552
  const cleaned = relPath.trim();
13378
14553
  if (!cleaned.startsWith("./") && !cleaned.startsWith("../")) return match;
13379
- const absPath = resolve5(skillDir, cleaned);
14554
+ const absPath = resolve4(skillDir, cleaned);
13380
14555
  const relative = relativePath(normalizedSkillDir, absPath);
13381
14556
  if (relative.startsWith("..") || isAbsolute2(relative)) return match;
13382
14557
  if (!existsSync3(absPath) || !absPath.endsWith(".md")) return match;
@@ -13526,7 +14701,7 @@ function prependSubjectDialogMarker(message, subjectDialogKey) {
13526
14701
  }
13527
14702
  function normalizeCliImageInput(input) {
13528
14703
  if (/^(https?:|data:|file:)/i.test(input)) return input;
13529
- const absolutePath = resolve5(input);
14704
+ const absolutePath = resolve4(input);
13530
14705
  if (!existsSync3(absolutePath)) return input;
13531
14706
  const base64 = readFileSync4(absolutePath).toString("base64");
13532
14707
  return `data:${imageMimeTypeForPath(absolutePath)};base64,${base64}`;
@@ -13545,22 +14720,6 @@ function imageMimeTypeForPath(path2) {
13545
14720
  }
13546
14721
  }
13547
14722
 
13548
- // packages/ai/memory/storeShared.ts
13549
- var retrievalCountOf = (item) => item.activationCount ?? 0;
13550
- var touchMemoryItemsInDb = async (db, items, now = (/* @__PURE__ */ new Date()).toISOString()) => {
13551
- if (items.length === 0) return;
13552
- const batch = db.batch();
13553
- for (const item of items) {
13554
- batch.put(createMemoryKey(item.ownerType, item.ownerId, item.id), {
13555
- ...item,
13556
- // retrieval bookkeeping on legacy storage names — see doc comment above
13557
- lastActivatedAt: now,
13558
- activationCount: retrievalCountOf(item) + 1
13559
- });
13560
- }
13561
- await batch.write();
13562
- };
13563
-
13564
14723
  // packages/ai/memory/vnext/detachedThrottle.ts
13565
14724
  var DEFAULT_DETACHED_MEMORY_COOLDOWN_MS = 10 * 60 * 1e3;
13566
14725
  var MAX_COOLDOWN_KEYS = 512;
@@ -13609,6 +14768,73 @@ var createDetachedThrottle = (input) => {
13609
14768
  };
13610
14769
  };
13611
14770
 
14771
+ // packages/ai/memory/vnext/recallBudget.ts
14772
+ var DEFAULT_DEEP_MEMORY_TOKENS = DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET;
14773
+ var resolveMemoryBudget = (value) => {
14774
+ const budget = value ?? DEFAULT_DEEP_MEMORY_TOKENS;
14775
+ if (!Number.isSafeInteger(budget) || budget < 512) {
14776
+ throw new Error("memory budget must be a safe integer >= 512 estimated tokens");
14777
+ }
14778
+ return budget;
14779
+ };
14780
+ var clipMemoryText = (text, maxTokens) => {
14781
+ if (estimateTokenCount(text) <= maxTokens) return text;
14782
+ const suffix = "\u2026[truncated]";
14783
+ if (estimateTokenCount(suffix) > maxTokens) return "";
14784
+ let lo = 0;
14785
+ let hi = text.length;
14786
+ while (lo < hi) {
14787
+ const mid = Math.ceil((lo + hi) / 2);
14788
+ if (estimateTokenCount(text.slice(0, mid) + suffix) <= maxTokens) lo = mid;
14789
+ else hi = mid - 1;
14790
+ }
14791
+ if (lo && /[\uD800-\uDBFF]/.test(text[lo - 1])) lo--;
14792
+ return text.slice(0, lo) + suffix;
14793
+ };
14794
+ var DESCRIPTIVE_FIELDS = /* @__PURE__ */ new Set(["text", "name", "facet", "subtype", "value", "aliases"]);
14795
+ var compactMemoryRow = (row, fieldTokens = 128) => Object.fromEntries(Object.entries(row).map(([key, value]) => [
14796
+ key,
14797
+ DESCRIPTIVE_FIELDS.has(key) && estimateTokenCount(typeof value === "string" ? value : JSON.stringify(value) ?? "") > fieldTokens ? clipMemoryText(typeof value === "string" ? value : JSON.stringify(value) ?? "", fieldTokens) : value
14798
+ ]));
14799
+ var memoryMessageTokens = (messages) => messages.reduce((sum, message) => sum + estimateTokenCount(message.content) + 8, 0);
14800
+ var buildBudgetedMemoryInput = (input) => {
14801
+ const maxTokens = resolveMemoryBudget(input.maxTokens);
14802
+ const query = clipMemoryText(input.query, Math.floor(maxTokens / 4));
14803
+ const rows = [];
14804
+ const messages = () => [
14805
+ { role: "system", content: input.system + "\nThis is a budgeted subset. Omitted candidates are unknown, not absent. Select only supplied exact ids; never infer nonexistence from omissions." },
14806
+ { role: "user", content: `Query:
14807
+ ${query}
14808
+
14809
+ Memory catalog:
14810
+ ${JSON.stringify({ candidates: rows })}` }
14811
+ ];
14812
+ if (memoryMessageTokens(messages()) > maxTokens) {
14813
+ throw new Error("memory budget cannot fit instructions and query");
14814
+ }
14815
+ let clipped = false;
14816
+ for (const original of input.rows) {
14817
+ const row = compactMemoryRow(original);
14818
+ rows.push(row);
14819
+ if (memoryMessageTokens(messages()) > maxTokens) rows.pop();
14820
+ else if (JSON.stringify(row) !== JSON.stringify(original)) clipped = true;
14821
+ }
14822
+ const result = messages();
14823
+ return {
14824
+ messages: result,
14825
+ rows,
14826
+ budget: {
14827
+ maxTokens,
14828
+ usedTokens: memoryMessageTokens(result),
14829
+ truncated: clipped || rows.length !== input.rows.length || query !== input.query,
14830
+ queryTruncated: query !== input.query,
14831
+ offeredCandidates: rows.length,
14832
+ totalCandidates: input.rows.length,
14833
+ omittedCandidates: input.rows.length - rows.length
14834
+ }
14835
+ };
14836
+ };
14837
+
13612
14838
  // packages/ai/memory/vnext/recall.ts
13613
14839
  var MAX_RECALL_REFS = 6;
13614
14840
  var stripFence = (raw) => {
@@ -13638,76 +14864,84 @@ var parseSelection = (raw) => {
13638
14864
  reason: obj.reason
13639
14865
  };
13640
14866
  };
13641
- var catalogText = (entities, states) => JSON.stringify(
13642
- {
13643
- entities: entities.map((entity) => ({
13644
- id: entity.id,
13645
- type: entity.type,
13646
- name: entity.name,
13647
- ...entity.subtype ? { subtype: entity.subtype } : {},
13648
- ...entity.aliases?.length ? { aliases: entity.aliases } : {}
13649
- })),
13650
- states: states.map((state2) => ({
13651
- id: state2.id,
13652
- entityId: state2.entityId,
13653
- facet: state2.facet,
13654
- text: state2.text,
13655
- // Retired (superseded) States stay listed as recoverable history; the
13656
- // boolean — not the retiredAt timestamp — enters the prompt so no
13657
- // timestamps reach LLM text.
13658
- ...state2.retiredAt ? { retired: true } : {}
13659
- }))
13660
- },
13661
- null,
13662
- 2
13663
- );
13664
14867
  var createMemoryVNextRecall = (input) => async (query) => {
13665
14868
  const startedAt = performance.now();
14869
+ const maxTokens = resolveMemoryBudget(input.maxInputTokens);
13666
14870
  const { entities, states } = await loadMemoryVNextCatalog(input.db, input.ownerId);
13667
- if (entities.length === 0 && states.length === 0) {
14871
+ if (!query.trim() || entities.length === 0 && states.length === 0) {
13668
14872
  return {
13669
14873
  query,
13670
14874
  refs: [],
13671
14875
  entities: [],
13672
14876
  states: [],
13673
- reason: "memory catalog is empty",
14877
+ reason: query.trim() ? "memory catalog is empty" : "query is empty",
13674
14878
  trace: {
13675
14879
  candidateEntities: 0,
13676
14880
  candidateStates: 0,
13677
14881
  selectedRefs: 0,
14882
+ budget: {
14883
+ maxTokens,
14884
+ usedTokens: 0,
14885
+ truncated: false,
14886
+ offeredCandidates: 0,
14887
+ totalCandidates: entities.length + states.length,
14888
+ omittedCandidates: entities.length + states.length
14889
+ },
13678
14890
  elapsedMs: Math.round((performance.now() - startedAt) * 10) / 10
13679
14891
  }
13680
14892
  };
13681
14893
  }
13682
- const result = await input.provider.complete(
13683
- [
13684
- {
13685
- role: "system",
13686
- content: [
13687
- "Select the smallest useful set of long-lived memory entrances for the user query.",
13688
- 'Return ONLY JSON: {"refs":["exact-id"],"reason":"short explanation"}.',
13689
- `Select at most ${MAX_RECALL_REFS} exact ids from the supplied catalog.`,
13690
- "Prefer State ids when current durable understanding answers the query.",
13691
- "Select an Entity id when it is a useful navigation anchor and no single State is enough.",
13692
- "Do not select unrelated memories merely because they are personal or interesting.",
13693
- "Historical-detail questions may select the relevant current State/Entity as an entrance; deeper evidence is handled by inspect, not here."
13694
- ].join("\n")
13695
- },
13696
- {
13697
- role: "user",
13698
- content: `Query:
13699
- ${query}
13700
-
13701
- Memory catalog:
13702
- ${catalogText(entities, states)}`
13703
- }
14894
+ const hits = recallMemoryVNextLocal({ query, entities, states, limit: states.length });
14895
+ const priority = new Set(hits.flatMap(({ state: state2 }) => [state2.id, state2.entityId]));
14896
+ const rankedStates = [
14897
+ ...hits.map(({ state: state2 }) => state2),
14898
+ ...states.filter((state2) => !priority.has(state2.id)).sort((a, b) => a.id.localeCompare(b.id))
14899
+ ];
14900
+ const rankedEntities = [...entities].sort((a, b) => Number(priority.has(b.id)) - Number(priority.has(a.id)) || a.id.localeCompare(b.id));
14901
+ const stateRows = rankedStates.map((state2) => ({
14902
+ kind: "state",
14903
+ id: state2.id,
14904
+ entityId: state2.entityId,
14905
+ facet: state2.facet,
14906
+ text: state2.text,
14907
+ ...state2.retiredAt ? { retired: true } : {}
14908
+ }));
14909
+ const entityRows = rankedEntities.map((entity) => ({
14910
+ kind: "entity",
14911
+ id: entity.id,
14912
+ type: entity.type,
14913
+ name: entity.name,
14914
+ ...entity.subtype ? { subtype: entity.subtype } : {},
14915
+ ...entity.aliases?.length ? { aliases: entity.aliases } : {}
14916
+ }));
14917
+ const request = buildBudgetedMemoryInput({
14918
+ query,
14919
+ maxTokens: input.maxInputTokens,
14920
+ rows: [
14921
+ ...stateRows.filter((row) => priority.has(row.id)),
14922
+ ...entityRows.filter((row) => priority.has(row.id)),
14923
+ ...stateRows.filter((row) => !priority.has(row.id)),
14924
+ ...entityRows.filter((row) => !priority.has(row.id))
13704
14925
  ],
14926
+ system: [
14927
+ "Select the smallest useful set of long-lived memory entrances for the user query.",
14928
+ 'Return ONLY JSON: {"refs":["exact-id"],"reason":"short explanation"}.',
14929
+ `Select at most ${MAX_RECALL_REFS} exact ids from the supplied catalog.`,
14930
+ "Prefer current State ids; retired States are history entrances, not current facts.",
14931
+ "Select an Entity when it is a useful navigation anchor.",
14932
+ "Do not select unrelated memories merely because they are personal or interesting.",
14933
+ "Historical questions may select a relevant entrance; deeper evidence is handled by inspect."
14934
+ ].join("\n")
14935
+ });
14936
+ const result = await input.provider.complete(
14937
+ request.messages,
13705
14938
  input.timeoutMs ? { timeoutMs: input.timeoutMs } : void 0
13706
14939
  );
13707
14940
  const selected = parseSelection(result.content);
13708
14941
  const entityById = new Map(entities.map((entity) => [entity.id, entity]));
13709
14942
  const stateById = new Map(states.map((state2) => [state2.id, state2]));
13710
- const validRefs = selected.refs.filter((ref) => entityById.has(ref) || stateById.has(ref));
14943
+ const offered = new Set(request.rows.map((row) => row.id));
14944
+ const validRefs = selected.refs.filter((ref) => offered.has(ref) && (entityById.has(ref) || stateById.has(ref)));
13711
14945
  return {
13712
14946
  query,
13713
14947
  refs: validRefs,
@@ -13724,6 +14958,7 @@ ${catalogText(entities, states)}`
13724
14958
  candidateEntities: entities.length,
13725
14959
  candidateStates: states.length,
13726
14960
  selectedRefs: validRefs.length,
14961
+ budget: request.budget,
13727
14962
  elapsedMs: Math.round((performance.now() - startedAt) * 10) / 10
13728
14963
  }
13729
14964
  };
@@ -13879,235 +15114,6 @@ var runMemoryVNextShadowRead = async (input) => {
13879
15114
  };
13880
15115
  var isMemoryVNextShadowReadEnabled = (env = typeof process !== "undefined" ? process.env : {}) => env.NOLO_MEMORY_VNEXT_SHADOW_READ === "1" || env.NOLO_MEMORY_VNEXT_SHADOW_READ === "true";
13881
15116
 
13882
- // packages/ai/memory/vnext/applyMutation.ts
13883
- async function validateMutation(db, ownerId, mutation) {
13884
- const pending = {
13885
- evidenceIds: /* @__PURE__ */ new Set(),
13886
- entityIds: /* @__PURE__ */ new Set(),
13887
- stateIds: /* @__PURE__ */ new Set(),
13888
- relationIds: /* @__PURE__ */ new Set()
13889
- };
13890
- for (const ev of mutation.evidence ?? []) {
13891
- if (!ev.id || typeof ev.id !== "string") {
13892
- throw new Error("evidence id must be a non-empty string");
13893
- }
13894
- if (pending.evidenceIds.has(ev.id)) {
13895
- throw new Error(`duplicate evidence id in mutation: ${ev.id}`);
13896
- }
13897
- pending.evidenceIds.add(ev.id);
13898
- }
13899
- for (const ent of mutation.entities ?? []) {
13900
- if (!ent.id || typeof ent.id !== "string") {
13901
- throw new Error("entity id must be a non-empty string");
13902
- }
13903
- if (pending.entityIds.has(ent.id)) {
13904
- throw new Error(`duplicate entity id in mutation: ${ent.id}`);
13905
- }
13906
- pending.entityIds.add(ent.id);
13907
- }
13908
- for (const st of mutation.states ?? []) {
13909
- if (!st.id || typeof st.id !== "string") {
13910
- throw new Error("state id must be a non-empty string");
13911
- }
13912
- if (pending.stateIds.has(st.id)) {
13913
- throw new Error(`duplicate state id in mutation: ${st.id}`);
13914
- }
13915
- pending.stateIds.add(st.id);
13916
- }
13917
- for (const rel of mutation.relations ?? []) {
13918
- if (!rel.id || typeof rel.id !== "string") {
13919
- throw new Error("relation id must be a non-empty string");
13920
- }
13921
- if (pending.relationIds.has(rel.id)) {
13922
- throw new Error(`duplicate relation id in mutation: ${rel.id}`);
13923
- }
13924
- pending.relationIds.add(rel.id);
13925
- }
13926
- const supersededIds = /* @__PURE__ */ new Set();
13927
- for (const sid of mutation.supersededStateIds ?? []) {
13928
- if (supersededIds.has(sid)) {
13929
- throw new Error(`duplicate supersededStateId in mutation: ${sid}`);
13930
- }
13931
- supersededIds.add(sid);
13932
- }
13933
- for (const ev of mutation.evidence ?? []) {
13934
- if (ev.ownerId !== ownerId) {
13935
- throw new Error(
13936
- `evidence ${ev.id} has ownerId ${ev.ownerId}, expected ${ownerId}`
13937
- );
13938
- }
13939
- }
13940
- for (const ent of mutation.entities ?? []) {
13941
- if (ent.ownerId !== ownerId) {
13942
- throw new Error(
13943
- `entity ${ent.id} has ownerId ${ent.ownerId}, expected ${ownerId}`
13944
- );
13945
- }
13946
- }
13947
- for (const st of mutation.states ?? []) {
13948
- if (st.ownerId !== ownerId) {
13949
- throw new Error(
13950
- `state ${st.id} has ownerId ${st.ownerId}, expected ${ownerId}`
13951
- );
13952
- }
13953
- }
13954
- for (const rel of mutation.relations ?? []) {
13955
- if (rel.ownerId !== ownerId) {
13956
- throw new Error(
13957
- `relation ${rel.id} has ownerId ${rel.ownerId}, expected ${ownerId}`
13958
- );
13959
- }
13960
- }
13961
- for (const st of mutation.states ?? []) {
13962
- if (supersededIds.has(st.id)) {
13963
- throw new Error(
13964
- `state ${st.id} appears in both states and supersededStateIds; a record cannot be created and retired in the same mutation`
13965
- );
13966
- }
13967
- }
13968
- const facetSlots = /* @__PURE__ */ new Set();
13969
- for (const st of mutation.states ?? []) {
13970
- const slot = `${st.entityId} ${st.facet}`;
13971
- if (facetSlots.has(slot)) {
13972
- throw new Error(
13973
- `mutation writes parallel current states for entity ${st.entityId} facet ${st.facet}`
13974
- );
13975
- }
13976
- facetSlots.add(slot);
13977
- }
13978
- for (const ev of mutation.evidence ?? []) {
13979
- const existing = await getMemoryEvidenceVNext(db, ownerId, ev.id);
13980
- if (existing) {
13981
- throw new Error(
13982
- `evidence ${ev.id} already exists (owner ${ownerId}); use a unique id`
13983
- );
13984
- }
13985
- }
13986
- for (const ent of mutation.entities ?? []) {
13987
- const existing = await getMemoryEntityVNext(db, ownerId, ent.id);
13988
- if (existing) {
13989
- throw new Error(
13990
- `entity ${ent.id} already exists (owner ${ownerId}); use a unique id`
13991
- );
13992
- }
13993
- }
13994
- for (const st of mutation.states ?? []) {
13995
- if (!pending.entityIds.has(st.entityId)) {
13996
- const entity = await getMemoryEntityVNext(db, ownerId, st.entityId);
13997
- if (!entity) {
13998
- throw new Error(
13999
- `memory state ${st.id} references missing entity ${st.entityId} (owner ${ownerId})`
14000
- );
14001
- }
14002
- }
14003
- for (const evidenceId of st.evidenceIds) {
14004
- if (!pending.evidenceIds.has(evidenceId)) {
14005
- const ev = await getMemoryEvidenceVNext(db, ownerId, evidenceId);
14006
- if (!ev) {
14007
- throw new Error(
14008
- `memory state ${st.id} references missing evidence ${evidenceId} (owner ${ownerId})`
14009
- );
14010
- }
14011
- }
14012
- }
14013
- const existing = await getMemoryStateVNext(db, ownerId, st.id);
14014
- if (existing) {
14015
- if (existing.retiredAt) {
14016
- throw new Error(
14017
- `cannot update retired memory state ${st.id} (owner ${ownerId})`
14018
- );
14019
- }
14020
- if (existing.entityId !== st.entityId || existing.facet !== st.facet) {
14021
- throw new Error(
14022
- `state ${st.id} already exists with different entity/facet (${existing.entityId}/${existing.facet} vs ${st.entityId}/${st.facet}); use supersede instead`
14023
- );
14024
- }
14025
- }
14026
- if (!existing) {
14027
- const existingStates = await listMemoryStatesForEntityVNext(db, ownerId, st.entityId);
14028
- for (const es of existingStates) {
14029
- if (es.facet === st.facet && !es.retiredAt) {
14030
- if (!supersededIds.has(es.id)) {
14031
- throw new Error(
14032
- `entity ${st.entityId} facet ${st.facet} already has current state ${es.id}; supersede it or use a different facet`
14033
- );
14034
- }
14035
- }
14036
- }
14037
- }
14038
- }
14039
- for (const sid of mutation.supersededStateIds ?? []) {
14040
- const existing = await getMemoryStateVNext(db, ownerId, sid);
14041
- if (!existing) {
14042
- throw new Error(
14043
- `cannot supersede missing memory state: ${sid} (owner ${ownerId})`
14044
- );
14045
- }
14046
- if (existing.retiredAt) {
14047
- throw new Error(
14048
- `cannot supersede already retired memory state: ${sid} (owner ${ownerId})`
14049
- );
14050
- }
14051
- const replacement = (mutation.states ?? []).find(
14052
- (st) => st.entityId === existing.entityId && st.facet === existing.facet
14053
- );
14054
- if (!replacement) {
14055
- throw new Error(
14056
- `superseded state ${sid} (entity ${existing.entityId} facet ${existing.facet}) has no replacement in this mutation`
14057
- );
14058
- }
14059
- }
14060
- for (const rel of mutation.relations ?? []) {
14061
- for (const [side, ref] of [
14062
- ["from", rel.from],
14063
- ["to", rel.to]
14064
- ]) {
14065
- if (pending.entityIds.has(ref) || pending.stateIds.has(ref) || pending.evidenceIds.has(ref)) {
14066
- continue;
14067
- }
14068
- const resolved = await getMemoryEntityVNext(db, ownerId, ref) ?? await getMemoryStateVNext(db, ownerId, ref) ?? await getMemoryEvidenceVNext(db, ownerId, ref);
14069
- if (!resolved) {
14070
- throw new Error(
14071
- `memory relation ${rel.id} references missing ${side} ${ref} (owner ${ownerId})`
14072
- );
14073
- }
14074
- }
14075
- }
14076
- }
14077
- var applyMemoryInterpreterMutation = async (db, ownerId, mutation) => {
14078
- await validateMutation(db, ownerId, mutation);
14079
- const batch = db.batch();
14080
- for (const ev of mutation.evidence ?? []) {
14081
- _appendEvidenceBatch(batch, ev);
14082
- }
14083
- for (const ent of mutation.entities ?? []) {
14084
- _appendEntityBatch(batch, ent);
14085
- }
14086
- for (const st of mutation.states ?? []) {
14087
- _appendStateBatch(batch, st);
14088
- }
14089
- for (const sid of mutation.supersededStateIds ?? []) {
14090
- const existing = await getMemoryStateVNext(db, ownerId, sid);
14091
- if (!existing) {
14092
- throw new Error(
14093
- `cannot supersede missing memory state: ${sid} (owner ${ownerId})`
14094
- );
14095
- }
14096
- const replacement = (mutation.states ?? []).find(
14097
- (st) => st.entityId === existing.entityId && st.facet === existing.facet
14098
- );
14099
- const retired = {
14100
- ...existing,
14101
- retiredAt: replacement?.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
14102
- };
14103
- _appendRetiredStateBatch(batch, retired);
14104
- }
14105
- for (const rel of mutation.relations ?? []) {
14106
- _appendRelationBatch(batch, rel);
14107
- }
14108
- await batch.write();
14109
- };
14110
-
14111
15117
  // packages/ai/memory/vnext/legacyMigrationApply.ts
14112
15118
  var isSameLegacyMemoryEvidence = (left, right) => left.id === right.id && left.ownerId === right.ownerId && left.text === right.text && left.sourceRef === right.sourceRef && left.confidence === right.confidence && left.createdAt === right.createdAt;
14113
15119
  var applyLegacyMemoryEvidence = async (db, item) => {
@@ -14725,75 +15731,10 @@ var isMemoryVNextLazyPromotionEnabled = (env = typeof process !== "undefined" ?
14725
15731
  // packages/ai/memory/vnext/pureReadGate.ts
14726
15732
  var isMemoryVNextPureReadEnabled = (env = typeof process !== "undefined" ? process.env : {}) => env.NOLO_MEMORY_VNEXT_PURE_READ === "1" || env.NOLO_MEMORY_VNEXT_PURE_READ === "true";
14727
15733
 
14728
- // packages/ai/memory/remember.ts
14729
- var RESIDENT_MAX_CONTENT_CHARS = 240;
14730
-
14731
- // packages/ai/memory/vnext/pureVNextRuntime.ts
14732
- function deriveStateResident(state2, ownerType) {
14733
- if (ownerType !== "user") return false;
14734
- if (state2.text.trim().length > RESIDENT_MAX_CONTENT_CHARS) return false;
14735
- return state2.facet === "preference" || state2.facet === "style";
14736
- }
14737
- var buildSynthesizedStateItem = (state2, entity, ownerType, ownerId) => ({
14738
- id: `vnext-state-${state2.id}`,
14739
- ownerType,
14740
- ownerId,
14741
- visibility: "private",
14742
- subjectType: "user",
14743
- subjectId: ownerId,
14744
- kind: "semantic",
14745
- content: state2.text.trim(),
14746
- createdAt: state2.createdAt,
14747
- lastActivatedAt: state2.createdAt,
14748
- activationCount: 1,
14749
- importance: 0.9,
14750
- confidence: 0.9,
14751
- resident: deriveStateResident(state2, ownerType)
14752
- });
14753
- async function resolvePureVNextRuntime(input) {
14754
- const { db, owners, userInput } = input;
14755
- if (owners.length === 0 || !userInput.trim()) {
14756
- return { selectedItems: [], promptBlock: null, recalledStateCount: 0 };
14757
- }
14758
- const ownerIds = owners.map((o) => `${o.ownerType}:${encodeURIComponent(o.ownerId)}`);
14759
- const catalogs = await Promise.all(
14760
- ownerIds.map((ownerId) => loadMemoryVNextCatalog(db, ownerId))
14761
- );
14762
- const selectedItems = [];
14763
- const seenStateKeys = /* @__PURE__ */ new Set();
14764
- for (let i = 0; i < owners.length; i++) {
14765
- const owner = owners[i];
14766
- const catalog = catalogs[i];
14767
- const currentStates = catalog.states.filter((s) => !s.retiredAt && s.text.trim());
14768
- const hits = recallMemoryVNextLocal({
14769
- query: userInput,
14770
- entities: catalog.entities,
14771
- states: currentStates
14772
- });
14773
- const entityById = new Map(catalog.entities.map((e) => [e.id, e]));
14774
- for (const hit of hits) {
14775
- const stateKey = `${hit.state.ownerId}\0${hit.state.id}`;
14776
- if (seenStateKeys.has(stateKey)) continue;
14777
- seenStateKeys.add(stateKey);
14778
- selectedItems.push(
14779
- buildSynthesizedStateItem(hit.state, entityById.get(hit.state.entityId), owner.ownerType, owner.ownerId)
14780
- );
14781
- }
14782
- }
14783
- const promptBlock = selectedItems.length === 0 ? null : buildMemoryOverlay(selectedItems, {
14784
- maxTokens: input.maxTokens ?? DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET
14785
- });
14786
- return {
14787
- selectedItems,
14788
- promptBlock,
14789
- recalledStateCount: selectedItems.length
14790
- };
14791
- }
14792
-
14793
15734
  // packages/ai/memory/vnext/primaryRead.ts
14794
15735
  var MEMORY_VNEXT_PRIMARY_READ_TIMEOUT_MS = 300;
14795
15736
  var isMemoryVNextPrimaryReadEnabled = (env = typeof process !== "undefined" ? process.env : {}) => env.NOLO_MEMORY_VNEXT_PRIMARY_READ === "1" || env.NOLO_MEMORY_VNEXT_PRIMARY_READ === "true";
14796
- var buildSynthesizedStateItem2 = (state2, entity, ownerType, ownerId) => ({
15737
+ var buildSynthesizedStateItem = (state2, entity, ownerType, ownerId) => ({
14797
15738
  id: `vnext-state-${state2.id}`,
14798
15739
  ownerType,
14799
15740
  ownerId,
@@ -14805,8 +15746,9 @@ var buildSynthesizedStateItem2 = (state2, entity, ownerType, ownerId) => ({
14805
15746
  createdAt: state2.createdAt,
14806
15747
  importance: 0.9,
14807
15748
  confidence: 0.9,
14808
- // Flag resident preferences so they flow into overlay's resident section.
14809
- resident: state2.facet === "preference" || state2.facet === "style",
15749
+ // 与 pureVNextRuntime / queryMemoryHandler 共用同一判定,避免四条合成路径分裂
15750
+ // (2026-11-15:这里原先各自写 facet,漏了 ownerType/长度约束)。
15751
+ resident: deriveStateResident(state2, ownerType),
14810
15752
  lastActivatedAt: state2.createdAt,
14811
15753
  activationCount: 1
14812
15754
  });
@@ -14838,7 +15780,7 @@ var resolveMemoryVNextM4Selection = async (input) => {
14838
15780
  if (recalledStateIds.has(hit.state.id)) continue;
14839
15781
  recalledStateIds.add(hit.state.id);
14840
15782
  recalledStates.push(
14841
- buildSynthesizedStateItem2(hit.state, entityById.get(hit.state.entityId), owner.ownerType, owner.ownerId)
15783
+ buildSynthesizedStateItem(hit.state, entityById.get(hit.state.entityId), owner.ownerType, owner.ownerId)
14842
15784
  );
14843
15785
  }
14844
15786
  }
@@ -14858,6 +15800,10 @@ var resolveMemoryVNextM4Selection = async (input) => {
14858
15800
  const renderItems = [...recalledStates, ...uncoveredLegacy];
14859
15801
  return {
14860
15802
  renderItems,
15803
+ sources: new Map([
15804
+ ...recalledStates.map((item) => [item, "vnext"]),
15805
+ ...uncoveredLegacy.map((item) => [item, "legacy-uncovered"])
15806
+ ]),
14861
15807
  recalledStateCount: recalledStates.length,
14862
15808
  uncoveredLegacyCount: uncoveredLegacy.length,
14863
15809
  coveredSuppressedCount
@@ -14979,245 +15925,282 @@ var selectRuntimeMemoryItems = (items, context, userInput = "") => {
14979
15925
  return selected;
14980
15926
  };
14981
15927
  var resolveMemoryRuntime = async (input) => {
14982
- const owners = chooseMemoryOwners({
14983
- userId: input.userId,
14984
- spaceId: input.spaceId
14985
- });
14986
- if (owners.length === 0) {
14987
- return { selectedItems: [], promptBlock: null };
14988
- }
14989
- if (isMemoryVNextPureReadEnabled()) {
14990
- const pureStartedAt = performance.now();
14991
- let pure;
14992
- let pureError = null;
14993
- try {
14994
- pure = await resolvePureVNextRuntime({
14995
- db: input.db,
14996
- owners,
14997
- userInput: input.userInput,
14998
- maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET
14999
- });
15000
- } catch (error) {
15001
- pureError = error;
15002
- pure = { selectedItems: [], promptBlock: null, recalledStateCount: 0 };
15003
- }
15004
- const pureLatencyMs = Math.round((performance.now() - pureStartedAt) * 10) / 10;
15005
- const emitPureRead = (observation) => {
15928
+ const configuredPure = isMemoryVNextPureReadEnabled();
15929
+ const configuredPrimary = isMemoryVNextPrimaryReadEnabled();
15930
+ let branch = "no_owner";
15931
+ let outcome = "error";
15932
+ let errorKind = "runtime_error";
15933
+ let fallbackKind = "none";
15934
+ let injection = emptyMemoryInjectionObservation();
15935
+ const injectionEmit = (observation) => {
15936
+ injection = observation;
15937
+ };
15938
+ const finish = (result) => {
15939
+ outcome = fallbackKind === "none" ? result.promptBlock ? "result" : "empty" : "fallback";
15940
+ errorKind = fallbackKind;
15941
+ return result;
15942
+ };
15943
+ try {
15944
+ const owners = chooseMemoryOwners({
15945
+ userId: input.userId,
15946
+ spaceId: input.spaceId
15947
+ });
15948
+ if (owners.length === 0) {
15949
+ return finish({ selectedItems: [], promptBlock: null });
15950
+ }
15951
+ if (configuredPure) {
15952
+ branch = "pure";
15953
+ const pureStartedAt = performance.now();
15954
+ let pure;
15955
+ let pureFailed = false;
15006
15956
  try {
15007
- if (input.pureReadEmit) {
15008
- input.pureReadEmit(observation);
15009
- } else if (input.primaryReadEmit) {
15010
- input.primaryReadEmit({
15011
- source: observation.source === "vnext" ? "vnext" : "none",
15012
- legacyHitCount: 0,
15013
- recalledStateCount: observation.vnextItemCount,
15014
- vnextLatencyMs: observation.vnextLatencyMs,
15015
- legacyLatencyMs: 0,
15016
- contextChars: observation.contextChars,
15017
- fallbackReason: observation.fallbackReason,
15018
- error: observation.error
15957
+ pure = await resolvePureVNextRuntime({
15958
+ db: input.db,
15959
+ owners,
15960
+ userInput: input.userInput,
15961
+ maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET,
15962
+ injectionEmit
15963
+ });
15964
+ } catch (error) {
15965
+ pureFailed = true;
15966
+ pure = { selectedItems: [], promptBlock: null, recalledStateCount: 0 };
15967
+ }
15968
+ const pureLatencyMs = Math.round((performance.now() - pureStartedAt) * 10) / 10;
15969
+ const emitPureRead = (observation) => {
15970
+ try {
15971
+ if (input.pureReadEmit) {
15972
+ input.pureReadEmit(observation);
15973
+ } else if (input.primaryReadEmit) {
15974
+ input.primaryReadEmit({
15975
+ source: observation.source === "vnext" ? "vnext" : "none",
15976
+ legacyHitCount: 0,
15977
+ recalledStateCount: observation.vnextItemCount,
15978
+ vnextLatencyMs: observation.vnextLatencyMs,
15979
+ legacyLatencyMs: 0,
15980
+ contextChars: observation.contextChars,
15981
+ fallbackReason: observation.fallbackReason,
15982
+ error: observation.error
15983
+ });
15984
+ } else {
15985
+ console.info("[memory] vnext pure read", {
15986
+ event: "memory_vnext_pure_read",
15987
+ ...observation
15988
+ });
15989
+ }
15990
+ } catch {
15991
+ }
15992
+ };
15993
+ if (pureFailed) {
15994
+ emitPureRead({
15995
+ source: "none",
15996
+ itemCount: 0,
15997
+ vnextItemCount: 0,
15998
+ vnextLatencyMs: pureLatencyMs,
15999
+ contextChars: 0,
16000
+ fallbackReason: "vnext_error",
16001
+ error: "runtime_error"
16002
+ });
16003
+ } else if (pure.selectedItems.length === 0) {
16004
+ emitPureRead({
16005
+ source: "none",
16006
+ itemCount: 0,
16007
+ vnextItemCount: 0,
16008
+ vnextLatencyMs: pureLatencyMs,
16009
+ contextChars: 0,
16010
+ fallbackReason: "no_vnext_context"
16011
+ });
16012
+ } else {
16013
+ emitPureRead({
16014
+ source: "vnext",
16015
+ itemCount: pure.selectedItems.length,
16016
+ vnextItemCount: pure.recalledStateCount,
16017
+ vnextLatencyMs: pureLatencyMs,
16018
+ contextChars: pure.promptBlock?.length ?? 0
16019
+ });
16020
+ }
16021
+ const lazyPromotionEnabled2 = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
16022
+ if (lazyPromotionEnabled2) {
16023
+ void (async () => {
16024
+ const ownerItems = await Promise.all(
16025
+ owners.map(
16026
+ (owner) => loadOwnerItemsFromDb(
16027
+ input.db,
16028
+ owner,
16029
+ input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT
16030
+ )
16031
+ )
16032
+ );
16033
+ const legacyCandidates = ownerItems.flat();
16034
+ if (legacyCandidates.length > 0) {
16035
+ const promotionPick = await pickFirstUncoveredLazyPromotionItem(
16036
+ input.db,
16037
+ legacyCandidates
16038
+ );
16039
+ if (promotionPick) {
16040
+ await runMemoryVNextLazyPromotion({
16041
+ db: input.db,
16042
+ item: promotionPick.item,
16043
+ selectedIndex: promotionPick.selectedIndex,
16044
+ skippedCoveredCount: promotionPick.skippedCoveredCount,
16045
+ skippedNoOpCount: promotionPick.skippedNoOpCount,
16046
+ provider: input.vNextShadowProvider,
16047
+ ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
16048
+ });
16049
+ }
16050
+ }
16051
+ })().catch(() => {
16052
+ });
16053
+ }
16054
+ const result = finish({ selectedItems: pure.selectedItems, promptBlock: pure.promptBlock });
16055
+ if (pureFailed) {
16056
+ outcome = "error";
16057
+ errorKind = "runtime_error";
16058
+ }
16059
+ return result;
16060
+ }
16061
+ branch = "legacy";
16062
+ const policy = resolveAgentMemoryPolicy({ agentKey: input.agentKey });
16063
+ const legacyStartedAt = performance.now();
16064
+ const candidates = await loadMemoryCandidatesFromDb(input.db, {
16065
+ owners,
16066
+ subjects: buildMemorySubjectsForAgent({
16067
+ userId: input.userId,
16068
+ spaceId: input.spaceId,
16069
+ agentKey: input.agentKey,
16070
+ memorySubjectId: input.memorySubjectId,
16071
+ policy
16072
+ }),
16073
+ kinds: ["episodic", "semantic", "procedural"],
16074
+ ownerLimit: input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT,
16075
+ ownerFallback: policy.ownerFallback,
16076
+ corroboratedProceduralReserve: input.corroboratedProceduralReserve ?? CORROBORATED_PROCEDURAL_RESERVE
16077
+ });
16078
+ const rankContext = {
16079
+ currentOwner: input.spaceId ? { ownerType: "space", ownerId: input.spaceId } : input.userId ? { ownerType: "user", ownerId: input.userId } : null,
16080
+ currentSubject: input.spaceId ? { subjectType: "space", subjectId: input.spaceId } : input.userId ? { subjectType: "user", subjectId: input.userId } : null
16081
+ };
16082
+ const residentItems = candidates.filter((item) => item.resident === true).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, RESIDENT_MEMORY_RUNTIME_LIMIT);
16083
+ const retrievalCandidates = candidates.filter((item) => item.resident !== true);
16084
+ const ranked = selectRuntimeMemoryItems(
16085
+ rankMemoryCandidates(retrievalCandidates, input.userInput, rankContext),
16086
+ rankContext,
16087
+ input.userInput
16088
+ );
16089
+ const selected = [...residentItems, ...ranked];
16090
+ const legacyLatencyMs = Math.round((performance.now() - legacyStartedAt) * 10) / 10;
16091
+ const renderOverlay = (items, sources) => buildMemoryOverlay(items, { maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET, sources, injectionEmit });
16092
+ let promptBlock = configuredPrimary ? null : renderOverlay(selected);
16093
+ const primaryRead = configuredPrimary;
16094
+ let allCoveredByVNext = false;
16095
+ if (primaryRead) {
16096
+ branch = "primary";
16097
+ const emitPrimary = (observation) => {
16098
+ try {
16099
+ (input.primaryReadEmit ?? ((o) => console.info("[memory] vnext primary read", { event: "memory_vnext_primary_read", ...o })))(observation);
16100
+ } catch {
16101
+ }
16102
+ };
16103
+ const base = { legacyHitCount: selected.length, legacyLatencyMs };
16104
+ const vnextStartedAt = performance.now();
16105
+ const vnextLatency = () => Math.round((performance.now() - vnextStartedAt) * 10) / 10;
16106
+ if (selected.length === 0) {
16107
+ emitPrimary({ ...base, source: "none" });
16108
+ } else {
16109
+ const timeoutMarker = {};
16110
+ try {
16111
+ let timer;
16112
+ const m4 = await Promise.race([
16113
+ resolveMemoryVNextM4Selection({ db: input.db, owners, query: input.userInput, selected }),
16114
+ new Promise((_, reject) => {
16115
+ timer = setTimeout(
16116
+ () => reject(timeoutMarker),
16117
+ MEMORY_VNEXT_PRIMARY_READ_TIMEOUT_MS
16118
+ );
16119
+ })
16120
+ ]).finally(() => clearTimeout(timer));
16121
+ promptBlock = renderOverlay(m4.renderItems, m4.sources);
16122
+ allCoveredByVNext = m4.uncoveredLegacyCount === 0 && m4.recalledStateCount > 0;
16123
+ const source = m4.recalledStateCount > 0 ? m4.uncoveredLegacyCount === 0 ? "vnext" : "hybrid" : m4.uncoveredLegacyCount > 0 ? "legacy_fallback" : "none";
16124
+ emitPrimary({
16125
+ ...base,
16126
+ source,
16127
+ uncoveredLegacyCount: m4.uncoveredLegacyCount,
16128
+ coveredSuppressedCount: m4.coveredSuppressedCount,
16129
+ recalledStateCount: m4.recalledStateCount,
16130
+ vnextLatencyMs: vnextLatency(),
16131
+ contextChars: promptBlock?.length ?? 0,
16132
+ ...source === "legacy_fallback" ? { fallbackReason: "no_vnext_context" } : {}
15019
16133
  });
15020
- } else {
15021
- console.info("[memory] vnext pure read", {
15022
- event: "memory_vnext_pure_read",
15023
- ...observation
16134
+ } catch (error) {
16135
+ promptBlock = renderOverlay(selected);
16136
+ fallbackKind = error === timeoutMarker ? "timeout" : "runtime_error";
16137
+ emitPrimary({
16138
+ ...base,
16139
+ source: "legacy_fallback",
16140
+ vnextLatencyMs: vnextLatency(),
16141
+ contextChars: promptBlock?.length ?? 0,
16142
+ fallbackReason: "vnext_error",
16143
+ error: error === timeoutMarker ? "TimeoutError" : "UnknownError"
15024
16144
  });
15025
16145
  }
15026
- } catch {
15027
16146
  }
15028
- };
15029
- if (pureError != null) {
15030
- emitPureRead({
15031
- source: "none",
15032
- itemCount: 0,
15033
- vnextItemCount: 0,
15034
- vnextLatencyMs: pureLatencyMs,
15035
- contextChars: 0,
15036
- fallbackReason: "vnext_error",
15037
- error: pureError instanceof Error ? pureError.message : String(pureError)
15038
- });
15039
- } else if (pure.selectedItems.length === 0) {
15040
- emitPureRead({
15041
- source: "none",
15042
- itemCount: 0,
15043
- vnextItemCount: 0,
15044
- vnextLatencyMs: pureLatencyMs,
15045
- contextChars: 0,
15046
- fallbackReason: "no_vnext_context"
15047
- });
15048
- } else {
15049
- emitPureRead({
15050
- source: "vnext",
15051
- itemCount: pure.selectedItems.length,
15052
- vnextItemCount: pure.recalledStateCount,
15053
- vnextLatencyMs: pureLatencyMs,
15054
- contextChars: pure.promptBlock?.length ?? 0
16147
+ }
16148
+ const shadowEnabled = !primaryRead && input.vNextShadowProvider != null && isMemoryVNextShadowReadEnabled();
16149
+ if (shadowEnabled) {
16150
+ void runMemoryVNextShadowRead({
16151
+ ctx: {
16152
+ db: input.db,
16153
+ owners,
16154
+ query: input.userInput,
16155
+ provider: input.vNextShadowProvider
16156
+ },
16157
+ legacyItems: selected,
16158
+ legacyLatencyMs,
16159
+ legacyContextChars: promptBlock?.length ?? 0
16160
+ }).catch(() => {
15055
16161
  });
15056
16162
  }
15057
- const lazyPromotionEnabled2 = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
15058
- if (lazyPromotionEnabled2) {
16163
+ const lazyPromotionEnabled = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
16164
+ if (lazyPromotionEnabled && selected.length > 0 && !allCoveredByVNext) {
15059
16165
  void (async () => {
15060
- const ownerItems = await Promise.all(
15061
- owners.map(
15062
- (owner) => loadOwnerItemsFromDb(
15063
- input.db,
15064
- owner,
15065
- input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT
15066
- )
15067
- )
16166
+ const promotionPick = await pickFirstUncoveredLazyPromotionItem(
16167
+ input.db,
16168
+ selected
15068
16169
  );
15069
- const legacyCandidates = ownerItems.flat();
15070
- if (legacyCandidates.length > 0) {
15071
- const promotionPick = await pickFirstUncoveredLazyPromotionItem(
15072
- input.db,
15073
- legacyCandidates
15074
- );
15075
- if (promotionPick) {
15076
- await runMemoryVNextLazyPromotion({
15077
- db: input.db,
15078
- item: promotionPick.item,
15079
- selectedIndex: promotionPick.selectedIndex,
15080
- skippedCoveredCount: promotionPick.skippedCoveredCount,
15081
- skippedNoOpCount: promotionPick.skippedNoOpCount,
15082
- provider: input.vNextShadowProvider,
15083
- ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
15084
- });
15085
- }
16170
+ if (promotionPick) {
16171
+ await runMemoryVNextLazyPromotion({
16172
+ db: input.db,
16173
+ item: promotionPick.item,
16174
+ selectedIndex: promotionPick.selectedIndex,
16175
+ skippedCoveredCount: promotionPick.skippedCoveredCount,
16176
+ skippedNoOpCount: promotionPick.skippedNoOpCount,
16177
+ provider: input.vNextShadowProvider,
16178
+ ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
16179
+ });
15086
16180
  }
15087
16181
  })().catch(() => {
15088
16182
  });
15089
16183
  }
15090
- return {
15091
- selectedItems: pure.selectedItems,
15092
- promptBlock: pure.promptBlock
15093
- };
15094
- }
15095
- const policy = resolveAgentMemoryPolicy({ agentKey: input.agentKey });
15096
- const legacyStartedAt = performance.now();
15097
- const candidates = await loadMemoryCandidatesFromDb(input.db, {
15098
- owners,
15099
- subjects: buildMemorySubjectsForAgent({
15100
- userId: input.userId,
15101
- spaceId: input.spaceId,
15102
- agentKey: input.agentKey,
15103
- memorySubjectId: input.memorySubjectId,
15104
- policy
15105
- }),
15106
- kinds: ["episodic", "semantic", "procedural"],
15107
- ownerLimit: input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT,
15108
- ownerFallback: policy.ownerFallback,
15109
- corroboratedProceduralReserve: input.corroboratedProceduralReserve ?? CORROBORATED_PROCEDURAL_RESERVE
15110
- });
15111
- const rankContext = {
15112
- currentOwner: input.spaceId ? { ownerType: "space", ownerId: input.spaceId } : input.userId ? { ownerType: "user", ownerId: input.userId } : null,
15113
- currentSubject: input.spaceId ? { subjectType: "space", subjectId: input.spaceId } : input.userId ? { subjectType: "user", subjectId: input.userId } : null
15114
- };
15115
- const residentItems = candidates.filter((item) => item.resident === true).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, RESIDENT_MEMORY_RUNTIME_LIMIT);
15116
- const retrievalCandidates = candidates.filter((item) => item.resident !== true);
15117
- const ranked = selectRuntimeMemoryItems(
15118
- rankMemoryCandidates(retrievalCandidates, input.userInput, rankContext),
15119
- rankContext,
15120
- input.userInput
15121
- );
15122
- const selected = [...residentItems, ...ranked];
15123
- const legacyLatencyMs = Math.round((performance.now() - legacyStartedAt) * 10) / 10;
15124
- const renderOverlay = (items) => items.length === 0 ? null : buildMemoryOverlay(items, { maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET });
15125
- let promptBlock = renderOverlay(selected);
15126
- const primaryRead = isMemoryVNextPrimaryReadEnabled();
15127
- let allCoveredByVNext = false;
15128
- if (primaryRead) {
15129
- const emitPrimary = (observation) => {
15130
- try {
15131
- (input.primaryReadEmit ?? ((o) => console.info("[memory] vnext primary read", { event: "memory_vnext_primary_read", ...o })))(observation);
15132
- } catch {
15133
- }
15134
- };
15135
- const base = { legacyHitCount: selected.length, legacyLatencyMs };
15136
- const vnextStartedAt = performance.now();
15137
- const vnextLatency = () => Math.round((performance.now() - vnextStartedAt) * 10) / 10;
15138
16184
  if (selected.length === 0) {
15139
- emitPrimary({ ...base, source: "none" });
15140
- } else {
15141
- try {
15142
- let timer;
15143
- const m4 = await Promise.race([
15144
- resolveMemoryVNextM4Selection({ db: input.db, owners, query: input.userInput, selected }),
15145
- new Promise((_, reject) => {
15146
- timer = setTimeout(
15147
- () => reject(Object.assign(new Error("timeout"), { name: "TimeoutError" })),
15148
- MEMORY_VNEXT_PRIMARY_READ_TIMEOUT_MS
15149
- );
15150
- })
15151
- ]).finally(() => clearTimeout(timer));
15152
- promptBlock = renderOverlay(m4.renderItems);
15153
- allCoveredByVNext = m4.uncoveredLegacyCount === 0 && m4.recalledStateCount > 0;
15154
- const source = m4.recalledStateCount > 0 ? m4.uncoveredLegacyCount === 0 ? "vnext" : "hybrid" : m4.uncoveredLegacyCount > 0 ? "legacy_fallback" : "none";
15155
- emitPrimary({
15156
- ...base,
15157
- source,
15158
- uncoveredLegacyCount: m4.uncoveredLegacyCount,
15159
- coveredSuppressedCount: m4.coveredSuppressedCount,
15160
- recalledStateCount: m4.recalledStateCount,
15161
- vnextLatencyMs: vnextLatency(),
15162
- contextChars: promptBlock?.length ?? 0,
15163
- ...source === "legacy_fallback" ? { fallbackReason: "no_vnext_context" } : {}
15164
- });
15165
- } catch (error) {
15166
- emitPrimary({
15167
- ...base,
15168
- source: "legacy_fallback",
15169
- vnextLatencyMs: vnextLatency(),
15170
- contextChars: promptBlock?.length ?? 0,
15171
- fallbackReason: "vnext_error",
15172
- error: error instanceof Error ? error.name : "UnknownError"
15173
- });
15174
- }
16185
+ return finish({ selectedItems: [], promptBlock: null });
16186
+ }
16187
+ await touchMemoryItemsInDb(input.db, selected);
16188
+ return finish({ selectedItems: selected, promptBlock });
16189
+ } finally {
16190
+ const observation = {
16191
+ ...injection,
16192
+ event: "memory_runtime_result",
16193
+ configuredPure,
16194
+ configuredPrimary,
16195
+ branch,
16196
+ outcome,
16197
+ errorKind
16198
+ };
16199
+ try {
16200
+ (input.runtimeResultEmit ?? ((event) => console.info("[memory] runtime result", event)))(observation);
16201
+ } catch {
15175
16202
  }
15176
16203
  }
15177
- const shadowEnabled = !primaryRead && input.vNextShadowProvider != null && isMemoryVNextShadowReadEnabled();
15178
- if (shadowEnabled) {
15179
- void runMemoryVNextShadowRead({
15180
- ctx: {
15181
- db: input.db,
15182
- owners,
15183
- query: input.userInput,
15184
- provider: input.vNextShadowProvider
15185
- },
15186
- legacyItems: selected,
15187
- legacyLatencyMs,
15188
- legacyContextChars: promptBlock?.length ?? 0
15189
- }).catch(() => {
15190
- });
15191
- }
15192
- const lazyPromotionEnabled = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
15193
- if (lazyPromotionEnabled && selected.length > 0 && !allCoveredByVNext) {
15194
- void (async () => {
15195
- const promotionPick = await pickFirstUncoveredLazyPromotionItem(
15196
- input.db,
15197
- selected
15198
- );
15199
- if (promotionPick) {
15200
- await runMemoryVNextLazyPromotion({
15201
- db: input.db,
15202
- item: promotionPick.item,
15203
- selectedIndex: promotionPick.selectedIndex,
15204
- skippedCoveredCount: promotionPick.skippedCoveredCount,
15205
- skippedNoOpCount: promotionPick.skippedNoOpCount,
15206
- provider: input.vNextShadowProvider,
15207
- ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
15208
- });
15209
- }
15210
- })().catch(() => {
15211
- });
15212
- }
15213
- if (selected.length === 0) {
15214
- return { selectedItems: [], promptBlock: null };
15215
- }
15216
- await touchMemoryItemsInDb(input.db, selected);
15217
- return {
15218
- selectedItems: selected,
15219
- promptBlock
15220
- };
15221
16204
  };
15222
16205
 
15223
16206
  // packages/cli/memoryRecall.ts
@@ -15406,6 +16389,35 @@ async function resolveAgentBoundMachineIdFromRecord(args) {
15406
16389
  return resolveBoundMachineId(record) || void 0;
15407
16390
  }
15408
16391
  async function runAgentRunCommand(args, deps) {
16392
+ const env = deps.env ?? process.env;
16393
+ const runId = env.NOLO_AGENT_RUN_ID;
16394
+ const controlDeps = { env, homedir: deps.homedir, fs: deps.fs, now: deps.now };
16395
+ const failStartup = async (error) => {
16396
+ if (!runId || readRunRecord(runId, controlDeps)?.status !== "running") return;
16397
+ const result = await settleRunTerminalAuthoritatively(runId, {
16398
+ status: "failed",
16399
+ exitCode: 1,
16400
+ failureReason: error instanceof RuntimeProtocolMismatchError ? "runtime_protocol_mismatch" : error instanceof RuntimeVersionMismatchError ? "runtime_version_mismatch" : "startup_failed",
16401
+ note: error ? toErrorMessage(error) : "Child initialization returned without terminal result"
16402
+ }, controlDeps, (id, update, d) => transitionRunToTerminal(id, update, d));
16403
+ if (result.kind === "contended") throw new Error(`Startup settlement lock busy: ${runId}`);
16404
+ };
16405
+ try {
16406
+ if (runId) {
16407
+ if (!readRunRecord(runId, controlDeps)) throw new Error("[local-writer-resource] missing child binding");
16408
+ await recordRunStartup(runId, "initializing", controlDeps);
16409
+ validateAgentRunProtocol(env.NOLO_AGENT_RUN_PROTOCOL);
16410
+ await recordRunStartup(runId, "protocol_validated", controlDeps);
16411
+ }
16412
+ const code = await runAgentRunCommandImpl(args, deps);
16413
+ if (runId) await failStartup();
16414
+ return code;
16415
+ } catch (error) {
16416
+ await failStartup(error);
16417
+ throw error;
16418
+ }
16419
+ }
16420
+ async function runAgentRunCommandImpl(args, deps) {
15409
16421
  const env = deps.env ?? process.env;
15410
16422
  const output = deps.output ?? {
15411
16423
  write: (chunk) => process.stdout.write(chunk),
@@ -15428,10 +16440,17 @@ async function runAgentRunCommand(args, deps) {
15428
16440
  return 1;
15429
16441
  }
15430
16442
  const rawRunner = deps.runner ?? runAgentTurn;
16443
+ let modelPhaseRecorded = false;
15431
16444
  const watchdogAbort = new AbortController();
15432
16445
  let activeRunner;
15433
16446
  const runner = (options) => {
15434
- activeRunner = Promise.resolve().then(() => rawRunner({ ...options, abortSignal: watchdogAbort.signal })).then((result) => {
16447
+ activeRunner = Promise.resolve().then(async () => {
16448
+ if (env.NOLO_AGENT_RUN_ID && !modelPhaseRecorded) {
16449
+ await recordRunStartup(env.NOLO_AGENT_RUN_ID, "model", { env, homedir: deps.homedir, fs: deps.fs, now: deps.now });
16450
+ modelPhaseRecorded = true;
16451
+ }
16452
+ return rawRunner({ ...options, abortSignal: watchdogAbort.signal });
16453
+ }).then((result) => {
15435
16454
  watchdogAbort.signal.throwIfAborted();
15436
16455
  return result;
15437
16456
  });
@@ -15444,8 +16463,8 @@ async function runAgentRunCommand(args, deps) {
15444
16463
  try {
15445
16464
  return await Promise.race([
15446
16465
  activeRunner.then(() => true, () => true),
15447
- new Promise((resolve6) => {
15448
- timer = setTimeout(() => resolve6(false), 100);
16466
+ new Promise((resolve5) => {
16467
+ timer = setTimeout(() => resolve5(false), 100);
15449
16468
  })
15450
16469
  ]);
15451
16470
  } finally {
@@ -15864,6 +16883,7 @@ async function runAgentRunCommand(args, deps) {
15864
16883
  );
15865
16884
  const shellApprovalChild = process.connected && typeof process.send === "function" ? createShellApprovalChild(process) : void 0;
15866
16885
  try {
16886
+ const imageUrls = await normalizeCliRunImages(parsed.imageUrls, normalizeCliImageInput);
15867
16887
  const buildRunOptions = (targetAgentKey, turnMessage = effectiveMessage) => ({
15868
16888
  ...shellApprovalChild ? { execShellApproval: targetAgentKey === agentKey ? shellApprovalChild.authority : {
15869
16889
  request: async () => {
@@ -15883,7 +16903,7 @@ async function runAgentRunCommand(args, deps) {
15883
16903
  responseViewport: "unknown",
15884
16904
  serverUrl: resolveServerUrl(env),
15885
16905
  message: formatTurnMessage(turnMessage),
15886
- imageUrls: parsed.imageUrls.map(normalizeCliImageInput),
16906
+ imageUrls,
15887
16907
  scriptDir: deps.scriptDir,
15888
16908
  env: runEnv,
15889
16909
  output,
@@ -16113,7 +17133,7 @@ async function runAgentRunCommand(args, deps) {
16113
17133
  acceptance.checks.observations = dodResults.map((check, index) => ({
16114
17134
  // Command lines/output can contain credentials. Persist only a digest
16115
17135
  // here; the pre-existing registry is the execution evidence reference.
16116
- commandFingerprint: `sha256:${createHash("sha256").update(check.command).digest("hex")}`,
17136
+ commandFingerprint: `sha256:${createHash3("sha256").update(check.command).digest("hex")}`,
16117
17137
  cwd: childRecordForDoD?.cwd || process.cwd(),
16118
17138
  exitCode: check.exitCode,
16119
17139
  evidence: `${childRunId}.json#/dodResults/${index}`,
@@ -16183,6 +17203,16 @@ async function runAgentRunCommand(args, deps) {
16183
17203
  }
16184
17204
 
16185
17205
  export {
17206
+ resolveAgentModelIdentity,
17207
+ resolveAgentContextWindow2 as resolveAgentContextWindow,
17208
+ platformCreditsFromUsage,
17209
+ formatCreditsChip,
17210
+ resolveAuthorityTurnCount,
17211
+ computeBaselineContextTokens,
17212
+ preserveContextUsageWithoutReceipt,
17213
+ resolveContextUsage,
17214
+ renderTokenStatus,
17215
+ redactSecrets,
16186
17216
  resolveCliColorEnabled,
16187
17217
  dimCliText,
16188
17218
  THEME_PALETTES,
@@ -16208,18 +17238,10 @@ export {
16208
17238
  formatAssistantDisplay,
16209
17239
  resolveHistoryLayoutGeometry,
16210
17240
  resolveHistoryViewportHeight,
17241
+ safeAskText,
17242
+ safeApprovalMultilineText,
16211
17243
  TUI_TREE_MARKER,
16212
17244
  TUI_TREE_TOOLS,
16213
- resolveAgentModelIdentity,
16214
- resolveAgentContextWindow2 as resolveAgentContextWindow,
16215
- platformCreditsFromUsage,
16216
- formatCreditsChip,
16217
- formatTokenCount,
16218
- resolveAuthorityTurnCount,
16219
- computeBaselineContextTokens,
16220
- preserveContextUsageWithoutReceipt,
16221
- resolveContextUsage,
16222
- renderTokenStatus,
16223
17245
  createIdleHeapReleaser,
16224
17246
  COLLAPSED_PASTE_PLACEHOLDER_RE,
16225
17247
  shouldCollapsePaste,
@@ -16235,6 +17257,7 @@ export {
16235
17257
  emitTerminalProgramStatus,
16236
17258
  contextRefusalDiagnostics,
16237
17259
  describeContextRefusal,
17260
+ inspectLocalRunWorkspace,
16238
17261
  isBalanceExhaustedError,
16239
17262
  OWNER_OAUTH_UNAVAILABLE_HINT,
16240
17263
  isOwnerOAuthUnavailableError,