nolo-cli 0.226.0-alpha.2 → 0.228.0-alpha.1

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 (198) hide show
  1. package/{_executeModel-IKZGZZXW.js → _executeModel-WZKT6XEU.js} +74 -75
  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-IZY3VF5F.js → agentDeleteCommand-PZWRHNXY.js} +114 -116
  6. package/{agentEmailCommands-YWL567CL.js → agentEmailCommands-QTKMEICX.js} +115 -117
  7. package/{agentFavoriteCommands-2LKGKSUD.js → agentFavoriteCommands-7LOP3HUD.js} +5 -5
  8. package/{agentGrantCommands-QQV4N4JW.js → agentGrantCommands-L6O2HVJI.js} +5 -5
  9. package/{agentListCommands-YBNOQ5T3.js → agentListCommands-GUGMORTK.js} +84 -70
  10. package/{agentMachineCommands-AXJ4A772.js → agentMachineCommands-7QGICJLM.js} +56 -55
  11. package/{agentProviderCommands-7BSJH7TO.js → agentProviderCommands-STI3DQ6A.js} +6 -6
  12. package/{agentPullCommand-XN6ZPBUW.js → agentPullCommand-KHV4EELF.js} +5 -5
  13. package/{agentRecordCommands-WUUC2CX7.js → agentRecordCommands-SLLADS5C.js} +102 -104
  14. package/{agentRunCommand-W6MDKVLJ.js → agentRunCommand-OFQLOF5Y.js} +113 -114
  15. package/{agentRunControl-DFEEOFC7.js → agentRunControl-MBG4U6SL.js} +20 -14
  16. package/{agentRuntimeLocal-GSTYFEX4.js → agentRuntimeLocal-TU4LA353.js} +39 -39
  17. package/{agentSlice-5F5U5X2U.js → agentSlice-L4SBGWTB.js} +16 -16
  18. package/{appDeleteCommands-L7HL4AWF.js → appDeleteCommands-JWP3XPUA.js} +50 -49
  19. package/{appDeployCommands-SGSUNFZR.js → appDeployCommands-6E4TQCWI.js} +50 -49
  20. package/{appDeployStatusCommands-AAA3XD54.js → appDeployStatusCommands-ALU4SADG.js} +50 -49
  21. package/{appGetCommands-LN72GAOA.js → appGetCommands-JEY4L6L4.js} +50 -49
  22. package/{appListCommands-IJQQ3VND.js → appListCommands-PCAVHU7M.js} +50 -49
  23. package/{authCommand-7JXW54U4.js → authCommand-CGRIIOOV.js} +26 -27
  24. package/{authCommands-YDNAIDEY.js → authCommands-55OGQGCR.js} +9 -10
  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-N5PQJKCY.js → chunk-2MCB7CD7.js} +13 -12
  29. package/{chunk-VFBVA3U2.js → chunk-2NPD3FTX.js} +3 -3
  30. package/{chunk-SBVTHMEG.js → chunk-2X7WFDT6.js} +1 -1
  31. package/{chunk-XI2BWJM5.js → chunk-324FWHUA.js} +20 -3
  32. package/{chunk-JWXITTQB.js → chunk-3P54D2E4.js} +1 -1
  33. package/{chunk-ZH6MUQEO.js → chunk-3U44JB3O.js} +1 -1
  34. package/{chunk-EUCFKKDM.js → chunk-4I2MXV5Q.js} +38 -10
  35. package/{chunk-C4WTX5TU.js → chunk-4ZGPHFLE.js} +2 -2
  36. package/{chunk-MOMR7NMG.js → chunk-547ENH5T.js} +1 -1
  37. package/chunk-5ZUOVCKT.js +32 -0
  38. package/{chunk-KOXKKHFE.js → chunk-6QHKRARD.js} +2 -2
  39. package/{chunk-YGMBIXCF.js → chunk-6XRPBZRS.js} +4 -2
  40. package/{chunk-EWPDMS4N.js → chunk-7JGMNKKG.js} +18 -14
  41. package/{chunk-2TIQO6TC.js → chunk-AGYPUBFW.js} +31 -205
  42. package/{chunk-UYOICCYG.js → chunk-ALAES342.js} +59 -88
  43. package/{chunk-VREDDN25.js → chunk-ATEKLSLR.js} +1 -1
  44. package/{chunk-GBZ4YKEO.js → chunk-AUAJTAFM.js} +8 -8
  45. package/chunk-BIDSIRTS.js +307 -0
  46. package/chunk-BIWI5M4E.js +62 -0
  47. package/{chunk-L5I543VB.js → chunk-BNMPUQW6.js} +1 -1
  48. package/{chunk-BGGHA5DV.js → chunk-BP5ZJ6B4.js} +1 -1
  49. package/{chunk-3QFLXA24.js → chunk-CBUZ6DKA.js} +3 -3
  50. package/{chunk-KYH7XW3K.js → chunk-CD3RU7XL.js} +16 -1
  51. package/{chunk-AVHRSJUH.js → chunk-CMMI3DAT.js} +13 -13
  52. package/{chunk-XN23AUVU.js → chunk-CYWNWA77.js} +5 -5
  53. package/{chunk-2VA6TU4I.js → chunk-D6YNCNM6.js} +17 -14
  54. package/{chunk-GOAPXKQU.js → chunk-DBUR22G5.js} +5 -5
  55. package/{chunk-QTMIHVLE.js → chunk-DDC6P6EH.js} +22 -19
  56. package/{chunk-PVZY6P3S.js → chunk-DEA37IUY.js} +2 -2
  57. package/{chunk-QLFCTYRH.js → chunk-DGYCDA6W.js} +3 -3
  58. package/{chunk-KNIIRXHF.js → chunk-DUUDXSLX.js} +21 -7
  59. package/{chunk-KFHREHUQ.js → chunk-DXWGFL2Z.js} +89 -1
  60. package/{chunk-JM5C4EUA.js → chunk-EEOOBRA7.js} +5 -5
  61. package/{chunk-KN3HEZIQ.js → chunk-EVGU5P4U.js} +1 -1
  62. package/{chunk-GBUDWITV.js → chunk-EXJK7TQO.js} +1837 -1112
  63. package/{chunk-YDBMZ7FV.js → chunk-F6Z6ZCUV.js} +2 -2
  64. package/{chunk-EOWLBDY6.js → chunk-FJSNBZXR.js} +1 -1
  65. package/{chunk-GNHMRBYZ.js → chunk-G7IUT2V3.js} +4 -3
  66. package/{chunk-4AMQZTE7.js → chunk-GACR7H6T.js} +14 -14
  67. package/{chunk-NEKH3XDV.js → chunk-GOCSSER3.js} +3 -3
  68. package/{chunk-3KNEE64G.js → chunk-GPOV42YM.js} +14 -14
  69. package/{chunk-UEKXWO7A.js → chunk-GUXZK7SE.js} +2 -2
  70. package/{chunk-JHRQXQ4A.js → chunk-GYS5FUYR.js} +19 -19
  71. package/{chunk-6O5YP6FX.js → chunk-H6L2NFHY.js} +6 -6
  72. package/{chunk-45LZIYXB.js → chunk-HBRDSQ3M.js} +1 -1
  73. package/{chunk-KZU52OJ5.js → chunk-HHFGE2WF.js} +6 -6
  74. package/{chunk-VV7TXWOC.js → chunk-HSSBDZLD.js} +3 -3
  75. package/{chunk-GIABSSWQ.js → chunk-HYLRQDEE.js} +4 -4
  76. package/{chunk-EFX3Q5SM.js → chunk-IAAIUH64.js} +15 -15
  77. package/{chunk-UJKTI5PG.js → chunk-ILHQ2AXT.js} +0 -1
  78. package/{chunk-EJU6WCDH.js → chunk-IXG6YXQM.js} +146 -114
  79. package/{chunk-KC4SCKXO.js → chunk-JUSHVFNF.js} +238 -185
  80. package/{chunk-BLSNUIZD.js → chunk-K67C2JUC.js} +10 -10
  81. package/{chunk-IZIN2UNJ.js → chunk-L32W3PRP.js} +46 -16
  82. package/{chunk-67BE44IS.js → chunk-M4SFKP5L.js} +1 -1
  83. package/{chunk-L4NFXFFF.js → chunk-MDZWUD3R.js} +18 -18
  84. package/{chunk-QZI44GWV.js → chunk-NHY322ZU.js} +150 -9
  85. package/{chunk-DISQCYPE.js → chunk-OBIC6EG7.js} +6 -6
  86. package/{chunk-AZQZ5XPM.js → chunk-OG6MQOQG.js} +96 -28
  87. package/{chunk-VQUWV3YR.js → chunk-OOJNQK6V.js} +1 -1
  88. package/{chunk-F7DU25CE.js → chunk-OWKNSIXL.js} +149 -54
  89. package/{chunk-RRVQ446B.js → chunk-OYU2MA5S.js} +25 -25
  90. package/{chunk-CKT6QUE2.js → chunk-Q3IVPFVO.js} +1 -1
  91. package/{chunk-FTQWYWUI.js → chunk-QBZCGP34.js} +1 -1
  92. package/{chunk-2ZKFCIJJ.js → chunk-QCB42576.js} +1 -1
  93. package/{chunk-HOCHUZQ7.js → chunk-QJTZ76CP.js} +24 -6
  94. package/{chunk-LM2PS3YS.js → chunk-QRGDJA4B.js} +9 -9
  95. package/{chunk-SOG7OEXX.js → chunk-QYB23WUH.js} +1 -1
  96. package/{chunk-W772FYAQ.js → chunk-R3NEQZ53.js} +285 -92
  97. package/{chunk-2VUZSVAS.js → chunk-R6Z5S5GA.js} +7 -7
  98. package/{chunk-MK2Q7ZJD.js → chunk-R7XWZDOH.js} +58 -24
  99. package/{chunk-GGKNJ42M.js → chunk-RBPUNSG5.js} +2 -2
  100. package/{chunk-GVGOEMNV.js → chunk-RG2DGNL6.js} +3 -3
  101. package/{chunk-4NA3YTBC.js → chunk-RTHFJZ6M.js} +7 -7
  102. package/{chunk-C4VAR65S.js → chunk-RYOLWYBK.js} +120 -116
  103. package/{chunk-D726I5AZ.js → chunk-S6FDXXZV.js} +2 -2
  104. package/{chunk-JVRQ6YVK.js → chunk-S6K5F3KP.js} +1 -1
  105. package/{chunk-HHL7WG65.js → chunk-SMJEXX2S.js} +122 -11
  106. package/{chunk-LJSNEV7M.js → chunk-SRCCSTIM.js} +7 -7
  107. package/{chunk-WSJMT3FA.js → chunk-STJ6LSQE.js} +746 -2519
  108. package/{chunk-6J4TTPS2.js → chunk-TGNIKIHR.js} +5 -5
  109. package/{chunk-AK5O76CC.js → chunk-TI2EPRHE.js} +2 -2
  110. package/{chunk-4HFTBHBF.js → chunk-TSPMLCWI.js} +6 -6
  111. package/{chunk-QVBXJNZ2.js → chunk-TUSTONB3.js} +1 -1
  112. package/{chunk-2COEG5ZV.js → chunk-UE2EVEYS.js} +2 -2
  113. package/{chunk-E5EIYI34.js → chunk-UWAIJOF2.js} +19 -19
  114. package/{chunk-KEN3N2TN.js → chunk-VMJVAJ6W.js} +13 -10
  115. package/{chunk-SOF4OWDM.js → chunk-VS276URX.js} +0 -2
  116. package/{chunk-BYH3HMUP.js → chunk-VSYTM22R.js} +3 -3
  117. package/{chunk-FIYSMXHY.js → chunk-WWTSEBDF.js} +1 -1
  118. package/{chunk-E2BESSAW.js → chunk-X4O7FJF5.js} +2 -0
  119. package/{chunk-T3T57NVP.js → chunk-XJPLSAPJ.js} +11 -11
  120. package/{chunk-UKS7D2NL.js → chunk-XSW4EXQV.js} +82 -18
  121. package/{chunk-TXGQ4O5S.js → chunk-YKY4OVOX.js} +11 -11
  122. package/{chunk-5RKUPJYL.js → chunk-ZH3KXFHS.js} +11 -3
  123. package/chunk-ZOHO6MOF.js +376 -0
  124. package/{chunk-OLMJR6UM.js → chunk-ZXF6D3I6.js} +9 -7
  125. package/{cliAgentConfigHelpers-KICKKNYQ.js → cliAgentConfigHelpers-BTRHMPW2.js} +12 -12
  126. package/{cliEnvHelpers-VPSJ4XWC.js → cliEnvHelpers-CNMP3RDX.js} +1 -1
  127. package/{cliExecutor-4MAX3PZL.js → cliExecutor-K6FDZTQ2.js} +3 -1
  128. package/{cliLocalAgentRecordReader-6FXGFBI3.js → cliLocalAgentRecordReader-M3F76NIP.js} +45 -45
  129. package/{commandRegistry-6EQXVODF.js → commandRegistry-ZLWHQVAI.js} +93 -93
  130. package/{contentThunks-ANUP57QV.js → contentThunks-4ZX2TO7C.js} +36 -35
  131. package/{cooldownCommands-X7P5M2V5.js → cooldownCommands-YB5H5BBK.js} +4 -4
  132. package/{createAgentAutomationAction-XMUWUDKQ.js → createAgentAutomationAction-L4CYUZJG.js} +36 -35
  133. package/{createDialogAction-43QJIQDH.js → createDialogAction-QTU2R2Q3.js} +37 -37
  134. package/{createPageAction-SJO7UC3J.js → createPageAction-F3GJTHW2.js} +37 -36
  135. package/{db-CS4ZJQKV.js → db-M7FU2GNK.js} +9 -6
  136. package/{dbSlice-ZJPDIFER.js → dbSlice-XRUZOGSU.js} +11 -11
  137. package/{deleteFile-Q3YDB4ML.js → deleteFile-6URDHYRB.js} +7 -7
  138. package/{dialogCommands-V5IYEOQP.js → dialogCommands-NRLCOPJR.js} +52 -52
  139. package/{dialogNotifyCommand-77B57PL6.js → dialogNotifyCommand-SHGPCU22.js} +13 -13
  140. package/{dialogSlice-FQ6WOKWJ.js → dialogSlice-P2S4LXQD.js} +34 -33
  141. package/{dialogUsageCommand-HTVPR2CX.js → dialogUsageCommand-W2WCSGKF.js} +1 -1
  142. package/{docCreateCommands-36WS33BK.js → docCreateCommands-YJRDA3RX.js} +48 -47
  143. package/{docDeleteCommands-C4CS4XLF.js → docDeleteCommands-A5QIHZNF.js} +50 -49
  144. package/{docReadCommands-QZMSFMPN.js → docReadCommands-CF2LTMYH.js} +48 -47
  145. package/{docStore-BZ2O7WLF.js → docStore-6O7NYL6A.js} +12 -12
  146. package/{docUpdateCommands-BYI64HVV.js → docUpdateCommands-QRKV4ZXE.js} +48 -47
  147. package/fetchMessages-TQEUZD7H.js +1 -1
  148. package/{getPricing-VNGFM4PN.js → getPricing-LF5C4XSI.js} +5 -5
  149. package/{handleSendMessageAction-I5J7QR7K.js → handleSendMessageAction-7IHLR37A.js} +65 -65
  150. package/{hostCredentialCreate-AVPMK7EQ.js → hostCredentialCreate-VNCQUAFT.js} +102 -104
  151. package/index.js +56 -18
  152. package/keys-RWF7UCB4.js +1 -1
  153. package/{localDialogRead-SVTPA5GY.js → localDialogRead-CCOCVGAP.js} +1 -1
  154. package/{localRuntimeAdapter-S56R76HN.js → localRuntimeAdapter-FOWVNMIK.js} +109 -111
  155. package/{machineCommands-77NFB2AE.js → machineCommands-ZGC3J4JB.js} +111 -113
  156. package/{machineWsRunDispatch-5XWFUJ53.js → machineWsRunDispatch-KK5U4M3G.js} +100 -102
  157. package/{memberThunks-JRYNONYV.js → memberThunks-7Y3OYSJQ.js} +15 -15
  158. package/{memoryCommands-5WC3T66U.js → memoryCommands-BC6REPQB.js} +4 -4
  159. package/{overlay-THLKYIWY.js → overlay-BBQZXGYI.js} +5 -3
  160. package/package.json +1 -1
  161. package/{projectArchive-GNOSYH6F.js → projectArchive-7ZDYBXAX.js} +42 -41
  162. package/{providerPresetApply-J3WMRPD2.js → providerPresetApply-WHAMP2D5.js} +6 -6
  163. package/{providerRegistry-KJGB5XWS.js → providerRegistry-ZI2KORJ7.js} +6 -6
  164. package/{read-Q7GOHGNP.js → read-TYMBGEXO.js} +8 -8
  165. package/{readDocTool-Z5OQ6422.js → readDocTool-SKQVHBLO.js} +1 -1
  166. package/{readlineWorkspace-2PONGBUP.js → readlineWorkspace-YHT4SX2C.js} +4794 -5229
  167. package/{removeDialogAgentAction-U3F2MNAY.js → removeDialogAgentAction-F5QE2O2B.js} +16 -16
  168. package/{runAgentClientLoop-WEXFFHVS.js → runAgentClientLoop-H4ED5V3K.js} +71 -68
  169. package/{runtimeDoctorCommands-UXKXYBW6.js → runtimeDoctorCommands-RRKPBGVO.js} +14 -14
  170. package/{secretCommands-LJXOOYA7.js → secretCommands-KZWBZIYS.js} +4 -4
  171. package/{setDialogExtraReferencesAction-G3WSJ7EM.js → setDialogExtraReferencesAction-72L27ERM.js} +13 -13
  172. package/{setPrimaryDialogAgentAction-6FHAHZBB.js → setPrimaryDialogAgentAction-GJJDUSGJ.js} +16 -16
  173. package/{settingThunks-AXTBX3Q5.js → settingThunks-ZRGWVGZD.js} +15 -15
  174. package/{skillDiscovery-B5V23AXP.js → skillDiscovery-I37M5KJC.js} +3 -3
  175. package/{spaceCommands-GUKMDRWN.js → spaceCommands-MEH3HJBC.js} +53 -52
  176. package/{store-JRVN62NM.js → store-Z53ICFL3.js} +3 -1
  177. package/{streamAgentChatTurn-D2WFS5MF.js → streamAgentChatTurn-ZXPOXU33.js} +89 -129
  178. package/{switchDialogAgentAction-UOFIAGPL.js → switchDialogAgentAction-IIJBPND3.js} +14 -14
  179. package/{tableCommands-HITDSLHS.js → tableCommands-FTAOCBTX.js} +11 -11
  180. package/{tools-YKE6PQHT.js → tools-2MRWA2PP.js} +58 -59
  181. package/tuiRestart-2IL37YIB.js +41 -0
  182. package/{tuiSummaryLlmCaller-7WLUKNP2.js → tuiSummaryLlmCaller-W2QN4VAC.js} +18 -18
  183. package/{updateCommands-RJVCRSBP.js → updateCommands-CPATDG6J.js} +8 -6
  184. package/{updateDialogTitleAction-D5NCA4FC.js → updateDialogTitleAction-RZ3KZSGQ.js} +36 -35
  185. package/{usageCommand-YPJ2ZI2F.js → usageCommand-2BF74MKF.js} +2 -2
  186. package/{usageRebuildCommand-FERQO74C.js → usageRebuildCommand-UHB55BQM.js} +3 -3
  187. package/{windowsSelfUpdate-KERHIAB4.js → windowsSelfUpdate-ZFD6J5HF.js} +2 -2
  188. package/chunk-2THCNKE4.js +0 -147
  189. package/chunk-BJF2MHJ3.js +0 -118
  190. package/chunk-KEPOVMF4.js +0 -91
  191. package/chunk-PMDVQBGA.js +0 -100
  192. package/{accountResolver-EK2S4PWF.js → accountResolver-QETKNC7T.js} +3 -3
  193. package/{chunk-AGP3YSEC.js → chunk-4N6G2CKP.js} +3 -3
  194. package/{chunk-BLVSFYQ3.js → chunk-LISC7BD4.js} +3 -3
  195. package/{chunk-SNBZZPYH.js → chunk-OQHIVPG4.js} +3 -3
  196. package/{chunk-47ITIXO7.js → chunk-USGHJSGO.js} +3 -3
  197. package/{offlineMarxistsAgentCommand-4IC3Y4C6.js → offlineMarxistsAgentCommand-XVXUE6G5.js} +3 -3
  198. 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-WSJMT3FA.js";
53
- import {
54
- clearCredentialAvailability,
55
- readEffectiveCredentialEntry
56
- } from "./chunk-FIYSMXHY.js";
57
- import {
58
- readDbRecord,
59
- resolveAgentRecordFromHybridStore
60
- } from "./chunk-2VA6TU4I.js";
38
+ } from "./chunk-STJ6LSQE.js";
61
39
  import {
62
40
  boxGlyphs,
63
41
  displayWidth,
@@ -65,26 +43,22 @@ import {
65
43
  stripAnsi,
66
44
  tokenizeAnsiLine,
67
45
  visibleWidth
68
- } from "./chunk-UKS7D2NL.js";
46
+ } from "./chunk-XSW4EXQV.js";
69
47
  import {
70
- deriveStateResident,
71
- resolvePureVNextRuntime,
72
- touchMemoryItemsInDb
73
- } from "./chunk-PMDVQBGA.js";
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";
74
57
  import {
75
- _appendEntityBatch,
76
- _appendEvidenceBatch,
77
- _appendRelationBatch,
78
- _appendRetiredStateBatch,
79
- _appendStateBatch,
80
- getMemoryEntityVNext,
81
- getMemoryEvidenceVNext,
82
58
  getMemoryEvidenceVNextStrict,
83
- getMemoryStateVNext,
84
- listMemoryStatesForEntityVNext,
85
59
  loadMemoryVNextCatalog,
86
60
  putMemoryEvidenceVNext
87
- } from "./chunk-XI2BWJM5.js";
61
+ } from "./chunk-324FWHUA.js";
88
62
  import {
89
63
  rankMemoryCandidates,
90
64
  recallMemoryVNextLocal
@@ -92,8 +66,9 @@ import {
92
66
  import {
93
67
  DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET,
94
68
  EXPLICIT_REMEMBER_PREFIX_REGEX,
95
- buildMemoryOverlay
96
- } from "./chunk-EUCFKKDM.js";
69
+ buildMemoryOverlay,
70
+ emptyMemoryInjectionObservation
71
+ } from "./chunk-4I2MXV5Q.js";
97
72
  import {
98
73
  buildLegacyMemoryEvidence,
99
74
  resolveLegacyMemoryPrincipal
@@ -101,38 +76,27 @@ import {
101
76
  import {
102
77
  isBuiltinNoloAgentRef,
103
78
  resolveLocalUserId
104
- } from "./chunk-KZU52OJ5.js";
105
- import {
106
- CliProviderQuotaError
107
- } from "./chunk-MK2Q7ZJD.js";
108
- import {
109
- resolveMachineId
110
- } from "./chunk-S73EPYNC.js";
79
+ } from "./chunk-HHFGE2WF.js";
111
80
  import {
112
81
  extractGoogleValidationLink
113
82
  } from "./chunk-BMQ2MJUK.js";
114
83
  import {
115
84
  resolveCliLocalRuntimeKeyCapability
116
- } from "./chunk-EJU6WCDH.js";
117
- import {
118
- isTransientFetchError
119
- } from "./chunk-KFHREHUQ.js";
85
+ } from "./chunk-IXG6YXQM.js";
120
86
  import {
121
87
  parseUiCard,
122
88
  uiCardFallback
123
- } from "./chunk-T3T57NVP.js";
89
+ } from "./chunk-XJPLSAPJ.js";
124
90
  import {
125
91
  isGatewayHttpStatus
126
92
  } from "./chunk-NF64D32W.js";
