nolo-cli 0.219.0 → 0.220.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-BNEMFCAO.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-7QTQNFCO.js} +114 -115
  6. package/{agentEmailCommands-6IE773VW.js → agentEmailCommands-I7SHOSD6.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-UMDKILU3.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-YTAMTHOY.js} +102 -103
  14. package/{agentRunCommand-KGOT2AFB.js → agentRunCommand-DBM6YNO6.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-DPG7Q7IA.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-QWYFFHCJ.js → chunk-3NNXR7EH.js} +10 -10
  33. package/{chunk-JWXITTQB.js → chunk-3P54D2E4.js} +1 -1
  34. package/{chunk-EGXPAWLG.js → chunk-3U44JB3O.js} +1 -1
  35. package/{chunk-KAVGK4ES.js → chunk-44J7Z5AQ.js} +18 -18
  36. package/{chunk-YL3EFYL3.js → chunk-4D4QD7FT.js} +3 -1
  37. package/{chunk-EUCFKKDM.js → chunk-4I2MXV5Q.js} +38 -10
  38. package/{chunk-C4WTX5TU.js → chunk-4ZGPHFLE.js} +2 -2
  39. package/{chunk-FVZW66K4.js → chunk-53MFERZ3.js} +177 -94
  40. package/{chunk-MOMR7NMG.js → chunk-547ENH5T.js} +1 -1
  41. package/{chunk-N7HVLYOY.js → chunk-5WKDR7HS.js} +3 -3
  42. package/chunk-5ZUOVCKT.js +32 -0
  43. package/{chunk-TRWT3EE3.js → chunk-62HXNQVV.js} +1 -1
  44. package/{chunk-KOXKKHFE.js → chunk-6QHKRARD.js} +2 -2
  45. package/{chunk-N3J4VDGV.js → chunk-6RDBLXVQ.js} +15 -15
  46. package/{chunk-YGMBIXCF.js → chunk-6XRPBZRS.js} +4 -2
  47. package/{chunk-JC5XLWZK.js → chunk-7JGMNKKG.js} +19 -15
  48. package/{chunk-FRSBYNWI.js → chunk-AGYPUBFW.js} +31 -205
  49. package/{chunk-UYOICCYG.js → chunk-ALAES342.js} +59 -88
  50. package/{chunk-VREDDN25.js → chunk-ATEKLSLR.js} +1 -1
  51. package/{chunk-6NKA6RKF.js → chunk-AUAJTAFM.js} +8 -8
  52. package/{chunk-7UH3DGV6.js → chunk-AWIL6EHN.js} +7 -7
  53. package/chunk-BIDSIRTS.js +307 -0
  54. package/chunk-BIWI5M4E.js +62 -0
  55. package/{chunk-L5I543VB.js → chunk-BNMPUQW6.js} +1 -1
  56. package/{chunk-BGGHA5DV.js → chunk-BP5ZJ6B4.js} +1 -1
  57. package/{chunk-Q6HOUF4O.js → chunk-CBUZ6DKA.js} +3 -3
  58. package/{chunk-LE6LGAJE.js → chunk-CD3RU7XL.js} +17 -2
  59. package/{chunk-AVHRSJUH.js → chunk-CMMI3DAT.js} +13 -13
  60. package/{chunk-H7R3365N.js → chunk-CYWNWA77.js} +5 -5
  61. package/{chunk-6D7NVU66.js → chunk-D6YNCNM6.js} +17 -14
  62. package/{chunk-6RQFZCKH.js → chunk-DBUR22G5.js} +6 -6
  63. package/{chunk-PVZY6P3S.js → chunk-DEA37IUY.js} +2 -2
  64. package/{chunk-QLFCTYRH.js → chunk-DGYCDA6W.js} +3 -3
  65. package/{chunk-SRL56PI2.js → chunk-DUUDXSLX.js} +21 -7
  66. package/{chunk-KFHREHUQ.js → chunk-DXWGFL2Z.js} +89 -1
  67. package/{chunk-PFJNLBRU.js → chunk-EEOOBRA7.js} +6 -6
  68. package/{chunk-KN3HEZIQ.js → chunk-EVGU5P4U.js} +1 -1
  69. package/{chunk-CXDPIPZ4.js → chunk-F6Z6ZCUV.js} +2 -2
  70. package/{chunk-EOWLBDY6.js → chunk-FJSNBZXR.js} +1 -1
  71. package/{chunk-GNHMRBYZ.js → chunk-G7IUT2V3.js} +4 -3
  72. package/{chunk-4NMHE7CX.js → chunk-GPOV42YM.js} +14 -14
  73. package/{chunk-SASHAZ67.js → chunk-GUXZK7SE.js} +2 -2
  74. package/{chunk-65XXHYZ5.js → chunk-GV6PRJBU.js} +3 -3
  75. package/{chunk-G2EJ7NL4.js → chunk-HBRDSQ3M.js} +2 -2
  76. package/{chunk-OOF7XDZF.js → chunk-HHFGE2WF.js} +6 -6
  77. package/{chunk-DJSTBAOU.js → chunk-HSSBDZLD.js} +4 -4
  78. package/{chunk-GIABSSWQ.js → chunk-HYLRQDEE.js} +4 -4
  79. package/{chunk-UJKTI5PG.js → chunk-ILHQ2AXT.js} +0 -1
  80. package/{chunk-S7SB7L2I.js → chunk-JJMR2EA3.js} +19 -19
  81. package/{chunk-3ESU44FG.js → chunk-JLAMNSBC.js} +3 -3
  82. package/{chunk-TVFRV3UQ.js → chunk-JUSHVFNF.js} +238 -185
  83. package/{chunk-MKQ2UTTX.js → chunk-KHVFJSVE.js} +22 -19
  84. package/{chunk-7WPAI5JJ.js → chunk-KRI6N5QZ.js} +14 -14
  85. package/{chunk-HCJFGH6Y.js → chunk-L32W3PRP.js} +46 -16
  86. package/{chunk-3N4ASIP6.js → chunk-LMRRCEDE.js} +11 -11
  87. package/{chunk-2KTUDBG7.js → chunk-M4SFKP5L.js} +1 -1
  88. package/{chunk-VHPAA6MT.js → chunk-MSMHU36U.js} +6 -6
  89. package/{chunk-F3TQURKK.js → chunk-MXKWTPUM.js} +19 -19
  90. package/{chunk-XFJ4ZPFC.js → chunk-MXRUXMZ3.js} +25 -25
  91. package/{chunk-OXKUPBAQ.js → chunk-NHY322ZU.js} +151 -10
  92. package/{chunk-UMRI2IRY.js → chunk-OBIC6EG7.js} +6 -6
  93. package/{chunk-VALBGPM6.js → chunk-OBSEKCVK.js} +17 -20
  94. package/{chunk-SYQR7FQS.js → chunk-OG6MQOQG.js} +96 -28
  95. package/{chunk-AMEOV5VZ.js → chunk-OOJNQK6V.js} +33 -33
  96. package/{chunk-K5FNYHZC.js → chunk-OWKNSIXL.js} +149 -54
  97. package/{chunk-CKT6QUE2.js → chunk-Q3IVPFVO.js} +1 -1
  98. package/{chunk-AFHOCBSP.js → chunk-QBZCGP34.js} +1 -1
  99. package/{chunk-2ZKFCIJJ.js → chunk-QCB42576.js} +1 -1
  100. package/{chunk-HOCHUZQ7.js → chunk-QJTZ76CP.js} +24 -6
  101. package/{chunk-XWGDCWXY.js → chunk-QRGDJA4B.js} +9 -9
  102. package/{chunk-4A2JIXR2.js → chunk-QYB23WUH.js} +1 -1
  103. package/{chunk-652XYZGP.js → chunk-R44TU3MZ.js} +8 -3
  104. package/{chunk-2VUZSVAS.js → chunk-R6Z5S5GA.js} +7 -7
  105. package/{chunk-MK2Q7ZJD.js → chunk-R7XWZDOH.js} +58 -24
  106. package/{chunk-GGKNJ42M.js → chunk-RBPUNSG5.js} +2 -2
  107. package/{chunk-GVGOEMNV.js → chunk-RG2DGNL6.js} +3 -3
  108. package/{chunk-2OLYKYNY.js → chunk-RTHFJZ6M.js} +8 -8
  109. package/{chunk-C4VAR65S.js → chunk-RYOLWYBK.js} +120 -116
  110. package/{chunk-T3O6BLYU.js → chunk-S5NA3C52.js} +147 -115
  111. package/{chunk-D726I5AZ.js → chunk-S6FDXXZV.js} +2 -2
  112. package/{chunk-JVRQ6YVK.js → chunk-S6K5F3KP.js} +1 -1
  113. package/{chunk-IWQAOW2X.js → chunk-SRCCSTIM.js} +8 -8
  114. package/{chunk-KO63FPG3.js → chunk-SZVMASJ2.js} +750 -2523
  115. package/{chunk-Q7WP5RPC.js → chunk-TGNIKIHR.js} +5 -5
  116. package/{chunk-AK5O76CC.js → chunk-TI2EPRHE.js} +2 -2
  117. package/{chunk-5R63B62U.js → chunk-TSPMLCWI.js} +7 -7
  118. package/{chunk-QVBXJNZ2.js → chunk-TUSTONB3.js} +1 -1
  119. package/{chunk-KEN3N2TN.js → chunk-VMJVAJ6W.js} +13 -10
  120. package/{chunk-SOF4OWDM.js → chunk-VS276URX.js} +0 -2
  121. package/{chunk-FIYSMXHY.js → chunk-WWTSEBDF.js} +1 -1
  122. package/{chunk-E2BESSAW.js → chunk-X4O7FJF5.js} +2 -0
  123. package/{chunk-J6T25AJ6.js → chunk-XSW4EXQV.js} +82 -18
  124. package/{chunk-O2CYENYJ.js → chunk-XTETTSKN.js} +2107 -1092
  125. package/{chunk-DVQH4BTR.js → chunk-YKY4OVOX.js} +14 -10
  126. package/{chunk-5RKUPJYL.js → chunk-ZH3KXFHS.js} +11 -3
  127. package/chunk-ZOHO6MOF.js +376 -0
  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-T3UBK6OA.js} +93 -93
  133. package/{contentThunks-G3TRPEAU.js → contentThunks-YEPZAHXU.js} +36 -35
  134. package/{cooldownCommands-X7P5M2V5.js → cooldownCommands-YB5H5BBK.js} +4 -4
  135. package/{createAgentAutomationAction-KHA4MXUJ.js → createAgentAutomationAction-TBIIO5WT.js} +36 -35
  136. package/{createDialogAction-KWSBNAPJ.js → createDialogAction-KBKMYFTQ.js} +37 -36
  137. package/{createPageAction-HXKJ7OFG.js → createPageAction-3FGAPLJO.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-DP2WTMNO.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-NDY3K3PK.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-IUGVVJ43.js} +65 -65
  153. package/{hostCredentialCreate-WS6D3EHT.js → hostCredentialCreate-X2ZFRXDR.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-KAG3T4LF.js} +109 -110
  159. package/{machineCommands-WFWV25IR.js → machineCommands-6NIQJE2A.js} +111 -112
  160. package/{machineWsRunDispatch-ZGXC3F2R.js → machineWsRunDispatch-RA5NOSGG.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-OIUP63MV.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-ZGC4KSXG.js} +3946 -4393
  172. package/{removeDialogAgentAction-U3F2MNAY.js → removeDialogAgentAction-F5QE2O2B.js} +16 -16
  173. package/{runAgentClientLoop-BVIEQUB3.js → runAgentClientLoop-NKUW2DSJ.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-FJTUUXHJ.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-ZXHIAOSP.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-JMKLKL4P.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-SZVMASJ2.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-S5NA3C52.js";
115
86
  import {
116
87
  parseUiCard,
117
88
  uiCardFallback
118
- } from "./chunk-3N4ASIP6.js";
89
+ } from "./chunk-LMRRCEDE.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-AWIL6EHN.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-53MFERZ3.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,27 +9062,976 @@ 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/cli/tui/redactSecrets.ts
9066
+ var REDACTED = "\u27E8redacted\u27E9";
9067
+ var NORMAL_GIST_SECRET_PATTERNS = [
9068
+ /\bbearer\s+[A-Za-z0-9._~+/=-]{8,}/i,
9069
+ /\bsk-(?:ant-)?(?:api)?[0-9a-zA-Z-]{10,}/,
9070
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{10,}/,
9071
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}/
9072
+ ];
9073
+ function withholdIfSecretLike(gist) {
9074
+ if (!gist) return "";
9075
+ if (findPotentialSecrets(gist).length > 0) return "";
9076
+ if (NORMAL_GIST_SECRET_PATTERNS.some((pattern) => pattern.test(gist))) return "";
9077
+ return gist;
9078
+ }
9079
+ function redactSecrets(text) {
9080
+ return text.replace(/\b(?:sk|pk)-[A-Za-z0-9_-]{10,}/g, REDACTED).replace(/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{12,}/gi, `$1${REDACTED}`).replace(
9081
+ /(^|\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,
9082
+ `$1$2${REDACTED}`
9083
+ ).replace(
9084
+ /\b((?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|token|secret|password|passwd|credential)s?\s*[=:]\s*["']?)[^\s"',;]{8,}/gi,
9085
+ `$1${REDACTED}`
9086
+ );
9087
+ }
9088
+
9089
+ // packages/core/shellCommandGist.ts
9090
+ function shellWords(text, validationOnly = false) {
9091
+ const words2 = [];
9092
+ let word = "", started = false;
9093
+ let quote;
9094
+ for (let i = 0; i < text.length; i++) {
9095
+ const ch = text[i];
9096
+ if (ch === "\\" && quote !== "'") {
9097
+ const next = text[++i];
9098
+ if (next === void 0) return null;
9099
+ word += next;
9100
+ started = true;
9101
+ continue;
9102
+ }
9103
+ if (ch === "$" && quote !== "'" || ch === "`" && quote !== "'") return null;
9104
+ if (quote) {
9105
+ if (ch === quote) quote = void 0;
9106
+ else word += ch;
9107
+ continue;
9108
+ }
9109
+ if (ch === "'" || ch === '"') {
9110
+ quote = ch;
9111
+ started = true;
9112
+ continue;
9113
+ }
9114
+ if (validationOnly && (ch === "|" || ch === "~")) {
9115
+ word += ch;
9116
+ started = true;
9117
+ continue;
9118
+ }
9119
+ if (/[<> &|;(){}*?\[\]#~]/.test(ch) && !/\s/.test(ch)) return null;
9120
+ if (/\s/.test(ch)) {
9121
+ if (started) words2.push(word);
9122
+ word = "";
9123
+ started = false;
9124
+ } else {
9125
+ word += ch;
9126
+ started = true;
8776
9127
  }
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
9128
  }
8783
- diffWithOptionsObj(oldTokens, newTokens, options, callback) {
8784
- var _a;
8785
- const done = (value) => {
8786
- value = this.postProcess(value, options);
8787
- if (callback) {
9129
+ if (quote) return null;
9130
+ if (started) words2.push(word);
9131
+ return words2;
9132
+ }
9133
+ function isSafeGitTarget(token) {
9134
+ if (!token || token.startsWith("-")) return false;
9135
+ if (/:\/\/|@/.test(token)) return false;
9136
+ return true;
9137
+ }
9138
+ function clipShortText(text, maxLen = 24) {
9139
+ const oneLine = text.replace(/\s+/g, " ").trim();
9140
+ if (!oneLine) return "";
9141
+ return oneLine.length <= maxLen ? oneLine : `${oneLine.slice(0, maxLen - 1)}\u2026`;
9142
+ }
9143
+ function parseGit(rest) {
9144
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9145
+ if (!tokens2) return null;
9146
+ let i = 0, context;
9147
+ while (tokens2[i]?.startsWith("-")) {
9148
+ const option = tokens2[i++];
9149
+ if (["-C", "-c", "--git-dir", "--work-tree"].includes(option)) {
9150
+ const value = tokens2[i++];
9151
+ if (!value || value.startsWith("-")) return null;
9152
+ if (option === "-C") context = value;
9153
+ } else if (!/^(--git-dir|--work-tree)=.+/.test(option) && !["--no-pager", "--no-optional-locks", "--literal-pathspecs"].includes(option)) return null;
9154
+ }
9155
+ const sub = tokens2[i++];
9156
+ const args = tokens2.slice(i);
9157
+ const result = (action, object, readOnly) => ({ action, object, context, readOnly });
9158
+ if (sub === "worktree") {
9159
+ const operation = args.shift();
9160
+ const operands = [];
9161
+ let end = false;
9162
+ for (let j = 0; j < args.length; j++) {
9163
+ const token = args[j];
9164
+ if (!end && token === "--") {
9165
+ end = true;
9166
+ continue;
9167
+ }
9168
+ if (!end && token.startsWith("-")) {
9169
+ if (operation === "add" && ["-b", "-B", "--reason"].includes(token)) {
9170
+ if (!args[++j] || args[j].startsWith("-")) return null;
9171
+ } 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;
9172
+ } else operands.push(token);
9173
+ }
9174
+ if (operation === "list" && !operands.length) return result("\u5217\u51FA\u5DE5\u4F5C\u533A", void 0, true);
9175
+ if (operation === "add" && operands.length >= 1 && operands.length <= 2) return result("\u521B\u5EFA\u5DE5\u4F5C\u533A", operands[0], false);
9176
+ if (operation === "remove" && operands.length === 1) return result("\u79FB\u9664\u5DE5\u4F5C\u533A", operands[0], false);
9177
+ return null;
9178
+ }
9179
+ if (sub === "branch") {
9180
+ let mode = "create", end = false;
9181
+ const operands = [];
9182
+ for (const token of args) {
9183
+ if (!end && token === "--") {
9184
+ end = true;
9185
+ continue;
9186
+ }
9187
+ if (!end && token.startsWith("-")) {
9188
+ if (["-d", "-D", "--delete"].includes(token) && mode === "create") mode = "delete";
9189
+ else if (["--list", "-a", "--all", "-r", "--remotes", "-v", "-vv", "--show-current"].includes(token) && mode === "create") mode = "list";
9190
+ else return null;
9191
+ } else operands.push(token);
9192
+ }
9193
+ if (mode === "delete" && operands.length === 1) return result("\u5220\u9664\u5206\u652F", operands[0], false);
9194
+ if (mode === "list" || !args.length) return result("\u5217\u51FA\u5206\u652F", void 0, true);
9195
+ if (mode === "create" && operands.length >= 1 && operands.length <= 2) return result("\u521B\u5EFA\u5206\u652F", operands[0], false);
9196
+ return null;
9197
+ }
9198
+ if (sub === "checkout" && args.some((t2) => t2 === "." || t2 === "--" || t2.includes("/"))) return null;
9199
+ const nonFlagArgs = (list) => {
9200
+ const out = [];
9201
+ for (let j = 0; j < list.length; j++) {
9202
+ const tok = list[j];
9203
+ if (tok === "--") {
9204
+ out.push(...list.slice(j + 1));
9205
+ break;
9206
+ }
9207
+ if (tok.startsWith("-")) {
9208
+ if (["-m", "-F", "-b", "-B", "-n", "--max-count", "--format", "--pretty", "--since", "--until", "--author", "-U"].includes(tok)) j++;
9209
+ continue;
9210
+ }
9211
+ out.push(tok);
9212
+ }
9213
+ return out;
9214
+ };
9215
+ switch (sub) {
9216
+ case "status":
9217
+ return result("\u67E5\u72B6\u6001", void 0, true);
9218
+ case "log":
9219
+ return result("\u67E5\u5386\u53F2", void 0, true);
9220
+ case "rev-list":
9221
+ return result("\u7EDF\u8BA1\u63D0\u4EA4", void 0, true);
9222
+ case "merge-base":
9223
+ return result("\u67E5\u5171\u540C\u7956\u5148", void 0, true);
9224
+ case "rev-parse":
9225
+ return result("\u67E5\u4ED3\u5E93\u4FE1\u606F", void 0, true);
9226
+ case "show": {
9227
+ const target = nonFlagArgs(args)[0];
9228
+ return result("\u770B\u63D0\u4EA4", isSafeGitTarget(target) ? clipShortText(target, 20) : void 0, true);
9229
+ }
9230
+ case "diff": {
9231
+ const target = nonFlagArgs(args).find(isSafeGitTarget);
9232
+ return result("\u770B\u5DEE\u5F02", target ? baseName(target) ?? clipShortText(target, 20) : void 0, true);
9233
+ }
9234
+ case "tag": {
9235
+ const hasMutating = args.some((t2) => ["-d", "--delete", "-a", "-s", "-f", "--force"].includes(t2)) || nonFlagArgs(args).length > 0;
9236
+ return hasMutating ? result("\u7BA1\u6807\u7B7E", void 0, false) : result("\u67E5\u6807\u7B7E", void 0, true);
9237
+ }
9238
+ case "add": {
9239
+ if (args.some((t2) => t2 === "-A" || t2 === "--all" || t2 === ".")) return result("\u6682\u5B58\u5168\u90E8\u4FEE\u6539", void 0, false);
9240
+ const files = nonFlagArgs(args).filter(isSafeGitTarget);
9241
+ if (files.length === 1) return result("\u6682\u5B58", baseName(files[0]) ?? files[0], false);
9242
+ if (files.length > 1) return result("\u6682\u5B58", `${files.length} \u9879`, false);
9243
+ return result("\u6682\u5B58\u4FEE\u6539", void 0, false);
9244
+ }
9245
+ case "commit":
9246
+ return result("\u63D0\u4EA4", void 0, false);
9247
+ case "merge": {
9248
+ const branch = nonFlagArgs(args).find(isSafeGitTarget);
9249
+ return result("\u5408\u5E76", branch ? clipShortText(branch, 28) : void 0, false);
9250
+ }
9251
+ case "checkout":
9252
+ case "switch": {
9253
+ const branch = nonFlagArgs(args).find(isSafeGitTarget);
9254
+ return result("\u5207\u6362\u5206\u652F", branch ? clipShortText(branch, 28) : void 0, false);
9255
+ }
9256
+ case "push": {
9257
+ const parts = nonFlagArgs(args).filter(isSafeGitTarget);
9258
+ const target = parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0];
9259
+ return result("\u63A8\u9001", target ? clipShortText(target, 28) : void 0, false);
9260
+ }
9261
+ case "pull": {
9262
+ const parts = nonFlagArgs(args).filter(isSafeGitTarget);
9263
+ const target = parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0];
9264
+ return result("\u62C9\u53D6", target ? clipShortText(target, 28) : void 0, false);
9265
+ }
9266
+ case "fetch": {
9267
+ const remote = nonFlagArgs(args).find(isSafeGitTarget);
9268
+ return result("\u83B7\u53D6\u8FDC\u7AEF", remote ? clipShortText(remote, 24) : void 0, true);
9269
+ }
9270
+ case "stash": {
9271
+ const op = nonFlagArgs(args)[0];
9272
+ return op === "list" ? result("\u67E5\u8D2E\u85CF", void 0, true) : result("\u6682\u5B58", void 0, false);
9273
+ }
9274
+ case "reset":
9275
+ return result("\u91CD\u7F6E", void 0, false);
9276
+ case "restore":
9277
+ return result("\u6062\u590D\u6587\u4EF6", void 0, false);
9278
+ default:
9279
+ return null;
9280
+ }
9281
+ }
9282
+ function baseName(path2) {
9283
+ const cleaned = path2.replace(/^['"]|['"]$/g, "").replace(/\/+$/, "");
9284
+ if (!cleaned || cleaned === "." || cleaned === "..") return void 0;
9285
+ const parts = cleaned.split("/").filter(Boolean);
9286
+ const base = parts.pop();
9287
+ return base || void 0;
9288
+ }
9289
+ function splitSegments(command) {
9290
+ const segments = [];
9291
+ let current = "";
9292
+ let quote = null;
9293
+ let hasFallback = false;
9294
+ for (let i = 0; i < command.length; i++) {
9295
+ const ch = command[i];
9296
+ const next = command[i + 1];
9297
+ if (quote) {
9298
+ if (ch === "\\" && next && quote === '"') {
9299
+ current += ch + next;
9300
+ i++;
9301
+ continue;
9302
+ }
9303
+ current += ch;
9304
+ if (ch === quote) quote = null;
9305
+ continue;
9306
+ }
9307
+ if (ch === '"' || ch === "'") {
9308
+ quote = ch;
9309
+ current += ch;
9310
+ continue;
9311
+ }
9312
+ if (ch === "\\" && next) {
9313
+ current += ch + next;
9314
+ i++;
9315
+ continue;
9316
+ }
9317
+ if (ch === "&" && next === "&") {
9318
+ const trimmed = current.trim();
9319
+ if (trimmed) segments.push(trimmed);
9320
+ current = "";
9321
+ i++;
9322
+ continue;
9323
+ }
9324
+ if (ch === "|" && next === "|") {
9325
+ hasFallback = true;
9326
+ current = "";
9327
+ i++;
9328
+ continue;
9329
+ }
9330
+ if (ch === ";") {
9331
+ const trimmed = current.trim();
9332
+ if (trimmed) segments.push(trimmed);
9333
+ current = "";
9334
+ continue;
9335
+ }
9336
+ current += ch;
9337
+ }
9338
+ const tail = current.trim();
9339
+ if (tail) segments.push(tail);
9340
+ return { segments, hasFallback };
9341
+ }
9342
+ function stripEnvAssignments(segment) {
9343
+ let rest = segment.trimStart();
9344
+ if (/^export\s+[A-Za-z_][A-Za-z0-9_]*=/.test(rest)) {
9345
+ rest = rest.replace(/^export\s+/, "");
9346
+ }
9347
+ while (/^[A-Za-z_][A-Za-z0-9_]*=(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\S*)\s*/.test(rest)) {
9348
+ const next = rest.replace(/^[A-Za-z_][A-Za-z0-9_]*=(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\S*)\s*/, "");
9349
+ if (next === rest) break;
9350
+ rest = next;
9351
+ }
9352
+ return rest;
9353
+ }
9354
+ function firstVerbToken(segment) {
9355
+ let rest = stripEnvAssignments(segment).trim();
9356
+ const wrappers = /* @__PURE__ */ new Set(["sudo", "env", "command", "time", "nohup", "exec"]);
9357
+ let guard = 0;
9358
+ while (guard++ < 6) {
9359
+ const before = rest;
9360
+ rest = stripEnvAssignments(rest).trim();
9361
+ const m = rest.match(/^(\S+)\s*(.*)$/s);
9362
+ if (!m) return { verb: "", rest: "" };
9363
+ const [, word, restAfter] = m;
9364
+ const base = word.replace(/^.*\//, "");
9365
+ if (wrappers.has(base) && restAfter.trim()) {
9366
+ rest = restAfter.trim();
9367
+ continue;
9368
+ }
9369
+ if (base === "timeout" && restAfter.trim()) {
9370
+ const tokens2 = shellWords(restAfter.trim());
9371
+ if (!tokens2 || tokens2.length < 2) return { verb: "timeout", rest: restAfter.trim() };
9372
+ let idx = 0;
9373
+ while (idx < tokens2.length && tokens2[idx].startsWith("-")) {
9374
+ const opt = tokens2[idx++];
9375
+ if (["-k", "-s", "--kill-after", "--signal"].includes(opt)) idx++;
9376
+ }
9377
+ if (idx < tokens2.length && /^\d+(?:\.\d+)?[smhd]?$/i.test(tokens2[idx])) idx++;
9378
+ if (idx < tokens2.length) {
9379
+ const inner = tokens2.slice(idx).map((q) => /\s/.test(q) ? JSON.stringify(q) : q).join(" ");
9380
+ rest = inner;
9381
+ continue;
9382
+ }
9383
+ }
9384
+ if (before !== rest && !rest) return { verb: "", rest: "" };
9385
+ return { verb: base, rest: restAfter.trim() };
9386
+ }
9387
+ return { verb: "", rest };
9388
+ }
9389
+ function extractSafeSearchTarget(rest) {
9390
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9391
+ if (!tokens2) return void 0;
9392
+ const valuedOpts = /* @__PURE__ */ new Set(["-e", "-f", "-g", "--glob", "-t", "--type", "-T", "--type-not", "-A", "-B", "-C", "-m", "--max-count", "--max-filesize", "--color", "--sort"]);
9393
+ let hasExtendedRegex = false;
9394
+ let pattern;
9395
+ for (let i = 0; i < tokens2.length; i++) {
9396
+ const tok = tokens2[i];
9397
+ if (tok === "--") {
9398
+ pattern = tokens2[i + 1];
9399
+ break;
9400
+ }
9401
+ if (tok.startsWith("-")) {
9402
+ if (tok === "-E" || tok === "-P" || tok === "--extended-regexp") hasExtendedRegex = true;
9403
+ if (valuedOpts.has(tok)) {
9404
+ if (tok === "-e" && !pattern && tokens2[i + 1]) pattern = tokens2[i + 1];
9405
+ i++;
9406
+ }
9407
+ continue;
9408
+ }
9409
+ pattern = tok;
9410
+ break;
9411
+ }
9412
+ if (!pattern || hasExtendedRegex || /[|[\]^$()*+?\\]/.test(pattern)) return void 0;
9413
+ return clipShortText(pattern, 22);
9414
+ }
9415
+ function parseSed(rest) {
9416
+ const rawTokens = shellWords(rest.split(/\s+\|\s+/)[0]);
9417
+ if (!rawTokens) return null;
9418
+ let quiet = false;
9419
+ let inPlace = false;
9420
+ const scripts = [];
9421
+ const positional = [];
9422
+ for (let i = 0; i < rawTokens.length; i++) {
9423
+ const tok = rawTokens[i];
9424
+ if (tok === "--") {
9425
+ positional.push(...rawTokens.slice(i + 1));
9426
+ break;
9427
+ }
9428
+ if (tok.startsWith("-") && tok.length > 1) {
9429
+ if (tok === "--quiet" || tok === "--silent") {
9430
+ quiet = true;
9431
+ continue;
9432
+ }
9433
+ if (tok === "--in-place" || tok.startsWith("--in-place=")) {
9434
+ inPlace = true;
9435
+ continue;
9436
+ }
9437
+ if (tok === "--regexp-extended") continue;
9438
+ if (tok.startsWith("--expression=")) {
9439
+ scripts.push(tok.slice("--expression=".length));
9440
+ continue;
9441
+ }
9442
+ if (tok === "--expression") {
9443
+ if (rawTokens[i + 1] === void 0) return null;
9444
+ scripts.push(rawTokens[++i]);
9445
+ continue;
9446
+ }
9447
+ if (tok.startsWith("--")) return null;
9448
+ for (let c = 1; c < tok.length; c++) {
9449
+ const flag = tok[c];
9450
+ if (flag === "n") {
9451
+ quiet = true;
9452
+ continue;
9453
+ }
9454
+ if (flag === "r" || flag === "E") continue;
9455
+ if (flag === "i") {
9456
+ inPlace = true;
9457
+ if (c === tok.length - 1 && rawTokens[i + 1] === "") i++;
9458
+ break;
9459
+ }
9460
+ if (flag === "e") {
9461
+ if (c + 1 < tok.length) {
9462
+ scripts.push(tok.slice(c + 1));
9463
+ } else {
9464
+ if (rawTokens[i + 1] === void 0) return null;
9465
+ scripts.push(rawTokens[++i]);
9466
+ }
9467
+ break;
9468
+ }
9469
+ return null;
9470
+ }
9471
+ continue;
9472
+ }
9473
+ positional.push(tok);
9474
+ }
9475
+ const isSedScript = (tok) => /^(?:\d+|\$)(?:,\s*(?:\d+|\$))?[pdq=!]?$/.test(tok) || /^s[|/#]/.test(tok) || /^\/.*\/[pd=!]?$/.test(tok) || /^\d+[ew]/.test(tok);
9476
+ for (const tok of positional) {
9477
+ if (isSedScript(tok)) scripts.push(tok);
9478
+ }
9479
+ const files = positional.filter((t2) => !isSedScript(t2));
9480
+ if (scripts.length === 0 && files.length >= 2) {
9481
+ scripts.push(files.shift());
9482
+ }
9483
+ const fileToken = files[files.length - 1];
9484
+ const target = fileToken ? baseName(fileToken) : void 0;
9485
+ if (inPlace) {
9486
+ const isSafeSub = (part) => {
9487
+ if (part.length < 4 || part[0] !== "s") return false;
9488
+ const delim = part[1];
9489
+ if (delim !== "|" && delim !== "/" && delim !== "#") return false;
9490
+ let delimsSeen = 1;
9491
+ let idx = 2;
9492
+ for (; idx < part.length && delimsSeen < 3; idx++) {
9493
+ const ch = part[idx];
9494
+ if (ch === "\\" && idx + 1 < part.length) {
9495
+ idx++;
9496
+ continue;
9497
+ }
9498
+ if (ch === delim) delimsSeen++;
9499
+ }
9500
+ if (delimsSeen !== 3) return false;
9501
+ return /^[gipI]*$/.test(part.slice(idx));
9502
+ };
9503
+ const allSafe = scripts.every((s) => {
9504
+ const parts = s.split(";").map((p) => p.trim()).filter(Boolean);
9505
+ return parts.length > 0 && parts.every(isSafeSub);
9506
+ });
9507
+ if (!allSafe) return null;
9508
+ const replaceCount = (rest.match(/s[|/#][^|/#]*[|/#][^|/#]*[|/#]/g) ?? []).length;
9509
+ return {
9510
+ verb: "\u7F16\u8F91",
9511
+ target,
9512
+ count: replaceCount > 1 ? replaceCount : void 0,
9513
+ unit: "\u5904\u66FF\u6362",
9514
+ readOnly: false
9515
+ };
9516
+ }
9517
+ if (quiet) {
9518
+ const isStrictReadOnlyPrint = (s) => /^(?:\d+|\$)(?:\s*,\s*(?:\d+|\$))?\s*p$/.test(s.trim());
9519
+ if (scripts.length === 0 || !scripts.every(isStrictReadOnlyPrint)) {
9520
+ return null;
9521
+ }
9522
+ return { verb: "\u67E5\u770B", target, readOnly: true };
9523
+ }
9524
+ return { verb: "\u5904\u7406\u6587\u672C", target, readOnly: false };
9525
+ }
9526
+ function parseNolo(rest) {
9527
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9528
+ if (!tokens2 || tokens2.length === 0) return null;
9529
+ const sub = tokens2[0];
9530
+ const action = tokens2[1];
9531
+ const nonFlag = tokens2.slice(2).filter((t2) => !t2.startsWith("-"));
9532
+ if (sub === "browser" || sub === "chrome") {
9533
+ const map = {
9534
+ status: ["\u67E5\u6D4F\u89C8\u5668\u72B6\u6001", true],
9535
+ "list-tabs": ["\u5217\u6D4F\u89C8\u5668\u6807\u7B7E", true],
9536
+ "read-page": ["\u6D4F\u89C8\u5668\u8BFB\u9875\u9762", true],
9537
+ "read-network": ["\u67E5\u6D4F\u89C8\u5668\u8BF7\u6C42", true],
9538
+ screenshot: ["\u6D4F\u89C8\u5668\u622A\u56FE", true],
9539
+ "open-tab": ["\u6D4F\u89C8\u5668\u5F00\u6807\u7B7E", false],
9540
+ click: ["\u6D4F\u89C8\u5668\u70B9\u51FB", false],
9541
+ type: ["\u6D4F\u89C8\u5668\u8F93\u5165", false],
9542
+ press: ["\u6D4F\u89C8\u5668\u6309\u952E", false]
9543
+ };
9544
+ if (action && map[action]) return { verb: map[action][0], readOnly: map[action][1] };
9545
+ return { verb: "\u6D4F\u89C8\u5668\u64CD\u4F5C", readOnly: false };
9546
+ }
9547
+ if (sub === "agent") {
9548
+ if (action === "list" || action === "providers" || action === "models") return { verb: action === "list" ? "\u5217\u667A\u80FD\u4F53" : "\u5217\u6A21\u578B\u901A\u9053", readOnly: true };
9549
+ if (action === "read") return { verb: "\u8BFB\u667A\u80FD\u4F53", target: nonFlag[0] ? clipShortText(nonFlag[0], 24) : void 0, readOnly: true };
9550
+ if (action === "create") return { verb: "\u521B\u5EFA\u667A\u80FD\u4F53", target: nonFlag[0] ? clipShortText(nonFlag[0], 24) : void 0, readOnly: false };
9551
+ if (action === "delete") return { verb: "\u5220\u9664\u667A\u80FD\u4F53", target: nonFlag[0] ? clipShortText(nonFlag[0], 24) : void 0, readOnly: false };
9552
+ return { verb: "\u7BA1\u7406\u667A\u80FD\u4F53", readOnly: false };
9553
+ }
9554
+ if (sub === "dialog") {
9555
+ if (action === "list") return { verb: "\u5217\u5BF9\u8BDD", readOnly: true };
9556
+ if (action === "read") return { verb: "\u8BFB\u5BF9\u8BDD", target: nonFlag[0] ? clipShortText(nonFlag[0], 20) : void 0, readOnly: true };
9557
+ if (action === "status") return { verb: "\u67E5\u5BF9\u8BDD\u72B6\u6001", readOnly: true };
9558
+ if (action === "search") return { verb: "\u641C\u5BF9\u8BDD", readOnly: true };
9559
+ return { verb: "\u7BA1\u5BF9\u8BDD", readOnly: false };
9560
+ }
9561
+ if (sub === "secret") {
9562
+ if (action === "list") return { verb: "\u5217\u51ED\u636E", readOnly: true };
9563
+ if (action === "run") return { verb: "\u5E26\u51ED\u636E\u6267\u884C", readOnly: false };
9564
+ return { verb: "\u7BA1\u51ED\u636E", readOnly: false };
9565
+ }
9566
+ if (sub === "ci") return { verb: "\u67E5 CI \u72B6\u6001", readOnly: true };
9567
+ return null;
9568
+ }
9569
+ function classifySegment(segment) {
9570
+ const { verb, rest } = firstVerbToken(segment);
9571
+ if (!verb) return null;
9572
+ switch (verb) {
9573
+ case "cd":
9574
+ return { verb: "\u8FDB\u5165\u76EE\u5F55", target: baseName(rest), readOnly: true };
9575
+ case "mkdir":
9576
+ return { verb: "\u5EFA\u76EE\u5F55", target: baseName(rest.replace(/^-\S+\s+/, "")), readOnly: false };
9577
+ case "cp":
9578
+ return { verb: "\u590D\u5236", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
9579
+ case "mv":
9580
+ return { verb: "\u79FB\u52A8", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
9581
+ case "rm":
9582
+ return { verb: "\u5220\u9664", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
9583
+ case "touch":
9584
+ return { verb: "\u521B\u5EFA\u6587\u4EF6", target: baseName(rest), readOnly: false };
9585
+ case "cat": {
9586
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9587
+ const file = tokens2?.find((t2) => !t2.startsWith("-"));
9588
+ return { verb: "\u8BFB\u53D6", target: baseName(file ?? rest.split(/\s+/)[0] ?? ""), readOnly: true };
9589
+ }
9590
+ case "ls": {
9591
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9592
+ const dir = tokens2?.find((t2) => !t2.startsWith("-"));
9593
+ return { verb: "\u5217\u51FA\u76EE\u5F55", target: dir ? baseName(dir) : void 0, readOnly: true };
9594
+ }
9595
+ case "grep":
9596
+ case "rg":
9597
+ return { verb: "\u641C\u7D22", target: extractSafeSearchTarget(rest), readOnly: true };
9598
+ case "chmod":
9599
+ return { verb: "\u6539\u6743\u9650", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
9600
+ case "chown":
9601
+ return { verb: "\u6539\u5C5E\u4E3B", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
9602
+ case "tar":
9603
+ case "unzip":
9604
+ return { verb: "\u89E3\u538B", readOnly: false };
9605
+ case "git": {
9606
+ const parsed = parseGit(rest);
9607
+ return parsed ? { verb: parsed.action, target: parsed.object, readOnly: parsed.readOnly } : null;
9608
+ }
9609
+ case "sed":
9610
+ return parseSed(rest);
9611
+ case "nolo":
9612
+ return parseNolo(rest);
9613
+ case "gh": {
9614
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9615
+ if (!tokens2?.length) return null;
9616
+ const sub = tokens2[0];
9617
+ const op = tokens2[1];
9618
+ const isRead = ["view", "list", "status", "checks", "diff"].includes(op ?? "");
9619
+ if (sub === "pr") return { verb: isRead ? "\u67E5 PR" : "\u64CD\u4F5C PR", readOnly: isRead };
9620
+ if (sub === "run") return { verb: isRead ? "\u67E5 CI \u8FD0\u884C" : "\u64CD\u4F5C CI \u8FD0\u884C", readOnly: isRead };
9621
+ if (sub === "issue") return { verb: isRead ? "\u67E5 Issue" : "\u64CD\u4F5C Issue", readOnly: isRead };
9622
+ if (sub === "api") return { verb: "\u8C03 GitHub API", readOnly: false };
9623
+ return null;
9624
+ }
9625
+ case "ps":
9626
+ return { verb: "\u67E5\u8FDB\u7A0B", readOnly: true };
9627
+ case "sha256sum": {
9628
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9629
+ const file = tokens2?.find((t2) => !t2.startsWith("-"));
9630
+ return { verb: "\u7B97\u6821\u9A8C\u548C", target: file ? baseName(file) : void 0, readOnly: true };
9631
+ }
9632
+ case "dnf":
9633
+ case "yum": {
9634
+ const sub = rest.split(/\s+/)[0] ?? "";
9635
+ if (sub === "install") return { verb: "\u88C5\u8F6F\u4EF6\u5305", readOnly: false };
9636
+ if (sub === "remove" || sub === "erase") return { verb: "\u5378\u8F7D\u8F6F\u4EF6\u5305", readOnly: false };
9637
+ if (sub === "update" || sub === "upgrade") return { verb: "\u66F4\u65B0\u7CFB\u7EDF", readOnly: false };
9638
+ if (sub === "search") return { verb: "\u641C\u7D22\u8F6F\u4EF6\u5305", readOnly: true };
9639
+ if (sub === "list") return { verb: "\u5217\u51FA\u8F6F\u4EF6\u5305", readOnly: true };
9640
+ if (sub === "history") return { verb: "\u67E5\u5B89\u88C5\u5386\u53F2", readOnly: true };
9641
+ return null;
9642
+ }
9643
+ case "rpm":
9644
+ case "pacman":
9645
+ case "apt":
9646
+ case "apt-get":
9647
+ return { verb: "\u7BA1\u8F6F\u4EF6\u5305", readOnly: false };
9648
+ case "systemctl":
9649
+ case "journalctl": {
9650
+ const tokens2 = rest.split(/\s+/).filter((t2) => t2 && !t2.startsWith("-"));
9651
+ const sub = tokens2[0] ?? "";
9652
+ if (verb === "journalctl") return { verb: "\u67E5\u65E5\u5FD7", readOnly: true };
9653
+ const sysVerbs = {
9654
+ start: ["\u542F\u52A8\u670D\u52A1", false],
9655
+ stop: ["\u505C\u6B62\u670D\u52A1", false],
9656
+ restart: ["\u91CD\u542F\u670D\u52A1", false],
9657
+ status: ["\u67E5\u670D\u52A1\u72B6\u6001", true],
9658
+ enable: ["\u542F\u7528\u670D\u52A1", false],
9659
+ disable: ["\u505C\u7528\u670D\u52A1", false],
9660
+ "daemon-reload": ["\u91CD\u8F7D\u670D\u52A1\u914D\u7F6E", false],
9661
+ "list-units": ["\u5217\u670D\u52A1", true],
9662
+ "list-unit-files": ["\u5217\u670D\u52A1", true],
9663
+ is: ["\u67E5\u670D\u52A1\u72B6\u6001", true],
9664
+ cat: ["\u770B\u670D\u52A1\u5B9A\u4E49", true]
9665
+ };
9666
+ const mapped = sysVerbs[sub];
9667
+ return mapped ? { verb: mapped[0], readOnly: mapped[1] } : null;
9668
+ }
9669
+ case "awk":
9670
+ return { verb: "\u5904\u7406\u6587\u672C", readOnly: true };
9671
+ case "find": {
9672
+ if (/(?:^|\s)(?:-delete|-exec|-execdir|-ok|-okdir)(?:\s|$)/.test(rest)) return null;
9673
+ return { verb: "\u67E5\u627E\u6587\u4EF6", readOnly: true };
9674
+ }
9675
+ case "curl":
9676
+ case "wget":
9677
+ return { verb: "\u4E0B\u8F7D", readOnly: false };
9678
+ case "bun":
9679
+ case "npm":
9680
+ case "pnpm":
9681
+ case "yarn": {
9682
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]) ?? rest.split(/\s+/).filter(Boolean);
9683
+ const sub = tokens2[0] ?? "";
9684
+ if (sub === "test") {
9685
+ const target = tokens2.slice(1).find((t2) => !t2.startsWith("-"));
9686
+ return { verb: "\u8DD1\u6D4B\u8BD5", target: target ? baseName(target) : void 0, readOnly: false };
9687
+ }
9688
+ if (sub === "install" || sub === "i" || sub === "add") return { verb: "\u88C5\u4F9D\u8D56", readOnly: false };
9689
+ if (sub === "run") {
9690
+ const script = tokens2[1];
9691
+ return { verb: "\u8DD1\u811A\u672C", target: script, readOnly: false };
9692
+ }
9693
+ if (sub === "build") return { verb: "\u6784\u5EFA", readOnly: false };
9694
+ if (sub === "x" || sub === "exec") {
9695
+ return { verb: "\u6267\u884C", target: tokens2[1], readOnly: false };
9696
+ }
9697
+ if (verb === "bun" && (sub === "-e" || sub === "-p" || sub === "--inline-heredoc" || tokens2.includes("--inline-heredoc"))) {
9698
+ return { verb: "\u6267\u884C\u5185\u8054\u811A\u672C (Bun)", readOnly: false };
9699
+ }
9700
+ const scriptFile = tokens2.find((t2) => !t2.startsWith("-") && (/\.(?:ts|tsx|js|mjs|mts|cjs)$/i.test(t2) || t2.includes("/")));
9701
+ if (scriptFile) {
9702
+ return { verb: "\u8FD0\u884C\u811A\u672C", target: baseName(scriptFile), readOnly: false };
9703
+ }
9704
+ return null;
9705
+ }
9706
+ case "python":
9707
+ case "python3": {
9708
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]) ?? [];
9709
+ if (tokens2.includes("--inline-heredoc") || /(?:^|\s)-[A-Za-z]*c(?:\s|$)/.test(rest)) {
9710
+ return { verb: "\u6267\u884C\u5185\u8054\u811A\u672C (Python)", readOnly: false };
9711
+ }
9712
+ const script = rest.split(/\s+/).find((t2) => t2 && !t2.startsWith("-"));
9713
+ return { verb: "\u6267\u884C\u811A\u672C", target: baseName(script ?? ""), readOnly: false };
9714
+ }
9715
+ case "node": {
9716
+ if (/(?:^|\s)-[A-Za-z]*e(?:\s|$)/.test(rest)) return null;
9717
+ const script = rest.split(/\s+/).find((t2) => t2 && !t2.startsWith("-"));
9718
+ return { verb: "\u6267\u884C\u811A\u672C", target: baseName(script ?? ""), readOnly: false };
9719
+ }
9720
+ case "bash":
9721
+ case "sh":
9722
+ case "zsh": {
9723
+ if (/(?:^|\s)-[A-Za-z]*[ce](?:\s|$)/.test(rest)) return null;
9724
+ const script = rest.split(/\s+/).find((t2) => t2 && !t2.startsWith("-"));
9725
+ return { verb: "\u6267\u884C\u811A\u672C", target: baseName(script ?? ""), readOnly: false };
9726
+ }
9727
+ case "echo":
9728
+ case "printf":
9729
+ return { verb: "\u8F93\u51FA", readOnly: true };
9730
+ case "head":
9731
+ case "tail":
9732
+ case "wc":
9733
+ case "sort":
9734
+ case "uniq": {
9735
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9736
+ let file;
9737
+ if (tokens2) {
9738
+ for (let i = 0; i < tokens2.length; i++) {
9739
+ const tok = tokens2[i];
9740
+ if (tok === "-n" || tok === "-c") {
9741
+ i++;
9742
+ continue;
9743
+ }
9744
+ if (tok.startsWith("-")) continue;
9745
+ file = tok;
9746
+ break;
9747
+ }
9748
+ }
9749
+ return file ? { verb: "\u67E5\u770B", target: baseName(file), readOnly: true } : { verb: "\u67E5\u770B\u8F93\u51FA", readOnly: true };
9750
+ }
9751
+ default:
9752
+ return null;
9753
+ }
9754
+ }
9755
+ function summarizeActions(actions) {
9756
+ const cds = actions.filter((a) => a.verb === "\u8FDB\u5165\u76EE\u5F55");
9757
+ const body = actions.filter((a) => a.verb !== "\u8FDB\u5165\u76EE\u5F55");
9758
+ const merged = [];
9759
+ for (const action of body) {
9760
+ const last = merged[merged.length - 1];
9761
+ if (last && last.verb === action.verb && last.target === action.target) {
9762
+ last.count = (last.count ?? 1) + (action.count ?? 1);
9763
+ continue;
9764
+ }
9765
+ merged.push({ ...action });
9766
+ }
9767
+ const renderOne = (a) => {
9768
+ if (a.count && a.count > 1) {
9769
+ const suffix = a.unit ?? (a.verb === "\u590D\u5236" || a.verb === "\u79FB\u52A8" || a.verb === "\u5220\u9664" ? "\u4E2A\u6587\u4EF6" : "\u9879");
9770
+ const head = a.unit && a.target ? `${a.verb} ${a.target}` : a.verb;
9771
+ return `${head} ${a.count} ${suffix}`;
9772
+ }
9773
+ return a.target ? `${a.verb} ${a.target}` : a.verb;
9774
+ };
9775
+ const parts = merged.map(renderOne);
9776
+ const cdPart = cds.length > 0 && cds[0].target ? `\u8FDB\u5165 ${cds[0].target}` : "";
9777
+ const joined = parts.length > 0 ? parts.join("\u3001") : "";
9778
+ if (cdPart && joined) return `${cdPart}\uFF1A${joined}`;
9779
+ return cdPart || joined;
9780
+ }
9781
+ var PIPELINE_FILTER_COMMANDS = /* @__PURE__ */ new Set([
9782
+ "head",
9783
+ "tail",
9784
+ "cat",
9785
+ "wc",
9786
+ "sort",
9787
+ "uniq",
9788
+ "cut",
9789
+ "tr",
9790
+ "nl",
9791
+ "column",
9792
+ "grep",
9793
+ "rg",
9794
+ "ag",
9795
+ "ack",
9796
+ "jq",
9797
+ "less",
9798
+ "more",
9799
+ "bat",
9800
+ "awk",
9801
+ "sed"
9802
+ ]);
9803
+ function hasNonFilterPipeline(command) {
9804
+ let quote = null;
9805
+ for (let i = 0; i < command.length; i++) {
9806
+ const ch = command[i];
9807
+ const next = command[i + 1];
9808
+ if (quote) {
9809
+ if (ch === "\\" && next && quote === '"') {
9810
+ i++;
9811
+ continue;
9812
+ }
9813
+ if (ch === quote) quote = null;
9814
+ continue;
9815
+ }
9816
+ if (ch === '"' || ch === "'") {
9817
+ quote = ch;
9818
+ continue;
9819
+ }
9820
+ if (ch === "\\" && next) {
9821
+ i++;
9822
+ continue;
9823
+ }
9824
+ if (ch === "|" && next !== "|" && command[i - 1] !== "|") {
9825
+ const afterPipe = command.slice(i + 1).trimStart();
9826
+ const m = afterPipe.match(/^(\S+)\s*(.*)$/s);
9827
+ if (!m) return true;
9828
+ let word = m[1].replace(/^.*\//, "");
9829
+ let restAfter = m[2];
9830
+ let guard = 0;
9831
+ while (guard++ < 4) {
9832
+ if (word === "sudo") {
9833
+ const opt = restAfter.match(/^(?:-\S+\s+)*(\S+)\s*(.*)$/s);
9834
+ if (!opt) return true;
9835
+ word = opt[1].replace(/^.*\//, "");
9836
+ restAfter = opt[2];
9837
+ continue;
9838
+ }
9839
+ if (word === "env" || word === "xargs") {
9840
+ const nxt = restAfter.match(/^(?:[A-Za-z_]\w*=\S*\s+|-\S+\s+)*(\S+)\s*(.*)$/s);
9841
+ if (!nxt) return true;
9842
+ word = nxt[1].replace(/^.*\//, "");
9843
+ restAfter = nxt[2];
9844
+ continue;
9845
+ }
9846
+ break;
9847
+ }
9848
+ if (!PIPELINE_FILTER_COMMANDS.has(word)) return true;
9849
+ }
9850
+ }
9851
+ return false;
9852
+ }
9853
+ function collapseSafeHeredocs(command) {
9854
+ const lines = command.split(/\r?\n/);
9855
+ const out = [];
9856
+ for (let i = 0; i < lines.length; i++) {
9857
+ const line = lines[i];
9858
+ const trimmed = line.trim();
9859
+ if (!trimmed) continue;
9860
+ const hd = trimmed.match(/^(.*?)\s*<<-?\s*'([A-Za-z0-9_]+)'\s*$/);
9861
+ if (hd) {
9862
+ const head = hd[1].trim();
9863
+ const tag = hd[2];
9864
+ let end = -1;
9865
+ for (let j = i + 1; j < lines.length; j++) {
9866
+ if (lines[j].trim() === tag) {
9867
+ end = j;
9868
+ break;
9869
+ }
9870
+ }
9871
+ if (end === -1) return null;
9872
+ out.push(`${head} --inline-heredoc`);
9873
+ i = end;
9874
+ continue;
9875
+ }
9876
+ out.push(trimmed);
9877
+ }
9878
+ return out.join("\n");
9879
+ }
9880
+ function normalizeTopLevelNewlines(command) {
9881
+ let out = "";
9882
+ let quote = null;
9883
+ for (let i = 0; i < command.length; i++) {
9884
+ const ch = command[i];
9885
+ const next = command[i + 1];
9886
+ if (quote) {
9887
+ if (ch === "\\" && next && quote === '"') {
9888
+ out += ch + next;
9889
+ i++;
9890
+ continue;
9891
+ }
9892
+ if (ch === quote) quote = null;
9893
+ out += ch === "\n" ? " " : ch;
9894
+ continue;
9895
+ }
9896
+ if (ch === '"' || ch === "'") {
9897
+ quote = ch;
9898
+ out += ch;
9899
+ continue;
9900
+ }
9901
+ if (ch === "\\" && next) {
9902
+ out += ch + next;
9903
+ i++;
9904
+ continue;
9905
+ }
9906
+ if (ch === "\n") {
9907
+ if (!out.endsWith("&& ") && out.trim().length > 0) out += " && ";
9908
+ continue;
9909
+ }
9910
+ out += ch;
9911
+ }
9912
+ return out.replace(/(?:\s*&&\s*)+$/, "").trim();
9913
+ }
9914
+ function summarizeShellCommand(command) {
9915
+ const collapsed = collapseSafeHeredocs(command);
9916
+ if (collapsed === null) return null;
9917
+ const normalized = normalizeTopLevelNewlines(collapsed);
9918
+ if (!normalized) return null;
9919
+ if (hasNonFilterPipeline(normalized)) return null;
9920
+ const { segments, hasFallback } = splitSegments(normalized);
9921
+ if (segments.length === 0) return null;
9922
+ if (hasFallback) return null;
9923
+ if (segments.some((segment) => !shellWords(segment, true))) return null;
9924
+ const actions = [];
9925
+ for (const segment of segments) {
9926
+ const action = classifySegment(segment);
9927
+ if (!action) return null;
9928
+ actions.push(action);
9929
+ }
9930
+ const summary = summarizeActions(actions);
9931
+ if (!summary) return null;
9932
+ const readOnly = actions.every((a) => a.readOnly === true);
9933
+ const single = segments.length === 1 ? firstVerbToken(segments[0]) : void 0;
9934
+ const git = single?.verb === "git" ? parseGit(single.rest) : null;
9935
+ const singleAction = segments.length === 1 && !actions[0]?.count ? { action: actions[0].verb, ...actions[0].target ? { object: actions[0].target } : {} } : {};
9936
+ return { summary, foldedSegments: segments.length, readOnly, ...singleAction, ...git ?? {} };
9937
+ }
9938
+
9939
+ // packages/core/toolActivityPresentation.ts
9940
+ var families = {
9941
+ readFile: ["read", "\u8BFB\u53D6", ["path"], true],
9942
+ read_file: ["read", "\u8BFB\u53D6", ["path"], true],
9943
+ readWorkspaceFile: ["read", "\u8BFB\u53D6", ["path"], true],
9944
+ writeFile: ["write", "\u5199\u5165", ["path"], false],
9945
+ editFile: ["edit", "\u4FEE\u6539", ["path"], false],
9946
+ globFiles: ["find", "\u67E5\u627E\u6587\u4EF6", ["pattern", "path"], true],
9947
+ search: ["search", "\u641C\u7D22", ["query", "pattern"], true],
9948
+ grep: ["search", "\u641C\u7D22", ["pattern", "query"], true],
9949
+ loadSkill: ["skill", "\u52A0\u8F7D\u6280\u80FD", ["name", "slug"], true]
9950
+ };
9951
+ var shellTools = /* @__PURE__ */ new Set(["execShell", "exec_shell", "runCommand", "launchProcess"]);
9952
+ function projectToolActivity(input, translate) {
9953
+ const text = (...keys) => {
9954
+ for (const key of keys) {
9955
+ const value = input.args?.[key];
9956
+ if (typeof value === "string" && value.length) return value;
9957
+ }
9958
+ return void 0;
9959
+ };
9960
+ let action = input.toolName, object, summary, readOnly = false;
9961
+ let confidence = "raw-fallback";
9962
+ let context = text("cwd");
9963
+ if (shellTools.has(input.toolName)) {
9964
+ object = text("command", "cmd");
9965
+ const gist = object ? summarizeShellCommand(object) : null;
9966
+ action = gist?.action ?? gist?.summary ?? "\u547D\u4EE4";
9967
+ if (gist) {
9968
+ object = gist.object;
9969
+ context = context ?? gist.context;
9970
+ summary = gist.summary;
9971
+ readOnly = gist.readOnly === true;
9972
+ confidence = "recognized";
9973
+ }
9974
+ if (!gist || gist.action) action = translate?.(gist?.action ? `toolActivity.shell.${gist.action}` : "toolActivity.shell", action) ?? action;
9975
+ } else {
9976
+ const family = families[input.toolName];
9977
+ if (family) {
9978
+ action = translate?.(`toolActivity.${family[0]}`, family[1]) ?? family[1];
9979
+ object = text(...family[2]);
9980
+ readOnly = family[3];
9981
+ confidence = "recognized";
9982
+ } else object = text("path", "query", "command", "url", "name");
9983
+ }
9984
+ 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 };
9985
+ }
9986
+ function canCoalesceToolActivities(previous, next) {
9987
+ 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;
9988
+ }
9989
+
9990
+ // packages/cli/tui/askTextSanitize.ts
9991
+ var ASK_SECRET_PLACEHOLDER = "\u27E8redacted\u27E9";
9992
+ var C0_C1_CONTROL_REGEX = /[\x00-\x1f\x7f-\x9f]/g;
9993
+ function toText(value) {
9994
+ return typeof value === "string" ? value : String(value ?? "");
9995
+ }
9996
+ function cleanAskText(value) {
9997
+ return stripAnsi(toText(value)).replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").replace(C0_C1_CONTROL_REGEX, "").replace(/\s+/g, " ").trim();
9998
+ }
9999
+ function safeAskText(value, max) {
10000
+ const cleaned = redactSecrets(cleanAskText(value));
10001
+ if (!cleaned) return "";
10002
+ const guarded = withholdIfSecretLike(cleaned) || ASK_SECRET_PLACEHOLDER;
10003
+ return max === void 0 ? guarded : clipCompactText(guarded, max, "\u2026");
10004
+ }
10005
+ function safeApprovalMultilineText(value) {
10006
+ const lines = stripAnsi(String(value ?? "")).replace(/\r\n?|\u2028|\u2029/g, "\n").split("\n");
10007
+ return lines.map((line) => {
10008
+ const cleaned = line.replace(/\t/g, " ").replace(C0_C1_CONTROL_REGEX, "");
10009
+ const redacted = redactSecrets(cleaned);
10010
+ return redacted ? withholdIfSecretLike(redacted) || ASK_SECRET_PLACEHOLDER : "";
10011
+ }).join("\n");
10012
+ }
10013
+
10014
+ // node_modules/diff/libesm/diff/base.js
10015
+ var Diff = class {
10016
+ diff(oldStr, newStr, options = {}) {
10017
+ let callback;
10018
+ if (typeof options === "function") {
10019
+ callback = options;
10020
+ options = {};
10021
+ } else if ("callback" in options) {
10022
+ callback = options.callback;
10023
+ }
10024
+ const oldString = this.castInput(oldStr, options);
10025
+ const newString = this.castInput(newStr, options);
10026
+ const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
10027
+ const newTokens = this.removeEmpty(this.tokenize(newString, options));
10028
+ return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
10029
+ }
10030
+ diffWithOptionsObj(oldTokens, newTokens, options, callback) {
10031
+ var _a;
10032
+ const done = (value) => {
10033
+ value = this.postProcess(value, options);
10034
+ if (callback) {
8788
10035
  setTimeout(function() {
8789
10036
  callback(value);
8790
10037
  }, 0);
@@ -9086,14 +10333,6 @@ function formatSearchItemQuery(query, path2, customHomedir) {
9086
10333
  if (!text) return "search";
9087
10334
  return text.length > 80 ? `${text.slice(0, 79)}\u2026` : text;
9088
10335
  }
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
10336
  function formatFetchItemUrl(url) {
9098
10337
  const text = (url || "").trim();
9099
10338
  if (!text) return "webpage";
@@ -9111,10 +10350,20 @@ function isRunToolName(name) {
9111
10350
  return name === "execShell" || name === "runCommand" || name === "launchProcess";
9112
10351
  }
9113
10352
  function isFailedToolResult(event) {
9114
- const exitCode = event.metadata?.exitCode;
9115
- if (event.metadata?.actionGate) return false;
10353
+ if (event.type === "tool-error") return true;
10354
+ const metadata = event.metadata ?? {};
10355
+ if (metadata.actionGate) return false;
10356
+ const exitCode = metadata.exitCode;
9116
10357
  if (typeof exitCode === "number" && exitCode !== 0) return true;
9117
- return Boolean(event.metadata?.timedOut);
10358
+ if (Boolean(metadata.timedOut) || Boolean(metadata.failed) || Boolean(event.metadata?.failed)) return true;
10359
+ if (metadata.success === false) return true;
10360
+ if (typeof metadata.error === "string" && metadata.error.trim().length > 0) return true;
10361
+ if (typeof metadata.errorMessage === "string" && metadata.errorMessage.trim().length > 0) return true;
10362
+ if (typeof event.content === "string") {
10363
+ const trimmed = event.content.trim();
10364
+ if (/^\[工具\s*"[^"]+"\s*执行失败:\s*[^\]]+\]$/.test(trimmed)) return true;
10365
+ }
10366
+ return false;
9118
10367
  }
9119
10368
  function parseUiAskChoiceForCli(event) {
9120
10369
  if (event.toolName !== "ask_user" && !event.metadata?.uiAskChoice) {
@@ -9154,9 +10403,9 @@ function formatUiAskChoiceBlock(event, colorEnabled) {
9154
10403
  lines.push("");
9155
10404
  const questionText = safeAskText(parsed.question, 200);
9156
10405
  if (colorEnabled) {
9157
- lines.push(`${themeText("\u2753 ", "info", true)}${styleCliText(questionText, "cyan", true)}`);
10406
+ lines.push(`${themeText("? ", "info", true)}${styleCliText(questionText, "cyan", true)}`);
9158
10407
  } else {
9159
- lines.push(`\u2753 ${questionText}`);
10408
+ lines.push(`? ${questionText}`);
9160
10409
  }
9161
10410
  if (parsed.resolved) {
9162
10411
  if (parsed.cancelled) {
@@ -9577,6 +10826,7 @@ function snippetLinesWithKind(snippet, kind, maxWidth = resolveEditSnippetMaxWid
9577
10826
  return lines.slice(0, EDIT_SNIPPET_MAX_LINES).map((line) => buildEditLine(kind, line, maxWidth));
9578
10827
  }
9579
10828
  function truncateByDisplayWidth(line, maxWidth) {
10829
+ if (maxWidth <= 0) return "";
9580
10830
  if (displayWidth(line) <= maxWidth) return line;
9581
10831
  let width = 0;
9582
10832
  let kept = "";
@@ -9703,7 +10953,7 @@ function memoryToolGist(toolName, metadata) {
9703
10953
  function normalToolGistRaw(event) {
9704
10954
  const metadata = event.metadata ?? {};
9705
10955
  const toolName = event.toolName || "";
9706
- if (toolName === "readFile") {
10956
+ if (toolName === "readFile" || toolName === "writeFile" || toolName === "editFile") {
9707
10957
  const path3 = typeof metadata.path === "string" ? metadata.path : typeof metadata.filePath === "string" ? metadata.filePath : "";
9708
10958
  if (path3) return gistClip(formatReadItemPath(path3, metadata), 52);
9709
10959
  }
@@ -9719,6 +10969,8 @@ function normalToolGistRaw(event) {
9719
10969
  if (isRunToolName(toolName)) {
9720
10970
  const command2 = typeof metadata.command === "string" ? metadata.command : "";
9721
10971
  if (command2) {
10972
+ const gist = summarizeShellCommand(command2);
10973
+ if (gist) return truncateByDisplayWidth(redactSecrets(gist.summary), normalRunGistMaxWidth());
9722
10974
  return commandFullGist(command2, normalRunGistMaxWidth());
9723
10975
  }
9724
10976
  }
@@ -9727,7 +10979,11 @@ function normalToolGistRaw(event) {
9727
10979
  const path2 = typeof metadata.path === "string" ? metadata.path : "";
9728
10980
  if (path2) return pathBasenameGist(path2);
9729
10981
  const command = typeof metadata.command === "string" ? metadata.command : "";
9730
- if (command) return commandFullGist(command, normalRunGistMaxWidth());
10982
+ if (command) {
10983
+ const gist = summarizeShellCommand(command);
10984
+ if (gist) return truncateByDisplayWidth(redactSecrets(gist.summary), normalRunGistMaxWidth());
10985
+ return commandFullGist(command, normalRunGistMaxWidth());
10986
+ }
9731
10987
  const query = typeof metadata.query === "string" ? metadata.query : "";
9732
10988
  if (query) return clipCompactText(query, 64, "\u2026");
9733
10989
  return "";
@@ -9740,6 +10996,21 @@ function formatNormalToolDuration(elapsedMs) {
9740
10996
  if (elapsedMs < 1e3) return `${Math.round(elapsedMs)}ms`;
9741
10997
  return `${(elapsedMs / 1e3).toFixed(1)}s`;
9742
10998
  }
10999
+ function normalResultSummary(event) {
11000
+ const m = event.metadata ?? {};
11001
+ const count = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
11002
+ if (event.toolName === "readFile" && count(m.startLine) && count(m.endLine))
11003
+ return `${Math.max(0, m.endLine - m.startLine + 1)} lines${m.truncated ? " \xB7 truncated" : ""}`;
11004
+ if (event.toolName === "writeFile" && count(m.bytes)) return `${m.bytes} bytes written`;
11005
+ if (event.toolName === "editFile" && count(m.replacements)) return `${m.replacements} replacements`;
11006
+ if (event.toolName === "searchText" && count(m.matchCount)) return `${m.matchCount} matches${m.truncated ? " \xB7 truncated" : ""}`;
11007
+ return "";
11008
+ }
11009
+ function fitNormalLine(head, tail, budget) {
11010
+ const status = budget === 1 ? tail.trimStart().slice(0, 1) : truncateByDisplayWidth(tail.trimStart(), budget);
11011
+ const room = Math.max(0, budget - displayWidth(status) - 2);
11012
+ return room ? `${truncateByDisplayWidth(head, room)} ${status}` : status;
11013
+ }
9743
11014
  function formatNormalToolLine(event, pending, colorEnabled, opts) {
9744
11015
  if (event.type === "tool-call") return "";
9745
11016
  const toolName = event.toolName || pending?.toolName || "tool";
@@ -9760,27 +11031,38 @@ function formatNormalToolLine(event, pending, colorEnabled, opts) {
9760
11031
  return formatShowInteractionBlock(event, colorEnabled);
9761
11032
  }
9762
11033
  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);
11034
+ const cols = typeof process !== "undefined" && typeof process.stdout?.columns === "number" && process.stdout.columns > 0 ? process.stdout.columns : 80;
11035
+ const totalBudget = Math.max(1, resolveHistoryLayoutGeometry(cols).contentWidth - displayWidth("\u25C8 "));
11036
+ if (readActionGate(event.metadata?.actionGate) || event.metadata?.permissionRequest) {
11037
+ const gist2 = opts?.tuiTrees ? normalToolGist(event) : "";
11038
+ const title = gist2 ? `${label} \xB7 ${gist2}` : label;
11039
+ return formatToolTraceLine(fitNormalLine(`\u25B8 ${title}`, `! ${t("toolNeedsAction")}`, totalBudget), colorEnabled, "error");
11040
+ }
11041
+ if (event.type === "tool-error" || event.metadata?.timedOut || isFailedToolResult(event)) {
11042
+ const reason = event.metadata?.timedOut ? t("toolTimedOut") : toolFailureReason(event) || t("toolFailed");
11043
+ const gist2 = opts?.tuiTrees ? normalToolGist(event) : "";
11044
+ const title = gist2 ? `${label} \xB7 ${gist2}` : label;
11045
+ return formatToolTraceLine(fitNormalLine(`\u25B8 ${title}`, `\u2717 ${reason}`, totalBudget), colorEnabled, "error");
11046
+ }
11047
+ const resultSummary = normalResultSummary(event);
11048
+ const gist = [normalToolGist(event), resultSummary].filter(Boolean).join(" \xB7 ");
9776
11049
  const hint = editFileResultHint(event);
9777
11050
  const statsInline = hint?.inline ? ` ${hint.inline}` : "";
9778
11051
  const durationInline = formatNormalToolDuration(event.elapsedMs);
9779
11052
  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
- );
11053
+ let fittedGist = gist;
11054
+ if (gist) {
11055
+ const prefix = `\u25B8 ${label} \xB7 `;
11056
+ const suffix = `${statsInline}${tail}`;
11057
+ const prefixWidth = displayWidth(prefix);
11058
+ const suffixWidth = displayWidth(suffix);
11059
+ const maxGistWidth = Math.max(0, totalBudget - prefixWidth - suffixWidth);
11060
+ if (displayWidth(gist) > maxGistWidth) {
11061
+ fittedGist = maxGistWidth > 0 ? truncateByDisplayWidth(gist, maxGistWidth) : "";
11062
+ }
11063
+ }
11064
+ const lineContent = fittedGist ? `\u25B8 ${label} \xB7 ${fittedGist}${statsInline}${tail}` : `\u25B8 ${label}${statsInline}${tail}`;
11065
+ const mainLine = formatToolTraceLine(fitNormalLine(lineContent.slice(0, -tail.length), tail, totalBudget), colorEnabled);
9784
11066
  if (hint?.detail?.length) {
9785
11067
  const filePath = typeof event.metadata?.path === "string" ? event.metadata.path : void 0;
9786
11068
  return `${mainLine}${formatEditDetailBlock(hint.detail, colorEnabled, filePath)}`;
@@ -9871,33 +11153,43 @@ var TUI_TREE_TOOLS = {
9871
11153
  Search: ["exa_search"],
9872
11154
  Fetch: ["fetchWebpage"]
9873
11155
  };
11156
+ function toolDetails(event, line) {
11157
+ const command = event.metadata?.command;
11158
+ return isRunToolName(event.toolName) && typeof command === "string" ? `${line}${safeApprovalMultilineText(command)}
11159
+ ` : line;
11160
+ }
9874
11161
  function createToolEventFormatter(colorEnabled = resolveCliColorEnabled(), opts = {}) {
9875
11162
  const pending = /* @__PURE__ */ new Map();
11163
+ let scope = 0;
9876
11164
  let tree = null;
9877
11165
  const treeKind = (name) => Object.keys(TUI_TREE_TOOLS).find((kind) => TUI_TREE_TOOLS[kind].includes(name)) ?? null;
9878
- const treeLine = (kind, items, fallback) => {
11166
+ const treeLine = (kind, items, fallback, details) => {
9879
11167
  const label = kind === "Run" ? toolLabel("execShell") : kind === "Read" ? toolLabel("readFile") : kind === "Fetch" ? toolLabel("fetchWebpage") : toolLabel("exa_search");
9880
11168
  const header = `${label} (${items.length}) \xB7 `;
9881
11169
  const columns = resolveHistoryLayoutGeometry(process.stdout.columns).contentWidth - displayWidth("\u25C8 ");
11170
+ const budget = Math.max(1, columns);
9882
11171
  let shown = 1;
9883
11172
  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;
11173
+ const suffix = count < items.length ? ", \u2026" : "";
11174
+ if (displayWidth(`\u25B8 ${header}${items.slice(0, count).join(", ")}${suffix} \u2713`) > budget) break;
9887
11175
  shown = count;
9888
11176
  }
9889
- const omitted = items.length - shown;
11177
+ const summary = fitNormalLine(`${header}${items.slice(0, shown).join(", ")}${shown < items.length ? ", \u2026" : ""}`, "\u2713", Math.max(1, budget - 2));
9890
11178
  const payload = {
9891
11179
  kind,
9892
- summary: `${header}${items.slice(0, shown).join(", ")}${omitted ? `, \u2026 +${omitted}` : ""} \u2713`,
9893
- fallback
11180
+ summary,
11181
+ fallback,
11182
+ details,
11183
+ previousRow: tree?.lastRow
9894
11184
  };
11185
+ if (tree) tree.lastRow = `\u25B8 ${summary}`;
9895
11186
  return `${TUI_TREE_MARKER}${JSON.stringify(payload)}${TUI_TREE_END}
9896
11187
  `;
9897
11188
  };
9898
11189
  const formatTreeEvent = (event, call) => {
11190
+ if (event.type === "tool-error") tree = null;
9899
11191
  if (!opts.tuiTrees || event.type !== "tool-result") return null;
9900
- if (isFailedToolResult(event) || event.metadata?.failed || event.metadata?.timedOut || readActionGate(event.metadata?.actionGate)) {
11192
+ if (isFailedToolResult(event) || event.metadata?.failed || event.metadata?.timedOut || readActionGate(event.metadata?.actionGate) || event.metadata?.permissionRequest) {
9901
11193
  tree = null;
9902
11194
  return null;
9903
11195
  }
@@ -9907,20 +11199,40 @@ function createToolEventFormatter(colorEnabled = resolveCliColorEnabled(), opts
9907
11199
  tree = null;
9908
11200
  return null;
9909
11201
  }
11202
+ const activity = projectToolActivity({
11203
+ key: event.toolCallId,
11204
+ toolName: name,
11205
+ args: event.metadata,
11206
+ state: "success",
11207
+ attention: [],
11208
+ mode: "ordinary",
11209
+ // Formatter lifecycle/reset is the real assistant-output boundary;
11210
+ // round comes from the execution stream, never from adjacent rows.
11211
+ scopeKey: `assistant:${scope}`,
11212
+ batchKey: Number.isInteger(event.round) && event.round >= 0 ? `round:${event.round}` : void 0,
11213
+ evidenceKey: event.toolCallId
11214
+ });
9910
11215
  let item = "";
9911
11216
  const m = event.metadata ?? {};
9912
11217
  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";
11218
+ item = activity.summary ?? (activity.confidence === "raw-fallback" ? clipCompactText(redactSecrets(activity.object ?? ""), 56, "\u2026") : [activity.action, activity.object].filter(Boolean).join(" "));
9915
11219
  }
9916
11220
  if (kind === "Read") item = formatReadItemPath(typeof m.path === "string" ? m.path : typeof m.filePath === "string" ? m.filePath : "file", m);
9917
11221
  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
11222
  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: [] };
11223
+ item = safeAskText(item) || toolLabel(name);
11224
+ if (tree?.kind !== kind || !canCoalesceToolActivities(tree.activity, activity)) tree = { kind, items: [], activity };
9921
11225
  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));
11226
+ if (tree.items.length < 2) {
11227
+ const line2 = formatNormalToolLine(event, call, colorEnabled, opts);
11228
+ tree.lastRow = stripAnsi(line2).trimEnd();
11229
+ const rawCommand = typeof m.command === "string" ? m.command : "";
11230
+ const runIdentity = kind === "Run" && activity.readOnly && rawCommand ? createHash2("sha256").update(rawCommand).digest("hex").slice(0, 16) : void 0;
11231
+ 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}
11232
+ `;
11233
+ }
11234
+ const line = formatNormalToolLine(event, call, colorEnabled, opts);
11235
+ return treeLine(kind, tree.items, line, toolDetails(event, line));
9924
11236
  };
9925
11237
  const format = (event) => {
9926
11238
  if (event.type === "tool-call") {
@@ -9934,10 +11246,16 @@ function createToolEventFormatter(colorEnabled = resolveCliColorEnabled(), opts
9934
11246
  pending.delete(event.toolCallId);
9935
11247
  const treeOutput = formatTreeEvent(event, call);
9936
11248
  if (treeOutput !== null) return treeOutput;
9937
- return formatNormalToolLine(event, call, colorEnabled, opts);
11249
+ const line = formatNormalToolLine(event, call, colorEnabled, opts);
11250
+ if (opts.tuiTrees && line && isRunToolName(event.toolName)) {
11251
+ return `${TUI_TREE_MARKER}${JSON.stringify({ kind: "Run", summary: "", fallback: line, details: toolDetails(event, line), appendOnly: true })}${TUI_TREE_END}
11252
+ `;
11253
+ }
11254
+ return line;
9938
11255
  };
9939
11256
  format.reset = () => {
9940
11257
  tree = null;
11258
+ scope++;
9941
11259
  };
9942
11260
  format.consume = (event) => {
9943
11261
  if (event.type === "tool-call") {
@@ -10185,10 +11503,6 @@ function shouldPromoteTuiNarration(text) {
10185
11503
  if (text.length >= TUI_PROGRESS_BUFFER_LIMIT) return true;
10186
11504
  return /(^|\n)\s*(?:#{1,3}\s|```|[-*+]\s|\d+[.)]\s)/.test(text);
10187
11505
  }
10188
- function narrationActivityLabel(text) {
10189
- const oneLine = stripAnsi(text).replace(/[`*_#>]/g, "").replace(/\s+/g, " ").trim();
10190
- return truncateThinkingHint(oneLine, 60);
10191
- }
10192
11506
  function createCliTurnOutput(params) {
10193
11507
  const { options } = params;
10194
11508
  const workingLabel = params.workingLabel ?? `${options.agentName} -> working`;
@@ -10201,12 +11515,7 @@ function createCliTurnOutput(params) {
10201
11515
  const assistantLabelManaged = options.output.assistantLabelManaged === true;
10202
11516
  const showThinking = !assistantLabelManaged && options.showThinking !== false;
10203
11517
  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;
11518
+ return false;
10210
11519
  };
10211
11520
  let streamedAssistantText = false;
10212
11521
  let everStreamedAnyText = false;
@@ -10280,11 +11589,6 @@ function createCliTurnOutput(params) {
10280
11589
  streamedAssistantText = true;
10281
11590
  options.activityReporter?.(null);
10282
11591
  };
10283
- const dropPendingTuiProgress = () => {
10284
- pendingTuiNarration = "";
10285
- tuiNarrationPromoted = false;
10286
- options.activityReporter?.(null);
10287
- };
10288
11592
  const writeVisibleAssistantChunk = (chunk) => {
10289
11593
  if (!chunk) return;
10290
11594
  if (!assistantLabelManaged) formatToolEvent.reset?.();
@@ -10303,6 +11607,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10303
11607
  }
10304
11608
  printedAssistantLabel = true;
10305
11609
  }
11610
+ if (assistantLabelManaged) options.activityReporter?.(t("generatingReply"));
10306
11611
  everStreamedAnyText = true;
10307
11612
  if (assistantLabelManaged) {
10308
11613
  if (tuiNarrationPromoted) {
@@ -10314,8 +11619,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10314
11619
  if (shouldPromoteTuiNarration(pendingTuiNarration)) {
10315
11620
  flushPendingTuiNarration();
10316
11621
  } else {
10317
- const label = narrationActivityLabel(pendingTuiNarration);
10318
- if (label) options.activityReporter?.(label);
11622
+ options.activityReporter?.(t("generatingReply"));
10319
11623
  }
10320
11624
  return;
10321
11625
  }
@@ -10336,7 +11640,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10336
11640
  }
10337
11641
  if (event.type === "tool-call") {
10338
11642
  if (assistantLabelManaged && pendingTuiNarration) {
10339
- dropPendingTuiProgress();
11643
+ flushPendingTuiNarration();
10340
11644
  }
10341
11645
  renderWriter.flush();
10342
11646
  if (!hidesRoutineTuiToolDetail(event)) {
@@ -10377,12 +11681,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10377
11681
  /**
10378
11682
  * Terminal cleanup for abort/error paths that never reach `finish()`.
10379
11683
  *
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.
11684
+ * Preserve original prose on both abort and transport failure.
10386
11685
  */
10387
11686
  cancel(cleanup) {
10388
11687
  if (assistantLabelManaged && cleanup?.preservePendingNarration) {
@@ -10392,7 +11691,8 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10392
11691
  options.output.write("\n");
10393
11692
  }
10394
11693
  }
10395
- dropPendingTuiProgress();
11694
+ flushPendingTuiNarration();
11695
+ renderWriter.flush();
10396
11696
  },
10397
11697
  pushText(chunk) {
10398
11698
  writeVisibleAssistantChunk(chunk);
@@ -10969,57 +12269,9 @@ function isBalanceExhaustedError(error) {
10969
12269
  return matchesBalanceError(message);
10970
12270
  }
10971
12271
 
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
12272
  // packages/cli/client/agentRun.ts
11021
12273
  async function loadRunLocalAgentTurn() {
11022
- const { runLocalAgentTurn } = await import("./agentRuntimeLocal-SD7U2EGY.js");
12274
+ const { runLocalAgentTurn } = await import("./agentRuntimeLocal-TU4LA353.js");
11023
12275
  return runLocalAgentTurn;
11024
12276
  }
11025
12277
  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 +12703,9 @@ function isStandaloneResetSentence(text, index) {
11451
12703
  var RATE_LIMIT_DETAIL_MAX_CHARS = 140;
11452
12704
  var UPSTREAM_TAG_MAX_CHARS = 64;
11453
12705
  function findJsonObjectEnd(text, from) {
11454
- const open = text[from];
11455
- if (open !== "{" && open !== "[") return -1;
11456
- const close = open === "{" ? "}" : "]";
12706
+ const open2 = text[from];
12707
+ if (open2 !== "{" && open2 !== "[") return -1;
12708
+ const close = open2 === "{" ? "}" : "]";
11457
12709
  let depth = 0;
11458
12710
  let inString = false;
11459
12711
  let escaped = false;
@@ -11466,7 +12718,7 @@ function findJsonObjectEnd(text, from) {
11466
12718
  continue;
11467
12719
  }
11468
12720
  if (ch === '"') inString = true;
11469
- else if (ch === open) depth += 1;
12721
+ else if (ch === open2) depth += 1;
11470
12722
  else if (ch === close) {
11471
12723
  depth -= 1;
11472
12724
  if (depth === 0) return i + 1;
@@ -11814,6 +13066,10 @@ function describeLocalRunFailure(message, rawError) {
11814
13066
  }
11815
13067
  if (isMissingBatchReceiptFailure(message)) {
11816
13068
  return `[nolo] ${describeMissingBatchReceipt()}.
13069
+ `;
13070
+ }
13071
+ if (/\bimage_model_unsupported\b/.test(message)) {
13072
+ return `[nolo] ${message}. ${NO_FALLBACK} Check the selected model's image capability or use a model known to support images.
11817
13073
  `;
11818
13074
  }
11819
13075
  const cls = classifyLocalRunError(message);
@@ -12163,6 +13419,17 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12163
13419
  options.modelOverride
12164
13420
  ) : resolvedBaseAdapter;
12165
13421
  if (adapter2) adapter2 = applyEphemeralIfRequested(options, adapter2);
13422
+ if (adapter2 && options.imageUrls?.length) {
13423
+ const imageAdapter = adapter2;
13424
+ adapter2 = { ...imageAdapter, loadAgentConfig: async (agentRef) => {
13425
+ const config = await imageAdapter.loadAgentConfig(agentRef);
13426
+ if (!config) return config;
13427
+ if (!resolveAgentImageInputSupport({ ...config, hasVision: config.hasVision ?? false })) {
13428
+ throw new Error("image_model_unsupported: child model image capability is unsupported or unknown");
13429
+ }
13430
+ return config;
13431
+ } };
13432
+ }
12166
13433
  return adapter2;
12167
13434
  })();
12168
13435
  if (!baseAdapter) {
@@ -12189,12 +13456,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12189
13456
  } : void 0;
12190
13457
  const currentDialogId = options.continueDialogId ?? ulid2();
12191
13458
  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
13459
  const turnId = `turn-${ulid2()}`;
12199
13460
  const runtimeContextWithOwnership = {
12200
13461
  ...runtimeContext ?? {},
@@ -12202,80 +13463,8 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12202
13463
  turnId,
12203
13464
  getProcessCausalDepth: options.getProcessCausalDepth
12204
13465
  };
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
13466
  const commandVersionBindings = /* @__PURE__ */ new Map();
12219
13467
  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
13468
  let batchProviderStarted = false;
12280
13469
  let mainProviderStarted = false;
12281
13470
  let refusalModel = "";
@@ -12298,9 +13487,9 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12298
13487
  }
12299
13488
  };
12300
13489
  const adapter = {
12301
- ...hostTask.adapter,
13490
+ ...commandAdapter,
12302
13491
  resolveProvider: async (...args) => {
12303
- const provider = await hostTask.adapter.resolveProvider(...args);
13492
+ const provider = await commandAdapter.resolveProvider(...args);
12304
13493
  const isTextOnly = Boolean(args[1]?.textOnly);
12305
13494
  if (!isTextOnly) refusalModel = provider.model;
12306
13495
  return {
@@ -12317,26 +13506,8 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12317
13506
  }
12318
13507
  };
12319
13508
  },
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
- },
13509
+ // 工具执行直接走 ...commandAdapter 展开(无需再写一行透传)。
12338
13510
  saveTurn: async (input) => {
12339
- if (usedReviewTool && options.hostTaskRef) await settleHostReviewsForScope(options.hostTaskRef, options.env, options.hostReviewContentAcceptance);
12340
13511
  const completeBatch = Boolean(batchIdentity && batchProviderStarted && !input.result.error);
12341
13512
  const injectedBatches = options.drainInjectedBatches ?? [];
12342
13513
  const injectedMessageIds = new Set(injectedBatches.flatMap((batch) => batch.messageIds));
@@ -12345,8 +13516,11 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12345
13516
  ...!input.result.error ? injectedBatches.map((batch) => batch.batchId) : []
12346
13517
  ];
12347
13518
  try {
12348
- const saved = await hostTask.adapter.saveTurn({
13519
+ const saved = await commandAdapter.saveTurn({
12349
13520
  ...input,
13521
+ // Receipt-backed user rows are excluded below to avoid duplicate persistence.
13522
+ // Keep their explicit identities for post-sync native memory capture.
13523
+ ...{ cliCaptureUserMessageIds: input.messages.filter((message) => message.role === "user").map((message) => message.cliMessageId).filter((id) => typeof id === "string") },
12350
13524
  messages: input.messages.filter((message) => {
12351
13525
  const cliMessageId = message.cliMessageId;
12352
13526
  if (!cliMessageId) return true;
@@ -12393,7 +13567,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12393
13567
  const runLocalAgentTurn = await loadRunLocalAgentTurn();
12394
13568
  const result = await runLocalAgentTurn({
12395
13569
  adapter,
12396
- ...hostTask.contract ? { taskExecutionContract: hostTask.contract } : {},
12397
13570
  agentRef: options.agentKey,
12398
13571
  userLanguage: options.userLanguage ?? options.env.NOLO_LANG ?? null,
12399
13572
  input: buildUserInputContent(messageForLocal, options.imageUrls),
@@ -12486,8 +13659,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12486
13659
  mainProviderAttempted: mainProviderStarted,
12487
13660
  exitCode: 0,
12488
13661
  stopReason: result.stopReason,
12489
- ...hostTask.result(),
12490
- ...options.hostTaskRef ? { hostTaskRef: options.hostTaskRef } : {},
12491
13662
  dialogId: result.dialogId,
12492
13663
  ...typeof result.content === "string" && result.content.trim() ? { finalText: result.content } : {},
12493
13664
  ...result.title !== void 0 ? { title: result.title } : {},
@@ -12525,10 +13696,8 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12525
13696
  const pendingToolName = error?.pendingToolName;
12526
13697
  return retainCommandObservations({
12527
13698
  exitCode: 0,
12528
- ...hostTask.result(),
12529
13699
  savedTurnPersisted: turnPersisted,
12530
13700
  mainProviderAttempted: mainProviderStarted,
12531
- ...options.hostTaskRef ? { hostTaskRef: options.hostTaskRef } : {},
12532
13701
  streamInterrupted: true,
12533
13702
  ...savedDialogId ? { dialogId: savedDialogId } : {},
12534
13703
  ...pendingToolName ? { pendingToolName } : {},
@@ -12574,7 +13743,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12574
13743
  }
12575
13744
  return retainCommandObservations({
12576
13745
  exitCode: 1,
12577
- ...hostTask.result(),
12578
13746
  localError: error,
12579
13747
  savedTurnPersisted: persisted,
12580
13748
  mainProviderAttempted: mainProviderStarted,
@@ -12642,7 +13810,6 @@ function foldLocalResultForTui(localResult) {
12642
13810
  const folded = {
12643
13811
  exitCode: localResult.exitCode,
12644
13812
  ...projectLocalTurnFacts(localResult),
12645
- ...localResult.hostTaskRef ? { hostTaskRef: localResult.hostTaskRef } : {},
12646
13813
  ...localResult.dialogId ? { dialogId: localResult.dialogId } : {},
12647
13814
  title: localResult.title,
12648
13815
  ...localResult.titlePatchPromise ? { titlePatchPromise: localResult.titlePatchPromise } : {},
@@ -12986,7 +14153,7 @@ function buildHostEnvironmentLayer(options) {
12986
14153
 
12987
14154
  // packages/agent-runtime/agentsMd.ts
12988
14155
  import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
12989
- import { resolve as resolve4 } from "node:path";
14156
+ import { resolve as resolve3 } from "node:path";
12990
14157
  var AGENTS_MD_MAX_BYTES = 8192;
12991
14158
  var AGENTS_MD_MARKER_RESERVE_BYTES = 512;
12992
14159
  var AGENTS_MD_CANDIDATES = ["AGENTS.md", "CLAUDE.md"];
@@ -13187,7 +14354,7 @@ ${entry.line}`;
13187
14354
  };
13188
14355
  function readAgentsMdLayerFromDisk(cwd) {
13189
14356
  for (const name of AGENTS_MD_CANDIDATES) {
13190
- const filePath = resolve4(cwd, name);
14357
+ const filePath = resolve3(cwd, name);
13191
14358
  if (!existsSync2(filePath)) continue;
13192
14359
  try {
13193
14360
  const raw = readFileSync3(filePath, "utf8");
@@ -13329,16 +14496,16 @@ function runDoDCommands(commands, cwd, deps = {}) {
13329
14496
 
13330
14497
  // packages/cli/agentRunPrompts.ts
13331
14498
  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";
14499
+ import { dirname, extname, isAbsolute as isAbsolute2, join as join2, relative as relativePath, resolve as resolve4, sep } from "node:path";
13333
14500
  function workflowRefToCandidatePath(cwd, ref) {
13334
14501
  const normalized = ref.trim();
13335
14502
  if (!normalized) return "";
13336
14503
  if (normalized.endsWith(".md") || normalized.includes("/") || normalized.includes("\\")) {
13337
- const directPath = resolve5(cwd, normalized);
14504
+ const directPath = resolve4(cwd, normalized);
13338
14505
  if (existsSync3(directPath)) return directPath;
13339
14506
  }
13340
14507
  const fileName = normalized.replace(/[^a-zA-Z0-9一-鿿]+/g, "-").replace(/^-+|-+$/g, "");
13341
- return resolve5(cwd, "docs", "workflows", `${fileName}.md`);
14508
+ return resolve4(cwd, "docs", "workflows", `${fileName}.md`);
13342
14509
  }
13343
14510
  var SKILL_SEARCH_DIRS = [
13344
14511
  ".agents/skills"
@@ -13347,15 +14514,15 @@ function skillRefToCandidatePath(cwd, ref) {
13347
14514
  const normalized = ref.trim();
13348
14515
  if (!normalized) return "";
13349
14516
  if (normalized.endsWith(".md") || normalized.includes("/") || normalized.includes("\\")) {
13350
- const directPath = resolve5(cwd, normalized);
14517
+ const directPath = resolve4(cwd, normalized);
13351
14518
  if (existsSync3(directPath)) return directPath;
13352
14519
  }
13353
14520
  const fileName = normalized.replace(/[^a-zA-Z0-9一-鿿]+/g, "-").replace(/^-+|-+$/g, "");
13354
14521
  for (const dir of SKILL_SEARCH_DIRS) {
13355
- const skillMdPath = resolve5(cwd, dir, fileName, "SKILL.md");
14522
+ const skillMdPath = resolve4(cwd, dir, fileName, "SKILL.md");
13356
14523
  if (existsSync3(skillMdPath)) return skillMdPath;
13357
14524
  }
13358
- return resolve5(cwd, ".agents", "skills", fileName, "SKILL.md");
14525
+ return resolve4(cwd, ".agents", "skills", fileName, "SKILL.md");
13359
14526
  }
13360
14527
  async function resolveWorkflowReference(ref, cwd = process.cwd()) {
13361
14528
  const path2 = workflowRefToCandidatePath(cwd, ref);
@@ -13372,11 +14539,11 @@ async function resolveWorkflowReference(ref, cwd = process.cwd()) {
13372
14539
  }
13373
14540
  function inlineRelativeRefs(body, skillDir) {
13374
14541
  const refPattern = /\[([^\]]+)\]\((\.\/[^)]+|[^)]+\/[^)]+)\)/g;
13375
- const normalizedSkillDir = resolve5(skillDir) + sep;
14542
+ const normalizedSkillDir = resolve4(skillDir) + sep;
13376
14543
  return body.replace(refPattern, (match, label, relPath) => {
13377
14544
  const cleaned = relPath.trim();
13378
14545
  if (!cleaned.startsWith("./") && !cleaned.startsWith("../")) return match;
13379
- const absPath = resolve5(skillDir, cleaned);
14546
+ const absPath = resolve4(skillDir, cleaned);
13380
14547
  const relative = relativePath(normalizedSkillDir, absPath);
13381
14548
  if (relative.startsWith("..") || isAbsolute2(relative)) return match;
13382
14549
  if (!existsSync3(absPath) || !absPath.endsWith(".md")) return match;
@@ -13526,7 +14693,7 @@ function prependSubjectDialogMarker(message, subjectDialogKey) {
13526
14693
  }
13527
14694
  function normalizeCliImageInput(input) {
13528
14695
  if (/^(https?:|data:|file:)/i.test(input)) return input;
13529
- const absolutePath = resolve5(input);
14696
+ const absolutePath = resolve4(input);
13530
14697
  if (!existsSync3(absolutePath)) return input;
13531
14698
  const base64 = readFileSync4(absolutePath).toString("base64");
13532
14699
  return `data:${imageMimeTypeForPath(absolutePath)};base64,${base64}`;
@@ -13545,22 +14712,6 @@ function imageMimeTypeForPath(path2) {
13545
14712
  }
13546
14713
  }
13547
14714
 
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
14715
  // packages/ai/memory/vnext/detachedThrottle.ts
13565
14716
  var DEFAULT_DETACHED_MEMORY_COOLDOWN_MS = 10 * 60 * 1e3;
13566
14717
  var MAX_COOLDOWN_KEYS = 512;
@@ -13609,6 +14760,73 @@ var createDetachedThrottle = (input) => {
13609
14760
  };
13610
14761
  };
13611
14762
 
14763
+ // packages/ai/memory/vnext/recallBudget.ts
14764
+ var DEFAULT_DEEP_MEMORY_TOKENS = DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET;
14765
+ var resolveMemoryBudget = (value) => {
14766
+ const budget = value ?? DEFAULT_DEEP_MEMORY_TOKENS;
14767
+ if (!Number.isSafeInteger(budget) || budget < 512) {
14768
+ throw new Error("memory budget must be a safe integer >= 512 estimated tokens");
14769
+ }
14770
+ return budget;
14771
+ };
14772
+ var clipMemoryText = (text, maxTokens) => {
14773
+ if (estimateTokenCount(text) <= maxTokens) return text;
14774
+ const suffix = "\u2026[truncated]";
14775
+ if (estimateTokenCount(suffix) > maxTokens) return "";
14776
+ let lo = 0;
14777
+ let hi = text.length;
14778
+ while (lo < hi) {
14779
+ const mid = Math.ceil((lo + hi) / 2);
14780
+ if (estimateTokenCount(text.slice(0, mid) + suffix) <= maxTokens) lo = mid;
14781
+ else hi = mid - 1;
14782
+ }
14783
+ if (lo && /[\uD800-\uDBFF]/.test(text[lo - 1])) lo--;
14784
+ return text.slice(0, lo) + suffix;
14785
+ };
14786
+ var DESCRIPTIVE_FIELDS = /* @__PURE__ */ new Set(["text", "name", "facet", "subtype", "value", "aliases"]);
14787
+ var compactMemoryRow = (row, fieldTokens = 128) => Object.fromEntries(Object.entries(row).map(([key, value]) => [
14788
+ key,
14789
+ DESCRIPTIVE_FIELDS.has(key) && estimateTokenCount(typeof value === "string" ? value : JSON.stringify(value) ?? "") > fieldTokens ? clipMemoryText(typeof value === "string" ? value : JSON.stringify(value) ?? "", fieldTokens) : value
14790
+ ]));
14791
+ var memoryMessageTokens = (messages) => messages.reduce((sum, message) => sum + estimateTokenCount(message.content) + 8, 0);
14792
+ var buildBudgetedMemoryInput = (input) => {
14793
+ const maxTokens = resolveMemoryBudget(input.maxTokens);
14794
+ const query = clipMemoryText(input.query, Math.floor(maxTokens / 4));
14795
+ const rows = [];
14796
+ const messages = () => [
14797
+ { 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." },
14798
+ { role: "user", content: `Query:
14799
+ ${query}
14800
+
14801
+ Memory catalog:
14802
+ ${JSON.stringify({ candidates: rows })}` }
14803
+ ];
14804
+ if (memoryMessageTokens(messages()) > maxTokens) {
14805
+ throw new Error("memory budget cannot fit instructions and query");
14806
+ }
14807
+ let clipped = false;
14808
+ for (const original of input.rows) {
14809
+ const row = compactMemoryRow(original);
14810
+ rows.push(row);
14811
+ if (memoryMessageTokens(messages()) > maxTokens) rows.pop();
14812
+ else if (JSON.stringify(row) !== JSON.stringify(original)) clipped = true;
14813
+ }
14814
+ const result = messages();
14815
+ return {
14816
+ messages: result,
14817
+ rows,
14818
+ budget: {
14819
+ maxTokens,
14820
+ usedTokens: memoryMessageTokens(result),
14821
+ truncated: clipped || rows.length !== input.rows.length || query !== input.query,
14822
+ queryTruncated: query !== input.query,
14823
+ offeredCandidates: rows.length,
14824
+ totalCandidates: input.rows.length,
14825
+ omittedCandidates: input.rows.length - rows.length
14826
+ }
14827
+ };
14828
+ };
14829
+
13612
14830
  // packages/ai/memory/vnext/recall.ts
13613
14831
  var MAX_RECALL_REFS = 6;
13614
14832
  var stripFence = (raw) => {
@@ -13638,76 +14856,84 @@ var parseSelection = (raw) => {
13638
14856
  reason: obj.reason
13639
14857
  };
13640
14858
  };
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
14859
  var createMemoryVNextRecall = (input) => async (query) => {
13665
14860
  const startedAt = performance.now();
14861
+ const maxTokens = resolveMemoryBudget(input.maxInputTokens);
13666
14862
  const { entities, states } = await loadMemoryVNextCatalog(input.db, input.ownerId);
13667
- if (entities.length === 0 && states.length === 0) {
14863
+ if (!query.trim() || entities.length === 0 && states.length === 0) {
13668
14864
  return {
13669
14865
  query,
13670
14866
  refs: [],
13671
14867
  entities: [],
13672
14868
  states: [],
13673
- reason: "memory catalog is empty",
14869
+ reason: query.trim() ? "memory catalog is empty" : "query is empty",
13674
14870
  trace: {
13675
14871
  candidateEntities: 0,
13676
14872
  candidateStates: 0,
13677
14873
  selectedRefs: 0,
14874
+ budget: {
14875
+ maxTokens,
14876
+ usedTokens: 0,
14877
+ truncated: false,
14878
+ offeredCandidates: 0,
14879
+ totalCandidates: entities.length + states.length,
14880
+ omittedCandidates: entities.length + states.length
14881
+ },
13678
14882
  elapsedMs: Math.round((performance.now() - startedAt) * 10) / 10
13679
14883
  }
13680
14884
  };
13681
14885
  }
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
- }
14886
+ const hits = recallMemoryVNextLocal({ query, entities, states, limit: states.length });
14887
+ const priority = new Set(hits.flatMap(({ state: state2 }) => [state2.id, state2.entityId]));
14888
+ const rankedStates = [
14889
+ ...hits.map(({ state: state2 }) => state2),
14890
+ ...states.filter((state2) => !priority.has(state2.id)).sort((a, b) => a.id.localeCompare(b.id))
14891
+ ];
14892
+ const rankedEntities = [...entities].sort((a, b) => Number(priority.has(b.id)) - Number(priority.has(a.id)) || a.id.localeCompare(b.id));
14893
+ const stateRows = rankedStates.map((state2) => ({
14894
+ kind: "state",
14895
+ id: state2.id,
14896
+ entityId: state2.entityId,
14897
+ facet: state2.facet,
14898
+ text: state2.text,
14899
+ ...state2.retiredAt ? { retired: true } : {}
14900
+ }));
14901
+ const entityRows = rankedEntities.map((entity) => ({
14902
+ kind: "entity",
14903
+ id: entity.id,
14904
+ type: entity.type,
14905
+ name: entity.name,
14906
+ ...entity.subtype ? { subtype: entity.subtype } : {},
14907
+ ...entity.aliases?.length ? { aliases: entity.aliases } : {}
14908
+ }));
14909
+ const request = buildBudgetedMemoryInput({
14910
+ query,
14911
+ maxTokens: input.maxInputTokens,
14912
+ rows: [
14913
+ ...stateRows.filter((row) => priority.has(row.id)),
14914
+ ...entityRows.filter((row) => priority.has(row.id)),
14915
+ ...stateRows.filter((row) => !priority.has(row.id)),
14916
+ ...entityRows.filter((row) => !priority.has(row.id))
13704
14917
  ],
14918
+ system: [
14919
+ "Select the smallest useful set of long-lived memory entrances for the user query.",
14920
+ 'Return ONLY JSON: {"refs":["exact-id"],"reason":"short explanation"}.',
14921
+ `Select at most ${MAX_RECALL_REFS} exact ids from the supplied catalog.`,
14922
+ "Prefer current State ids; retired States are history entrances, not current facts.",
14923
+ "Select an Entity when it is a useful navigation anchor.",
14924
+ "Do not select unrelated memories merely because they are personal or interesting.",
14925
+ "Historical questions may select a relevant entrance; deeper evidence is handled by inspect."
14926
+ ].join("\n")
14927
+ });
14928
+ const result = await input.provider.complete(
14929
+ request.messages,
13705
14930
  input.timeoutMs ? { timeoutMs: input.timeoutMs } : void 0
13706
14931
  );
13707
14932
  const selected = parseSelection(result.content);
13708
14933
  const entityById = new Map(entities.map((entity) => [entity.id, entity]));
13709
14934
  const stateById = new Map(states.map((state2) => [state2.id, state2]));
13710
- const validRefs = selected.refs.filter((ref) => entityById.has(ref) || stateById.has(ref));
14935
+ const offered = new Set(request.rows.map((row) => row.id));
14936
+ const validRefs = selected.refs.filter((ref) => offered.has(ref) && (entityById.has(ref) || stateById.has(ref)));
13711
14937
  return {
13712
14938
  query,
13713
14939
  refs: validRefs,
@@ -13724,6 +14950,7 @@ ${catalogText(entities, states)}`
13724
14950
  candidateEntities: entities.length,
13725
14951
  candidateStates: states.length,
13726
14952
  selectedRefs: validRefs.length,
14953
+ budget: request.budget,
13727
14954
  elapsedMs: Math.round((performance.now() - startedAt) * 10) / 10
13728
14955
  }
13729
14956
  };
@@ -13879,235 +15106,6 @@ var runMemoryVNextShadowRead = async (input) => {
13879
15106
  };
13880
15107
  var isMemoryVNextShadowReadEnabled = (env = typeof process !== "undefined" ? process.env : {}) => env.NOLO_MEMORY_VNEXT_SHADOW_READ === "1" || env.NOLO_MEMORY_VNEXT_SHADOW_READ === "true";
13881
15108
 
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
15109
  // packages/ai/memory/vnext/legacyMigrationApply.ts
14112
15110
  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
15111
  var applyLegacyMemoryEvidence = async (db, item) => {
@@ -14725,75 +15723,10 @@ var isMemoryVNextLazyPromotionEnabled = (env = typeof process !== "undefined" ?
14725
15723
  // packages/ai/memory/vnext/pureReadGate.ts
14726
15724
  var isMemoryVNextPureReadEnabled = (env = typeof process !== "undefined" ? process.env : {}) => env.NOLO_MEMORY_VNEXT_PURE_READ === "1" || env.NOLO_MEMORY_VNEXT_PURE_READ === "true";
14727
15725
 
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
15726
  // packages/ai/memory/vnext/primaryRead.ts
14794
15727
  var MEMORY_VNEXT_PRIMARY_READ_TIMEOUT_MS = 300;
14795
15728
  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) => ({
15729
+ var buildSynthesizedStateItem = (state2, entity, ownerType, ownerId) => ({
14797
15730
  id: `vnext-state-${state2.id}`,
14798
15731
  ownerType,
14799
15732
  ownerId,
@@ -14805,8 +15738,9 @@ var buildSynthesizedStateItem2 = (state2, entity, ownerType, ownerId) => ({
14805
15738
  createdAt: state2.createdAt,
14806
15739
  importance: 0.9,
14807
15740
  confidence: 0.9,
14808
- // Flag resident preferences so they flow into overlay's resident section.
14809
- resident: state2.facet === "preference" || state2.facet === "style",
15741
+ // 与 pureVNextRuntime / queryMemoryHandler 共用同一判定,避免四条合成路径分裂
15742
+ // (2026-11-15:这里原先各自写 facet,漏了 ownerType/长度约束)。
15743
+ resident: deriveStateResident(state2, ownerType),
14810
15744
  lastActivatedAt: state2.createdAt,
14811
15745
  activationCount: 1
14812
15746
  });
@@ -14838,7 +15772,7 @@ var resolveMemoryVNextM4Selection = async (input) => {
14838
15772
  if (recalledStateIds.has(hit.state.id)) continue;
14839
15773
  recalledStateIds.add(hit.state.id);
14840
15774
  recalledStates.push(
14841
- buildSynthesizedStateItem2(hit.state, entityById.get(hit.state.entityId), owner.ownerType, owner.ownerId)
15775
+ buildSynthesizedStateItem(hit.state, entityById.get(hit.state.entityId), owner.ownerType, owner.ownerId)
14842
15776
  );
14843
15777
  }
14844
15778
  }
@@ -14858,6 +15792,10 @@ var resolveMemoryVNextM4Selection = async (input) => {
14858
15792
  const renderItems = [...recalledStates, ...uncoveredLegacy];
14859
15793
  return {
14860
15794
  renderItems,
15795
+ sources: new Map([
15796
+ ...recalledStates.map((item) => [item, "vnext"]),
15797
+ ...uncoveredLegacy.map((item) => [item, "legacy-uncovered"])
15798
+ ]),
14861
15799
  recalledStateCount: recalledStates.length,
14862
15800
  uncoveredLegacyCount: uncoveredLegacy.length,
14863
15801
  coveredSuppressedCount
@@ -14979,245 +15917,282 @@ var selectRuntimeMemoryItems = (items, context, userInput = "") => {
14979
15917
  return selected;
14980
15918
  };
14981
15919
  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) => {
15920
+ const configuredPure = isMemoryVNextPureReadEnabled();
15921
+ const configuredPrimary = isMemoryVNextPrimaryReadEnabled();
15922
+ let branch = "no_owner";
15923
+ let outcome = "error";
15924
+ let errorKind = "runtime_error";
15925
+ let fallbackKind = "none";
15926
+ let injection = emptyMemoryInjectionObservation();
15927
+ const injectionEmit = (observation) => {
15928
+ injection = observation;
15929
+ };
15930
+ const finish = (result) => {
15931
+ outcome = fallbackKind === "none" ? result.promptBlock ? "result" : "empty" : "fallback";
15932
+ errorKind = fallbackKind;
15933
+ return result;
15934
+ };
15935
+ try {
15936
+ const owners = chooseMemoryOwners({
15937
+ userId: input.userId,
15938
+ spaceId: input.spaceId
15939
+ });
15940
+ if (owners.length === 0) {
15941
+ return finish({ selectedItems: [], promptBlock: null });
15942
+ }
15943
+ if (configuredPure) {
15944
+ branch = "pure";
15945
+ const pureStartedAt = performance.now();
15946
+ let pure;
15947
+ let pureFailed = false;
15006
15948
  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
15949
+ pure = await resolvePureVNextRuntime({
15950
+ db: input.db,
15951
+ owners,
15952
+ userInput: input.userInput,
15953
+ maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET,
15954
+ injectionEmit
15955
+ });
15956
+ } catch (error) {
15957
+ pureFailed = true;
15958
+ pure = { selectedItems: [], promptBlock: null, recalledStateCount: 0 };
15959
+ }
15960
+ const pureLatencyMs = Math.round((performance.now() - pureStartedAt) * 10) / 10;
15961
+ const emitPureRead = (observation) => {
15962
+ try {
15963
+ if (input.pureReadEmit) {
15964
+ input.pureReadEmit(observation);
15965
+ } else if (input.primaryReadEmit) {
15966
+ input.primaryReadEmit({
15967
+ source: observation.source === "vnext" ? "vnext" : "none",
15968
+ legacyHitCount: 0,
15969
+ recalledStateCount: observation.vnextItemCount,
15970
+ vnextLatencyMs: observation.vnextLatencyMs,
15971
+ legacyLatencyMs: 0,
15972
+ contextChars: observation.contextChars,
15973
+ fallbackReason: observation.fallbackReason,
15974
+ error: observation.error
15975
+ });
15976
+ } else {
15977
+ console.info("[memory] vnext pure read", {
15978
+ event: "memory_vnext_pure_read",
15979
+ ...observation
15980
+ });
15981
+ }
15982
+ } catch {
15983
+ }
15984
+ };
15985
+ if (pureFailed) {
15986
+ emitPureRead({
15987
+ source: "none",
15988
+ itemCount: 0,
15989
+ vnextItemCount: 0,
15990
+ vnextLatencyMs: pureLatencyMs,
15991
+ contextChars: 0,
15992
+ fallbackReason: "vnext_error",
15993
+ error: "runtime_error"
15994
+ });
15995
+ } else if (pure.selectedItems.length === 0) {
15996
+ emitPureRead({
15997
+ source: "none",
15998
+ itemCount: 0,
15999
+ vnextItemCount: 0,
16000
+ vnextLatencyMs: pureLatencyMs,
16001
+ contextChars: 0,
16002
+ fallbackReason: "no_vnext_context"
16003
+ });
16004
+ } else {
16005
+ emitPureRead({
16006
+ source: "vnext",
16007
+ itemCount: pure.selectedItems.length,
16008
+ vnextItemCount: pure.recalledStateCount,
16009
+ vnextLatencyMs: pureLatencyMs,
16010
+ contextChars: pure.promptBlock?.length ?? 0
16011
+ });
16012
+ }
16013
+ const lazyPromotionEnabled2 = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
16014
+ if (lazyPromotionEnabled2) {
16015
+ void (async () => {
16016
+ const ownerItems = await Promise.all(
16017
+ owners.map(
16018
+ (owner) => loadOwnerItemsFromDb(
16019
+ input.db,
16020
+ owner,
16021
+ input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT
16022
+ )
16023
+ )
16024
+ );
16025
+ const legacyCandidates = ownerItems.flat();
16026
+ if (legacyCandidates.length > 0) {
16027
+ const promotionPick = await pickFirstUncoveredLazyPromotionItem(
16028
+ input.db,
16029
+ legacyCandidates
16030
+ );
16031
+ if (promotionPick) {
16032
+ await runMemoryVNextLazyPromotion({
16033
+ db: input.db,
16034
+ item: promotionPick.item,
16035
+ selectedIndex: promotionPick.selectedIndex,
16036
+ skippedCoveredCount: promotionPick.skippedCoveredCount,
16037
+ skippedNoOpCount: promotionPick.skippedNoOpCount,
16038
+ provider: input.vNextShadowProvider,
16039
+ ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
16040
+ });
16041
+ }
16042
+ }
16043
+ })().catch(() => {
16044
+ });
16045
+ }
16046
+ const result = finish({ selectedItems: pure.selectedItems, promptBlock: pure.promptBlock });
16047
+ if (pureFailed) {
16048
+ outcome = "error";
16049
+ errorKind = "runtime_error";
16050
+ }
16051
+ return result;
16052
+ }
16053
+ branch = "legacy";
16054
+ const policy = resolveAgentMemoryPolicy({ agentKey: input.agentKey });
16055
+ const legacyStartedAt = performance.now();
16056
+ const candidates = await loadMemoryCandidatesFromDb(input.db, {
16057
+ owners,
16058
+ subjects: buildMemorySubjectsForAgent({
16059
+ userId: input.userId,
16060
+ spaceId: input.spaceId,
16061
+ agentKey: input.agentKey,
16062
+ memorySubjectId: input.memorySubjectId,
16063
+ policy
16064
+ }),
16065
+ kinds: ["episodic", "semantic", "procedural"],
16066
+ ownerLimit: input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT,
16067
+ ownerFallback: policy.ownerFallback,
16068
+ corroboratedProceduralReserve: input.corroboratedProceduralReserve ?? CORROBORATED_PROCEDURAL_RESERVE
16069
+ });
16070
+ const rankContext = {
16071
+ currentOwner: input.spaceId ? { ownerType: "space", ownerId: input.spaceId } : input.userId ? { ownerType: "user", ownerId: input.userId } : null,
16072
+ currentSubject: input.spaceId ? { subjectType: "space", subjectId: input.spaceId } : input.userId ? { subjectType: "user", subjectId: input.userId } : null
16073
+ };
16074
+ const residentItems = candidates.filter((item) => item.resident === true).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, RESIDENT_MEMORY_RUNTIME_LIMIT);
16075
+ const retrievalCandidates = candidates.filter((item) => item.resident !== true);
16076
+ const ranked = selectRuntimeMemoryItems(
16077
+ rankMemoryCandidates(retrievalCandidates, input.userInput, rankContext),
16078
+ rankContext,
16079
+ input.userInput
16080
+ );
16081
+ const selected = [...residentItems, ...ranked];
16082
+ const legacyLatencyMs = Math.round((performance.now() - legacyStartedAt) * 10) / 10;
16083
+ const renderOverlay = (items, sources) => buildMemoryOverlay(items, { maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET, sources, injectionEmit });
16084
+ let promptBlock = configuredPrimary ? null : renderOverlay(selected);
16085
+ const primaryRead = configuredPrimary;
16086
+ let allCoveredByVNext = false;
16087
+ if (primaryRead) {
16088
+ branch = "primary";
16089
+ const emitPrimary = (observation) => {
16090
+ try {
16091
+ (input.primaryReadEmit ?? ((o) => console.info("[memory] vnext primary read", { event: "memory_vnext_primary_read", ...o })))(observation);
16092
+ } catch {
16093
+ }
16094
+ };
16095
+ const base = { legacyHitCount: selected.length, legacyLatencyMs };
16096
+ const vnextStartedAt = performance.now();
16097
+ const vnextLatency = () => Math.round((performance.now() - vnextStartedAt) * 10) / 10;
16098
+ if (selected.length === 0) {
16099
+ emitPrimary({ ...base, source: "none" });
16100
+ } else {
16101
+ const timeoutMarker = {};
16102
+ try {
16103
+ let timer;
16104
+ const m4 = await Promise.race([
16105
+ resolveMemoryVNextM4Selection({ db: input.db, owners, query: input.userInput, selected }),
16106
+ new Promise((_, reject) => {
16107
+ timer = setTimeout(
16108
+ () => reject(timeoutMarker),
16109
+ MEMORY_VNEXT_PRIMARY_READ_TIMEOUT_MS
16110
+ );
16111
+ })
16112
+ ]).finally(() => clearTimeout(timer));
16113
+ promptBlock = renderOverlay(m4.renderItems, m4.sources);
16114
+ allCoveredByVNext = m4.uncoveredLegacyCount === 0 && m4.recalledStateCount > 0;
16115
+ const source = m4.recalledStateCount > 0 ? m4.uncoveredLegacyCount === 0 ? "vnext" : "hybrid" : m4.uncoveredLegacyCount > 0 ? "legacy_fallback" : "none";
16116
+ emitPrimary({
16117
+ ...base,
16118
+ source,
16119
+ uncoveredLegacyCount: m4.uncoveredLegacyCount,
16120
+ coveredSuppressedCount: m4.coveredSuppressedCount,
16121
+ recalledStateCount: m4.recalledStateCount,
16122
+ vnextLatencyMs: vnextLatency(),
16123
+ contextChars: promptBlock?.length ?? 0,
16124
+ ...source === "legacy_fallback" ? { fallbackReason: "no_vnext_context" } : {}
15019
16125
  });
15020
- } else {
15021
- console.info("[memory] vnext pure read", {
15022
- event: "memory_vnext_pure_read",
15023
- ...observation
16126
+ } catch (error) {
16127
+ promptBlock = renderOverlay(selected);
16128
+ fallbackKind = error === timeoutMarker ? "timeout" : "runtime_error";
16129
+ emitPrimary({
16130
+ ...base,
16131
+ source: "legacy_fallback",
16132
+ vnextLatencyMs: vnextLatency(),
16133
+ contextChars: promptBlock?.length ?? 0,
16134
+ fallbackReason: "vnext_error",
16135
+ error: error === timeoutMarker ? "TimeoutError" : "UnknownError"
15024
16136
  });
15025
16137
  }
15026
- } catch {
15027
16138
  }
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
16139
+ }
16140
+ const shadowEnabled = !primaryRead && input.vNextShadowProvider != null && isMemoryVNextShadowReadEnabled();
16141
+ if (shadowEnabled) {
16142
+ void runMemoryVNextShadowRead({
16143
+ ctx: {
16144
+ db: input.db,
16145
+ owners,
16146
+ query: input.userInput,
16147
+ provider: input.vNextShadowProvider
16148
+ },
16149
+ legacyItems: selected,
16150
+ legacyLatencyMs,
16151
+ legacyContextChars: promptBlock?.length ?? 0
16152
+ }).catch(() => {
15055
16153
  });
15056
16154
  }
15057
- const lazyPromotionEnabled2 = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
15058
- if (lazyPromotionEnabled2) {
16155
+ const lazyPromotionEnabled = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
16156
+ if (lazyPromotionEnabled && selected.length > 0 && !allCoveredByVNext) {
15059
16157
  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
- )
16158
+ const promotionPick = await pickFirstUncoveredLazyPromotionItem(
16159
+ input.db,
16160
+ selected
15068
16161
  );
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
- }
16162
+ if (promotionPick) {
16163
+ await runMemoryVNextLazyPromotion({
16164
+ db: input.db,
16165
+ item: promotionPick.item,
16166
+ selectedIndex: promotionPick.selectedIndex,
16167
+ skippedCoveredCount: promotionPick.skippedCoveredCount,
16168
+ skippedNoOpCount: promotionPick.skippedNoOpCount,
16169
+ provider: input.vNextShadowProvider,
16170
+ ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
16171
+ });
15086
16172
  }
15087
16173
  })().catch(() => {
15088
16174
  });
15089
16175
  }
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
16176
  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
- }
16177
+ return finish({ selectedItems: [], promptBlock: null });
16178
+ }
16179
+ await touchMemoryItemsInDb(input.db, selected);
16180
+ return finish({ selectedItems: selected, promptBlock });
16181
+ } finally {
16182
+ const observation = {
16183
+ ...injection,
16184
+ event: "memory_runtime_result",
16185
+ configuredPure,
16186
+ configuredPrimary,
16187
+ branch,
16188
+ outcome,
16189
+ errorKind
16190
+ };
16191
+ try {
16192
+ (input.runtimeResultEmit ?? ((event) => console.info("[memory] runtime result", event)))(observation);
16193
+ } catch {
15175
16194
  }
15176
16195
  }
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
16196
  };
15222
16197
 
15223
16198
  // packages/cli/memoryRecall.ts
@@ -15406,6 +16381,35 @@ async function resolveAgentBoundMachineIdFromRecord(args) {
15406
16381
  return resolveBoundMachineId(record) || void 0;
15407
16382
  }
15408
16383
  async function runAgentRunCommand(args, deps) {
16384
+ const env = deps.env ?? process.env;
16385
+ const runId = env.NOLO_AGENT_RUN_ID;
16386
+ const controlDeps = { env, homedir: deps.homedir, fs: deps.fs, now: deps.now };
16387
+ const failStartup = async (error) => {
16388
+ if (!runId || readRunRecord(runId, controlDeps)?.status !== "running") return;
16389
+ const result = await settleRunTerminalAuthoritatively(runId, {
16390
+ status: "failed",
16391
+ exitCode: 1,
16392
+ failureReason: error instanceof RuntimeProtocolMismatchError ? "runtime_protocol_mismatch" : error instanceof RuntimeVersionMismatchError ? "runtime_version_mismatch" : "startup_failed",
16393
+ note: error ? toErrorMessage(error) : "Child initialization returned without terminal result"
16394
+ }, controlDeps, (id, update, d) => transitionRunToTerminal(id, update, d));
16395
+ if (result.kind === "contended") throw new Error(`Startup settlement lock busy: ${runId}`);
16396
+ };
16397
+ try {
16398
+ if (runId) {
16399
+ if (!readRunRecord(runId, controlDeps)) throw new Error("[local-writer-resource] missing child binding");
16400
+ await recordRunStartup(runId, "initializing", controlDeps);
16401
+ validateAgentRunProtocol(env.NOLO_AGENT_RUN_PROTOCOL);
16402
+ await recordRunStartup(runId, "protocol_validated", controlDeps);
16403
+ }
16404
+ const code = await runAgentRunCommandImpl(args, deps);
16405
+ if (runId) await failStartup();
16406
+ return code;
16407
+ } catch (error) {
16408
+ await failStartup(error);
16409
+ throw error;
16410
+ }
16411
+ }
16412
+ async function runAgentRunCommandImpl(args, deps) {
15409
16413
  const env = deps.env ?? process.env;
15410
16414
  const output = deps.output ?? {
15411
16415
  write: (chunk) => process.stdout.write(chunk),
@@ -15428,10 +16432,17 @@ async function runAgentRunCommand(args, deps) {
15428
16432
  return 1;
15429
16433
  }
15430
16434
  const rawRunner = deps.runner ?? runAgentTurn;
16435
+ let modelPhaseRecorded = false;
15431
16436
  const watchdogAbort = new AbortController();
15432
16437
  let activeRunner;
15433
16438
  const runner = (options) => {
15434
- activeRunner = Promise.resolve().then(() => rawRunner({ ...options, abortSignal: watchdogAbort.signal })).then((result) => {
16439
+ activeRunner = Promise.resolve().then(async () => {
16440
+ if (env.NOLO_AGENT_RUN_ID && !modelPhaseRecorded) {
16441
+ await recordRunStartup(env.NOLO_AGENT_RUN_ID, "model", { env, homedir: deps.homedir, fs: deps.fs, now: deps.now });
16442
+ modelPhaseRecorded = true;
16443
+ }
16444
+ return rawRunner({ ...options, abortSignal: watchdogAbort.signal });
16445
+ }).then((result) => {
15435
16446
  watchdogAbort.signal.throwIfAborted();
15436
16447
  return result;
15437
16448
  });
@@ -15444,8 +16455,8 @@ async function runAgentRunCommand(args, deps) {
15444
16455
  try {
15445
16456
  return await Promise.race([
15446
16457
  activeRunner.then(() => true, () => true),
15447
- new Promise((resolve6) => {
15448
- timer = setTimeout(() => resolve6(false), 100);
16458
+ new Promise((resolve5) => {
16459
+ timer = setTimeout(() => resolve5(false), 100);
15449
16460
  })
15450
16461
  ]);
15451
16462
  } finally {
@@ -15864,6 +16875,7 @@ async function runAgentRunCommand(args, deps) {
15864
16875
  );
15865
16876
  const shellApprovalChild = process.connected && typeof process.send === "function" ? createShellApprovalChild(process) : void 0;
15866
16877
  try {
16878
+ const imageUrls = await normalizeCliRunImages(parsed.imageUrls, normalizeCliImageInput);
15867
16879
  const buildRunOptions = (targetAgentKey, turnMessage = effectiveMessage) => ({
15868
16880
  ...shellApprovalChild ? { execShellApproval: targetAgentKey === agentKey ? shellApprovalChild.authority : {
15869
16881
  request: async () => {
@@ -15883,7 +16895,7 @@ async function runAgentRunCommand(args, deps) {
15883
16895
  responseViewport: "unknown",
15884
16896
  serverUrl: resolveServerUrl(env),
15885
16897
  message: formatTurnMessage(turnMessage),
15886
- imageUrls: parsed.imageUrls.map(normalizeCliImageInput),
16898
+ imageUrls,
15887
16899
  scriptDir: deps.scriptDir,
15888
16900
  env: runEnv,
15889
16901
  output,
@@ -16113,7 +17125,7 @@ async function runAgentRunCommand(args, deps) {
16113
17125
  acceptance.checks.observations = dodResults.map((check, index) => ({
16114
17126
  // Command lines/output can contain credentials. Persist only a digest
16115
17127
  // here; the pre-existing registry is the execution evidence reference.
16116
- commandFingerprint: `sha256:${createHash("sha256").update(check.command).digest("hex")}`,
17128
+ commandFingerprint: `sha256:${createHash3("sha256").update(check.command).digest("hex")}`,
16117
17129
  cwd: childRecordForDoD?.cwd || process.cwd(),
16118
17130
  exitCode: check.exitCode,
16119
17131
  evidence: `${childRunId}.json#/dodResults/${index}`,
@@ -16183,6 +17195,16 @@ async function runAgentRunCommand(args, deps) {
16183
17195
  }
16184
17196
 
16185
17197
  export {
17198
+ resolveAgentModelIdentity,
17199
+ resolveAgentContextWindow2 as resolveAgentContextWindow,
17200
+ platformCreditsFromUsage,
17201
+ formatCreditsChip,
17202
+ resolveAuthorityTurnCount,
17203
+ computeBaselineContextTokens,
17204
+ preserveContextUsageWithoutReceipt,
17205
+ resolveContextUsage,
17206
+ renderTokenStatus,
17207
+ redactSecrets,
16186
17208
  resolveCliColorEnabled,
16187
17209
  dimCliText,
16188
17210
  THEME_PALETTES,
@@ -16208,18 +17230,10 @@ export {
16208
17230
  formatAssistantDisplay,
16209
17231
  resolveHistoryLayoutGeometry,
16210
17232
  resolveHistoryViewportHeight,
17233
+ safeAskText,
17234
+ safeApprovalMultilineText,
16211
17235
  TUI_TREE_MARKER,
16212
17236
  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
17237
  createIdleHeapReleaser,
16224
17238
  COLLAPSED_PASTE_PLACEHOLDER_RE,
16225
17239
  shouldCollapsePaste,
@@ -16235,6 +17249,7 @@ export {
16235
17249
  emitTerminalProgramStatus,
16236
17250
  contextRefusalDiagnostics,
16237
17251
  describeContextRefusal,
17252
+ inspectLocalRunWorkspace,
16238
17253
  isBalanceExhaustedError,
16239
17254
  OWNER_OAUTH_UNAVAILABLE_HINT,
16240
17255
  isOwnerOAuthUnavailableError,