127
93
  import {
128
94
  buildMemorySubjectsForAgent,
129
- resolveAgentMemoryPolicy
130
- } from "./chunk-HHL7WG65.js";
131
- import {
132
95
  chooseMemoryOwners,
133
96
  loadMemoryCandidatesFromDb,
134
- loadOwnerItemsFromDb
135
- } from "./chunk-BJF2MHJ3.js";
97
+ loadOwnerItemsFromDb,
98
+ resolveAgentMemoryPolicy
99
+ } from "./chunk-SMJEXX2S.js";
136
100
  import {
137
101
  API_REPORTED_COST_MULTIPLIER,
138
102
  estimateMessagesTokens,
@@ -142,7 +106,17 @@ import {
142
106
  resolveAgentContextWindow,
143
107
  resolveOccupancy,
144
108
  resolveOccupancyWindow
145
- } from "./chunk-W772FYAQ.js";
109
+ } from "./chunk-R3NEQZ53.js";
110
+ import {
111
+ parsePositiveFiniteNumberOrFallback
112
+ } from "./chunk-Y5GCAMGP.js";
113
+ import {
114
+ readDbRecord,
115
+ resolveAgentRecordFromHybridStore
116
+ } from "./chunk-D6YNCNM6.js";
117
+ import {
118
+ isTransientFetchError
119
+ } from "./chunk-DXWGFL2Z.js";
146
120
  import {
147
121
  isCliAuthorityBrokerProtocolError,
148
122
  isCliAuthorityBrokerTimeoutError,
@@ -151,19 +125,55 @@ import {
151
125
  import {
152
126
  getDefaultCliLocalRuntimeDb
153
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";
154
159
  import {
155
160
  isLocalCliAgentKey
156
161
  } from "./chunk-BR3GT6MR.js";
162
+ import {
163
+ buildSkillDiscoveryContextLayer
164
+ } from "./chunk-Q3IVPFVO.js";
157
165
  import {
158
166
  LOCAL_AGENT_CONFIG_MISSING_CODE,
159
167
  LOCAL_TURN_ABORTED_CODE,
160
- evaluateTaskExecutionContract,
161
168
  markCliUserBatchPhase,
162
169
  readActionGate
163
- } from "./chunk-KC4SCKXO.js";
170
+ } from "./chunk-JUSHVFNF.js";
164
171
  import {
165
172
  resolveAgentRuntimeConfigFromRecord
166
- } from "./chunk-UEKXWO7A.js";
173
+ } from "./chunk-GUXZK7SE.js";
174
+ import {
175
+ resolveAgentImageInputSupport
176
+ } from "./chunk-DUUDXSLX.js";
167
177
  import {
168
178
  createThinkParserState,
169
179
  flushThinkParser,
@@ -175,18 +185,18 @@ import {
175
185
  isQuotaExhaustedText,
176
186
  resolveAvailabilityAction,
177
187
  resolveCredentialKeyWithFallback
178
- } from "./chunk-HOCHUZQ7.js";
188
+ } from "./chunk-QJTZ76CP.js";
179
189
  import {
180
190
  ATTACHMENT_PART_TYPE,
181
191
  ATTACHMENT_PART_VERSION,
182
192
  describeAttachmentForModel,
183
193
  normalizeAttachmentPart
184
- } from "./chunk-LM2PS3YS.js";
194
+ } from "./chunk-QRGDJA4B.js";
185
195
  import {
186
196
  findCodexOAuthPinnedContextWindow,
187
197
  normalizeUsage,
188
198
  readCacheReadInputTokensOrNull
189
- } from "./chunk-IZIN2UNJ.js";
199
+ } from "./chunk-L32W3PRP.js";
190
200
  import {
191
201
  isOAuthApiKeyRef
192
202
  } from "./chunk-UKZX3NHN.js";
@@ -196,13 +206,17 @@ import {
196
206
  import {
197
207
  normalizeRuntimeToolPolicyOverride,
198
208
  resolveEffectiveRuntimeToolPolicy
199
- } from "./chunk-47ITIXO7.js";
209
+ } from "./chunk-USGHJSGO.js";
200
210
  import {
201
211
  compactWhitespace
202
212
  } from "./chunk-DWLEOOGR.js";
203
213
  import {
204
- isAntigravityOAuthAgent
205
- } from "./chunk-EWPDMS4N.js";
214
+ QUOTA_ERROR_PATTERNS,
215
+ isQuotaExhaustedError
216
+ } from "./chunk-EWQ3HGNZ.js";
217
+ import {
218
+ estimateTokenCount
219
+ } from "./chunk-PSCNXBYA.js";
206
220
  import {
207
221
  parseExternalSkillMarkdown,
208
222
  parseSkillDocProtocol
@@ -212,16 +226,13 @@ import {
212
226
  BUILTIN_NOLO_AGENT_NAME,
213
227
  builtinAgentCatalogEntryById,
214
228
  parseBuiltinPlatformAgentId
215
- } from "./chunk-UJKTI5PG.js";
229
+ } from "./chunk-ILHQ2AXT.js";
216
230
  import {
217
231
  parsePublicAgentId
218
232
  } from "./chunk-M2EJHDJP.js";
219
233
  import {
220
234
  ulid
221
235
  } from "./chunk-OJKUU3LP.js";
222
- import {
223
- buildSkillDiscoveryContextLayer
224
- } from "./chunk-CKT6QUE2.js";
225
236
  import {
226
237
  buildAgentsMdLayer,
227
238
  buildAgentsMdLayerHeader,
@@ -229,55 +240,35 @@ import {
229
240
  buildMemoryUseGuidanceLayer,
230
241
  partitionScopedBlocks,
231
242
  renderTurnContextBlocksWithScope
232
- } from "./chunk-JWXITTQB.js";
243
+ } from "./chunk-3P54D2E4.js";
233
244
  import {
234
245
  exitCliFromWatchdog,
235
246
  getLogger,
236
247
  normalizeError
237
- } 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";
238
259
  import {
239
260
  agentRunCardLabels,
240
261
  getCliLocale,
241
262
  t,
242
263
  toolLabel,
243
264
  toolLabelVariants
244
- } from "./chunk-OB6DVWPF.js";
245
- import {
246
- awaitLocalWriterChild,
247
- createRunActivityTracker,
248
- createShellApprovalChild,
249
- getRunResultHeaderMeta,
250
- isHistoryIntegrityFailure,
251
- popSingleQueueMessage,
252
- readRunRecord,
253
- recordRunResultHeaderMeta,
254
- registerLocalForegroundWriter,
255
- reportRunProcessIdentity,
256
- resolveResultServerMeta,
257
- resolveRunQueuePath,
258
- resolveRunsDir,
259
- serverOriginForDialog,
260
- settleRunTerminalAuthoritatively,
261
- spawnLocalBackgroundRun
262
- } from "./chunk-F7DU25CE.js";
263
- import {
264
- formatAgentListCard,
265
- formatFinishedRunCard,
266
- formatIdentityRow,
267
- formatListRunsCard,
268
- formatNotFoundRunCard,
269
- formatStatusRunCard,
270
- formatStopRunCard,
271
- getAgentRunStatusIcon,
272
- isAgentRunTerminalStatus
273
- } from "./chunk-VQUWV3YR.js";
265
+ } from "./chunk-262R3XNN.js";
274
266
  import {
275
- QUOTA_ERROR_PATTERNS,
276
- isQuotaExhaustedError
277
- } from "./chunk-EWQ3HGNZ.js";
267
+ isAntigravityOAuthAgent
268
+ } from "./chunk-7JGMNKKG.js";
278
269
  import {
279
270
  resolveClientVersion
280
- } from "./chunk-4NA3YTBC.js";
271
+ } from "./chunk-RTHFJZ6M.js";
281
272
  import {
282
273
  toErrorMessage
283
274
  } from "./chunk-HNMXYYJR.js";
@@ -286,7 +277,10 @@ import {
286
277
  } from "./chunk-3EUW3WEO.js";
287
278
  import {
288
279
  findModelConfig
289
- } from "./chunk-KYH7XW3K.js";
280
+ } from "./chunk-CD3RU7XL.js";
281
+ import {
282
+ asOptionalTrimmedString
283
+ } from "./chunk-G3SUCT4W.js";
290
284
  import {
291
285
  CLIENT_VERSION_TOO_OLD_CODE,
292
286
  NOLO_CLIENT_VERSION_HEADER,
@@ -295,20 +289,372 @@ import {
295
289
  import {
296
290
  asTrimmedLowercaseString
297
291
  } from "./chunk-QSJ3HFEF.js";
298
- import {
299
- resolveAuthToken
300
- } from "./chunk-2THCNKE4.js";
301
- import {
302
- asOptionalTrimmedString
303
- } from "./chunk-G3SUCT4W.js";
304
292
 
305
293
  // packages/cli/agentRunCommand.ts
294
+ import { createHash as createHash3 } from "node:crypto";
295
+
296
+ // packages/cli/agentRunLocalWorkspace.ts
306
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
+ }
307
653
 
308
654
  // packages/cli/client/instaboxRunConfigWrite.ts
309
655
  import { randomUUID } from "node:crypto";
310
656
  import { lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
311
- import { isAbsolute, join, normalize, resolve } from "node:path";
657
+ import { isAbsolute, join, normalize, resolve as resolve2 } from "node:path";
312
658
  var InstaboxRunConfigWriteError = class extends Error {
313
659
  code;
314
660
  constructor(code, message) {
@@ -345,7 +691,7 @@ function writeInstaboxRunConfig(options) {
345
691
  if (!rawPath) {
346
692
  fail("missing_manifest_path", 'workspaceMode \u4E3A "snapshot" \u65F6\u5FC5\u987B\u63D0\u4F9B manifest \u6587\u4EF6\u8DEF\u5F84');
347
693
  }
348
- const resolvedManifestPath = resolve(rawPath);
694
+ const resolvedManifestPath = resolve2(rawPath);
349
695
  let rawText = "";
350
696
  try {
351
697
  const reader = options.readTextFile ?? ((p) => readFileSync(p, "utf8"));
@@ -415,7 +761,7 @@ function writeInstaboxRunConfig(options) {
415
761
  config.manifestSha256 = manifestSha256;
416
762
  }
417
763
  const runsDir = options.runsDir ?? resolveRunsDir(env);
418
- const normalizedRunsDir = normalize(resolve(runsDir));
764
+ const normalizedRunsDir = normalize(resolve2(runsDir));
419
765
  try {
420
766
  mkdirSync(normalizedRunsDir, { recursive: true, mode: 448 });
421
767
  } catch (err) {
@@ -520,78 +866,6 @@ function resolveCliBatchIdentity(options) {
520
866
  return { batchId, messageIds };
521
867
  }
522
868
 
523
- // packages/cli/client/agentRun.ts
524
- import { resolve as resolveHostReviewPath } from "node:path";
525
-
526
- // packages/cli/client/hostTaskBinding.ts
527
- import { resolve as resolve2 } from "node:path";
528
- function bindHostTask(args) {
529
- let latest;
530
- let completion;
531
- function load() {
532
- if (!args.reference) return void 0;
533
- if (resolve2(args.reference.workspace) !== resolve2(args.workspace) || args.reference.dialogId !== args.dialogId) {
534
- return { authorization: "unknown", reason: "scope_mismatch" };
535
- }
536
- return readHostTask(hostTaskEventsRoot(args.env), args.reference);
537
- }
538
- latest = load();
539
- const contract = args.completionEvidenceProvider && latest && latest.authorization !== "unknown" ? latest.contract : void 0;
540
- const adapter = !args.reference ? args.adapter : {
541
- ...args.adapter,
542
- // Re-read authority before each protected action. A review-only binding owns
543
- // typed review tools, not ordinary chat tools or their existing permission gates.
544
- // Explicit completion tasks retain their all-tool stop semantics; unknown scope
545
- // fails closed. Already running tools are not cancelled by this entry guard.
546
- executeTool: async (call, opts) => {
547
- latest = load();
548
- const authorization = latest?.authorization ?? "unknown";
549
- const protectedTool = call.name === "requestTaskReview" || call.name === "recordTaskReviewDecision";
550
- if (authorization !== "active" && (args.completionEvidenceProvider || protectedTool || authorization === "unknown")) {
551
- const code = authorization === "paused" ? "authorization_paused" : authorization === "revoked" ? "authorization_revoked" : "authorization_unknown";
552
- throw Object.assign(new Error(`host task authority ${authorization}: tool "${call.name}" was not executed`), { code });
553
- }
554
- return args.adapter.executeTool(call, opts);
555
- },
556
- saveTurn: async (input) => {
557
- latest = load();
558
- const stopped = args.signal?.aborted || input.result.businessCompletion?.reasons.includes("stopped");
559
- if (args.completionEvidenceProvider) {
560
- const snapshot = latest && latest.authorization !== "unknown" ? latest.contract : void 0;
561
- let evidence;
562
- try {
563
- evidence = snapshot ? await args.completionEvidenceProvider(snapshot) : void 0;
564
- } catch {
565
- }
566
- latest = load();
567
- const current = latest && latest.authorization !== "unknown" ? latest.contract : void 0;
568
- 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 }, {
569
- stopped,
570
- executionFailed: input.result.error === true || !!input.result.runtimeProviderFailure || !!input.result.emptyAssistantFallbackReason,
571
- budgetExhausted: input.result.businessCompletion?.reasons.includes("budget_exhausted")
572
- });
573
- }
574
- const result = { ...input.result };
575
- delete result.businessCompletion;
576
- if (completion) result.businessCompletion = completion;
577
- try {
578
- return await args.adapter.saveTurn({ ...input, result });
579
- } catch (error) {
580
- if (args.completionEvidenceProvider) completion = { taskId: args.reference.taskId, status: "blocked", reasons: ["execution_failed"] };
581
- throw error;
582
- }
583
- }
584
- };
585
- return {
586
- adapter,
587
- contract,
588
- result: () => args.reference ? {
589
- taskAuthorization: latest?.authorization ?? "unknown",
590
- ...args.completionEvidenceProvider ? { businessCompletion: completion ?? unknownTaskCompletion(args.reference.taskId) } : {}
591
- } : {}
592
- };
593
- }
594
-
595
869
  // packages/agent-runtime/modelLayerOverride.ts
596
870
  var MODEL_LAYER_KEYS = [
597
871
  "provider",
@@ -2652,8 +2926,8 @@ function stripHtmlTags(s) {
2652
2926
  }
2653
2927
  return out;
2654
2928
  }
2655
- function unwrap(s, open, close) {
2656
- 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;
2657
2931
  }
2658
2932
  function cleanLabel(raw) {
2659
2933
  const trimmed = stripHtmlTags(raw.trim()).trim();
@@ -2663,11 +2937,11 @@ function cleanLabel(raw) {
2663
2937
  }
2664
2938
  function displayGenerics(s) {
2665
2939
  let out = "";
2666
- let open = false;
2940
+ let open2 = false;
2667
2941
  for (const c of s) {
2668
2942
  if (c === "~") {
2669
- out += open ? ">" : "<";
2670
- open = !open;
2943
+ out += open2 ? ">" : "<";
2944
+ open2 = !open2;
2671
2945
  } else {
2672
2946
  out += c;
2673
2947
  }
@@ -4748,15 +5022,15 @@ function parseClass(src) {
4748
5022
  }
4749
5023
  if (first === "class") {
4750
5024
  const rest = st.slice("class".length).trim();
4751
- const open = rest.endsWith("{");
4752
- let name = open ? rest.slice(0, -1).trim() : rest;
5025
+ const open2 = rest.endsWith("{");
5026
+ let name = open2 ? rest.slice(0, -1).trim() : rest;
4753
5027
  let label = null;
4754
5028
  const labeled = /^(\S+?)\[(.+)\](:::\S+)?$/.exec(name);
4755
5029
  if (labeled) {
4756
5030
  name = labeled[1] + (labeled[3] ?? "");
4757
5031
  label = nonEmpty(cleanLabel(labeled[2]));
4758
5032
  }
4759
- if (!open && /\s/.test(name)) {
5033
+ if (!open2 && /\s/.test(name)) {
4760
5034
  const assign = parseClassAssign(name);
4761
5035
  if (assign)
4762
5036
  classAssignments.push(assign);
@@ -4764,7 +5038,7 @@ function parseClass(src) {
4764
5038
  graph.drop(st);
4765
5039
  } else if (name === "" || /\s/.test(name)) {
4766
5040
  graph.drop(st);
4767
- if (open)
5041
+ if (open2)
4768
5042
  curClass = "skip";
4769
5043
  } else {
4770
5044
  const idx = declare(name);
@@ -4775,7 +5049,7 @@ function parseClass(src) {
4775
5049
  if (title)
4776
5050
  title[title.length - 1] = label;
4777
5051
  }
4778
- if (open)
5052
+ if (open2)
4779
5053
  curClass = idx ?? "skip";
4780
5054
  }
4781
5055
  } else if (st.startsWith("<<")) {
@@ -4960,15 +5234,15 @@ function parseEr(src) {
4960
5234
  });
4961
5235
  }
4962
5236
  } else {
4963
- const open = st.endsWith("{");
4964
- const decl = open ? st.slice(0, -1).trim() : st;
5237
+ const open2 = st.endsWith("{");
5238
+ const decl = open2 ? st.slice(0, -1).trim() : st;
4965
5239
  if (decl === "" || erTokens(decl).length !== 1) {
4966
5240
  graph.drop(st);
4967
- if (open)
5241
+ if (open2)
4968
5242
  curEntity = "skip";
4969
5243
  } else {
4970
5244
  const idx = erEntity(graph, decl);
4971
- if (open)
5245
+ if (open2)
4972
5246
  curEntity = idx ?? "skip";
4973
5247
  }
4974
5248
  }
@@ -4980,14 +5254,14 @@ function parseEr(src) {
4980
5254
  return graph.nodes.length === 0 ? null : graph;
4981
5255
  }
4982
5256
  function erEntity(graph, token) {
4983
- const open = token.startsWith('"') ? -1 : token.indexOf("[");
5257
+ const open2 = token.startsWith('"') ? -1 : token.indexOf("[");
4984
5258
  let idx;
4985
- if (open !== -1) {
4986
- const id = token.slice(0, open);
5259
+ if (open2 !== -1) {
5260
+ const id = token.slice(0, open2);
4987
5261
  if (!token.endsWith("]")) {
4988
5262
  graph.warnings.push(`entity "${id}": alias is missing its closing \`]\``);
4989
5263
  }
4990
- const label = cleanLabel(token.slice(open + 1).replace(/\]+$/, ""));
5264
+ const label = cleanLabel(token.slice(open2 + 1).replace(/\]+$/, ""));
4991
5265
  if (id === "" || label === "")
4992
5266
  return null;
4993
5267
  idx = graph.nodeLabel(id, label);
@@ -5169,10 +5443,10 @@ function parseSubgraphDecl(rest) {
5169
5443
  return [label, decodeHtmlEntities(label)];
5170
5444
  }
5171
5445
  }
5172
- const open = rest.indexOf("[");
5173
- if (open !== -1) {
5174
- const id = rest.slice(0, open).trim();
5175
- 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());
5176
5450
  if (id !== "" && label !== "")
5177
5451
  return [id, label];
5178
5452
  }
@@ -5733,10 +6007,10 @@ var SHAPES = [
5733
6007
  ["(", ")"]
5734
6008
  ];
5735
6009
  function nodeText(body) {
5736
- for (const [open, close] of SHAPES) {
5737
- const at = body.indexOf(open);
5738
- if (at !== -1 && body.endsWith(close) && body.length > at + open.length + close.length - 1) {
5739
- 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));
5740
6014
  }
5741
6015
  }
5742
6016
  return cleanLabel(body);
@@ -6310,9 +6584,9 @@ function parseState(src) {
6310
6584
  inNote = true;
6311
6585
  } else if (first === "state") {
6312
6586
  const rest = st.slice(firstWord(st).length).trim();
6313
- const open = rest.endsWith("{");
6314
- const body = open ? rest.slice(0, -1).trim() : rest;
6315
- if (!open) {
6587
+ const open2 = rest.endsWith("{");
6588
+ const body = open2 ? rest.slice(0, -1).trim() : rest;
6589
+ if (!open2) {
6316
6590
  if (parseStateDecl(body, graph) === null)
6317
6591
  graph.drop(st);
6318
6592
  } else {
@@ -8144,7 +8418,7 @@ function normalizeListLine(line) {
8144
8418
  }
8145
8419
  return line;
8146
8420
  }
8147
- var TOOL_TREE_HEADER_RE = /^•\s+(.+?)\s+\((\d+)\) · (.*?) ✓$/;
8421
+ var TOOL_TREE_HEADER_RE = /^(?:▸|•)\s+(.+?)\s+\((\d+)\) · (.*?) ✓$/;
8148
8422
  var TOOL_SINGLE_RE = /^▸\s+(.+?)(?:\s+·\s+(.*?))?(?:\s{2}(✓|✗|!)(?:\s+(.*))?)$/;
8149
8423
  function plainToolLine(line) {
8150
8424
  return stripAnsi(line);
@@ -8190,23 +8464,40 @@ function statusColorSeq(marker, brightness) {
8190
8464
  if (marker === "\u2717") return colorSeq("danger", brightness);
8191
8465
  return colorSeq("warning", brightness);
8192
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
+ }
8193
8474
  function styleTuiToolLine(line, brightness) {
8194
8475
  const plain = plainToolLine(line);
8195
8476
  const chrome = colorSeq("chrome", brightness);
8196
8477
  const muted = colorSeq("muted", brightness);
8478
+ const info = colorSeq("info", brightness);
8479
+ const danger = colorSeq("danger", brightness);
8197
8480
  const header = toolTreeHeaderMatch(plain);
8198
8481
  if (header) {
8199
- 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}`;
8200
8484
  }
8201
8485
  const single = plain.match(TOOL_SINGLE_RE);
8202
8486
  if (single) {
8203
8487
  const [, label, detail, marker, statusDetail] = single;
8204
- let rendered = `${chrome}\u25B8${STYLE.reset} ${STYLE.bold}${muted}${label}${STYLE.reset}`;
8205
- 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
+ }
8206
8494
  rendered += ` ${statusColorSeq(marker, brightness)}${marker}${STYLE.reset}`;
8207
8495
  if (statusDetail) {
8208
- const metaSeq = marker === "\u2713" ? chrome : statusColorSeq(marker, brightness);
8209
- 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
+ }
8210
8501
  }
8211
8502
  return rendered;
8212
8503
  }
@@ -8737,6 +9028,9 @@ function formatAssistantTextForCli(text) {
8737
9028
  return text.replace(/\u003cthink\u003e[\s\S]*?\u003c\/think\u003e\s*/gi, "").replace(/\n{3,}/g, "\n\n").trim();
8738
9029
  }
8739
9030
 
9031
+ // packages/cli/client/toolOutput.ts
9032
+ import { createHash as createHash2 } from "node:crypto";
9033
+
8740
9034
  // packages/cli/tui/tuiLayout.ts
8741
9035
  var DEFAULT_TERMINAL_ROWS = 24;
8742
9036
  var DEFAULT_TERMINAL_COLUMNS = 80;
@@ -8768,30 +9062,254 @@ function resolveHistoryViewportHeight(terminalRows, composerRows, foregroundRese
8768
9062
  return Math.max(0, rows - composer - reserved);
8769
9063
  }
8770
9064
 
8771
- // packages/cli/tui/shellCommandGist.ts
8772
- function baseName(path2) {
8773
- const cleaned = path2.replace(/^['"]|['"]$/g, "").replace(/\/+$/, "");
8774
- if (!cleaned || cleaned === "." || cleaned === "..") return void 0;
8775
- const parts = cleaned.split("/").filter(Boolean);
8776
- const base = parts.pop();
8777
- return base || void 0;
9065
+ // packages/core/redactSecrets.ts
9066
+ var REDACTED = "\u27E8redacted\u27E9";
9067
+ function redactSecrets(text) {
9068
+ return text.replace(/\b(?:sk|pk)-[A-Za-z0-9_-]{10,}/g, REDACTED).replace(
9069
+ /\b(Authorization:\s*Basic\s+)[A-Za-z0-9._~+/=-]{8,}/gi,
9070
+ `$1${REDACTED}`
9071
+ ).replace(/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{12,}/gi, `$1${REDACTED}`).replace(
9072
+ /(^|\s)((?:--[a-z0-9-]*(?:token|key|secret|password|credential)[a-z0-9-]*)(?:[^\S\r\n]*=[^\S\r\n]*|[^\S\r\n]+))(?:"(?:\\[^\r\n]|[^"\\\r\n]){8,}(?:"|(?=[\r\n]|$))|'(?:\\[^\r\n]|[^'\\\r\n]){8,}(?:'|(?=[\r\n]|$))|[^\s"']{8,})/gi,
9073
+ `$1$2${REDACTED}`
9074
+ ).replace(
9075
+ /(^|[^\w-])((?:[A-Z0-9]+_)*(?:API[_-]?KEY|APIKEY|ACCESS[_-]?TOKEN|AUTH[_-]?TOKEN|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|KEY)\s*[=:]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n]){8,}(?:"|(?=[\r\n]|$))|'(?:\\[^\r\n]|[^'\\\r\n]){8,}(?:'|(?=[\r\n]|$))|[^\s"',;]{8,})/g,
9076
+ `$1$2${REDACTED}`
9077
+ ).replace(
9078
+ /\b((?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|token|secret|password|passwd|credential)s?\s*[=:]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n]){8,}(?:"|(?=[\r\n]|$))|'(?:\\[^\r\n]|[^'\\\r\n]){8,}(?:'|(?=[\r\n]|$))|[^\s"',;]{8,})/gi,
9079
+ `$1${REDACTED}`
9080
+ );
8778
9081
  }
8779
- function splitSegments(command) {
8780
- const segments = [];
8781
- let current = "";
8782
- let quote = null;
8783
- let hasFallback = false;
8784
- for (let i = 0; i < command.length; i++) {
8785
- const ch = command[i];
8786
- const next = command[i + 1];
8787
- if (quote) {
8788
- if (ch === "\\" && next && quote === '"') {
8789
- current += ch + next;
8790
- i++;
8791
- continue;
8792
- }
8793
- current += ch;
8794
- if (ch === quote) quote = null;
9082
+
9083
+ // packages/cli/tui/redactSecrets.ts
9084
+ var NORMAL_GIST_SECRET_PATTERNS = [
9085
+ /\bbearer\s+[A-Za-z0-9._~+/=-]{8,}/i,
9086
+ /\bsk-(?:ant-)?(?:api)?[0-9a-zA-Z-]{10,}/,
9087
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{10,}/,
9088
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}/
9089
+ ];
9090
+ function withholdIfSecretLike(gist) {
9091
+ if (!gist) return "";
9092
+ if (findPotentialSecrets(gist).length > 0) return "";
9093
+ if (NORMAL_GIST_SECRET_PATTERNS.some((pattern) => pattern.test(gist))) return "";
9094
+ return gist;
9095
+ }
9096
+
9097
+ // packages/core/shellCommandGist.ts
9098
+ function shellWords(text, validationOnly = false) {
9099
+ const words2 = [];
9100
+ let word = "", started = false;
9101
+ let quote;
9102
+ for (let i = 0; i < text.length; i++) {
9103
+ const ch = text[i];
9104
+ if (ch === "\\" && quote !== "'") {
9105
+ const next = text[++i];
9106
+ if (next === void 0) return null;
9107
+ word += next;
9108
+ started = true;
9109
+ continue;
9110
+ }
9111
+ if (ch === "$" && quote !== "'" || ch === "`" && quote !== "'") return null;
9112
+ if (quote) {
9113
+ if (ch === quote) quote = void 0;
9114
+ else word += ch;
9115
+ continue;
9116
+ }
9117
+ if (ch === "'" || ch === '"') {
9118
+ quote = ch;
9119
+ started = true;
9120
+ continue;
9121
+ }
9122
+ if (validationOnly && (ch === "|" || ch === "~")) {
9123
+ word += ch;
9124
+ started = true;
9125
+ continue;
9126
+ }
9127
+ if (/[<> &|;(){}*?\[\]#~]/.test(ch) && !/\s/.test(ch)) return null;
9128
+ if (/\s/.test(ch)) {
9129
+ if (started) words2.push(word);
9130
+ word = "";
9131
+ started = false;
9132
+ } else {
9133
+ word += ch;
9134
+ started = true;
9135
+ }
9136
+ }
9137
+ if (quote) return null;
9138
+ if (started) words2.push(word);
9139
+ return words2;
9140
+ }
9141
+ function isSafeGitTarget(token) {
9142
+ if (!token || token.startsWith("-")) return false;
9143
+ if (/:\/\/|@/.test(token)) return false;
9144
+ return true;
9145
+ }
9146
+ function clipShortText(text, maxLen = 24) {
9147
+ const oneLine = text.replace(/\s+/g, " ").trim();
9148
+ if (!oneLine) return "";
9149
+ return oneLine.length <= maxLen ? oneLine : `${oneLine.slice(0, maxLen - 1)}\u2026`;
9150
+ }
9151
+ function parseGit(rest) {
9152
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9153
+ if (!tokens2) return null;
9154
+ let i = 0, context;
9155
+ while (tokens2[i]?.startsWith("-")) {
9156
+ const option = tokens2[i++];
9157
+ if (["-C", "-c", "--git-dir", "--work-tree"].includes(option)) {
9158
+ const value = tokens2[i++];
9159
+ if (!value || value.startsWith("-")) return null;
9160
+ if (option === "-C") context = value;
9161
+ } else if (!/^(--git-dir|--work-tree)=.+/.test(option) && !["--no-pager", "--no-optional-locks", "--literal-pathspecs"].includes(option)) return null;
9162
+ }
9163
+ const sub = tokens2[i++];
9164
+ const args = tokens2.slice(i);
9165
+ const result = (action, object, readOnly) => ({ action, object, context, readOnly });
9166
+ if (sub === "worktree") {
9167
+ const operation = args.shift();
9168
+ const operands = [];
9169
+ let end = false;
9170
+ for (let j = 0; j < args.length; j++) {
9171
+ const token = args[j];
9172
+ if (!end && token === "--") {
9173
+ end = true;
9174
+ continue;
9175
+ }
9176
+ if (!end && token.startsWith("-")) {
9177
+ if (operation === "add" && ["-b", "-B", "--reason"].includes(token)) {
9178
+ if (!args[++j] || args[j].startsWith("-")) return null;
9179
+ } else if (!(operation === "add" && ["--detach", "--checkout", "--no-checkout", "--lock"].includes(token)) && !(operation === "list" && ["--porcelain", "-v", "--verbose", "-z"].includes(token)) && !(operation === "remove" && ["-f", "--force"].includes(token))) return null;
9180
+ } else operands.push(token);
9181
+ }
9182
+ if (operation === "list" && !operands.length) return result("\u5217\u51FA\u5DE5\u4F5C\u533A", void 0, true);
9183
+ if (operation === "add" && operands.length >= 1 && operands.length <= 2) return result("\u521B\u5EFA\u5DE5\u4F5C\u533A", operands[0], false);
9184
+ if (operation === "remove" && operands.length === 1) return result("\u79FB\u9664\u5DE5\u4F5C\u533A", operands[0], false);
9185
+ return null;
9186
+ }
9187
+ if (sub === "branch") {
9188
+ let mode = "create", end = false;
9189
+ const operands = [];
9190
+ for (const token of args) {
9191
+ if (!end && token === "--") {
9192
+ end = true;
9193
+ continue;
9194
+ }
9195
+ if (!end && token.startsWith("-")) {
9196
+ if (["-d", "-D", "--delete"].includes(token) && mode === "create") mode = "delete";
9197
+ else if (["--list", "-a", "--all", "-r", "--remotes", "-v", "-vv", "--show-current"].includes(token) && mode === "create") mode = "list";
9198
+ else return null;
9199
+ } else operands.push(token);
9200
+ }
9201
+ if (mode === "delete" && operands.length === 1) return result("\u5220\u9664\u5206\u652F", operands[0], false);
9202
+ if (mode === "list" || !args.length) return result("\u5217\u51FA\u5206\u652F", void 0, true);
9203
+ if (mode === "create" && operands.length >= 1 && operands.length <= 2) return result("\u521B\u5EFA\u5206\u652F", operands[0], false);
9204
+ return null;
9205
+ }
9206
+ if (sub === "checkout" && args.some((t2) => t2 === "." || t2 === "--" || t2.includes("/"))) return null;
9207
+ const nonFlagArgs = (list) => {
9208
+ const out = [];
9209
+ for (let j = 0; j < list.length; j++) {
9210
+ const tok = list[j];
9211
+ if (tok === "--") {
9212
+ out.push(...list.slice(j + 1));
9213
+ break;
9214
+ }
9215
+ if (tok.startsWith("-")) {
9216
+ if (["-m", "-F", "-b", "-B", "-n", "--max-count", "--format", "--pretty", "--since", "--until", "--author", "-U"].includes(tok)) j++;
9217
+ continue;
9218
+ }
9219
+ out.push(tok);
9220
+ }
9221
+ return out;
9222
+ };
9223
+ switch (sub) {
9224
+ case "status":
9225
+ return result("\u67E5\u72B6\u6001", void 0, true);
9226
+ case "log":
9227
+ return result("\u67E5\u5386\u53F2", void 0, true);
9228
+ case "rev-list":
9229
+ return result("\u7EDF\u8BA1\u63D0\u4EA4", void 0, true);
9230
+ case "merge-base":
9231
+ return result("\u67E5\u5171\u540C\u7956\u5148", void 0, true);
9232
+ case "rev-parse":
9233
+ return result("\u67E5\u4ED3\u5E93\u4FE1\u606F", void 0, true);
9234
+ case "show": {
9235
+ const target = nonFlagArgs(args)[0];
9236
+ return result("\u770B\u63D0\u4EA4", isSafeGitTarget(target) ? clipShortText(target, 20) : void 0, true);
9237
+ }
9238
+ case "diff": {
9239
+ const target = nonFlagArgs(args).find(isSafeGitTarget);
9240
+ return result("\u770B\u5DEE\u5F02", target ? baseName(target) ?? clipShortText(target, 20) : void 0, true);
9241
+ }
9242
+ case "tag": {
9243
+ const hasMutating = args.some((t2) => ["-d", "--delete", "-a", "-s", "-f", "--force"].includes(t2)) || nonFlagArgs(args).length > 0;
9244
+ return hasMutating ? result("\u7BA1\u6807\u7B7E", void 0, false) : result("\u67E5\u6807\u7B7E", void 0, true);
9245
+ }
9246
+ case "add": {
9247
+ if (args.some((t2) => t2 === "-A" || t2 === "--all" || t2 === ".")) return result("\u6682\u5B58\u5168\u90E8\u4FEE\u6539", void 0, false);
9248
+ const files = nonFlagArgs(args).filter(isSafeGitTarget);
9249
+ if (files.length === 1) return result("\u6682\u5B58", baseName(files[0]) ?? files[0], false);
9250
+ if (files.length > 1) return result("\u6682\u5B58", `${files.length} \u9879`, false);
9251
+ return result("\u6682\u5B58\u4FEE\u6539", void 0, false);
9252
+ }
9253
+ case "commit":
9254
+ return result("\u63D0\u4EA4", void 0, false);
9255
+ case "merge": {
9256
+ const branch = nonFlagArgs(args).find(isSafeGitTarget);
9257
+ return result("\u5408\u5E76", branch ? clipShortText(branch, 28) : void 0, false);
9258
+ }
9259
+ case "checkout":
9260
+ case "switch": {
9261
+ const branch = nonFlagArgs(args).find(isSafeGitTarget);
9262
+ return result("\u5207\u6362\u5206\u652F", branch ? clipShortText(branch, 28) : void 0, false);
9263
+ }
9264
+ case "push": {
9265
+ const parts = nonFlagArgs(args).filter(isSafeGitTarget);
9266
+ const target = parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0];
9267
+ return result("\u63A8\u9001", target ? clipShortText(target, 28) : void 0, false);
9268
+ }
9269
+ case "pull": {
9270
+ const parts = nonFlagArgs(args).filter(isSafeGitTarget);
9271
+ const target = parts.length >= 2 ? `${parts[0]}/${parts[1]}` : parts[0];
9272
+ return result("\u62C9\u53D6", target ? clipShortText(target, 28) : void 0, false);
9273
+ }
9274
+ case "fetch": {
9275
+ const remote = nonFlagArgs(args).find(isSafeGitTarget);
9276
+ return result("\u83B7\u53D6\u8FDC\u7AEF", remote ? clipShortText(remote, 24) : void 0, true);
9277
+ }
9278
+ case "stash": {
9279
+ const op = nonFlagArgs(args)[0];
9280
+ return op === "list" ? result("\u67E5\u8D2E\u85CF", void 0, true) : result("\u6682\u5B58", void 0, false);
9281
+ }
9282
+ case "reset":
9283
+ return result("\u91CD\u7F6E", void 0, false);
9284
+ case "restore":
9285
+ return result("\u6062\u590D\u6587\u4EF6", void 0, false);
9286
+ default:
9287
+ return null;
9288
+ }
9289
+ }
9290
+ function baseName(path2) {
9291
+ const cleaned = path2.replace(/^['"]|['"]$/g, "").replace(/\/+$/, "");
9292
+ if (!cleaned || cleaned === "." || cleaned === "..") return void 0;
9293
+ const parts = cleaned.split("/").filter(Boolean);
9294
+ const base = parts.pop();
9295
+ return base || void 0;
9296
+ }
9297
+ function splitSegments(command) {
9298
+ const segments = [];
9299
+ let current = "";
9300
+ let quote = null;
9301
+ let hasFallback = false;
9302
+ for (let i = 0; i < command.length; i++) {
9303
+ const ch = command[i];
9304
+ const next = command[i + 1];
9305
+ if (quote) {
9306
+ if (ch === "\\" && next && quote === '"') {
9307
+ current += ch + next;
9308
+ i++;
9309
+ continue;
9310
+ }
9311
+ current += ch;
9312
+ if (ch === quote) quote = null;
8795
9313
  continue;
8796
9314
  }
8797
9315
  if (ch === '"' || ch === "'") {
@@ -8830,9 +9348,14 @@ function splitSegments(command) {
8830
9348
  return { segments, hasFallback };
8831
9349
  }
8832
9350
  function stripEnvAssignments(segment) {
8833
- let rest = segment;
8834
- while (/^[A-Za-z_][A-Za-z0-9_]*=\S*\s+/.test(rest)) {
8835
- rest = rest.replace(/^[A-Za-z_][A-Za-z0-9_]*=\S*\s+/, "");
9351
+ let rest = segment.trimStart();
9352
+ if (/^export\s+[A-Za-z_][A-Za-z0-9_]*=/.test(rest)) {
9353
+ rest = rest.replace(/^export\s+/, "");
9354
+ }
9355
+ while (/^[A-Za-z_][A-Za-z0-9_]*=(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\S*)\s*/.test(rest)) {
9356
+ const next = rest.replace(/^[A-Za-z_][A-Za-z0-9_]*=(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\S*)\s*/, "");
9357
+ if (next === rest) break;
9358
+ rest = next;
8836
9359
  }
8837
9360
  return rest;
8838
9361
  }
@@ -8840,182 +9363,399 @@ function firstVerbToken(segment) {
8840
9363
  let rest = stripEnvAssignments(segment).trim();
8841
9364
  const wrappers = /* @__PURE__ */ new Set(["sudo", "env", "command", "time", "nohup", "exec"]);
8842
9365
  let guard = 0;
8843
- while (guard++ < 5) {
9366
+ while (guard++ < 6) {
8844
9367
  const before = rest;
8845
9368
  rest = stripEnvAssignments(rest).trim();
8846
9369
  const m = rest.match(/^(\S+)\s*(.*)$/s);
8847
9370
  if (!m) return { verb: "", rest: "" };
8848
9371
  const [, word, restAfter] = m;
8849
- if (wrappers.has(word) && restAfter.trim()) {
9372
+ const base = word.replace(/^.*\//, "");
9373
+ if (wrappers.has(base) && restAfter.trim()) {
8850
9374
  rest = restAfter.trim();
8851
9375
  continue;
8852
9376
  }
9377
+ if (base === "timeout" && restAfter.trim()) {
9378
+ const tokens2 = shellWords(restAfter.trim());
9379
+ if (!tokens2 || tokens2.length < 2) return { verb: "timeout", rest: restAfter.trim() };
9380
+ let idx = 0;
9381
+ while (idx < tokens2.length && tokens2[idx].startsWith("-")) {
9382
+ const opt = tokens2[idx++];
9383
+ if (["-k", "-s", "--kill-after", "--signal"].includes(opt)) idx++;
9384
+ }
9385
+ if (idx < tokens2.length && /^\d+(?:\.\d+)?[smhd]?$/i.test(tokens2[idx])) idx++;
9386
+ if (idx < tokens2.length) {
9387
+ const inner = tokens2.slice(idx).map((q) => /\s/.test(q) ? JSON.stringify(q) : q).join(" ");
9388
+ rest = inner;
9389
+ continue;
9390
+ }
9391
+ }
8853
9392
  if (before !== rest && !rest) return { verb: "", rest: "" };
8854
- return { verb: word.replace(/^.*\//, ""), rest: restAfter.trim() };
9393
+ return { verb: base, rest: restAfter.trim() };
8855
9394
  }
8856
9395
  return { verb: "", rest };
8857
9396
  }
9397
+ function extractSafeSearchTarget(rest) {
9398
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9399
+ if (!tokens2) return void 0;
9400
+ const valuedOpts = /* @__PURE__ */ new Set(["-e", "-f", "-g", "--glob", "-t", "--type", "-T", "--type-not", "-A", "-B", "-C", "-m", "--max-count", "--max-filesize", "--color", "--sort"]);
9401
+ let hasExtendedRegex = false;
9402
+ let pattern;
9403
+ for (let i = 0; i < tokens2.length; i++) {
9404
+ const tok = tokens2[i];
9405
+ if (tok === "--") {
9406
+ pattern = tokens2[i + 1];
9407
+ break;
9408
+ }
9409
+ if (tok.startsWith("-")) {
9410
+ if (tok === "-E" || tok === "-P" || tok === "--extended-regexp") hasExtendedRegex = true;
9411
+ if (valuedOpts.has(tok)) {
9412
+ if (tok === "-e" && !pattern && tokens2[i + 1]) pattern = tokens2[i + 1];
9413
+ i++;
9414
+ }
9415
+ continue;
9416
+ }
9417
+ pattern = tok;
9418
+ break;
9419
+ }
9420
+ if (!pattern || hasExtendedRegex || /[|[\]^$()*+?\\]/.test(pattern)) return void 0;
9421
+ return clipShortText(pattern, 22);
9422
+ }
9423
+ function parseSed(rest) {
9424
+ const rawTokens = shellWords(rest.split(/\s+\|\s+/)[0]);
9425
+ if (!rawTokens) return null;
9426
+ let quiet = false;
9427
+ let inPlace = false;
9428
+ const scripts = [];
9429
+ const positional = [];
9430
+ for (let i = 0; i < rawTokens.length; i++) {
9431
+ const tok = rawTokens[i];
9432
+ if (tok === "--") {
9433
+ positional.push(...rawTokens.slice(i + 1));
9434
+ break;
9435
+ }
9436
+ if (tok.startsWith("-") && tok.length > 1) {
9437
+ if (tok === "--quiet" || tok === "--silent") {
9438
+ quiet = true;
9439
+ continue;
9440
+ }
9441
+ if (tok === "--in-place" || tok.startsWith("--in-place=")) {
9442
+ inPlace = true;
9443
+ continue;
9444
+ }
9445
+ if (tok === "--regexp-extended") continue;
9446
+ if (tok.startsWith("--expression=")) {
9447
+ scripts.push(tok.slice("--expression=".length));
9448
+ continue;
9449
+ }
9450
+ if (tok === "--expression") {
9451
+ if (rawTokens[i + 1] === void 0) return null;
9452
+ scripts.push(rawTokens[++i]);
9453
+ continue;
9454
+ }
9455
+ if (tok.startsWith("--")) return null;
9456
+ for (let c = 1; c < tok.length; c++) {
9457
+ const flag = tok[c];
9458
+ if (flag === "n") {
9459
+ quiet = true;
9460
+ continue;
9461
+ }
9462
+ if (flag === "r" || flag === "E") continue;
9463
+ if (flag === "i") {
9464
+ inPlace = true;
9465
+ if (c === tok.length - 1 && rawTokens[i + 1] === "") i++;
9466
+ break;
9467
+ }
9468
+ if (flag === "e") {
9469
+ if (c + 1 < tok.length) {
9470
+ scripts.push(tok.slice(c + 1));
9471
+ } else {
9472
+ if (rawTokens[i + 1] === void 0) return null;
9473
+ scripts.push(rawTokens[++i]);
9474
+ }
9475
+ break;
9476
+ }
9477
+ return null;
9478
+ }
9479
+ continue;
9480
+ }
9481
+ positional.push(tok);
9482
+ }
9483
+ const isSedScript = (tok) => /^(?:\d+|\$)(?:,\s*(?:\d+|\$))?[pdq=!]?$/.test(tok) || /^s[|/#]/.test(tok) || /^\/.*\/[pd=!]?$/.test(tok) || /^\d+[ew]/.test(tok);
9484
+ for (const tok of positional) {
9485
+ if (isSedScript(tok)) scripts.push(tok);
9486
+ }
9487
+ const files = positional.filter((t2) => !isSedScript(t2));
9488
+ if (scripts.length === 0 && files.length >= 2) {
9489
+ scripts.push(files.shift());
9490
+ }
9491
+ const fileToken = files[files.length - 1];
9492
+ const target = fileToken ? baseName(fileToken) : void 0;
9493
+ if (inPlace) {
9494
+ const isSafeSub = (part) => {
9495
+ if (part.length < 4 || part[0] !== "s") return false;
9496
+ const delim = part[1];
9497
+ if (delim !== "|" && delim !== "/" && delim !== "#") return false;
9498
+ let delimsSeen = 1;
9499
+ let idx = 2;
9500
+ for (; idx < part.length && delimsSeen < 3; idx++) {
9501
+ const ch = part[idx];
9502
+ if (ch === "\\" && idx + 1 < part.length) {
9503
+ idx++;
9504
+ continue;
9505
+ }
9506
+ if (ch === delim) delimsSeen++;
9507
+ }
9508
+ if (delimsSeen !== 3) return false;
9509
+ return /^[gipI]*$/.test(part.slice(idx));
9510
+ };
9511
+ const allSafe = scripts.every((s) => {
9512
+ const parts = s.split(";").map((p) => p.trim()).filter(Boolean);
9513
+ return parts.length > 0 && parts.every(isSafeSub);
9514
+ });
9515
+ if (!allSafe) return null;
9516
+ const replaceCount = (rest.match(/s[|/#][^|/#]*[|/#][^|/#]*[|/#]/g) ?? []).length;
9517
+ return {
9518
+ verb: "\u7F16\u8F91",
9519
+ target,
9520
+ count: replaceCount > 1 ? replaceCount : void 0,
9521
+ unit: "\u5904\u66FF\u6362",
9522
+ readOnly: false
9523
+ };
9524
+ }
9525
+ if (quiet) {
9526
+ const isStrictReadOnlyPrint = (s) => /^(?:\d+|\$)(?:\s*,\s*(?:\d+|\$))?\s*p$/.test(s.trim());
9527
+ if (scripts.length === 0 || !scripts.every(isStrictReadOnlyPrint)) {
9528
+ return null;
9529
+ }
9530
+ return { verb: "\u67E5\u770B", target, readOnly: true };
9531
+ }
9532
+ return { verb: "\u5904\u7406\u6587\u672C", target, readOnly: false };
9533
+ }
9534
+ function parseNolo(rest) {
9535
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9536
+ if (!tokens2 || tokens2.length === 0) return null;
9537
+ const sub = tokens2[0];
9538
+ const action = tokens2[1];
9539
+ const nonFlag = tokens2.slice(2).filter((t2) => !t2.startsWith("-"));
9540
+ if (sub === "browser" || sub === "chrome") {
9541
+ const map = {
9542
+ status: ["\u67E5\u6D4F\u89C8\u5668\u72B6\u6001", true],
9543
+ "list-tabs": ["\u5217\u6D4F\u89C8\u5668\u6807\u7B7E", true],
9544
+ "read-page": ["\u6D4F\u89C8\u5668\u8BFB\u9875\u9762", true],
9545
+ "read-network": ["\u67E5\u6D4F\u89C8\u5668\u8BF7\u6C42", true],
9546
+ screenshot: ["\u6D4F\u89C8\u5668\u622A\u56FE", true],
9547
+ "open-tab": ["\u6D4F\u89C8\u5668\u5F00\u6807\u7B7E", false],
9548
+ click: ["\u6D4F\u89C8\u5668\u70B9\u51FB", false],
9549
+ type: ["\u6D4F\u89C8\u5668\u8F93\u5165", false],
9550
+ press: ["\u6D4F\u89C8\u5668\u6309\u952E", false]
9551
+ };
9552
+ if (action && map[action]) return { verb: map[action][0], readOnly: map[action][1] };
9553
+ return { verb: "\u6D4F\u89C8\u5668\u64CD\u4F5C", readOnly: false };
9554
+ }
9555
+ if (sub === "agent") {
9556
+ if (action === "list" || action === "providers" || action === "models") return { verb: action === "list" ? "\u5217\u667A\u80FD\u4F53" : "\u5217\u6A21\u578B\u901A\u9053", readOnly: true };
9557
+ if (action === "read") return { verb: "\u8BFB\u667A\u80FD\u4F53", target: nonFlag[0] ? clipShortText(nonFlag[0], 24) : void 0, readOnly: true };
9558
+ if (action === "create") return { verb: "\u521B\u5EFA\u667A\u80FD\u4F53", target: nonFlag[0] ? clipShortText(nonFlag[0], 24) : void 0, readOnly: false };
9559
+ if (action === "delete") return { verb: "\u5220\u9664\u667A\u80FD\u4F53", target: nonFlag[0] ? clipShortText(nonFlag[0], 24) : void 0, readOnly: false };
9560
+ return { verb: "\u7BA1\u7406\u667A\u80FD\u4F53", readOnly: false };
9561
+ }
9562
+ if (sub === "dialog") {
9563
+ if (action === "list") return { verb: "\u5217\u5BF9\u8BDD", readOnly: true };
9564
+ if (action === "read") return { verb: "\u8BFB\u5BF9\u8BDD", target: nonFlag[0] ? clipShortText(nonFlag[0], 20) : void 0, readOnly: true };
9565
+ if (action === "status") return { verb: "\u67E5\u5BF9\u8BDD\u72B6\u6001", readOnly: true };
9566
+ if (action === "search") return { verb: "\u641C\u5BF9\u8BDD", readOnly: true };
9567
+ return { verb: "\u7BA1\u5BF9\u8BDD", readOnly: false };
9568
+ }
9569
+ if (sub === "secret") {
9570
+ if (action === "list") return { verb: "\u5217\u51ED\u636E", readOnly: true };
9571
+ if (action === "run") return { verb: "\u5E26\u51ED\u636E\u6267\u884C", readOnly: false };
9572
+ return { verb: "\u7BA1\u51ED\u636E", readOnly: false };
9573
+ }
9574
+ if (sub === "ci") return { verb: "\u67E5 CI \u72B6\u6001", readOnly: true };
9575
+ return null;
9576
+ }
8858
9577
  function classifySegment(segment) {
8859
9578
  const { verb, rest } = firstVerbToken(segment);
8860
9579
  if (!verb) return null;
8861
9580
  switch (verb) {
8862
9581
  case "cd":
8863
- return { verb: "\u8FDB\u5165\u76EE\u5F55", target: baseName(rest) };
9582
+ return { verb: "\u8FDB\u5165\u76EE\u5F55", target: baseName(rest), readOnly: true };
8864
9583
  case "mkdir":
8865
- return { verb: "\u5EFA\u76EE\u5F55", target: baseName(rest.replace(/^-\S+\s+/, "")) };
9584
+ return { verb: "\u5EFA\u76EE\u5F55", target: baseName(rest.replace(/^-\S+\s+/, "")), readOnly: false };
8866
9585
  case "cp":
8867
- return { verb: "\u590D\u5236", target: baseName(rest.split(/\s+/).pop() ?? "") };
9586
+ return { verb: "\u590D\u5236", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
8868
9587
  case "mv":
8869
- return { verb: "\u79FB\u52A8", target: baseName(rest.split(/\s+/).pop() ?? "") };
9588
+ return { verb: "\u79FB\u52A8", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
8870
9589
  case "rm":
8871
- return { verb: "\u5220\u9664", target: baseName(rest.split(/\s+/).pop() ?? "") };
9590
+ return { verb: "\u5220\u9664", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
8872
9591
  case "touch":
8873
- return { verb: "\u521B\u5EFA\u6587\u4EF6", target: baseName(rest) };
8874
- case "cat":
8875
- return { verb: "\u8BFB\u53D6", target: baseName(rest.split(/\s+/)[0] ?? "") };
8876
- case "ls":
8877
- return { verb: "\u5217\u51FA\u76EE\u5F55" };
9592
+ return { verb: "\u521B\u5EFA\u6587\u4EF6", target: baseName(rest), readOnly: false };
9593
+ case "cat": {
9594
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9595
+ const file = tokens2?.find((t2) => !t2.startsWith("-"));
9596
+ return { verb: "\u8BFB\u53D6", target: baseName(file ?? rest.split(/\s+/)[0] ?? ""), readOnly: true };
9597
+ }
9598
+ case "ls": {
9599
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9600
+ const dir = tokens2?.find((t2) => !t2.startsWith("-"));
9601
+ return { verb: "\u5217\u51FA\u76EE\u5F55", target: dir ? baseName(dir) : void 0, readOnly: true };
9602
+ }
8878
9603
  case "grep":
8879
9604
  case "rg":
8880
- return { verb: "\u641C\u7D22" };
9605
+ return { verb: "\u641C\u7D22", target: extractSafeSearchTarget(rest), readOnly: true };
8881
9606
  case "chmod":
8882
- return { verb: "\u6539\u6743\u9650", target: baseName(rest.split(/\s+/).pop() ?? "") };
9607
+ return { verb: "\u6539\u6743\u9650", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
8883
9608
  case "chown":
8884
- return { verb: "\u6539\u5C5E\u4E3B", target: baseName(rest.split(/\s+/).pop() ?? "") };
9609
+ return { verb: "\u6539\u5C5E\u4E3B", target: baseName(rest.split(/\s+/).pop() ?? ""), readOnly: false };
8885
9610
  case "tar":
8886
9611
  case "unzip":
8887
- return { verb: "\u89E3\u538B" };
9612
+ return { verb: "\u89E3\u538B", readOnly: false };
8888
9613
  case "git": {
8889
- const rawTokens = rest.split(/\s+/).filter(Boolean);
8890
- const subIndex = rawTokens.findIndex((t2) => !t2.startsWith("-"));
8891
- const sub = subIndex >= 0 ? rawTokens[subIndex] : "";
8892
- if (sub === "checkout") {
8893
- const args = rawTokens.slice(subIndex + 1);
8894
- const looksLikePath = args.some(
8895
- (t2) => t2 === "." || t2 === "--" || t2.includes("/") || t2.endsWith("*")
8896
- );
8897
- if (looksLikePath) return null;
8898
- }
8899
- const gitVerbs = {
8900
- clone: "\u514B\u9686\u4ED3\u5E93",
8901
- status: "\u67E5\u72B6\u6001",
8902
- add: "\u6682\u5B58\u6539\u52A8",
8903
- commit: "\u63D0\u4EA4",
8904
- push: "\u63A8\u9001",
8905
- pull: "\u62C9\u53D6",
8906
- fetch: "\u6293\u53D6\u8FDC\u7AEF",
8907
- checkout: "\u5207\u6362\u5206\u652F",
8908
- switch: "\u5207\u6362\u5206\u652F",
8909
- merge: "\u5408\u5E76",
8910
- rebase: "\u53D8\u57FA",
8911
- log: "\u67E5\u5386\u53F2",
8912
- diff: "\u770B\u5DEE\u5F02",
8913
- worktree: "\u7BA1\u7406\u5DE5\u4F5C\u533A",
8914
- branch: "\u7BA1\u7406\u5206\u652F",
8915
- stash: "\u6682\u5B58",
8916
- reset: "\u91CD\u7F6E",
8917
- restore: "\u6062\u590D\u6587\u4EF6"
8918
- };
8919
- const mapped = gitVerbs[sub];
8920
- return mapped ? { verb: mapped } : null;
9614
+ const parsed = parseGit(rest);
9615
+ return parsed ? { verb: parsed.action, target: parsed.object, readOnly: parsed.readOnly } : null;
9616
+ }
9617
+ case "sed":
9618
+ return parseSed(rest);
9619
+ case "nolo":
9620
+ return parseNolo(rest);
9621
+ case "gh": {
9622
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9623
+ if (!tokens2?.length) return null;
9624
+ const sub = tokens2[0];
9625
+ const op = tokens2[1];
9626
+ const isRead = ["view", "list", "status", "checks", "diff"].includes(op ?? "");
9627
+ if (sub === "pr") return { verb: isRead ? "\u67E5 PR" : "\u64CD\u4F5C PR", readOnly: isRead };
9628
+ if (sub === "run") return { verb: isRead ? "\u67E5 CI \u8FD0\u884C" : "\u64CD\u4F5C CI \u8FD0\u884C", readOnly: isRead };
9629
+ if (sub === "issue") return { verb: isRead ? "\u67E5 Issue" : "\u64CD\u4F5C Issue", readOnly: isRead };
9630
+ if (sub === "api") return { verb: "\u8C03 GitHub API", readOnly: false };
9631
+ return null;
8921
9632
  }
8922
- case "sed": {
8923
- const replaceCount = (rest.match(/s[|/#][^|/#]*[|/#][^|/#]*[|/#]/g) ?? []).length;
8924
- const tokens2 = rest.split(/\s+/).filter((t2) => t2 && !t2.startsWith("-"));
8925
- const fileToken = [...tokens2].reverse().find((t2) => !/[|/#]/.test(t2));
8926
- return {
8927
- verb: "\u7F16\u8F91",
8928
- target: baseName(fileToken ?? ""),
8929
- count: replaceCount > 1 ? replaceCount : void 0,
8930
- unit: "\u5904\u66FF\u6362"
8931
- };
9633
+ case "ps":
9634
+ return { verb: "\u67E5\u8FDB\u7A0B", readOnly: true };
9635
+ case "sha256sum": {
9636
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9637
+ const file = tokens2?.find((t2) => !t2.startsWith("-"));
9638
+ return { verb: "\u7B97\u6821\u9A8C\u548C", target: file ? baseName(file) : void 0, readOnly: true };
8932
9639
  }
8933
9640
  case "dnf":
8934
9641
  case "yum": {
8935
9642
  const sub = rest.split(/\s+/)[0] ?? "";
8936
- if (sub === "install") return { verb: "\u88C5\u8F6F\u4EF6\u5305" };
8937
- if (sub === "remove" || sub === "erase") return { verb: "\u5378\u8F7D\u8F6F\u4EF6\u5305" };
8938
- if (sub === "update" || sub === "upgrade") return { verb: "\u66F4\u65B0\u7CFB\u7EDF" };
8939
- if (sub === "search") return { verb: "\u641C\u7D22\u8F6F\u4EF6\u5305" };
8940
- if (sub === "list") return { verb: "\u5217\u51FA\u8F6F\u4EF6\u5305" };
8941
- if (sub === "history") return { verb: "\u67E5\u5B89\u88C5\u5386\u53F2" };
9643
+ if (sub === "install") return { verb: "\u88C5\u8F6F\u4EF6\u5305", readOnly: false };
9644
+ if (sub === "remove" || sub === "erase") return { verb: "\u5378\u8F7D\u8F6F\u4EF6\u5305", readOnly: false };
9645
+ if (sub === "update" || sub === "upgrade") return { verb: "\u66F4\u65B0\u7CFB\u7EDF", readOnly: false };
9646
+ if (sub === "search") return { verb: "\u641C\u7D22\u8F6F\u4EF6\u5305", readOnly: true };
9647
+ if (sub === "list") return { verb: "\u5217\u51FA\u8F6F\u4EF6\u5305", readOnly: true };
9648
+ if (sub === "history") return { verb: "\u67E5\u5B89\u88C5\u5386\u53F2", readOnly: true };
8942
9649
  return null;
8943
9650
  }
8944
9651
  case "rpm":
8945
9652
  case "pacman":
8946
9653
  case "apt":
8947
9654
  case "apt-get":
8948
- return { verb: "\u7BA1\u8F6F\u4EF6\u5305" };
9655
+ return { verb: "\u7BA1\u8F6F\u4EF6\u5305", readOnly: false };
8949
9656
  case "systemctl":
8950
9657
  case "journalctl": {
8951
9658
  const tokens2 = rest.split(/\s+/).filter((t2) => t2 && !t2.startsWith("-"));
8952
9659
  const sub = tokens2[0] ?? "";
8953
- if (verb === "journalctl") return { verb: "\u67E5\u65E5\u5FD7" };
9660
+ if (verb === "journalctl") return { verb: "\u67E5\u65E5\u5FD7", readOnly: true };
8954
9661
  const sysVerbs = {
8955
- start: "\u542F\u52A8\u670D\u52A1",
8956
- stop: "\u505C\u6B62\u670D\u52A1",
8957
- restart: "\u91CD\u542F\u670D\u52A1",
8958
- status: "\u67E5\u670D\u52A1\u72B6\u6001",
8959
- enable: "\u542F\u7528\u670D\u52A1",
8960
- disable: "\u505C\u7528\u670D\u52A1",
8961
- "daemon-reload": "\u91CD\u8F7D\u670D\u52A1\u914D\u7F6E",
8962
- "list-units": "\u5217\u670D\u52A1",
8963
- "list-unit-files": "\u5217\u670D\u52A1",
8964
- is: "\u67E5\u670D\u52A1\u72B6\u6001",
8965
- cat: "\u770B\u670D\u52A1\u5B9A\u4E49"
9662
+ start: ["\u542F\u52A8\u670D\u52A1", false],
9663
+ stop: ["\u505C\u6B62\u670D\u52A1", false],
9664
+ restart: ["\u91CD\u542F\u670D\u52A1", false],
9665
+ status: ["\u67E5\u670D\u52A1\u72B6\u6001", true],
9666
+ enable: ["\u542F\u7528\u670D\u52A1", false],
9667
+ disable: ["\u505C\u7528\u670D\u52A1", false],
9668
+ "daemon-reload": ["\u91CD\u8F7D\u670D\u52A1\u914D\u7F6E", false],
9669
+ "list-units": ["\u5217\u670D\u52A1", true],
9670
+ "list-unit-files": ["\u5217\u670D\u52A1", true],
9671
+ is: ["\u67E5\u670D\u52A1\u72B6\u6001", true],
9672
+ cat: ["\u770B\u670D\u52A1\u5B9A\u4E49", true]
8966
9673
  };
8967
9674
  const mapped = sysVerbs[sub];
8968
- return mapped ? { verb: mapped } : null;
9675
+ return mapped ? { verb: mapped[0], readOnly: mapped[1] } : null;
8969
9676
  }
8970
9677
  case "awk":
8971
- return { verb: "\u5904\u7406\u6587\u672C" };
9678
+ return { verb: "\u5904\u7406\u6587\u672C", readOnly: true };
8972
9679
  case "find": {
8973
9680
  if (/(?:^|\s)(?:-delete|-exec|-execdir|-ok|-okdir)(?:\s|$)/.test(rest)) return null;
8974
- return { verb: "\u67E5\u627E\u6587\u4EF6" };
9681
+ return { verb: "\u67E5\u627E\u6587\u4EF6", readOnly: true };
8975
9682
  }
8976
9683
  case "curl":
8977
9684
  case "wget":
8978
- return { verb: "\u4E0B\u8F7D" };
9685
+ return { verb: "\u4E0B\u8F7D", readOnly: false };
8979
9686
  case "bun":
8980
9687
  case "npm":
8981
9688
  case "pnpm":
8982
9689
  case "yarn": {
8983
- const tokens2 = rest.split(/\s+/).filter(Boolean);
9690
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]) ?? rest.split(/\s+/).filter(Boolean);
8984
9691
  const sub = tokens2[0] ?? "";
8985
9692
  if (sub === "test") {
8986
9693
  const target = tokens2.slice(1).find((t2) => !t2.startsWith("-"));
8987
- return { verb: "\u8DD1\u6D4B\u8BD5", target: target ? baseName(target) : void 0 };
9694
+ return { verb: "\u8DD1\u6D4B\u8BD5", target: target ? baseName(target) : void 0, readOnly: false };
8988
9695
  }
8989
- if (sub === "install" || sub === "i" || sub === "add") return { verb: "\u88C5\u4F9D\u8D56" };
9696
+ if (sub === "install" || sub === "i" || sub === "add") return { verb: "\u88C5\u4F9D\u8D56", readOnly: false };
8990
9697
  if (sub === "run") {
8991
9698
  const script = tokens2[1];
8992
- return { verb: "\u8DD1\u811A\u672C", target: script };
9699
+ return { verb: "\u8DD1\u811A\u672C", target: script, readOnly: false };
8993
9700
  }
8994
- if (sub === "build") return { verb: "\u6784\u5EFA" };
9701
+ if (sub === "build") return { verb: "\u6784\u5EFA", readOnly: false };
8995
9702
  if (sub === "x" || sub === "exec") {
8996
- return { verb: "\u6267\u884C", target: tokens2[1] };
9703
+ return { verb: "\u6267\u884C", target: tokens2[1], readOnly: false };
9704
+ }
9705
+ if (verb === "bun" && (sub === "-e" || sub === "-p" || sub === "--inline-heredoc" || tokens2.includes("--inline-heredoc"))) {
9706
+ return { verb: "\u6267\u884C\u5185\u8054\u811A\u672C (Bun)", readOnly: false };
9707
+ }
9708
+ const scriptFile = tokens2.find((t2) => !t2.startsWith("-") && (/\.(?:ts|tsx|js|mjs|mts|cjs)$/i.test(t2) || t2.includes("/")));
9709
+ if (scriptFile) {
9710
+ return { verb: "\u8FD0\u884C\u811A\u672C", target: baseName(scriptFile), readOnly: false };
8997
9711
  }
8998
9712
  return null;
8999
9713
  }
9000
- case "node":
9001
9714
  case "python":
9002
- case "python3":
9715
+ case "python3": {
9716
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]) ?? [];
9717
+ if (tokens2.includes("--inline-heredoc") || /(?:^|\s)-[A-Za-z]*c(?:\s|$)/.test(rest)) {
9718
+ return { verb: "\u6267\u884C\u5185\u8054\u811A\u672C (Python)", readOnly: false };
9719
+ }
9720
+ const script = rest.split(/\s+/).find((t2) => t2 && !t2.startsWith("-"));
9721
+ return { verb: "\u6267\u884C\u811A\u672C", target: baseName(script ?? ""), readOnly: false };
9722
+ }
9723
+ case "node": {
9724
+ if (/(?:^|\s)-[A-Za-z]*e(?:\s|$)/.test(rest)) return null;
9725
+ const script = rest.split(/\s+/).find((t2) => t2 && !t2.startsWith("-"));
9726
+ return { verb: "\u6267\u884C\u811A\u672C", target: baseName(script ?? ""), readOnly: false };
9727
+ }
9003
9728
  case "bash":
9004
9729
  case "sh":
9005
9730
  case "zsh": {
9006
9731
  if (/(?:^|\s)-[A-Za-z]*[ce](?:\s|$)/.test(rest)) return null;
9007
9732
  const script = rest.split(/\s+/).find((t2) => t2 && !t2.startsWith("-"));
9008
- return { verb: "\u6267\u884C\u811A\u672C", target: baseName(script ?? "") };
9733
+ return { verb: "\u6267\u884C\u811A\u672C", target: baseName(script ?? ""), readOnly: false };
9009
9734
  }
9010
9735
  case "echo":
9011
9736
  case "printf":
9012
- return { verb: "\u8F93\u51FA" };
9737
+ return { verb: "\u8F93\u51FA", readOnly: true };
9013
9738
  case "head":
9014
9739
  case "tail":
9015
9740
  case "wc":
9016
9741
  case "sort":
9017
- case "uniq":
9018
- return { verb: "\u67E5\u770B\u8F93\u51FA" };
9742
+ case "uniq": {
9743
+ const tokens2 = shellWords(rest.split(/\s+\|\s+/)[0]);
9744
+ let file;
9745
+ if (tokens2) {
9746
+ for (let i = 0; i < tokens2.length; i++) {
9747
+ const tok = tokens2[i];
9748
+ if (tok === "-n" || tok === "-c") {
9749
+ i++;
9750
+ continue;
9751
+ }
9752
+ if (tok.startsWith("-")) continue;
9753
+ file = tok;
9754
+ break;
9755
+ }
9756
+ }
9757
+ return file ? { verb: "\u67E5\u770B", target: baseName(file), readOnly: true } : { verb: "\u67E5\u770B\u8F93\u51FA", readOnly: true };
9758
+ }
9019
9759
  default:
9020
9760
  return null;
9021
9761
  }
@@ -9118,13 +9858,77 @@ function hasNonFilterPipeline(command) {
9118
9858
  }
9119
9859
  return false;
9120
9860
  }
9861
+ function collapseSafeHeredocs(command) {
9862
+ const lines = command.split(/\r?\n/);
9863
+ const out = [];
9864
+ for (let i = 0; i < lines.length; i++) {
9865
+ const line = lines[i];
9866
+ const trimmed = line.trim();
9867
+ if (!trimmed) continue;
9868
+ const hd = trimmed.match(/^(.*?)\s*<<-?\s*'([A-Za-z0-9_]+)'\s*$/);
9869
+ if (hd) {
9870
+ const head = hd[1].trim();
9871
+ const tag = hd[2];
9872
+ let end = -1;
9873
+ for (let j = i + 1; j < lines.length; j++) {
9874
+ if (lines[j].trim() === tag) {
9875
+ end = j;
9876
+ break;
9877
+ }
9878
+ }
9879
+ if (end === -1) return null;
9880
+ out.push(`${head} --inline-heredoc`);
9881
+ i = end;
9882
+ continue;
9883
+ }
9884
+ out.push(trimmed);
9885
+ }
9886
+ return out.join("\n");
9887
+ }
9888
+ function normalizeTopLevelNewlines(command) {
9889
+ let out = "";
9890
+ let quote = null;
9891
+ for (let i = 0; i < command.length; i++) {
9892
+ const ch = command[i];
9893
+ const next = command[i + 1];
9894
+ if (quote) {
9895
+ if (ch === "\\" && next && quote === '"') {
9896
+ out += ch + next;
9897
+ i++;
9898
+ continue;
9899
+ }
9900
+ if (ch === quote) quote = null;
9901
+ out += ch === "\n" ? " " : ch;
9902
+ continue;
9903
+ }
9904
+ if (ch === '"' || ch === "'") {
9905
+ quote = ch;
9906
+ out += ch;
9907
+ continue;
9908
+ }
9909
+ if (ch === "\\" && next) {
9910
+ out += ch + next;
9911
+ i++;
9912
+ continue;
9913
+ }
9914
+ if (ch === "\n") {
9915
+ if (!out.endsWith("&& ") && out.trim().length > 0) out += " && ";
9916
+ continue;
9917
+ }
9918
+ out += ch;
9919
+ }
9920
+ return out.replace(/(?:\s*&&\s*)+$/, "").trim();
9921
+ }
9121
9922
  function summarizeShellCommand(command) {
9122
- const normalized = command.split(/\r?\n/).map((line) => line.replace(/\s+/g, " ").trim()).filter(Boolean).join(" && ");
9923
+ const collapsed = collapseSafeHeredocs(command);
9924
+ if (collapsed === null) return null;
9925
+ const normalized = normalizeTopLevelNewlines(collapsed);
9123
9926
  if (!normalized) return null;
9124
9927
  if (hasNonFilterPipeline(normalized)) return null;
9125
9928
  const { segments, hasFallback } = splitSegments(normalized);
9126
9929
  if (segments.length === 0) return null;
9127
9930
  if (hasFallback) return null;
9931
+ if (segments.some((segment) => !shellWords(segment, true))) return null;
9128
9932
  const actions = [];
9129
9933
  for (const segment of segments) {
9130
9934
  const action = classifySegment(segment);
@@ -9133,7 +9937,86 @@ function summarizeShellCommand(command) {
9133
9937
  }
9134
9938
  const summary = summarizeActions(actions);
9135
9939
  if (!summary) return null;
9136
- return { summary, foldedSegments: segments.length };
9940
+ const readOnly = actions.every((a) => a.readOnly === true);
9941
+ const single = segments.length === 1 ? firstVerbToken(segments[0]) : void 0;
9942
+ const git = single?.verb === "git" ? parseGit(single.rest) : null;
9943
+ const singleAction = segments.length === 1 && !actions[0]?.count ? { action: actions[0].verb, ...actions[0].target ? { object: actions[0].target } : {} } : {};
9944
+ return { summary, foldedSegments: segments.length, readOnly, ...singleAction, ...git ?? {} };
9945
+ }
9946
+
9947
+ // packages/core/toolActivityPresentation.ts
9948
+ var families = {
9949
+ readFile: ["read", "\u8BFB\u53D6", ["path"], true],
9950
+ read_file: ["read", "\u8BFB\u53D6", ["path"], true],
9951
+ readWorkspaceFile: ["read", "\u8BFB\u53D6", ["path"], true],
9952
+ writeFile: ["write", "\u5199\u5165", ["path"], false],
9953
+ editFile: ["edit", "\u4FEE\u6539", ["path"], false],
9954
+ globFiles: ["find", "\u67E5\u627E\u6587\u4EF6", ["pattern", "path"], true],
9955
+ search: ["search", "\u641C\u7D22", ["query", "pattern"], true],
9956
+ grep: ["search", "\u641C\u7D22", ["pattern", "query"], true],
9957
+ loadSkill: ["skill", "\u52A0\u8F7D\u6280\u80FD", ["name", "slug"], true]
9958
+ };
9959
+ var shellTools = /* @__PURE__ */ new Set(["execShell", "exec_shell", "runCommand", "launchProcess"]);
9960
+ function projectToolActivity(input, translate) {
9961
+ const text = (...keys) => {
9962
+ for (const key of keys) {
9963
+ const value = input.args?.[key];
9964
+ if (typeof value === "string" && value.length) return value;
9965
+ }
9966
+ return void 0;
9967
+ };
9968
+ let action = input.toolName, object, summary, readOnly = false;
9969
+ let confidence = "raw-fallback";
9970
+ let context = text("cwd");
9971
+ if (shellTools.has(input.toolName)) {
9972
+ object = text("command", "cmd");
9973
+ const gist = object ? summarizeShellCommand(object) : null;
9974
+ action = gist?.action ?? gist?.summary ?? "\u547D\u4EE4";
9975
+ if (gist) {
9976
+ object = gist.object;
9977
+ context = context ?? gist.context;
9978
+ summary = gist.summary;
9979
+ readOnly = gist.readOnly === true;
9980
+ confidence = "recognized";
9981
+ }
9982
+ if (!gist || gist.action) action = translate?.(gist?.action ? `toolActivity.shell.${gist.action}` : "toolActivity.shell", action) ?? action;
9983
+ } else {
9984
+ const family = families[input.toolName];
9985
+ if (family) {
9986
+ action = translate?.(`toolActivity.${family[0]}`, family[1]) ?? family[1];
9987
+ object = text(...family[2]);
9988
+ readOnly = family[3];
9989
+ confidence = "recognized";
9990
+ } else object = text("path", "query", "command", "url", "name");
9991
+ }
9992
+ return { key: input.key, action, object, context, ...summary ? { summary } : {}, readOnly, confidence, state: input.state, attention: input.attention, standalone: input.mode !== "ordinary" || input.attention.length > 0 || ["failed", "cancelled", "repairing"].includes(input.state), scopeKey: input.scopeKey, batchKey: input.batchKey, evidenceKey: input.evidenceKey };
9993
+ }
9994
+ function canCoalesceToolActivities(previous, next) {
9995
+ return !previous.standalone && !next.standalone && previous.attention.length === 0 && next.attention.length === 0 && !!previous.scopeKey && previous.scopeKey === next.scopeKey && !!previous.batchKey && previous.batchKey === next.batchKey;
9996
+ }
9997
+
9998
+ // packages/cli/tui/askTextSanitize.ts
9999
+ var ASK_SECRET_PLACEHOLDER = "\u27E8redacted\u27E9";
10000
+ var C0_C1_CONTROL_REGEX = /[\x00-\x1f\x7f-\x9f]/g;
10001
+ function toText(value) {
10002
+ return typeof value === "string" ? value : String(value ?? "");
10003
+ }
10004
+ function cleanAskText(value) {
10005
+ return stripAnsi(toText(value)).replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").replace(C0_C1_CONTROL_REGEX, "").replace(/\s+/g, " ").trim();
10006
+ }
10007
+ function safeAskText(value, max) {
10008
+ const cleaned = redactSecrets(cleanAskText(value));
10009
+ if (!cleaned) return "";
10010
+ const guarded = withholdIfSecretLike(cleaned) || ASK_SECRET_PLACEHOLDER;
10011
+ return max === void 0 ? guarded : clipCompactText(guarded, max, "\u2026");
10012
+ }
10013
+ function safeApprovalMultilineText(value) {
10014
+ const lines = stripAnsi(String(value ?? "")).replace(/\r\n?|\u2028|\u2029/g, "\n").split("\n");
10015
+ return lines.map((line) => {
10016
+ const cleaned = line.replace(/\t/g, " ").replace(C0_C1_CONTROL_REGEX, "");
10017
+ const redacted = redactSecrets(cleaned);
10018
+ return redacted ? withholdIfSecretLike(redacted) || ASK_SECRET_PLACEHOLDER : "";
10019
+ }).join("\n");
9137
10020
  }
9138
10021
 
9139
10022
  // node_modules/diff/libesm/diff/base.js
@@ -9458,14 +10341,6 @@ function formatSearchItemQuery(query, path2, customHomedir) {
9458
10341
  if (!text) return "search";
9459
10342
  return text.length > 80 ? `${text.slice(0, 79)}\u2026` : text;
9460
10343
  }
9461
- function formatRunItemCommand(command, exitCode, timedOut) {
9462
- let text = compactWhitespace(command || "");
9463
- if (!text) text = "command";
9464
- text = text.length > 80 ? `${text.slice(0, 79)}\u2026` : text;
9465
- if (timedOut) return `${text} (timed out)`;
9466
- if (typeof exitCode === "number" && exitCode !== 0) return `${text} (exit ${exitCode})`;
9467
- return text;
9468
- }
9469
10344
  function formatFetchItemUrl(url) {
9470
10345
  const text = (url || "").trim();
9471
10346
  if (!text) return "webpage";
@@ -9483,10 +10358,20 @@ function isRunToolName(name) {
9483
10358
  return name === "execShell" || name === "runCommand" || name === "launchProcess";
9484
10359
  }
9485
10360
  function isFailedToolResult(event) {
9486
- const exitCode = event.metadata?.exitCode;
9487
- if (event.metadata?.actionGate) return false;
10361
+ if (event.type === "tool-error") return true;
10362
+ const metadata = event.metadata ?? {};
10363
+ if (metadata.actionGate) return false;
10364
+ const exitCode = metadata.exitCode;
9488
10365
  if (typeof exitCode === "number" && exitCode !== 0) return true;
9489
- return Boolean(event.metadata?.timedOut);
10366
+ if (Boolean(metadata.timedOut) || Boolean(metadata.failed) || Boolean(event.metadata?.failed)) return true;
10367
+ if (metadata.success === false) return true;
10368
+ if (typeof metadata.error === "string" && metadata.error.trim().length > 0) return true;
10369
+ if (typeof metadata.errorMessage === "string" && metadata.errorMessage.trim().length > 0) return true;
10370
+ if (typeof event.content === "string") {
10371
+ const trimmed = event.content.trim();
10372
+ if (/^\[工具\s*"[^"]+"\s*执行失败:\s*[^\]]+\]$/.test(trimmed)) return true;
10373
+ }
10374
+ return false;
9490
10375
  }
9491
10376
  function parseUiAskChoiceForCli(event) {
9492
10377
  if (event.toolName !== "ask_user" && !event.metadata?.uiAskChoice) {
@@ -9526,9 +10411,9 @@ function formatUiAskChoiceBlock(event, colorEnabled) {
9526
10411
  lines.push("");
9527
10412
  const questionText = safeAskText(parsed.question, 200);
9528
10413
  if (colorEnabled) {
9529
- lines.push(`${themeText("\u2753 ", "info", true)}${styleCliText(questionText, "cyan", true)}`);
10414
+ lines.push(`${themeText("? ", "info", true)}${styleCliText(questionText, "cyan", true)}`);
9530
10415
  } else {
9531
- lines.push(`\u2753 ${questionText}`);
10416
+ lines.push(`? ${questionText}`);
9532
10417
  }
9533
10418
  if (parsed.resolved) {
9534
10419
  if (parsed.cancelled) {
@@ -9949,6 +10834,7 @@ function snippetLinesWithKind(snippet, kind, maxWidth = resolveEditSnippetMaxWid
9949
10834
  return lines.slice(0, EDIT_SNIPPET_MAX_LINES).map((line) => buildEditLine(kind, line, maxWidth));
9950
10835
  }
9951
10836
  function truncateByDisplayWidth(line, maxWidth) {
10837
+ if (maxWidth <= 0) return "";
9952
10838
  if (displayWidth(line) <= maxWidth) return line;
9953
10839
  let width = 0;
9954
10840
  let kept = "";
@@ -10075,7 +10961,7 @@ function memoryToolGist(toolName, metadata) {
10075
10961
  function normalToolGistRaw(event) {
10076
10962
  const metadata = event.metadata ?? {};
10077
10963
  const toolName = event.toolName || "";
10078
- if (toolName === "readFile") {
10964
+ if (toolName === "readFile" || toolName === "writeFile" || toolName === "editFile") {
10079
10965
  const path3 = typeof metadata.path === "string" ? metadata.path : typeof metadata.filePath === "string" ? metadata.filePath : "";
10080
10966
  if (path3) return gistClip(formatReadItemPath(path3, metadata), 52);
10081
10967
  }
@@ -10118,6 +11004,21 @@ function formatNormalToolDuration(elapsedMs) {
10118
11004
  if (elapsedMs < 1e3) return `${Math.round(elapsedMs)}ms`;
10119
11005
  return `${(elapsedMs / 1e3).toFixed(1)}s`;
10120
11006
  }
11007
+ function normalResultSummary(event) {
11008
+ const m = event.metadata ?? {};
11009
+ const count = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
11010
+ if (event.toolName === "readFile" && count(m.startLine) && count(m.endLine))
11011
+ return `${Math.max(0, m.endLine - m.startLine + 1)} lines${m.truncated ? " \xB7 truncated" : ""}`;
11012
+ if (event.toolName === "writeFile" && count(m.bytes)) return `${m.bytes} bytes written`;
11013
+ if (event.toolName === "editFile" && count(m.replacements)) return `${m.replacements} replacements`;
11014
+ if (event.toolName === "searchText" && count(m.matchCount)) return `${m.matchCount} matches${m.truncated ? " \xB7 truncated" : ""}`;
11015
+ return "";
11016
+ }
11017
+ function fitNormalLine(head, tail, budget) {
11018
+ const status = budget === 1 ? tail.trimStart().slice(0, 1) : truncateByDisplayWidth(tail.trimStart(), budget);
11019
+ const room = Math.max(0, budget - displayWidth(status) - 2);
11020
+ return room ? `${truncateByDisplayWidth(head, room)} ${status}` : status;
11021
+ }
10121
11022
  function formatNormalToolLine(event, pending, colorEnabled, opts) {
10122
11023
  if (event.type === "tool-call") return "";
10123
11024
  const toolName = event.toolName || pending?.toolName || "tool";
@@ -10138,27 +11039,38 @@ function formatNormalToolLine(event, pending, colorEnabled, opts) {
10138
11039
  return formatShowInteractionBlock(event, colorEnabled);
10139
11040
  }
10140
11041
  const label = toolLabel(toolName);
10141
- if (readActionGate(event.metadata?.actionGate)) {
10142
- return formatToolTraceLine(`\u25B8 ${label} ! ${t("toolNeedsAction")}`, colorEnabled, "error");
10143
- }
10144
- if (event.type === "tool-error") {
10145
- return formatToolTraceLine(`\u25B8 ${label} \u2717 ${toolFailureReason(event) || t("toolFailed")}`, colorEnabled, "error");
10146
- }
10147
- if (event.metadata?.timedOut) {
10148
- return formatToolTraceLine(`\u25B8 ${label} \u2717 ${t("toolTimedOut")}`, colorEnabled, "error");
10149
- }
10150
- if (isFailedToolResult(event)) {
10151
- return formatToolTraceLine(`\u25B8 ${label} \u2717 ${toolFailureReason(event) || t("toolFailed")}`, colorEnabled, "error");
10152
- }
10153
- const gist = normalToolGist(event);
11042
+ const cols = typeof process !== "undefined" && typeof process.stdout?.columns === "number" && process.stdout.columns > 0 ? process.stdout.columns : 80;
11043
+ const totalBudget = Math.max(1, resolveHistoryLayoutGeometry(cols).contentWidth - displayWidth("\u25C8 "));
11044
+ if (readActionGate(event.metadata?.actionGate) || event.metadata?.permissionRequest) {
11045
+ const gist2 = opts?.tuiTrees ? normalToolGist(event) : "";
11046
+ const title = gist2 ? `${label} \xB7 ${gist2}` : label;
11047
+ return formatToolTraceLine(fitNormalLine(`\u25B8 ${title}`, `! ${t("toolNeedsAction")}`, totalBudget), colorEnabled, "error");
11048
+ }
11049
+ if (event.type === "tool-error" || event.metadata?.timedOut || isFailedToolResult(event)) {
11050
+ const reason = event.metadata?.timedOut ? t("toolTimedOut") : toolFailureReason(event) || t("toolFailed");
11051
+ const gist2 = opts?.tuiTrees ? normalToolGist(event) : "";
11052
+ const title = gist2 ? `${label} \xB7 ${gist2}` : label;
11053
+ return formatToolTraceLine(fitNormalLine(`\u25B8 ${title}`, `\u2717 ${reason}`, totalBudget), colorEnabled, "error");
11054
+ }
11055
+ const resultSummary = normalResultSummary(event);
11056
+ const gist = [normalToolGist(event), resultSummary].filter(Boolean).join(" \xB7 ");
10154
11057
  const hint = editFileResultHint(event);
10155
11058
  const statsInline = hint?.inline ? ` ${hint.inline}` : "";
10156
11059
  const durationInline = formatNormalToolDuration(event.elapsedMs);
10157
11060
  const tail = durationInline ? ` \u2713 ${durationInline}` : " \u2713";
10158
- const mainLine = formatToolTraceLine(
10159
- gist ? `\u25B8 ${label} \xB7 ${gist}${statsInline}${tail}` : `\u25B8 ${label}${statsInline}${tail}`,
10160
- colorEnabled
10161
- );
11061
+ let fittedGist = gist;
11062
+ if (gist) {
11063
+ const prefix = `\u25B8 ${label} \xB7 `;
11064
+ const suffix = `${statsInline}${tail}`;
11065
+ const prefixWidth = displayWidth(prefix);
11066
+ const suffixWidth = displayWidth(suffix);
11067
+ const maxGistWidth = Math.max(0, totalBudget - prefixWidth - suffixWidth);
11068
+ if (displayWidth(gist) > maxGistWidth) {
11069
+ fittedGist = maxGistWidth > 0 ? truncateByDisplayWidth(gist, maxGistWidth) : "";
11070
+ }
11071
+ }
11072
+ const lineContent = fittedGist ? `\u25B8 ${label} \xB7 ${fittedGist}${statsInline}${tail}` : `\u25B8 ${label}${statsInline}${tail}`;
11073
+ const mainLine = formatToolTraceLine(fitNormalLine(lineContent.slice(0, -tail.length), tail, totalBudget), colorEnabled);
10162
11074
  if (hint?.detail?.length) {
10163
11075
  const filePath = typeof event.metadata?.path === "string" ? event.metadata.path : void 0;
10164
11076
  return `${mainLine}${formatEditDetailBlock(hint.detail, colorEnabled, filePath)}`;
@@ -10249,33 +11161,43 @@ var TUI_TREE_TOOLS = {
10249
11161
  Search: ["exa_search"],
10250
11162
  Fetch: ["fetchWebpage"]
10251
11163
  };
11164
+ function toolDetails(event, line) {
11165
+ const command = event.metadata?.command;
11166
+ return isRunToolName(event.toolName) && typeof command === "string" ? `${line}${safeApprovalMultilineText(command)}
11167
+ ` : line;
11168
+ }
10252
11169
  function createToolEventFormatter(colorEnabled = resolveCliColorEnabled(), opts = {}) {
10253
11170
  const pending = /* @__PURE__ */ new Map();
11171
+ let scope = 0;
10254
11172
  let tree = null;
10255
11173
  const treeKind = (name) => Object.keys(TUI_TREE_TOOLS).find((kind) => TUI_TREE_TOOLS[kind].includes(name)) ?? null;
10256
- const treeLine = (kind, items, fallback) => {
11174
+ const treeLine = (kind, items, fallback, details) => {
10257
11175
  const label = kind === "Run" ? toolLabel("execShell") : kind === "Read" ? toolLabel("readFile") : kind === "Fetch" ? toolLabel("fetchWebpage") : toolLabel("exa_search");
10258
11176
  const header = `${label} (${items.length}) \xB7 `;
10259
11177
  const columns = resolveHistoryLayoutGeometry(process.stdout.columns).contentWidth - displayWidth("\u25C8 ");
11178
+ const budget = Math.max(1, columns);
10260
11179
  let shown = 1;
10261
11180
  for (let count = 2; count <= items.length; count++) {
10262
- const omitted2 = items.length - count;
10263
- const suffix = omitted2 ? `, \u2026 +${omitted2}` : "";
10264
- if (displayWidth(`\u2022 ${header}${items.slice(0, count).join(", ")}${suffix} \u2713`) > columns) break;
11181
+ const suffix = count < items.length ? ", \u2026" : "";
11182
+ if (displayWidth(`\u25B8 ${header}${items.slice(0, count).join(", ")}${suffix} \u2713`) > budget) break;
10265
11183
  shown = count;
10266
11184
  }
10267
- const omitted = items.length - shown;
11185
+ const summary = fitNormalLine(`${header}${items.slice(0, shown).join(", ")}${shown < items.length ? ", \u2026" : ""}`, "\u2713", Math.max(1, budget - 2));
10268
11186
  const payload = {
10269
11187
  kind,
10270
- summary: `${header}${items.slice(0, shown).join(", ")}${omitted ? `, \u2026 +${omitted}` : ""} \u2713`,
10271
- fallback
11188
+ summary,
11189
+ fallback,
11190
+ details,
11191
+ previousRow: tree?.lastRow
10272
11192
  };
11193
+ if (tree) tree.lastRow = `\u25B8 ${summary}`;
10273
11194
  return `${TUI_TREE_MARKER}${JSON.stringify(payload)}${TUI_TREE_END}
10274
11195
  `;
10275
11196
  };
10276
11197
  const formatTreeEvent = (event, call) => {
11198
+ if (event.type === "tool-error") tree = null;
10277
11199
  if (!opts.tuiTrees || event.type !== "tool-result") return null;
10278
- if (isFailedToolResult(event) || event.metadata?.failed || event.metadata?.timedOut || readActionGate(event.metadata?.actionGate)) {
11200
+ if (isFailedToolResult(event) || event.metadata?.failed || event.metadata?.timedOut || readActionGate(event.metadata?.actionGate) || event.metadata?.permissionRequest) {
10279
11201
  tree = null;
10280
11202
  return null;
10281
11203
  }
@@ -10285,20 +11207,40 @@ function createToolEventFormatter(colorEnabled = resolveCliColorEnabled(), opts
10285
11207
  tree = null;
10286
11208
  return null;
10287
11209
  }
11210
+ const activity = projectToolActivity({
11211
+ key: event.toolCallId,
11212
+ toolName: name,
11213
+ args: event.metadata,
11214
+ state: "success",
11215
+ attention: [],
11216
+ mode: "ordinary",
11217
+ // Formatter lifecycle/reset is the real assistant-output boundary;
11218
+ // round comes from the execution stream, never from adjacent rows.
11219
+ scopeKey: `assistant:${scope}`,
11220
+ batchKey: Number.isInteger(event.round) && event.round >= 0 ? `round:${event.round}` : void 0,
11221
+ evidenceKey: event.toolCallId
11222
+ });
10288
11223
  let item = "";
10289
11224
  const m = event.metadata ?? {};
10290
11225
  if (kind === "Run") {
10291
- const command = typeof m.command === "string" ? m.command : "";
10292
- item = command ? formatRunItemCommand(command, typeof m.exitCode === "number" ? m.exitCode : void 0, Boolean(m.timedOut)) : "command";
11226
+ item = activity.summary ?? (activity.confidence === "raw-fallback" ? clipCompactText(redactSecrets(activity.object ?? ""), 56, "\u2026") : [activity.action, activity.object].filter(Boolean).join(" "));
10293
11227
  }
10294
11228
  if (kind === "Read") item = formatReadItemPath(typeof m.path === "string" ? m.path : typeof m.filePath === "string" ? m.filePath : "file", m);
10295
11229
  if (kind === "Search") item = formatSearchItemQuery(typeof m.query === "string" ? m.query : typeof m.pattern === "string" ? m.pattern : "search", typeof m.path === "string" ? m.path : void 0);
10296
11230
  if (kind === "Fetch") item = formatFetchItemUrl(typeof m.url === "string" ? m.url : "webpage");
10297
- item = withholdIfSecretLike(item) || toolLabel(name);
10298
- if (tree?.kind !== kind) tree = { kind, items: [] };
11231
+ item = safeAskText(item) || toolLabel(name);
11232
+ if (tree?.kind !== kind || !canCoalesceToolActivities(tree.activity, activity)) tree = { kind, items: [], activity };
10299
11233
  tree.items.push(item);
10300
- if (tree.items.length < 2) return formatNormalToolLine(event, call, colorEnabled, opts);
10301
- return treeLine(kind, tree.items, formatNormalToolLine(event, call, colorEnabled, opts));
11234
+ if (tree.items.length < 2) {
11235
+ const line2 = formatNormalToolLine(event, call, colorEnabled, opts);
11236
+ tree.lastRow = stripAnsi(line2).trimEnd();
11237
+ const rawCommand = typeof m.command === "string" ? m.command : "";
11238
+ const runIdentity = kind === "Run" && activity.readOnly && rawCommand ? createHash2("sha256").update(rawCommand).digest("hex").slice(0, 16) : void 0;
11239
+ return `${TUI_TREE_MARKER}${JSON.stringify({ kind, summary: stripAnsi(line2).trimEnd().replace(/^▸ /, ""), fallback: line2, details: toolDetails(event, line2), appendOnly: true, ...runIdentity ? { readOnly: true, runIdentity } : {} })}${TUI_TREE_END}
11240
+ `;
11241
+ }
11242
+ const line = formatNormalToolLine(event, call, colorEnabled, opts);
11243
+ return treeLine(kind, tree.items, line, toolDetails(event, line));
10302
11244
  };
10303
11245
  const format = (event) => {
10304
11246
  if (event.type === "tool-call") {
@@ -10312,10 +11254,16 @@ function createToolEventFormatter(colorEnabled = resolveCliColorEnabled(), opts
10312
11254
  pending.delete(event.toolCallId);
10313
11255
  const treeOutput = formatTreeEvent(event, call);
10314
11256
  if (treeOutput !== null) return treeOutput;
10315
- return formatNormalToolLine(event, call, colorEnabled, opts);
11257
+ const line = formatNormalToolLine(event, call, colorEnabled, opts);
11258
+ if (opts.tuiTrees && line && isRunToolName(event.toolName)) {
11259
+ return `${TUI_TREE_MARKER}${JSON.stringify({ kind: "Run", summary: "", fallback: line, details: toolDetails(event, line), appendOnly: true })}${TUI_TREE_END}
11260
+ `;
11261
+ }
11262
+ return line;
10316
11263
  };
10317
11264
  format.reset = () => {
10318
11265
  tree = null;
11266
+ scope++;
10319
11267
  };
10320
11268
  format.consume = (event) => {
10321
11269
  if (event.type === "tool-call") {
@@ -10563,10 +11511,6 @@ function shouldPromoteTuiNarration(text) {
10563
11511
  if (text.length >= TUI_PROGRESS_BUFFER_LIMIT) return true;
10564
11512
  return /(^|\n)\s*(?:#{1,3}\s|```|[-*+]\s|\d+[.)]\s)/.test(text);
10565
11513
  }
10566
- function narrationActivityLabel(text) {
10567
- const oneLine = stripAnsi(text).replace(/[`*_#>]/g, "").replace(/\s+/g, " ").trim();
10568
- return truncateThinkingHint(oneLine, 60);
10569
- }
10570
11514
  function createCliTurnOutput(params) {
10571
11515
  const { options } = params;
10572
11516
  const workingLabel = params.workingLabel ?? `${options.agentName} -> working`;
@@ -10579,12 +11523,7 @@ function createCliTurnOutput(params) {
10579
11523
  const assistantLabelManaged = options.output.assistantLabelManaged === true;
10580
11524
  const showThinking = !assistantLabelManaged && options.showThinking !== false;
10581
11525
  const hidesRoutineTuiToolDetail = (event) => {
10582
- if (!assistantLabelManaged || event.toolName !== "editFile") return false;
10583
- if (event.type === "tool-error") return false;
10584
- if (readActionGate(event.metadata?.actionGate)) return false;
10585
- if (event.metadata?.timedOut || event.metadata?.failed || event.metadata?.error) return false;
10586
- if (typeof event.metadata?.exitCode === "number" && event.metadata.exitCode !== 0) return false;
10587
- return true;
11526
+ return false;
10588
11527
  };
10589
11528
  let streamedAssistantText = false;
10590
11529
  let everStreamedAnyText = false;
@@ -10658,11 +11597,6 @@ function createCliTurnOutput(params) {
10658
11597
  streamedAssistantText = true;
10659
11598
  options.activityReporter?.(null);
10660
11599
  };
10661
- const dropPendingTuiProgress = () => {
10662
- pendingTuiNarration = "";
10663
- tuiNarrationPromoted = false;
10664
- options.activityReporter?.(null);
10665
- };
10666
11600
  const writeVisibleAssistantChunk = (chunk) => {
10667
11601
  if (!chunk) return;
10668
11602
  if (!assistantLabelManaged) formatToolEvent.reset?.();
@@ -10681,6 +11615,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10681
11615
  }
10682
11616
  printedAssistantLabel = true;
10683
11617
  }
11618
+ if (assistantLabelManaged) options.activityReporter?.(t("generatingReply"));
10684
11619
  everStreamedAnyText = true;
10685
11620
  if (assistantLabelManaged) {
10686
11621
  if (tuiNarrationPromoted) {
@@ -10692,8 +11627,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10692
11627
  if (shouldPromoteTuiNarration(pendingTuiNarration)) {
10693
11628
  flushPendingTuiNarration();
10694
11629
  } else {
10695
- const label = narrationActivityLabel(pendingTuiNarration);
10696
- if (label) options.activityReporter?.(label);
11630
+ options.activityReporter?.(t("generatingReply"));
10697
11631
  }
10698
11632
  return;
10699
11633
  }
@@ -10714,7 +11648,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10714
11648
  }
10715
11649
  if (event.type === "tool-call") {
10716
11650
  if (assistantLabelManaged && pendingTuiNarration) {
10717
- dropPendingTuiProgress();
11651
+ flushPendingTuiNarration();
10718
11652
  }
10719
11653
  renderWriter.flush();
10720
11654
  if (!hidesRoutineTuiToolDetail(event)) {
@@ -10755,12 +11689,7 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10755
11689
  /**
10756
11690
  * Terminal cleanup for abort/error paths that never reach `finish()`.
10757
11691
  *
10758
- * A user abort discards the transient TUI progress buffer: the user stopped
10759
- * on purpose and the dock already showed that text as activity. A genuine
10760
- * failure must not swallow prose that never got the chance to be *proven*
10761
- * durable (only a following tool call proves "progress"), so it promotes the
10762
- * pending buffer and flushes what was already promoted — otherwise a short
10763
- * final answer followed by a transport error disappears from the transcript.
11692
+ * Preserve original prose on both abort and transport failure.
10764
11693
  */
10765
11694
  cancel(cleanup) {
10766
11695
  if (assistantLabelManaged && cleanup?.preservePendingNarration) {
@@ -10770,7 +11699,8 @@ ${options.agentName}${IDENTITY_LABEL_SEPARATOR}`);
10770
11699
  options.output.write("\n");
10771
11700
  }
10772
11701
  }
10773
- dropPendingTuiProgress();
11702
+ flushPendingTuiNarration();
11703
+ renderWriter.flush();
10774
11704
  },
10775
11705
  pushText(chunk) {
10776
11706
  writeVisibleAssistantChunk(chunk);
@@ -11347,57 +12277,9 @@ function isBalanceExhaustedError(error) {
11347
12277
  return matchesBalanceError(message);
11348
12278
  }
11349
12279
 
11350
- // packages/cli/client/hostTaskWorkspaceAssessment.ts
11351
- import { resolve as resolve3 } from "node:path";
11352
- var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
11353
- var present = (value) => typeof value === "string" && value.trim().length > 0;
11354
- function resolveCurrentHostTaskReference(input) {
11355
- const ref = input.reference;
11356
- 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;
11357
- return structuredClone(ref);
11358
- }
11359
- async function assessHostTaskWorkspace(input) {
11360
- const ref = resolveCurrentHostTaskReference(input);
11361
- if (!ref) return void 0;
11362
- const root = hostTaskEventsRoot(input.env);
11363
- const blocked = (reason, businessReason = "invalid_contract") => ({
11364
- exitCode: 1,
11365
- hostTaskWorkspaceBlocker: reason,
11366
- businessCompletion: { taskId: ref.taskId, status: "blocked", reasons: [businessReason] }
11367
- });
11368
- const fresh = await collectHostTaskWorkspace(ref, input.env);
11369
- const plan = readHostTaskAcceptancePlan(ref, input.env);
11370
- let planned;
11371
- if (plan) {
11372
- try {
11373
- planned = { status: "ready", context: await collectHostTaskPlannedWorkspace(ref, input.env) };
11374
- } catch {
11375
- planned = { status: "blocked", reason: "task_planned_workspace_unavailable" };
11376
- }
11377
- }
11378
- const authority = readHostTask(root, ref).authorization;
11379
- if (authority === "paused" || authority === "revoked") return blocked(`authorization_${authority}`, `authorization_${authority}`);
11380
- if (authority !== "active") return blocked("task_authority_unavailable");
11381
- const supplied = object(input.evidence);
11382
- if (supplied?.status === "blocked") return blocked(present(supplied.reason) ? supplied.reason : "workspace_blocked");
11383
- if (fresh.status === "blocked") return blocked(fresh.reason);
11384
- if (planned?.status === "blocked") return blocked(planned.reason);
11385
- if (planned?.status === "ready" && planned.context.baseline !== fresh.context.baseline) {
11386
- return blocked("task_plan_baseline_mismatch");
11387
- }
11388
- const context = object(supplied?.context);
11389
- const scope = object(context?.scope);
11390
- 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");
11391
- 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]);
11392
- if (!matches(fresh.context) && !(planned?.status === "ready" && matches(planned.context))) {
11393
- return blocked("workspace_evidence_mismatch");
11394
- }
11395
- return void 0;
11396
- }
11397
-
11398
12280
  // packages/cli/client/agentRun.ts
11399
12281
  async function loadRunLocalAgentTurn() {
11400
- const { runLocalAgentTurn } = await import("./agentRuntimeLocal-GSTYFEX4.js");
12282
+ const { runLocalAgentTurn } = await import("./agentRuntimeLocal-TU4LA353.js");
11401
12283
  return runLocalAgentTurn;
11402
12284
  }
11403
12285
  var stripDebugNoise = (s) => s.replace(/\s*raw="[\s\S]*"/g, "").replace(/\s*raw=\S+/g, "").replace(/\s*headers=\[[^\]]*\]/g, "").replace(/\s*headers=\S+/g, "").trim();
@@ -11829,9 +12711,9 @@ function isStandaloneResetSentence(text, index) {
11829
12711
  var RATE_LIMIT_DETAIL_MAX_CHARS = 140;
11830
12712
  var UPSTREAM_TAG_MAX_CHARS = 64;
11831
12713
  function findJsonObjectEnd(text, from) {
11832
- const open = text[from];
11833
- if (open !== "{" && open !== "[") return -1;
11834
- const close = open === "{" ? "}" : "]";
12714
+ const open2 = text[from];
12715
+ if (open2 !== "{" && open2 !== "[") return -1;
12716
+ const close = open2 === "{" ? "}" : "]";
11835
12717
  let depth = 0;
11836
12718
  let inString = false;
11837
12719
  let escaped = false;
@@ -11844,7 +12726,7 @@ function findJsonObjectEnd(text, from) {
11844
12726
  continue;
11845
12727
  }
11846
12728
  if (ch === '"') inString = true;
11847
- else if (ch === open) depth += 1;
12729
+ else if (ch === open2) depth += 1;
11848
12730
  else if (ch === close) {
11849
12731
  depth -= 1;
11850
12732
  if (depth === 0) return i + 1;
@@ -12192,6 +13074,10 @@ function describeLocalRunFailure(message, rawError) {
12192
13074
  }
12193
13075
  if (isMissingBatchReceiptFailure(message)) {
12194
13076
  return `[nolo] ${describeMissingBatchReceipt()}.
13077
+ `;
13078
+ }
13079
+ if (/\bimage_model_unsupported\b/.test(message)) {
13080
+ return `[nolo] ${message}. ${NO_FALLBACK} Check the selected model's image capability or use a model known to support images.
12195
13081
  `;
12196
13082
  }
12197
13083
  const cls = classifyLocalRunError(message);
@@ -12541,6 +13427,17 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12541
13427
  options.modelOverride
12542
13428
  ) : resolvedBaseAdapter;
12543
13429
  if (adapter2) adapter2 = applyEphemeralIfRequested(options, adapter2);
13430
+ if (adapter2 && options.imageUrls?.length) {
13431
+ const imageAdapter = adapter2;
13432
+ adapter2 = { ...imageAdapter, loadAgentConfig: async (agentRef) => {
13433
+ const config = await imageAdapter.loadAgentConfig(agentRef);
13434
+ if (!config) return config;
13435
+ if (!resolveAgentImageInputSupport({ ...config, hasVision: config.hasVision ?? false })) {
13436
+ throw new Error("image_model_unsupported: child model image capability is unsupported or unknown");
13437
+ }
13438
+ return config;
13439
+ } };
13440
+ }
12544
13441
  return adapter2;
12545
13442
  })();
12546
13443
  if (!baseAdapter) {
@@ -12567,12 +13464,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12567
13464
  } : void 0;
12568
13465
  const currentDialogId = options.continueDialogId ?? ulid2();
12569
13466
  const freshDialog = options.freshDialog ?? !options.continueDialogId;
12570
- options = { ...options, hostTaskRef: resolveCurrentHostTaskReference({
12571
- reference: options.hostTaskRef,
12572
- workspace: options.localRuntimeCwd ?? process.cwd(),
12573
- dialogId: currentDialogId,
12574
- env: options.env
12575
- }) };
12576
13467
  const turnId = `turn-${ulid2()}`;
12577
13468
  const runtimeContextWithOwnership = {
12578
13469
  ...runtimeContext ?? {},
@@ -12580,80 +13471,8 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12580
13471
  turnId,
12581
13472
  getProcessCausalDepth: options.getProcessCausalDepth
12582
13473
  };
12583
- const installReviewHost = baseAdapter.installTaskReviewHost;
12584
- if (options.hostTaskRef && installReviewHost) {
12585
- const scope = structuredClone(options.hostTaskRef);
12586
- const authorExecutionId = createHostAuthorExecution(options.env, scope, turnId);
12587
- installReviewHost({ scope, authorExecutionId, authorize: async () => {
12588
- 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");
12589
- } });
12590
- }
12591
- let reviewContext;
12592
- const requestedReview = options.hostReviewDispatch;
12593
- if (requestedReview && options.hostTaskRef && requestedReview.scope.taskId === options.hostTaskRef.taskId && requestedReview.scope.dialogId === currentDialogId && resolveHostReviewPath(requestedReview.scope.workspace) === resolveHostReviewPath(options.hostTaskRef.workspace)) {
12594
- reviewContext = { ...requestedReview, authorExecutionId: createHostAuthorExecution(options.env, options.hostTaskRef, turnId) };
12595
- }
12596
13474
  const commandVersionBindings = /* @__PURE__ */ new Map();
12597
13475
  const commandAdapter = !options.runtimeKey || options.runtimeKey === "local" ? wrapLocalCommandWorkspaceObservation(baseAdapter, options.localRuntimeCwd ?? process.cwd(), commandVersionBindings, void 0, options.abortSignal) : baseAdapter;
12598
- const reviewAdapter = {
12599
- ...commandAdapter,
12600
- executeTool: async (call, opts) => {
12601
- let args = {};
12602
- try {
12603
- args = typeof call.arguments === "string" ? JSON.parse(call.arguments) : call.arguments ?? {};
12604
- } catch {
12605
- }
12606
- const matched = call.name === "startAgentRun" && matchesHostReviewDispatch(reviewContext, call, args);
12607
- const result = await withHostReviewDispatch(matched ? reviewContext : void 0, () => commandAdapter.executeTool(call, opts));
12608
- return result;
12609
- }
12610
- };
12611
- const completionEvidenceProvider = options.hostTaskRef ? options.hostTaskCompletionEvidenceProvider : void 0;
12612
- let hostTask = bindHostTask({
12613
- adapter: reviewAdapter,
12614
- reference: options.hostTaskRef,
12615
- workspace: options.localRuntimeCwd ?? process.cwd(),
12616
- dialogId: currentDialogId,
12617
- env: options.env,
12618
- signal: options.abortSignal,
12619
- completionEvidenceProvider
12620
- });
12621
- if (options.hostTaskRef && options.hostTaskWorkspaceEvidence !== void 0 && readHostTask(hostTaskEventsRoot(options.env), options.hostTaskRef).authorization === "active") {
12622
- const blocker = await assessHostTaskWorkspace({
12623
- reference: options.hostTaskRef,
12624
- workspace: options.localRuntimeCwd ?? process.cwd(),
12625
- dialogId: currentDialogId,
12626
- env: options.env,
12627
- evidence: options.hostTaskWorkspaceEvidence
12628
- });
12629
- if (blocker) {
12630
- options.output.write(`[auto-review] blocked: ${blocker.hostTaskWorkspaceBlocker}
12631
- `);
12632
- try {
12633
- const saved = await reviewAdapter.saveTurn({
12634
- agentKey: options.agentKey,
12635
- messages: [{ role: "user", content: options.message }],
12636
- continueDialogId: currentDialogId,
12637
- runtimeContext: runtimeContextWithOwnership,
12638
- result: {
12639
- model: "host-workspace-assessment",
12640
- content: "",
12641
- error: true,
12642
- businessCompletion: blocker.businessCompletion
12643
- }
12644
- });
12645
- return {
12646
- ...blocker,
12647
- hostTaskRef: options.hostTaskRef,
12648
- dialogId: saved.dialogId,
12649
- taskAuthorization: readHostTask(hostTaskEventsRoot(options.env), options.hostTaskRef).authorization
12650
- };
12651
- } catch (localError) {
12652
- return { ...blocker, hostTaskRef: options.hostTaskRef, localError };
12653
- }
12654
- }
12655
- }
12656
- let usedReviewTool = false;
12657
13476
  let batchProviderStarted = false;
12658
13477
  let mainProviderStarted = false;
12659
13478
  let refusalModel = "";
@@ -12676,9 +13495,9 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12676
13495
  }
12677
13496
  };
12678
13497
  const adapter = {
12679
- ...hostTask.adapter,
13498
+ ...commandAdapter,
12680
13499
  resolveProvider: async (...args) => {
12681
- const provider = await hostTask.adapter.resolveProvider(...args);
13500
+ const provider = await commandAdapter.resolveProvider(...args);
12682
13501
  const isTextOnly = Boolean(args[1]?.textOnly);
12683
13502
  if (!isTextOnly) refusalModel = provider.model;
12684
13503
  return {
@@ -12695,26 +13514,8 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12695
13514
  }
12696
13515
  };
12697
13516
  },
12698
- executeTool: async (call, opts) => {
12699
- const protectedReview = call.name === "requestTaskReview" || call.name === "recordTaskReviewDecision";
12700
- if (!protectedReview) return reviewAdapter.executeTool(call, opts);
12701
- usedReviewTool = true;
12702
- if (options.hostTaskRef?.taskInstanceId) {
12703
- const authorize = baseAdapter.authorizeAccountTask;
12704
- if (!authorize) throw new Error("task_review_account_authorization_unavailable");
12705
- await authorize(options.hostTaskRef);
12706
- }
12707
- if (!options.hostTaskRef && ["requestTaskReview", "recordTaskReviewDecision"].includes(call.name)) {
12708
- const admit = baseAdapter.admitAccountReviewTurn;
12709
- if (!admit) throw new Error("task_review_account_admission_unavailable");
12710
- const reference = await admit(currentDialogId, turnId);
12711
- options = { ...options, hostTaskRef: reference };
12712
- hostTask = bindHostTask({ adapter: reviewAdapter, reference, workspace: options.localRuntimeCwd ?? process.cwd(), dialogId: currentDialogId, env: options.env, signal: options.abortSignal });
12713
- }
12714
- return hostTask.adapter.executeTool(call, opts);
12715
- },
13517
+ // 工具执行直接走 ...commandAdapter 展开(无需再写一行透传)。
12716
13518
  saveTurn: async (input) => {
12717
- if (usedReviewTool && options.hostTaskRef) await settleHostReviewsForScope(options.hostTaskRef, options.env, options.hostReviewContentAcceptance);
12718
13519
  const completeBatch = Boolean(batchIdentity && batchProviderStarted && !input.result.error);
12719
13520
  const injectedBatches = options.drainInjectedBatches ?? [];
12720
13521
  const injectedMessageIds = new Set(injectedBatches.flatMap((batch) => batch.messageIds));
@@ -12723,8 +13524,11 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12723
13524
  ...!input.result.error ? injectedBatches.map((batch) => batch.batchId) : []
12724
13525
  ];
12725
13526
  try {
12726
- const saved = await hostTask.adapter.saveTurn({
13527
+ const saved = await commandAdapter.saveTurn({
12727
13528
  ...input,
13529
+ // Receipt-backed user rows are excluded below to avoid duplicate persistence.
13530
+ // Keep their explicit identities for post-sync native memory capture.
13531
+ ...{ cliCaptureUserMessageIds: input.messages.filter((message) => message.role === "user").map((message) => message.cliMessageId).filter((id) => typeof id === "string") },
12728
13532
  messages: input.messages.filter((message) => {
12729
13533
  const cliMessageId = message.cliMessageId;
12730
13534
  if (!cliMessageId) return true;
@@ -12771,7 +13575,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12771
13575
  const runLocalAgentTurn = await loadRunLocalAgentTurn();
12772
13576
  const result = await runLocalAgentTurn({
12773
13577
  adapter,
12774
- ...hostTask.contract ? { taskExecutionContract: hostTask.contract } : {},
12775
13578
  agentRef: options.agentKey,
12776
13579
  userLanguage: options.userLanguage ?? options.env.NOLO_LANG ?? null,
12777
13580
  input: buildUserInputContent(messageForLocal, options.imageUrls),
@@ -12864,8 +13667,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12864
13667
  mainProviderAttempted: mainProviderStarted,
12865
13668
  exitCode: 0,
12866
13669
  stopReason: result.stopReason,
12867
- ...hostTask.result(),
12868
- ...options.hostTaskRef ? { hostTaskRef: options.hostTaskRef } : {},
12869
13670
  dialogId: result.dialogId,
12870
13671
  ...typeof result.content === "string" && result.content.trim() ? { finalText: result.content } : {},
12871
13672
  ...result.title !== void 0 ? { title: result.title } : {},
@@ -12903,10 +13704,8 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12903
13704
  const pendingToolName = error?.pendingToolName;
12904
13705
  return retainCommandObservations({
12905
13706
  exitCode: 0,
12906
- ...hostTask.result(),
12907
13707
  savedTurnPersisted: turnPersisted,
12908
13708
  mainProviderAttempted: mainProviderStarted,
12909
- ...options.hostTaskRef ? { hostTaskRef: options.hostTaskRef } : {},
12910
13709
  streamInterrupted: true,
12911
13710
  ...savedDialogId ? { dialogId: savedDialogId } : {},
12912
13711
  ...pendingToolName ? { pendingToolName } : {},
@@ -12952,7 +13751,6 @@ async function executeLocalAgentTurnForCliWithAdapter(options, settings, resolve
12952
13751
  }
12953
13752
  return retainCommandObservations({
12954
13753
  exitCode: 1,
12955
- ...hostTask.result(),
12956
13754
  localError: error,
12957
13755
  savedTurnPersisted: persisted,
12958
13756
  mainProviderAttempted: mainProviderStarted,
@@ -13020,7 +13818,6 @@ function foldLocalResultForTui(localResult) {
13020
13818
  const folded = {
13021
13819
  exitCode: localResult.exitCode,
13022
13820
  ...projectLocalTurnFacts(localResult),
13023
- ...localResult.hostTaskRef ? { hostTaskRef: localResult.hostTaskRef } : {},
13024
13821
  ...localResult.dialogId ? { dialogId: localResult.dialogId } : {},
13025
13822
  title: localResult.title,
13026
13823
  ...localResult.titlePatchPromise ? { titlePatchPromise: localResult.titlePatchPromise } : {},
@@ -13364,7 +14161,7 @@ function buildHostEnvironmentLayer(options) {
13364
14161
 
13365
14162
  // packages/agent-runtime/agentsMd.ts
13366
14163
  import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
13367
- import { resolve as resolve4 } from "node:path";
14164
+ import { resolve as resolve3 } from "node:path";
13368
14165
  var AGENTS_MD_MAX_BYTES = 8192;
13369
14166
  var AGENTS_MD_MARKER_RESERVE_BYTES = 512;
13370
14167
  var AGENTS_MD_CANDIDATES = ["AGENTS.md", "CLAUDE.md"];
@@ -13565,7 +14362,7 @@ ${entry.line}`;
13565
14362
  };
13566
14363
  function readAgentsMdLayerFromDisk(cwd) {
13567
14364
  for (const name of AGENTS_MD_CANDIDATES) {
13568
- const filePath = resolve4(cwd, name);
14365
+ const filePath = resolve3(cwd, name);
13569
14366
  if (!existsSync2(filePath)) continue;
13570
14367
  try {
13571
14368
  const raw = readFileSync3(filePath, "utf8");
@@ -13707,16 +14504,16 @@ function runDoDCommands(commands, cwd, deps = {}) {
13707
14504
 
13708
14505
  // packages/cli/agentRunPrompts.ts
13709
14506
  import { existsSync as existsSync3, readFileSync as readFileSync4, readdirSync, statSync as statSync2 } from "node:fs";
13710
- import { dirname, extname, isAbsolute as isAbsolute2, join as join2, relative as relativePath, resolve as resolve5, sep } from "node:path";
14507
+ import { dirname, extname, isAbsolute as isAbsolute2, join as join2, relative as relativePath, resolve as resolve4, sep } from "node:path";
13711
14508
  function workflowRefToCandidatePath(cwd, ref) {
13712
14509
  const normalized = ref.trim();
13713
14510
  if (!normalized) return "";
13714
14511
  if (normalized.endsWith(".md") || normalized.includes("/") || normalized.includes("\\")) {
13715
- const directPath = resolve5(cwd, normalized);
14512
+ const directPath = resolve4(cwd, normalized);
13716
14513
  if (existsSync3(directPath)) return directPath;
13717
14514
  }
13718
14515
  const fileName = normalized.replace(/[^a-zA-Z0-9一-鿿]+/g, "-").replace(/^-+|-+$/g, "");
13719
- return resolve5(cwd, "docs", "workflows", `${fileName}.md`);
14516
+ return resolve4(cwd, "docs", "workflows", `${fileName}.md`);
13720
14517
  }
13721
14518
  var SKILL_SEARCH_DIRS = [
13722
14519
  ".agents/skills"
@@ -13725,15 +14522,15 @@ function skillRefToCandidatePath(cwd, ref) {
13725
14522
  const normalized = ref.trim();
13726
14523
  if (!normalized) return "";
13727
14524
  if (normalized.endsWith(".md") || normalized.includes("/") || normalized.includes("\\")) {
13728
- const directPath = resolve5(cwd, normalized);
14525
+ const directPath = resolve4(cwd, normalized);
13729
14526
  if (existsSync3(directPath)) return directPath;
13730
14527
  }
13731
14528
  const fileName = normalized.replace(/[^a-zA-Z0-9一-鿿]+/g, "-").replace(/^-+|-+$/g, "");
13732
14529
  for (const dir of SKILL_SEARCH_DIRS) {
13733
- const skillMdPath = resolve5(cwd, dir, fileName, "SKILL.md");
14530
+ const skillMdPath = resolve4(cwd, dir, fileName, "SKILL.md");
13734
14531
  if (existsSync3(skillMdPath)) return skillMdPath;
13735
14532
  }
13736
- return resolve5(cwd, ".agents", "skills", fileName, "SKILL.md");
14533
+ return resolve4(cwd, ".agents", "skills", fileName, "SKILL.md");
13737
14534
  }
13738
14535
  async function resolveWorkflowReference(ref, cwd = process.cwd()) {
13739
14536
  const path2 = workflowRefToCandidatePath(cwd, ref);
@@ -13750,11 +14547,11 @@ async function resolveWorkflowReference(ref, cwd = process.cwd()) {
13750
14547
  }
13751
14548
  function inlineRelativeRefs(body, skillDir) {
13752
14549
  const refPattern = /\[([^\]]+)\]\((\.\/[^)]+|[^)]+\/[^)]+)\)/g;
13753
- const normalizedSkillDir = resolve5(skillDir) + sep;
14550
+ const normalizedSkillDir = resolve4(skillDir) + sep;
13754
14551
  return body.replace(refPattern, (match, label, relPath) => {
13755
14552
  const cleaned = relPath.trim();
13756
14553
  if (!cleaned.startsWith("./") && !cleaned.startsWith("../")) return match;
13757
- const absPath = resolve5(skillDir, cleaned);
14554
+ const absPath = resolve4(skillDir, cleaned);
13758
14555
  const relative = relativePath(normalizedSkillDir, absPath);
13759
14556
  if (relative.startsWith("..") || isAbsolute2(relative)) return match;
13760
14557
  if (!existsSync3(absPath) || !absPath.endsWith(".md")) return match;
@@ -13904,7 +14701,7 @@ function prependSubjectDialogMarker(message, subjectDialogKey) {
13904
14701
  }
13905
14702
  function normalizeCliImageInput(input) {
13906
14703
  if (/^(https?:|data:|file:)/i.test(input)) return input;
13907
- const absolutePath = resolve5(input);
14704
+ const absolutePath = resolve4(input);
13908
14705
  if (!existsSync3(absolutePath)) return input;
13909
14706
  const base64 = readFileSync4(absolutePath).toString("base64");
13910
14707
  return `data:${imageMimeTypeForPath(absolutePath)};base64,${base64}`;
@@ -13971,6 +14768,73 @@ var createDetachedThrottle = (input) => {
13971
14768
  };
13972
14769
  };
13973
14770
 
14771
+ // packages/ai/memory/vnext/recallBudget.ts
14772
+ var DEFAULT_DEEP_MEMORY_TOKENS = DEFAULT_MEMORY_OVERLAY_TOKEN_BUDGET;
14773
+ var resolveMemoryBudget = (value) => {
14774
+ const budget = value ?? DEFAULT_DEEP_MEMORY_TOKENS;
14775
+ if (!Number.isSafeInteger(budget) || budget < 512) {
14776
+ throw new Error("memory budget must be a safe integer >= 512 estimated tokens");
14777
+ }
14778
+ return budget;
14779
+ };
14780
+ var clipMemoryText = (text, maxTokens) => {
14781
+ if (estimateTokenCount(text) <= maxTokens) return text;
14782
+ const suffix = "\u2026[truncated]";
14783
+ if (estimateTokenCount(suffix) > maxTokens) return "";
14784
+ let lo = 0;
14785
+ let hi = text.length;
14786
+ while (lo < hi) {
14787
+ const mid = Math.ceil((lo + hi) / 2);
14788
+ if (estimateTokenCount(text.slice(0, mid) + suffix) <= maxTokens) lo = mid;
14789
+ else hi = mid - 1;
14790
+ }
14791
+ if (lo && /[\uD800-\uDBFF]/.test(text[lo - 1])) lo--;
14792
+ return text.slice(0, lo) + suffix;
14793
+ };
14794
+ var DESCRIPTIVE_FIELDS = /* @__PURE__ */ new Set(["text", "name", "facet", "subtype", "value", "aliases"]);
14795
+ var compactMemoryRow = (row, fieldTokens = 128) => Object.fromEntries(Object.entries(row).map(([key, value]) => [
14796
+ key,
14797
+ DESCRIPTIVE_FIELDS.has(key) && estimateTokenCount(typeof value === "string" ? value : JSON.stringify(value) ?? "") > fieldTokens ? clipMemoryText(typeof value === "string" ? value : JSON.stringify(value) ?? "", fieldTokens) : value
14798
+ ]));
14799
+ var memoryMessageTokens = (messages) => messages.reduce((sum, message) => sum + estimateTokenCount(message.content) + 8, 0);
14800
+ var buildBudgetedMemoryInput = (input) => {
14801
+ const maxTokens = resolveMemoryBudget(input.maxTokens);
14802
+ const query = clipMemoryText(input.query, Math.floor(maxTokens / 4));
14803
+ const rows = [];
14804
+ const messages = () => [
14805
+ { role: "system", content: input.system + "\nThis is a budgeted subset. Omitted candidates are unknown, not absent. Select only supplied exact ids; never infer nonexistence from omissions." },
14806
+ { role: "user", content: `Query:
14807
+ ${query}
14808
+
14809
+ Memory catalog:
14810
+ ${JSON.stringify({ candidates: rows })}` }
14811
+ ];
14812
+ if (memoryMessageTokens(messages()) > maxTokens) {
14813
+ throw new Error("memory budget cannot fit instructions and query");
14814
+ }
14815
+ let clipped = false;
14816
+ for (const original of input.rows) {
14817
+ const row = compactMemoryRow(original);
14818
+ rows.push(row);
14819
+ if (memoryMessageTokens(messages()) > maxTokens) rows.pop();
14820
+ else if (JSON.stringify(row) !== JSON.stringify(original)) clipped = true;
14821
+ }
14822
+ const result = messages();
14823
+ return {
14824
+ messages: result,
14825
+ rows,
14826
+ budget: {
14827
+ maxTokens,
14828
+ usedTokens: memoryMessageTokens(result),
14829
+ truncated: clipped || rows.length !== input.rows.length || query !== input.query,
14830
+ queryTruncated: query !== input.query,
14831
+ offeredCandidates: rows.length,
14832
+ totalCandidates: input.rows.length,
14833
+ omittedCandidates: input.rows.length - rows.length
14834
+ }
14835
+ };
14836
+ };
14837
+
13974
14838
  // packages/ai/memory/vnext/recall.ts
13975
14839
  var MAX_RECALL_REFS = 6;
13976
14840
  var stripFence = (raw) => {
@@ -14000,76 +14864,84 @@ var parseSelection = (raw) => {
14000
14864
  reason: obj.reason
14001
14865
  };
14002
14866
  };
14003
- var catalogText = (entities, states) => JSON.stringify(
14004
- {
14005
- entities: entities.map((entity) => ({
14006
- id: entity.id,
14007
- type: entity.type,
14008
- name: entity.name,
14009
- ...entity.subtype ? { subtype: entity.subtype } : {},
14010
- ...entity.aliases?.length ? { aliases: entity.aliases } : {}
14011
- })),
14012
- states: states.map((state2) => ({
14013
- id: state2.id,
14014
- entityId: state2.entityId,
14015
- facet: state2.facet,
14016
- text: state2.text,
14017
- // Retired (superseded) States stay listed as recoverable history; the
14018
- // boolean — not the retiredAt timestamp — enters the prompt so no
14019
- // timestamps reach LLM text.
14020
- ...state2.retiredAt ? { retired: true } : {}
14021
- }))
14022
- },
14023
- null,
14024
- 2
14025
- );
14026
14867
  var createMemoryVNextRecall = (input) => async (query) => {
14027
14868
  const startedAt = performance.now();
14869
+ const maxTokens = resolveMemoryBudget(input.maxInputTokens);
14028
14870
  const { entities, states } = await loadMemoryVNextCatalog(input.db, input.ownerId);
14029
- if (entities.length === 0 && states.length === 0) {
14871
+ if (!query.trim() || entities.length === 0 && states.length === 0) {
14030
14872
  return {
14031
14873
  query,
14032
14874
  refs: [],
14033
14875
  entities: [],
14034
14876
  states: [],
14035
- reason: "memory catalog is empty",
14877
+ reason: query.trim() ? "memory catalog is empty" : "query is empty",
14036
14878
  trace: {
14037
14879
  candidateEntities: 0,
14038
14880
  candidateStates: 0,
14039
14881
  selectedRefs: 0,
14882
+ budget: {
14883
+ maxTokens,
14884
+ usedTokens: 0,
14885
+ truncated: false,
14886
+ offeredCandidates: 0,
14887
+ totalCandidates: entities.length + states.length,
14888
+ omittedCandidates: entities.length + states.length
14889
+ },
14040
14890
  elapsedMs: Math.round((performance.now() - startedAt) * 10) / 10
14041
14891
  }
14042
14892
  };
14043
14893
  }
14044
- const result = await input.provider.complete(
14045
- [
14046
- {
14047
- role: "system",
14048
- content: [
14049
- "Select the smallest useful set of long-lived memory entrances for the user query.",
14050
- 'Return ONLY JSON: {"refs":["exact-id"],"reason":"short explanation"}.',
14051
- `Select at most ${MAX_RECALL_REFS} exact ids from the supplied catalog.`,
14052
- "Prefer State ids when current durable understanding answers the query.",
14053
- "Select an Entity id when it is a useful navigation anchor and no single State is enough.",
14054
- "Do not select unrelated memories merely because they are personal or interesting.",
14055
- "Historical-detail questions may select the relevant current State/Entity as an entrance; deeper evidence is handled by inspect, not here."
14056
- ].join("\n")
14057
- },
14058
- {
14059
- role: "user",
14060
- content: `Query:
14061
- ${query}
14062
-
14063
- Memory catalog:
14064
- ${catalogText(entities, states)}`
14065
- }
14894
+ const hits = recallMemoryVNextLocal({ query, entities, states, limit: states.length });
14895
+ const priority = new Set(hits.flatMap(({ state: state2 }) => [state2.id, state2.entityId]));
14896
+ const rankedStates = [
14897
+ ...hits.map(({ state: state2 }) => state2),
14898
+ ...states.filter((state2) => !priority.has(state2.id)).sort((a, b) => a.id.localeCompare(b.id))
14899
+ ];
14900
+ const rankedEntities = [...entities].sort((a, b) => Number(priority.has(b.id)) - Number(priority.has(a.id)) || a.id.localeCompare(b.id));
14901
+ const stateRows = rankedStates.map((state2) => ({
14902
+ kind: "state",
14903
+ id: state2.id,
14904
+ entityId: state2.entityId,
14905
+ facet: state2.facet,
14906
+ text: state2.text,
14907
+ ...state2.retiredAt ? { retired: true } : {}
14908
+ }));
14909
+ const entityRows = rankedEntities.map((entity) => ({
14910
+ kind: "entity",
14911
+ id: entity.id,
14912
+ type: entity.type,
14913
+ name: entity.name,
14914
+ ...entity.subtype ? { subtype: entity.subtype } : {},
14915
+ ...entity.aliases?.length ? { aliases: entity.aliases } : {}
14916
+ }));
14917
+ const request = buildBudgetedMemoryInput({
14918
+ query,
14919
+ maxTokens: input.maxInputTokens,
14920
+ rows: [
14921
+ ...stateRows.filter((row) => priority.has(row.id)),
14922
+ ...entityRows.filter((row) => priority.has(row.id)),
14923
+ ...stateRows.filter((row) => !priority.has(row.id)),
14924
+ ...entityRows.filter((row) => !priority.has(row.id))
14066
14925
  ],
14926
+ system: [
14927
+ "Select the smallest useful set of long-lived memory entrances for the user query.",
14928
+ 'Return ONLY JSON: {"refs":["exact-id"],"reason":"short explanation"}.',
14929
+ `Select at most ${MAX_RECALL_REFS} exact ids from the supplied catalog.`,
14930
+ "Prefer current State ids; retired States are history entrances, not current facts.",
14931
+ "Select an Entity when it is a useful navigation anchor.",
14932
+ "Do not select unrelated memories merely because they are personal or interesting.",
14933
+ "Historical questions may select a relevant entrance; deeper evidence is handled by inspect."
14934
+ ].join("\n")
14935
+ });
14936
+ const result = await input.provider.complete(
14937
+ request.messages,
14067
14938
  input.timeoutMs ? { timeoutMs: input.timeoutMs } : void 0
14068
14939
  );
14069
14940
  const selected = parseSelection(result.content);
14070
14941
  const entityById = new Map(entities.map((entity) => [entity.id, entity]));
14071
14942
  const stateById = new Map(states.map((state2) => [state2.id, state2]));
14072
- const validRefs = selected.refs.filter((ref) => entityById.has(ref) || stateById.has(ref));
14943
+ const offered = new Set(request.rows.map((row) => row.id));
14944
+ const validRefs = selected.refs.filter((ref) => offered.has(ref) && (entityById.has(ref) || stateById.has(ref)));
14073
14945
  return {
14074
14946
  query,
14075
14947
  refs: validRefs,
@@ -14086,6 +14958,7 @@ ${catalogText(entities, states)}`
14086
14958
  candidateEntities: entities.length,
14087
14959
  candidateStates: states.length,
14088
14960
  selectedRefs: validRefs.length,
14961
+ budget: request.budget,
14089
14962
  elapsedMs: Math.round((performance.now() - startedAt) * 10) / 10
14090
14963
  }
14091
14964
  };
@@ -14241,235 +15114,6 @@ var runMemoryVNextShadowRead = async (input) => {
14241
15114
  };
14242
15115
  var isMemoryVNextShadowReadEnabled = (env = typeof process !== "undefined" ? process.env : {}) => env.NOLO_MEMORY_VNEXT_SHADOW_READ === "1" || env.NOLO_MEMORY_VNEXT_SHADOW_READ === "true";
14243
15116
 
14244
- // packages/ai/memory/vnext/applyMutation.ts
14245
- async function validateMutation(db, ownerId, mutation) {
14246
- const pending = {
14247
- evidenceIds: /* @__PURE__ */ new Set(),
14248
- entityIds: /* @__PURE__ */ new Set(),
14249
- stateIds: /* @__PURE__ */ new Set(),
14250
- relationIds: /* @__PURE__ */ new Set()
14251
- };
14252
- for (const ev of mutation.evidence ?? []) {
14253
- if (!ev.id || typeof ev.id !== "string") {
14254
- throw new Error("evidence id must be a non-empty string");
14255
- }
14256
- if (pending.evidenceIds.has(ev.id)) {
14257
- throw new Error(`duplicate evidence id in mutation: ${ev.id}`);
14258
- }
14259
- pending.evidenceIds.add(ev.id);
14260
- }
14261
- for (const ent of mutation.entities ?? []) {
14262
- if (!ent.id || typeof ent.id !== "string") {
14263
- throw new Error("entity id must be a non-empty string");
14264
- }
14265
- if (pending.entityIds.has(ent.id)) {
14266
- throw new Error(`duplicate entity id in mutation: ${ent.id}`);
14267
- }
14268
- pending.entityIds.add(ent.id);
14269
- }
14270
- for (const st of mutation.states ?? []) {
14271
- if (!st.id || typeof st.id !== "string") {
14272
- throw new Error("state id must be a non-empty string");
14273
- }
14274
- if (pending.stateIds.has(st.id)) {
14275
- throw new Error(`duplicate state id in mutation: ${st.id}`);
14276
- }
14277
- pending.stateIds.add(st.id);
14278
- }
14279
- for (const rel of mutation.relations ?? []) {
14280
- if (!rel.id || typeof rel.id !== "string") {
14281
- throw new Error("relation id must be a non-empty string");
14282
- }
14283
- if (pending.relationIds.has(rel.id)) {
14284
- throw new Error(`duplicate relation id in mutation: ${rel.id}`);
14285
- }
14286
- pending.relationIds.add(rel.id);
14287
- }
14288
- const supersededIds = /* @__PURE__ */ new Set();
14289
- for (const sid of mutation.supersededStateIds ?? []) {
14290
- if (supersededIds.has(sid)) {
14291
- throw new Error(`duplicate supersededStateId in mutation: ${sid}`);
14292
- }
14293
- supersededIds.add(sid);
14294
- }
14295
- for (const ev of mutation.evidence ?? []) {
14296
- if (ev.ownerId !== ownerId) {
14297
- throw new Error(
14298
- `evidence ${ev.id} has ownerId ${ev.ownerId}, expected ${ownerId}`
14299
- );
14300
- }
14301
- }
14302
- for (const ent of mutation.entities ?? []) {
14303
- if (ent.ownerId !== ownerId) {
14304
- throw new Error(
14305
- `entity ${ent.id} has ownerId ${ent.ownerId}, expected ${ownerId}`
14306
- );
14307
- }
14308
- }
14309
- for (const st of mutation.states ?? []) {
14310
- if (st.ownerId !== ownerId) {
14311
- throw new Error(
14312
- `state ${st.id} has ownerId ${st.ownerId}, expected ${ownerId}`
14313
- );
14314
- }
14315
- }
14316
- for (const rel of mutation.relations ?? []) {
14317
- if (rel.ownerId !== ownerId) {
14318
- throw new Error(
14319
- `relation ${rel.id} has ownerId ${rel.ownerId}, expected ${ownerId}`
14320
- );
14321
- }
14322
- }
14323
- for (const st of mutation.states ?? []) {
14324
- if (supersededIds.has(st.id)) {
14325
- throw new Error(
14326
- `state ${st.id} appears in both states and supersededStateIds; a record cannot be created and retired in the same mutation`
14327
- );
14328
- }
14329
- }
14330
- const facetSlots = /* @__PURE__ */ new Set();
14331
- for (const st of mutation.states ?? []) {
14332
- const slot = `${st.entityId} ${st.facet}`;
14333
- if (facetSlots.has(slot)) {
14334
- throw new Error(
14335
- `mutation writes parallel current states for entity ${st.entityId} facet ${st.facet}`
14336
- );
14337
- }
14338
- facetSlots.add(slot);
14339
- }
14340
- for (const ev of mutation.evidence ?? []) {
14341
- const existing = await getMemoryEvidenceVNext(db, ownerId, ev.id);
14342
- if (existing) {
14343
- throw new Error(
14344
- `evidence ${ev.id} already exists (owner ${ownerId}); use a unique id`
14345
- );
14346
- }
14347
- }
14348
- for (const ent of mutation.entities ?? []) {
14349
- const existing = await getMemoryEntityVNext(db, ownerId, ent.id);
14350
- if (existing) {
14351
- throw new Error(
14352
- `entity ${ent.id} already exists (owner ${ownerId}); use a unique id`
14353
- );
14354
- }
14355
- }
14356
- for (const st of mutation.states ?? []) {
14357
- if (!pending.entityIds.has(st.entityId)) {
14358
- const entity = await getMemoryEntityVNext(db, ownerId, st.entityId);
14359
- if (!entity) {
14360
- throw new Error(
14361
- `memory state ${st.id} references missing entity ${st.entityId} (owner ${ownerId})`
14362
- );
14363
- }
14364
- }
14365
- for (const evidenceId of st.evidenceIds) {
14366
- if (!pending.evidenceIds.has(evidenceId)) {
14367
- const ev = await getMemoryEvidenceVNext(db, ownerId, evidenceId);
14368
- if (!ev) {
14369
- throw new Error(
14370
- `memory state ${st.id} references missing evidence ${evidenceId} (owner ${ownerId})`
14371
- );
14372
- }
14373
- }
14374
- }
14375
- const existing = await getMemoryStateVNext(db, ownerId, st.id);
14376
- if (existing) {
14377
- if (existing.retiredAt) {
14378
- throw new Error(
14379
- `cannot update retired memory state ${st.id} (owner ${ownerId})`
14380
- );
14381
- }
14382
- if (existing.entityId !== st.entityId || existing.facet !== st.facet) {
14383
- throw new Error(
14384
- `state ${st.id} already exists with different entity/facet (${existing.entityId}/${existing.facet} vs ${st.entityId}/${st.facet}); use supersede instead`
14385
- );
14386
- }
14387
- }
14388
- if (!existing) {
14389
- const existingStates = await listMemoryStatesForEntityVNext(db, ownerId, st.entityId);
14390
- for (const es of existingStates) {
14391
- if (es.facet === st.facet && !es.retiredAt) {
14392
- if (!supersededIds.has(es.id)) {
14393
- throw new Error(
14394
- `entity ${st.entityId} facet ${st.facet} already has current state ${es.id}; supersede it or use a different facet`
14395
- );
14396
- }
14397
- }
14398
- }
14399
- }
14400
- }
14401
- for (const sid of mutation.supersededStateIds ?? []) {
14402
- const existing = await getMemoryStateVNext(db, ownerId, sid);
14403
- if (!existing) {
14404
- throw new Error(
14405
- `cannot supersede missing memory state: ${sid} (owner ${ownerId})`
14406
- );
14407
- }
14408
- if (existing.retiredAt) {
14409
- throw new Error(
14410
- `cannot supersede already retired memory state: ${sid} (owner ${ownerId})`
14411
- );
14412
- }
14413
- const replacement = (mutation.states ?? []).find(
14414
- (st) => st.entityId === existing.entityId && st.facet === existing.facet
14415
- );
14416
- if (!replacement) {
14417
- throw new Error(
14418
- `superseded state ${sid} (entity ${existing.entityId} facet ${existing.facet}) has no replacement in this mutation`
14419
- );
14420
- }
14421
- }
14422
- for (const rel of mutation.relations ?? []) {
14423
- for (const [side, ref] of [
14424
- ["from", rel.from],
14425
- ["to", rel.to]
14426
- ]) {
14427
- if (pending.entityIds.has(ref) || pending.stateIds.has(ref) || pending.evidenceIds.has(ref)) {
14428
- continue;
14429
- }
14430
- const resolved = await getMemoryEntityVNext(db, ownerId, ref) ?? await getMemoryStateVNext(db, ownerId, ref) ?? await getMemoryEvidenceVNext(db, ownerId, ref);
14431
- if (!resolved) {
14432
- throw new Error(
14433
- `memory relation ${rel.id} references missing ${side} ${ref} (owner ${ownerId})`
14434
- );
14435
- }
14436
- }
14437
- }
14438
- }
14439
- var applyMemoryInterpreterMutation = async (db, ownerId, mutation) => {
14440
- await validateMutation(db, ownerId, mutation);
14441
- const batch = db.batch();
14442
- for (const ev of mutation.evidence ?? []) {
14443
- _appendEvidenceBatch(batch, ev);
14444
- }
14445
- for (const ent of mutation.entities ?? []) {
14446
- _appendEntityBatch(batch, ent);
14447
- }
14448
- for (const st of mutation.states ?? []) {
14449
- _appendStateBatch(batch, st);
14450
- }
14451
- for (const sid of mutation.supersededStateIds ?? []) {
14452
- const existing = await getMemoryStateVNext(db, ownerId, sid);
14453
- if (!existing) {
14454
- throw new Error(
14455
- `cannot supersede missing memory state: ${sid} (owner ${ownerId})`
14456
- );
14457
- }
14458
- const replacement = (mutation.states ?? []).find(
14459
- (st) => st.entityId === existing.entityId && st.facet === existing.facet
14460
- );
14461
- const retired = {
14462
- ...existing,
14463
- retiredAt: replacement?.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString()
14464
- };
14465
- _appendRetiredStateBatch(batch, retired);
14466
- }
14467
- for (const rel of mutation.relations ?? []) {
14468
- _appendRelationBatch(batch, rel);
14469
- }
14470
- await batch.write();
14471
- };
14472
-
14473
15117
  // packages/ai/memory/vnext/legacyMigrationApply.ts
14474
15118
  var isSameLegacyMemoryEvidence = (left, right) => left.id === right.id && left.ownerId === right.ownerId && left.text === right.text && left.sourceRef === right.sourceRef && left.confidence === right.confidence && left.createdAt === right.createdAt;
14475
15119
  var applyLegacyMemoryEvidence = async (db, item) => {
@@ -15156,6 +15800,10 @@ var resolveMemoryVNextM4Selection = async (input) => {
15156
15800
  const renderItems = [...recalledStates, ...uncoveredLegacy];
15157
15801
  return {
15158
15802
  renderItems,
15803
+ sources: new Map([
15804
+ ...recalledStates.map((item) => [item, "vnext"]),
15805
+ ...uncoveredLegacy.map((item) => [item, "legacy-uncovered"])
15806
+ ]),
15159
15807
  recalledStateCount: recalledStates.length,
15160
15808
  uncoveredLegacyCount: uncoveredLegacy.length,
15161
15809
  coveredSuppressedCount
@@ -15277,245 +15925,282 @@ var selectRuntimeMemoryItems = (items, context, userInput = "") => {
15277
15925
  return selected;
15278
15926
  };
15279
15927
  var resolveMemoryRuntime = async (input) => {
15280
- const owners = chooseMemoryOwners({
15281
- userId: input.userId,
15282
- spaceId: input.spaceId
15283
- });
15284
- if (owners.length === 0) {
15285
- return { selectedItems: [], promptBlock: null };
15286
- }
15287
- if (isMemoryVNextPureReadEnabled()) {
15288
- const pureStartedAt = performance.now();
15289
- let pure;
15290
- let pureError = null;
15291
- try {
15292
- pure = await resolvePureVNextRuntime({
15293
- db: input.db,
15294
- owners,
15295
- userInput: input.userInput,
15296
- maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET
15297
- });
15298
- } catch (error) {
15299
- pureError = error;
15300
- pure = { selectedItems: [], promptBlock: null, recalledStateCount: 0 };
15301
- }
15302
- const pureLatencyMs = Math.round((performance.now() - pureStartedAt) * 10) / 10;
15303
- const emitPureRead = (observation) => {
15928
+ const configuredPure = isMemoryVNextPureReadEnabled();
15929
+ const configuredPrimary = isMemoryVNextPrimaryReadEnabled();
15930
+ let branch = "no_owner";
15931
+ let outcome = "error";
15932
+ let errorKind = "runtime_error";
15933
+ let fallbackKind = "none";
15934
+ let injection = emptyMemoryInjectionObservation();
15935
+ const injectionEmit = (observation) => {
15936
+ injection = observation;
15937
+ };
15938
+ const finish = (result) => {
15939
+ outcome = fallbackKind === "none" ? result.promptBlock ? "result" : "empty" : "fallback";
15940
+ errorKind = fallbackKind;
15941
+ return result;
15942
+ };
15943
+ try {
15944
+ const owners = chooseMemoryOwners({
15945
+ userId: input.userId,
15946
+ spaceId: input.spaceId
15947
+ });
15948
+ if (owners.length === 0) {
15949
+ return finish({ selectedItems: [], promptBlock: null });
15950
+ }
15951
+ if (configuredPure) {
15952
+ branch = "pure";
15953
+ const pureStartedAt = performance.now();
15954
+ let pure;
15955
+ let pureFailed = false;
15304
15956
  try {
15305
- if (input.pureReadEmit) {
15306
- input.pureReadEmit(observation);
15307
- } else if (input.primaryReadEmit) {
15308
- input.primaryReadEmit({
15309
- source: observation.source === "vnext" ? "vnext" : "none",
15310
- legacyHitCount: 0,
15311
- recalledStateCount: observation.vnextItemCount,
15312
- vnextLatencyMs: observation.vnextLatencyMs,
15313
- legacyLatencyMs: 0,
15314
- contextChars: observation.contextChars,
15315
- fallbackReason: observation.fallbackReason,
15316
- error: observation.error
15957
+ pure = await resolvePureVNextRuntime({
15958
+ db: input.db,
15959
+ owners,
15960
+ userInput: input.userInput,
15961
+ maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET,
15962
+ injectionEmit
15963
+ });
15964
+ } catch (error) {
15965
+ pureFailed = true;
15966
+ pure = { selectedItems: [], promptBlock: null, recalledStateCount: 0 };
15967
+ }
15968
+ const pureLatencyMs = Math.round((performance.now() - pureStartedAt) * 10) / 10;
15969
+ const emitPureRead = (observation) => {
15970
+ try {
15971
+ if (input.pureReadEmit) {
15972
+ input.pureReadEmit(observation);
15973
+ } else if (input.primaryReadEmit) {
15974
+ input.primaryReadEmit({
15975
+ source: observation.source === "vnext" ? "vnext" : "none",
15976
+ legacyHitCount: 0,
15977
+ recalledStateCount: observation.vnextItemCount,
15978
+ vnextLatencyMs: observation.vnextLatencyMs,
15979
+ legacyLatencyMs: 0,
15980
+ contextChars: observation.contextChars,
15981
+ fallbackReason: observation.fallbackReason,
15982
+ error: observation.error
15983
+ });
15984
+ } else {
15985
+ console.info("[memory] vnext pure read", {
15986
+ event: "memory_vnext_pure_read",
15987
+ ...observation
15988
+ });
15989
+ }
15990
+ } catch {
15991
+ }
15992
+ };
15993
+ if (pureFailed) {
15994
+ emitPureRead({
15995
+ source: "none",
15996
+ itemCount: 0,
15997
+ vnextItemCount: 0,
15998
+ vnextLatencyMs: pureLatencyMs,
15999
+ contextChars: 0,
16000
+ fallbackReason: "vnext_error",
16001
+ error: "runtime_error"
16002
+ });
16003
+ } else if (pure.selectedItems.length === 0) {
16004
+ emitPureRead({
16005
+ source: "none",
16006
+ itemCount: 0,
16007
+ vnextItemCount: 0,
16008
+ vnextLatencyMs: pureLatencyMs,
16009
+ contextChars: 0,
16010
+ fallbackReason: "no_vnext_context"
16011
+ });
16012
+ } else {
16013
+ emitPureRead({
16014
+ source: "vnext",
16015
+ itemCount: pure.selectedItems.length,
16016
+ vnextItemCount: pure.recalledStateCount,
16017
+ vnextLatencyMs: pureLatencyMs,
16018
+ contextChars: pure.promptBlock?.length ?? 0
16019
+ });
16020
+ }
16021
+ const lazyPromotionEnabled2 = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
16022
+ if (lazyPromotionEnabled2) {
16023
+ void (async () => {
16024
+ const ownerItems = await Promise.all(
16025
+ owners.map(
16026
+ (owner) => loadOwnerItemsFromDb(
16027
+ input.db,
16028
+ owner,
16029
+ input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT
16030
+ )
16031
+ )
16032
+ );
16033
+ const legacyCandidates = ownerItems.flat();
16034
+ if (legacyCandidates.length > 0) {
16035
+ const promotionPick = await pickFirstUncoveredLazyPromotionItem(
16036
+ input.db,
16037
+ legacyCandidates
16038
+ );
16039
+ if (promotionPick) {
16040
+ await runMemoryVNextLazyPromotion({
16041
+ db: input.db,
16042
+ item: promotionPick.item,
16043
+ selectedIndex: promotionPick.selectedIndex,
16044
+ skippedCoveredCount: promotionPick.skippedCoveredCount,
16045
+ skippedNoOpCount: promotionPick.skippedNoOpCount,
16046
+ provider: input.vNextShadowProvider,
16047
+ ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
16048
+ });
16049
+ }
16050
+ }
16051
+ })().catch(() => {
16052
+ });
16053
+ }
16054
+ const result = finish({ selectedItems: pure.selectedItems, promptBlock: pure.promptBlock });
16055
+ if (pureFailed) {
16056
+ outcome = "error";
16057
+ errorKind = "runtime_error";
16058
+ }
16059
+ return result;
16060
+ }
16061
+ branch = "legacy";
16062
+ const policy = resolveAgentMemoryPolicy({ agentKey: input.agentKey });
16063
+ const legacyStartedAt = performance.now();
16064
+ const candidates = await loadMemoryCandidatesFromDb(input.db, {
16065
+ owners,
16066
+ subjects: buildMemorySubjectsForAgent({
16067
+ userId: input.userId,
16068
+ spaceId: input.spaceId,
16069
+ agentKey: input.agentKey,
16070
+ memorySubjectId: input.memorySubjectId,
16071
+ policy
16072
+ }),
16073
+ kinds: ["episodic", "semantic", "procedural"],
16074
+ ownerLimit: input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT,
16075
+ ownerFallback: policy.ownerFallback,
16076
+ corroboratedProceduralReserve: input.corroboratedProceduralReserve ?? CORROBORATED_PROCEDURAL_RESERVE
16077
+ });
16078
+ const rankContext = {
16079
+ currentOwner: input.spaceId ? { ownerType: "space", ownerId: input.spaceId } : input.userId ? { ownerType: "user", ownerId: input.userId } : null,
16080
+ currentSubject: input.spaceId ? { subjectType: "space", subjectId: input.spaceId } : input.userId ? { subjectType: "user", subjectId: input.userId } : null
16081
+ };
16082
+ const residentItems = candidates.filter((item) => item.resident === true).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, RESIDENT_MEMORY_RUNTIME_LIMIT);
16083
+ const retrievalCandidates = candidates.filter((item) => item.resident !== true);
16084
+ const ranked = selectRuntimeMemoryItems(
16085
+ rankMemoryCandidates(retrievalCandidates, input.userInput, rankContext),
16086
+ rankContext,
16087
+ input.userInput
16088
+ );
16089
+ const selected = [...residentItems, ...ranked];
16090
+ const legacyLatencyMs = Math.round((performance.now() - legacyStartedAt) * 10) / 10;
16091
+ const renderOverlay = (items, sources) => buildMemoryOverlay(items, { maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET, sources, injectionEmit });
16092
+ let promptBlock = configuredPrimary ? null : renderOverlay(selected);
16093
+ const primaryRead = configuredPrimary;
16094
+ let allCoveredByVNext = false;
16095
+ if (primaryRead) {
16096
+ branch = "primary";
16097
+ const emitPrimary = (observation) => {
16098
+ try {
16099
+ (input.primaryReadEmit ?? ((o) => console.info("[memory] vnext primary read", { event: "memory_vnext_primary_read", ...o })))(observation);
16100
+ } catch {
16101
+ }
16102
+ };
16103
+ const base = { legacyHitCount: selected.length, legacyLatencyMs };
16104
+ const vnextStartedAt = performance.now();
16105
+ const vnextLatency = () => Math.round((performance.now() - vnextStartedAt) * 10) / 10;
16106
+ if (selected.length === 0) {
16107
+ emitPrimary({ ...base, source: "none" });
16108
+ } else {
16109
+ const timeoutMarker = {};
16110
+ try {
16111
+ let timer;
16112
+ const m4 = await Promise.race([
16113
+ resolveMemoryVNextM4Selection({ db: input.db, owners, query: input.userInput, selected }),
16114
+ new Promise((_, reject) => {
16115
+ timer = setTimeout(
16116
+ () => reject(timeoutMarker),
16117
+ MEMORY_VNEXT_PRIMARY_READ_TIMEOUT_MS
16118
+ );
16119
+ })
16120
+ ]).finally(() => clearTimeout(timer));
16121
+ promptBlock = renderOverlay(m4.renderItems, m4.sources);
16122
+ allCoveredByVNext = m4.uncoveredLegacyCount === 0 && m4.recalledStateCount > 0;
16123
+ const source = m4.recalledStateCount > 0 ? m4.uncoveredLegacyCount === 0 ? "vnext" : "hybrid" : m4.uncoveredLegacyCount > 0 ? "legacy_fallback" : "none";
16124
+ emitPrimary({
16125
+ ...base,
16126
+ source,
16127
+ uncoveredLegacyCount: m4.uncoveredLegacyCount,
16128
+ coveredSuppressedCount: m4.coveredSuppressedCount,
16129
+ recalledStateCount: m4.recalledStateCount,
16130
+ vnextLatencyMs: vnextLatency(),
16131
+ contextChars: promptBlock?.length ?? 0,
16132
+ ...source === "legacy_fallback" ? { fallbackReason: "no_vnext_context" } : {}
15317
16133
  });
15318
- } else {
15319
- console.info("[memory] vnext pure read", {
15320
- event: "memory_vnext_pure_read",
15321
- ...observation
16134
+ } catch (error) {
16135
+ promptBlock = renderOverlay(selected);
16136
+ fallbackKind = error === timeoutMarker ? "timeout" : "runtime_error";
16137
+ emitPrimary({
16138
+ ...base,
16139
+ source: "legacy_fallback",
16140
+ vnextLatencyMs: vnextLatency(),
16141
+ contextChars: promptBlock?.length ?? 0,
16142
+ fallbackReason: "vnext_error",
16143
+ error: error === timeoutMarker ? "TimeoutError" : "UnknownError"
15322
16144
  });
15323
16145
  }
15324
- } catch {
15325
16146
  }
15326
- };
15327
- if (pureError != null) {
15328
- emitPureRead({
15329
- source: "none",
15330
- itemCount: 0,
15331
- vnextItemCount: 0,
15332
- vnextLatencyMs: pureLatencyMs,
15333
- contextChars: 0,
15334
- fallbackReason: "vnext_error",
15335
- error: pureError instanceof Error ? pureError.message : String(pureError)
15336
- });
15337
- } else if (pure.selectedItems.length === 0) {
15338
- emitPureRead({
15339
- source: "none",
15340
- itemCount: 0,
15341
- vnextItemCount: 0,
15342
- vnextLatencyMs: pureLatencyMs,
15343
- contextChars: 0,
15344
- fallbackReason: "no_vnext_context"
15345
- });
15346
- } else {
15347
- emitPureRead({
15348
- source: "vnext",
15349
- itemCount: pure.selectedItems.length,
15350
- vnextItemCount: pure.recalledStateCount,
15351
- vnextLatencyMs: pureLatencyMs,
15352
- contextChars: pure.promptBlock?.length ?? 0
16147
+ }
16148
+ const shadowEnabled = !primaryRead && input.vNextShadowProvider != null && isMemoryVNextShadowReadEnabled();
16149
+ if (shadowEnabled) {
16150
+ void runMemoryVNextShadowRead({
16151
+ ctx: {
16152
+ db: input.db,
16153
+ owners,
16154
+ query: input.userInput,
16155
+ provider: input.vNextShadowProvider
16156
+ },
16157
+ legacyItems: selected,
16158
+ legacyLatencyMs,
16159
+ legacyContextChars: promptBlock?.length ?? 0
16160
+ }).catch(() => {
15353
16161
  });
15354
16162
  }
15355
- const lazyPromotionEnabled2 = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
15356
- if (lazyPromotionEnabled2) {
16163
+ const lazyPromotionEnabled = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
16164
+ if (lazyPromotionEnabled && selected.length > 0 && !allCoveredByVNext) {
15357
16165
  void (async () => {
15358
- const ownerItems = await Promise.all(
15359
- owners.map(
15360
- (owner) => loadOwnerItemsFromDb(
15361
- input.db,
15362
- owner,
15363
- input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT
15364
- )
15365
- )
16166
+ const promotionPick = await pickFirstUncoveredLazyPromotionItem(
16167
+ input.db,
16168
+ selected
15366
16169
  );
15367
- const legacyCandidates = ownerItems.flat();
15368
- if (legacyCandidates.length > 0) {
15369
- const promotionPick = await pickFirstUncoveredLazyPromotionItem(
15370
- input.db,
15371
- legacyCandidates
15372
- );
15373
- if (promotionPick) {
15374
- await runMemoryVNextLazyPromotion({
15375
- db: input.db,
15376
- item: promotionPick.item,
15377
- selectedIndex: promotionPick.selectedIndex,
15378
- skippedCoveredCount: promotionPick.skippedCoveredCount,
15379
- skippedNoOpCount: promotionPick.skippedNoOpCount,
15380
- provider: input.vNextShadowProvider,
15381
- ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
15382
- });
15383
- }
16170
+ if (promotionPick) {
16171
+ await runMemoryVNextLazyPromotion({
16172
+ db: input.db,
16173
+ item: promotionPick.item,
16174
+ selectedIndex: promotionPick.selectedIndex,
16175
+ skippedCoveredCount: promotionPick.skippedCoveredCount,
16176
+ skippedNoOpCount: promotionPick.skippedNoOpCount,
16177
+ provider: input.vNextShadowProvider,
16178
+ ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
16179
+ });
15384
16180
  }
15385
16181
  })().catch(() => {
15386
16182
  });
15387
16183
  }
15388
- return {
15389
- selectedItems: pure.selectedItems,
15390
- promptBlock: pure.promptBlock
15391
- };
15392
- }
15393
- const policy = resolveAgentMemoryPolicy({ agentKey: input.agentKey });
15394
- const legacyStartedAt = performance.now();
15395
- const candidates = await loadMemoryCandidatesFromDb(input.db, {
15396
- owners,
15397
- subjects: buildMemorySubjectsForAgent({
15398
- userId: input.userId,
15399
- spaceId: input.spaceId,
15400
- agentKey: input.agentKey,
15401
- memorySubjectId: input.memorySubjectId,
15402
- policy
15403
- }),
15404
- kinds: ["episodic", "semantic", "procedural"],
15405
- ownerLimit: input.ownerLimit ?? DEFAULT_MEMORY_RUNTIME_OWNER_LIMIT,
15406
- ownerFallback: policy.ownerFallback,
15407
- corroboratedProceduralReserve: input.corroboratedProceduralReserve ?? CORROBORATED_PROCEDURAL_RESERVE
15408
- });
15409
- const rankContext = {
15410
- currentOwner: input.spaceId ? { ownerType: "space", ownerId: input.spaceId } : input.userId ? { ownerType: "user", ownerId: input.userId } : null,
15411
- currentSubject: input.spaceId ? { subjectType: "space", subjectId: input.spaceId } : input.userId ? { subjectType: "user", subjectId: input.userId } : null
15412
- };
15413
- const residentItems = candidates.filter((item) => item.resident === true).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, RESIDENT_MEMORY_RUNTIME_LIMIT);
15414
- const retrievalCandidates = candidates.filter((item) => item.resident !== true);
15415
- const ranked = selectRuntimeMemoryItems(
15416
- rankMemoryCandidates(retrievalCandidates, input.userInput, rankContext),
15417
- rankContext,
15418
- input.userInput
15419
- );
15420
- const selected = [...residentItems, ...ranked];
15421
- const legacyLatencyMs = Math.round((performance.now() - legacyStartedAt) * 10) / 10;
15422
- const renderOverlay = (items) => items.length === 0 ? null : buildMemoryOverlay(items, { maxTokens: MEMORY_OVERLAY_TOKEN_BUDGET });
15423
- let promptBlock = renderOverlay(selected);
15424
- const primaryRead = isMemoryVNextPrimaryReadEnabled();
15425
- let allCoveredByVNext = false;
15426
- if (primaryRead) {
15427
- const emitPrimary = (observation) => {
15428
- try {
15429
- (input.primaryReadEmit ?? ((o) => console.info("[memory] vnext primary read", { event: "memory_vnext_primary_read", ...o })))(observation);
15430
- } catch {
15431
- }
15432
- };
15433
- const base = { legacyHitCount: selected.length, legacyLatencyMs };
15434
- const vnextStartedAt = performance.now();
15435
- const vnextLatency = () => Math.round((performance.now() - vnextStartedAt) * 10) / 10;
15436
16184
  if (selected.length === 0) {
15437
- emitPrimary({ ...base, source: "none" });
15438
- } else {
15439
- try {
15440
- let timer;
15441
- const m4 = await Promise.race([
15442
- resolveMemoryVNextM4Selection({ db: input.db, owners, query: input.userInput, selected }),
15443
- new Promise((_, reject) => {
15444
- timer = setTimeout(
15445
- () => reject(Object.assign(new Error("timeout"), { name: "TimeoutError" })),
15446
- MEMORY_VNEXT_PRIMARY_READ_TIMEOUT_MS
15447
- );
15448
- })
15449
- ]).finally(() => clearTimeout(timer));
15450
- promptBlock = renderOverlay(m4.renderItems);
15451
- allCoveredByVNext = m4.uncoveredLegacyCount === 0 && m4.recalledStateCount > 0;
15452
- const source = m4.recalledStateCount > 0 ? m4.uncoveredLegacyCount === 0 ? "vnext" : "hybrid" : m4.uncoveredLegacyCount > 0 ? "legacy_fallback" : "none";
15453
- emitPrimary({
15454
- ...base,
15455
- source,
15456
- uncoveredLegacyCount: m4.uncoveredLegacyCount,
15457
- coveredSuppressedCount: m4.coveredSuppressedCount,
15458
- recalledStateCount: m4.recalledStateCount,
15459
- vnextLatencyMs: vnextLatency(),
15460
- contextChars: promptBlock?.length ?? 0,
15461
- ...source === "legacy_fallback" ? { fallbackReason: "no_vnext_context" } : {}
15462
- });
15463
- } catch (error) {
15464
- emitPrimary({
15465
- ...base,
15466
- source: "legacy_fallback",
15467
- vnextLatencyMs: vnextLatency(),
15468
- contextChars: promptBlock?.length ?? 0,
15469
- fallbackReason: "vnext_error",
15470
- error: error instanceof Error ? error.name : "UnknownError"
15471
- });
15472
- }
16185
+ return finish({ selectedItems: [], promptBlock: null });
16186
+ }
16187
+ await touchMemoryItemsInDb(input.db, selected);
16188
+ return finish({ selectedItems: selected, promptBlock });
16189
+ } finally {
16190
+ const observation = {
16191
+ ...injection,
16192
+ event: "memory_runtime_result",
16193
+ configuredPure,
16194
+ configuredPrimary,
16195
+ branch,
16196
+ outcome,
16197
+ errorKind
16198
+ };
16199
+ try {
16200
+ (input.runtimeResultEmit ?? ((event) => console.info("[memory] runtime result", event)))(observation);
16201
+ } catch {
15473
16202
  }
15474
16203
  }
15475
- const shadowEnabled = !primaryRead && input.vNextShadowProvider != null && isMemoryVNextShadowReadEnabled();
15476
- if (shadowEnabled) {
15477
- void runMemoryVNextShadowRead({
15478
- ctx: {
15479
- db: input.db,
15480
- owners,
15481
- query: input.userInput,
15482
- provider: input.vNextShadowProvider
15483
- },
15484
- legacyItems: selected,
15485
- legacyLatencyMs,
15486
- legacyContextChars: promptBlock?.length ?? 0
15487
- }).catch(() => {
15488
- });
15489
- }
15490
- const lazyPromotionEnabled = input.vNextShadowProvider != null && isMemoryVNextLazyPromotionEnabled();
15491
- if (lazyPromotionEnabled && selected.length > 0 && !allCoveredByVNext) {
15492
- void (async () => {
15493
- const promotionPick = await pickFirstUncoveredLazyPromotionItem(
15494
- input.db,
15495
- selected
15496
- );
15497
- if (promotionPick) {
15498
- await runMemoryVNextLazyPromotion({
15499
- db: input.db,
15500
- item: promotionPick.item,
15501
- selectedIndex: promotionPick.selectedIndex,
15502
- skippedCoveredCount: promotionPick.skippedCoveredCount,
15503
- skippedNoOpCount: promotionPick.skippedNoOpCount,
15504
- provider: input.vNextShadowProvider,
15505
- ...input.lazyPromotionEmit ? { emit: input.lazyPromotionEmit } : {}
15506
- });
15507
- }
15508
- })().catch(() => {
15509
- });
15510
- }
15511
- if (selected.length === 0) {
15512
- return { selectedItems: [], promptBlock: null };
15513
- }
15514
- await touchMemoryItemsInDb(input.db, selected);
15515
- return {
15516
- selectedItems: selected,
15517
- promptBlock
15518
- };
15519
16204
  };
15520
16205
 
15521
16206
  // packages/cli/memoryRecall.ts
@@ -15704,6 +16389,35 @@ async function resolveAgentBoundMachineIdFromRecord(args) {
15704
16389
  return resolveBoundMachineId(record) || void 0;
15705
16390
  }
15706
16391
  async function runAgentRunCommand(args, deps) {
16392
+ const env = deps.env ?? process.env;
16393
+ const runId = env.NOLO_AGENT_RUN_ID;
16394
+ const controlDeps = { env, homedir: deps.homedir, fs: deps.fs, now: deps.now };
16395
+ const failStartup = async (error) => {
16396
+ if (!runId || readRunRecord(runId, controlDeps)?.status !== "running") return;
16397
+ const result = await settleRunTerminalAuthoritatively(runId, {
16398
+ status: "failed",
16399
+ exitCode: 1,
16400
+ failureReason: error instanceof RuntimeProtocolMismatchError ? "runtime_protocol_mismatch" : error instanceof RuntimeVersionMismatchError ? "runtime_version_mismatch" : "startup_failed",
16401
+ note: error ? toErrorMessage(error) : "Child initialization returned without terminal result"
16402
+ }, controlDeps, (id, update, d) => transitionRunToTerminal(id, update, d));
16403
+ if (result.kind === "contended") throw new Error(`Startup settlement lock busy: ${runId}`);
16404
+ };
16405
+ try {
16406
+ if (runId) {
16407
+ if (!readRunRecord(runId, controlDeps)) throw new Error("[local-writer-resource] missing child binding");
16408
+ await recordRunStartup(runId, "initializing", controlDeps);
16409
+ validateAgentRunProtocol(env.NOLO_AGENT_RUN_PROTOCOL);
16410
+ await recordRunStartup(runId, "protocol_validated", controlDeps);
16411
+ }
16412
+ const code = await runAgentRunCommandImpl(args, deps);
16413
+ if (runId) await failStartup();
16414
+ return code;
16415
+ } catch (error) {
16416
+ await failStartup(error);
16417
+ throw error;
16418
+ }
16419
+ }
16420
+ async function runAgentRunCommandImpl(args, deps) {
15707
16421
  const env = deps.env ?? process.env;
15708
16422
  const output = deps.output ?? {
15709
16423
  write: (chunk) => process.stdout.write(chunk),
@@ -15726,10 +16440,17 @@ async function runAgentRunCommand(args, deps) {
15726
16440
  return 1;
15727
16441
  }
15728
16442
  const rawRunner = deps.runner ?? runAgentTurn;
16443
+ let modelPhaseRecorded = false;
15729
16444
  const watchdogAbort = new AbortController();
15730
16445
  let activeRunner;
15731
16446
  const runner = (options) => {
15732
- activeRunner = Promise.resolve().then(() => rawRunner({ ...options, abortSignal: watchdogAbort.signal })).then((result) => {
16447
+ activeRunner = Promise.resolve().then(async () => {
16448
+ if (env.NOLO_AGENT_RUN_ID && !modelPhaseRecorded) {
16449
+ await recordRunStartup(env.NOLO_AGENT_RUN_ID, "model", { env, homedir: deps.homedir, fs: deps.fs, now: deps.now });
16450
+ modelPhaseRecorded = true;
16451
+ }
16452
+ return rawRunner({ ...options, abortSignal: watchdogAbort.signal });
16453
+ }).then((result) => {
15733
16454
  watchdogAbort.signal.throwIfAborted();
15734
16455
  return result;
15735
16456
  });
@@ -15742,8 +16463,8 @@ async function runAgentRunCommand(args, deps) {
15742
16463
  try {
15743
16464
  return await Promise.race([
15744
16465
  activeRunner.then(() => true, () => true),
15745
- new Promise((resolve6) => {
15746
- timer = setTimeout(() => resolve6(false), 100);
16466
+ new Promise((resolve5) => {
16467
+ timer = setTimeout(() => resolve5(false), 100);
15747
16468
  })
15748
16469
  ]);
15749
16470
  } finally {
@@ -16162,6 +16883,7 @@ async function runAgentRunCommand(args, deps) {
16162
16883
  );
16163
16884
  const shellApprovalChild = process.connected && typeof process.send === "function" ? createShellApprovalChild(process) : void 0;
16164
16885
  try {
16886
+ const imageUrls = await normalizeCliRunImages(parsed.imageUrls, normalizeCliImageInput);
16165
16887
  const buildRunOptions = (targetAgentKey, turnMessage = effectiveMessage) => ({
16166
16888
  ...shellApprovalChild ? { execShellApproval: targetAgentKey === agentKey ? shellApprovalChild.authority : {
16167
16889
  request: async () => {
@@ -16181,7 +16903,7 @@ async function runAgentRunCommand(args, deps) {
16181
16903
  responseViewport: "unknown",
16182
16904
  serverUrl: resolveServerUrl(env),
16183
16905
  message: formatTurnMessage(turnMessage),
16184
- imageUrls: parsed.imageUrls.map(normalizeCliImageInput),
16906
+ imageUrls,
16185
16907
  scriptDir: deps.scriptDir,
16186
16908
  env: runEnv,
16187
16909
  output,
@@ -16411,7 +17133,7 @@ async function runAgentRunCommand(args, deps) {
16411
17133
  acceptance.checks.observations = dodResults.map((check, index) => ({
16412
17134
  // Command lines/output can contain credentials. Persist only a digest
16413
17135
  // here; the pre-existing registry is the execution evidence reference.
16414
- commandFingerprint: `sha256:${createHash("sha256").update(check.command).digest("hex")}`,
17136
+ commandFingerprint: `sha256:${createHash3("sha256").update(check.command).digest("hex")}`,
16415
17137
  cwd: childRecordForDoD?.cwd || process.cwd(),
16416
17138
  exitCode: check.exitCode,
16417
17139
  evidence: `${childRunId}.json#/dodResults/${index}`,
@@ -16481,6 +17203,16 @@ async function runAgentRunCommand(args, deps) {
16481
17203
  }
16482
17204
 
16483
17205
  export {
17206
+ resolveAgentModelIdentity,
17207
+ resolveAgentContextWindow2 as resolveAgentContextWindow,
17208
+ platformCreditsFromUsage,
17209
+ formatCreditsChip,
17210
+ resolveAuthorityTurnCount,
17211
+ computeBaselineContextTokens,
17212
+ preserveContextUsageWithoutReceipt,
17213
+ resolveContextUsage,
17214
+ renderTokenStatus,
17215
+ redactSecrets,
16484
17216
  resolveCliColorEnabled,
16485
17217
  dimCliText,
16486
17218
  THEME_PALETTES,
@@ -16506,18 +17238,10 @@ export {
16506
17238
  formatAssistantDisplay,
16507
17239
  resolveHistoryLayoutGeometry,
16508
17240
  resolveHistoryViewportHeight,
17241
+ safeAskText,
17242
+ safeApprovalMultilineText,
16509
17243
  TUI_TREE_MARKER,
16510
17244
  TUI_TREE_TOOLS,
16511
- resolveAgentModelIdentity,
16512
- resolveAgentContextWindow2 as resolveAgentContextWindow,
16513
- platformCreditsFromUsage,
16514
- formatCreditsChip,
16515
- formatTokenCount,
16516
- resolveAuthorityTurnCount,
16517
- computeBaselineContextTokens,
16518
- preserveContextUsageWithoutReceipt,
16519
- resolveContextUsage,
16520
- renderTokenStatus,
16521
17245
  createIdleHeapReleaser,
16522
17246
  COLLAPSED_PASTE_PLACEHOLDER_RE,
16523
17247
  shouldCollapsePaste,
@@ -16533,6 +17257,7 @@ export {
16533
17257
  emitTerminalProgramStatus,
16534
17258
  contextRefusalDiagnostics,
16535
17259
  describeContextRefusal,
17260
+ inspectLocalRunWorkspace,
16536
17261
  isBalanceExhaustedError,
16537
17262
  OWNER_OAUTH_UNAVAILABLE_HINT,
16538
17263
  isOwnerOAuthUnavailableError,