nolo-cli 0.226.0-alpha.2 → 0.227.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 (165) hide show
  1. package/{_executeModel-IKZGZZXW.js → _executeModel-JKQGZ3HU.js} +60 -60
  2. package/accountResolver-EK2S4PWF.js +1 -1
  3. package/action-CK64LS6S.js +3 -3
  4. package/{addContentAction-EQXMFNPR.js → addContentAction-CARFID6E.js} +11 -11
  5. package/{addDialogAgentAction-RSDZDASD.js → addDialogAgentAction-APLZLFW5.js} +10 -10
  6. package/{agentDeleteCommand-IZY3VF5F.js → agentDeleteCommand-NVR2V2HH.js} +86 -87
  7. package/{agentEmailCommands-YWL567CL.js → agentEmailCommands-UCVOWD3S.js} +86 -87
  8. package/{agentFavoriteCommands-2LKGKSUD.js → agentFavoriteCommands-4PDOP3GW.js} +3 -3
  9. package/{agentGrantCommands-QQV4N4JW.js → agentGrantCommands-FLCEXLUH.js} +4 -4
  10. package/{agentListCommands-YBNOQ5T3.js → agentListCommands-C65UESYM.js} +70 -57
  11. package/{agentMachineCommands-AXJ4A772.js → agentMachineCommands-V3DGEJU4.js} +43 -43
  12. package/{agentProviderCommands-7BSJH7TO.js → agentProviderCommands-7QBFRFRK.js} +4 -4
  13. package/{agentPullCommand-XN6ZPBUW.js → agentPullCommand-E6JBGBVG.js} +3 -3
  14. package/{agentRecordCommands-WUUC2CX7.js → agentRecordCommands-6RCJS2EY.js} +83 -84
  15. package/{agentRunCommand-W6MDKVLJ.js → agentRunCommand-P3GRKXKS.js} +86 -86
  16. package/{agentRunControl-DFEEOFC7.js → agentRunControl-SNZZ5XP4.js} +10 -10
  17. package/{agentRuntimeLocal-GSTYFEX4.js → agentRuntimeLocal-GOX2DIY7.js} +38 -38
  18. package/{agentSlice-5F5U5X2U.js → agentSlice-N7H2FRJA.js} +15 -15
  19. package/{appDeleteCommands-L7HL4AWF.js → appDeleteCommands-LZDN26FU.js} +47 -47
  20. package/{appDeployCommands-SGSUNFZR.js → appDeployCommands-6IO6TTZH.js} +47 -47
  21. package/{appDeployStatusCommands-AAA3XD54.js → appDeployStatusCommands-FG3LX24J.js} +47 -47
  22. package/{appGetCommands-LN72GAOA.js → appGetCommands-NAKVDVD4.js} +47 -47
  23. package/{appListCommands-IJQQ3VND.js → appListCommands-KL56RN73.js} +47 -47
  24. package/{authCommand-7JXW54U4.js → authCommand-AUN5MXV2.js} +20 -20
  25. package/{authCommands-YDNAIDEY.js → authCommands-D2IPS6ES.js} +7 -7
  26. package/{builtinSkillRegistry-PXH7EGQB.js → builtinSkillRegistry-UQGLKRYP.js} +5 -5
  27. package/{chromeOpsCommands-YKX2QX3A.js → chromeOpsCommands-UJWN5HWH.js} +5 -5
  28. package/{chunk-3QFLXA24.js → chunk-2G3YSVO6.js} +1 -1
  29. package/{chunk-2COEG5ZV.js → chunk-2SKTCNWO.js} +2 -2
  30. package/{chunk-KNIIRXHF.js → chunk-3HTP4WZQ.js} +2 -2
  31. package/{chunk-2TIQO6TC.js → chunk-3VFYQH3I.js} +21 -170
  32. package/{chunk-AZQZ5XPM.js → chunk-4OKTPFNX.js} +27 -27
  33. package/{chunk-UYOICCYG.js → chunk-5HL4KC4A.js} +9 -9
  34. package/{chunk-2VA6TU4I.js → chunk-5LQDHFBN.js} +14 -14
  35. package/{chunk-QLFCTYRH.js → chunk-5RKRXQ2H.js} +2 -2
  36. package/{chunk-PDCV7P5W.js → chunk-6XIE5ZGI.js} +1 -1
  37. package/{chunk-QTMIHVLE.js → chunk-7Z3WUZ4Q.js} +27 -24
  38. package/{chunk-BLSNUIZD.js → chunk-ABGULE7H.js} +13 -13
  39. package/{chunk-VQUWV3YR.js → chunk-AXYH4734.js} +12 -12
  40. package/{chunk-UEKXWO7A.js → chunk-C2B7M567.js} +4 -4
  41. package/{chunk-2ZKFCIJJ.js → chunk-CLCXHIBS.js} +1 -1
  42. package/{chunk-GBZ4YKEO.js → chunk-CQVGR3MX.js} +2 -2
  43. package/{chunk-KC4SCKXO.js → chunk-CVERLOJM.js} +51 -52
  44. package/{chunk-KN3HEZIQ.js → chunk-EVGU5P4U.js} +1 -1
  45. package/{chunk-QZI44GWV.js → chunk-F5AY2UZL.js} +145 -4
  46. package/{chunk-WSJMT3FA.js → chunk-FKEZOMIF.js} +426 -2459
  47. package/{chunk-PVZY6P3S.js → chunk-G6HJUMST.js} +2 -2
  48. package/{chunk-NEKH3XDV.js → chunk-GOLPOTG5.js} +3 -3
  49. package/{chunk-GVGOEMNV.js → chunk-GOQ6ZVTN.js} +1 -1
  50. package/{chunk-T3T57NVP.js → chunk-GRXSJR2Z.js} +19 -19
  51. package/{chunk-GGKNJ42M.js → chunk-GUVXQSFZ.js} +2 -2
  52. package/{chunk-UKS7D2NL.js → chunk-HYKGIXNO.js} +9 -9
  53. package/{chunk-6O5YP6FX.js → chunk-IAJJYHIB.js} +5 -5
  54. package/{chunk-SOF4OWDM.js → chunk-IC2I373Q.js} +3 -5
  55. package/{chunk-UJKTI5PG.js → chunk-ILHQ2AXT.js} +0 -1
  56. package/{chunk-VV7TXWOC.js → chunk-IX2BXN2K.js} +3 -3
  57. package/{chunk-RRVQ446B.js → chunk-JHF6VLVL.js} +29 -29
  58. package/{chunk-DISQCYPE.js → chunk-KJAAPGBE.js} +1 -1
  59. package/{chunk-N5PQJKCY.js → chunk-KMRKZNGT.js} +5 -5
  60. package/{chunk-GNHMRBYZ.js → chunk-KRRE4A7D.js} +3 -3
  61. package/{chunk-6J4TTPS2.js → chunk-L42CBKBZ.js} +4 -4
  62. package/{chunk-BYH3HMUP.js → chunk-LA7JYAKF.js} +3 -3
  63. package/{chunk-EJU6WCDH.js → chunk-LXTC53TN.js} +84 -72
  64. package/{chunk-67BE44IS.js → chunk-M3Y4IBIR.js} +4 -4
  65. package/{chunk-GIABSSWQ.js → chunk-MWHOH4RJ.js} +1 -1
  66. package/{chunk-3KNEE64G.js → chunk-NAOO4PVX.js} +16 -16
  67. package/{chunk-MOMR7NMG.js → chunk-NO3VBWTL.js} +1 -1
  68. package/{chunk-YDBMZ7FV.js → chunk-OXA5GWHU.js} +2 -2
  69. package/{chunk-FTQWYWUI.js → chunk-PHOSZT3E.js} +1 -1
  70. package/{chunk-C4WTX5TU.js → chunk-PLPLH2XZ.js} +1 -1
  71. package/{chunk-W772FYAQ.js → chunk-PVAWNHP5.js} +52 -52
  72. package/{chunk-OLMJR6UM.js → chunk-PXKF5CV4.js} +4 -4
  73. package/{chunk-ZH6MUQEO.js → chunk-RU6DULV4.js} +1 -1
  74. package/{chunk-JVRQ6YVK.js → chunk-S6K5F3KP.js} +1 -1
  75. package/{chunk-AVHRSJUH.js → chunk-SFTTXGPM.js} +10 -10
  76. package/{chunk-4HFTBHBF.js → chunk-SRG5CNLC.js} +4 -4
  77. package/{chunk-HHL7WG65.js → chunk-SW6OD4KE.js} +6 -6
  78. package/{chunk-TXGQ4O5S.js → chunk-T43K75CK.js} +13 -13
  79. package/{chunk-KZU52OJ5.js → chunk-T5N6NHAT.js} +6 -6
  80. package/{chunk-JHRQXQ4A.js → chunk-TINJKQSO.js} +11 -11
  81. package/{chunk-JM5C4EUA.js → chunk-TOKPHZ55.js} +1 -1
  82. package/{chunk-GBUDWITV.js → chunk-UAPNPNSG.js} +892 -625
  83. package/{chunk-BGGHA5DV.js → chunk-UCFPVYP7.js} +1 -1
  84. package/{chunk-SOG7OEXX.js → chunk-ULAQPRHX.js} +1 -1
  85. package/{chunk-SBVTHMEG.js → chunk-UN7HIYMH.js} +1 -1
  86. package/{chunk-GOAPXKQU.js → chunk-UVUVQVZ6.js} +4 -4
  87. package/{chunk-4AMQZTE7.js → chunk-VIHDJ3FK.js} +5 -5
  88. package/{chunk-EWPDMS4N.js → chunk-VPAZ6BEN.js} +1 -1
  89. package/{chunk-XN23AUVU.js → chunk-VZW34YUL.js} +3 -3
  90. package/{chunk-D726I5AZ.js → chunk-WJP4TH6U.js} +1 -1
  91. package/{chunk-EOWLBDY6.js → chunk-X2KRQP7V.js} +1 -1
  92. package/{chunk-F7DU25CE.js → chunk-XIEYGCN6.js} +4 -10
  93. package/{chunk-KOXKKHFE.js → chunk-XZODOEKU.js} +1 -1
  94. package/{chunk-QVBXJNZ2.js → chunk-YGILMZ7N.js} +1 -1
  95. package/{chunk-C4VAR65S.js → chunk-YOT437BH.js} +5 -5
  96. package/{chunk-VFBVA3U2.js → chunk-YPPKC6FL.js} +2 -2
  97. package/{chunk-LM2PS3YS.js → chunk-YQETUZ5V.js} +5 -5
  98. package/{chunk-E5EIYI34.js → chunk-ZADGPNTV.js} +24 -24
  99. package/{chunk-L4NFXFFF.js → chunk-ZI5SZ3MV.js} +11 -11
  100. package/{chunk-EFX3Q5SM.js → chunk-ZYA2YDB6.js} +18 -18
  101. package/{cliAgentConfigHelpers-KICKKNYQ.js → cliAgentConfigHelpers-QVSQYTKC.js} +10 -10
  102. package/{cliEnvHelpers-VPSJ4XWC.js → cliEnvHelpers-D6HMC46Z.js} +2 -2
  103. package/{cliLocalAgentRecordReader-6FXGFBI3.js → cliLocalAgentRecordReader-SPKAJYME.js} +45 -45
  104. package/{commandRegistry-6EQXVODF.js → commandRegistry-TKR6OWXP.js} +91 -91
  105. package/{contentThunks-ANUP57QV.js → contentThunks-BQWRPCTM.js} +29 -29
  106. package/{createAgentAutomationAction-XMUWUDKQ.js → createAgentAutomationAction-GFI6SJZV.js} +32 -32
  107. package/{createDialogAction-43QJIQDH.js → createDialogAction-MMBIHFFU.js} +30 -30
  108. package/{createPageAction-SJO7UC3J.js → createPageAction-EEYUE5FB.js} +32 -32
  109. package/{dbSlice-ZJPDIFER.js → dbSlice-X4Z4E4QU.js} +10 -10
  110. package/{deleteFile-Q3YDB4ML.js → deleteFile-QOOP2UK7.js} +5 -5
  111. package/{dialogCommands-V5IYEOQP.js → dialogCommands-OXBQ73DD.js} +48 -48
  112. package/{dialogNotifyCommand-77B57PL6.js → dialogNotifyCommand-VWS5G4OO.js} +13 -13
  113. package/{dialogSlice-FQ6WOKWJ.js → dialogSlice-KGYIABDY.js} +27 -27
  114. package/{dialogUsageCommand-HTVPR2CX.js → dialogUsageCommand-FEWCN7IA.js} +6 -6
  115. package/{docCreateCommands-36WS33BK.js → docCreateCommands-LS32VKY3.js} +47 -47
  116. package/{docDeleteCommands-C4CS4XLF.js → docDeleteCommands-JTYR5RPH.js} +48 -48
  117. package/{docReadCommands-QZMSFMPN.js → docReadCommands-E5LTVKWN.js} +47 -47
  118. package/{docStore-BZ2O7WLF.js → docStore-TVS2FNER.js} +12 -12
  119. package/{docUpdateCommands-BYI64HVV.js → docUpdateCommands-I3J3JDZ2.js} +47 -47
  120. package/{fetchMessages-TQEUZD7H.js → fetchMessages-Q3INLN5F.js} +2 -2
  121. package/getPricing-VNGFM4PN.js +2 -2
  122. package/{handleSendMessageAction-I5J7QR7K.js → handleSendMessageAction-SSON36TJ.js} +54 -54
  123. package/{hostCredentialCreate-AVPMK7EQ.js → hostCredentialCreate-WTW4THJF.js} +83 -84
  124. package/index.js +12 -12
  125. package/{localDialogRead-SVTPA5GY.js → localDialogRead-V36DX2Q2.js} +1 -1
  126. package/{localRuntimeAdapter-S56R76HN.js → localRuntimeAdapter-MI2JGXSF.js} +83 -84
  127. package/{machineCommands-77NFB2AE.js → machineCommands-3LROJZDK.js} +86 -87
  128. package/{machineWsRunDispatch-5XWFUJ53.js → machineWsRunDispatch-BUUJRUUB.js} +82 -83
  129. package/{memberThunks-JRYNONYV.js → memberThunks-CFEPHAND.js} +14 -14
  130. package/{memoryCommands-5WC3T66U.js → memoryCommands-JQMEJO7J.js} +3 -3
  131. package/package.json +1 -1
  132. package/{projectArchive-GNOSYH6F.js → projectArchive-3X54XFVN.js} +32 -32
  133. package/{providerPresetApply-J3WMRPD2.js → providerPresetApply-FO36N5TX.js} +5 -5
  134. package/{providerRegistry-KJGB5XWS.js → providerRegistry-U2BSFE6K.js} +5 -5
  135. package/{read-Q7GOHGNP.js → read-KA3L2V7O.js} +6 -6
  136. package/{readDocTool-Z5OQ6422.js → readDocTool-AMAZAPAW.js} +1 -1
  137. package/{readlineWorkspace-2PONGBUP.js → readlineWorkspace-Z3YUH4SX.js} +599 -1264
  138. package/{removeDialogAgentAction-U3F2MNAY.js → removeDialogAgentAction-JQOJSUM7.js} +12 -12
  139. package/{runAgentClientLoop-WEXFFHVS.js → runAgentClientLoop-4FCFLMDJ.js} +63 -59
  140. package/{runtimeDoctorCommands-UXKXYBW6.js → runtimeDoctorCommands-CXOCVDPU.js} +5 -5
  141. package/{secretCommands-LJXOOYA7.js → secretCommands-GGUAWAE7.js} +3 -3
  142. package/{setDialogExtraReferencesAction-G3WSJ7EM.js → setDialogExtraReferencesAction-YXQTGXIN.js} +11 -11
  143. package/{setPrimaryDialogAgentAction-6FHAHZBB.js → setPrimaryDialogAgentAction-YNLB66WE.js} +12 -12
  144. package/{settingThunks-AXTBX3Q5.js → settingThunks-E6N7RSSS.js} +16 -16
  145. package/{spaceCommands-GUKMDRWN.js → spaceCommands-DB5DKC2J.js} +43 -43
  146. package/{streamAgentChatTurn-D2WFS5MF.js → streamAgentChatTurn-FCBGMD4D.js} +84 -123
  147. package/{switchDialogAgentAction-UOFIAGPL.js → switchDialogAgentAction-LAHLUECU.js} +10 -10
  148. package/{tools-YKE6PQHT.js → tools-6JD36D6K.js} +49 -49
  149. package/{tuiSummaryLlmCaller-7WLUKNP2.js → tuiSummaryLlmCaller-UHZIPGAX.js} +14 -14
  150. package/{updateCommands-RJVCRSBP.js → updateCommands-KZ54HCU5.js} +6 -6
  151. package/{updateDialogTitleAction-D5NCA4FC.js → updateDialogTitleAction-RV3EUEN3.js} +32 -32
  152. package/{usageCommand-YPJ2ZI2F.js → usageCommand-KFVV6UL3.js} +1 -1
  153. package/{usageRebuildCommand-FERQO74C.js → usageRebuildCommand-HHFSNK46.js} +2 -2
  154. package/{chunk-4NA3YTBC.js → chunk-6EDAMVG6.js} +6 -6
  155. package/{chunk-W6RFEDN4.js → chunk-AETZ7AD6.js} +3 -3
  156. package/{chunk-2VUZSVAS.js → chunk-CSW7IPVD.js} +9 -9
  157. package/{chunk-KEN3N2TN.js → chunk-HVUDBOQG.js} +7 -7
  158. package/{chunk-SNBZZPYH.js → chunk-OQHIVPG4.js} +3 -3
  159. package/{chunk-47ITIXO7.js → chunk-SSGTV4FC.js} +3 -3
  160. package/{chunk-IZIN2UNJ.js → chunk-T2BEPTAG.js} +6 -6
  161. package/{chunk-HXER7YJF.js → chunk-VXL2FZTP.js} +3 -3
  162. package/{chunk-2THCNKE4.js → chunk-WACI5I6V.js} +3 -3
  163. package/{cooldownCommands-X7P5M2V5.js → cooldownCommands-FZYQOWI5.js} +1 -1
  164. package/{offlineMarxistsAgentCommand-4IC3Y4C6.js → offlineMarxistsAgentCommand-AGA2X5E4.js} +6 -6
  165. package/{tableCommands-HITDSLHS.js → tableCommands-VNSXHAMG.js} +9 -9
@@ -1,9 +1,6 @@
1
1
  import {
2
2
  BROWSER_SHELL_BRIDGE_ENV
3
3
  } from "./chunk-2YGBI2XB.js";
4
- import {
5
- findPotentialSecrets
6
- } from "./chunk-6QDYSCPW.js";
7
4
  import {
8
5
  defaultLoopbackRequest
9
6
  } from "./chunk-VP3BINY7.js";
@@ -16,7 +13,7 @@ import {
16
13
  CREDENTIAL_STORE_SESSION_FALLBACK_WARNING,
17
14
  OAUTH_PROVIDER_REFS,
18
15
  getSharedSessionCredentialBroker
19
- } from "./chunk-2VA6TU4I.js";
16
+ } from "./chunk-5LQDHFBN.js";
20
17
  import {
21
18
  customNativeAuthHeaders,
22
19
  detectDeclaredCustomNativeWire,
@@ -33,9 +30,8 @@ import {
33
30
  refreshOpenAiCodexToken,
34
31
  resolveClaudeCodeVersion,
35
32
  resolveServerSyncConfig,
36
- stripAnsi,
37
33
  xaiRefresh
38
- } from "./chunk-UKS7D2NL.js";
34
+ } from "./chunk-HYKGIXNO.js";
39
35
  import {
40
36
  isCursorOAuthAgent
41
37
  } from "./chunk-VIWDGTDA.js";
@@ -43,7 +39,7 @@ import {
43
39
  DialogNotifyError,
44
40
  deliverDialogNotification,
45
41
  sha256Hex
46
- } from "./chunk-67BE44IS.js";
42
+ } from "./chunk-M3Y4IBIR.js";
47
43
  import {
48
44
  SANDBOX_HELPER_PATH,
49
45
  SANDBOX_OUTPUT_LIMITS,
@@ -64,10 +60,10 @@ import {
64
60
  localTurnHasSubjectRefs,
65
61
  resolveLocalUserId,
66
62
  withResolvedRuntimeToolSurface
67
- } from "./chunk-KZU52OJ5.js";
63
+ } from "./chunk-T5N6NHAT.js";
68
64
  import {
69
65
  createTuiSummaryLlmCaller
70
- } from "./chunk-4HFTBHBF.js";
66
+ } from "./chunk-SRG5CNLC.js";
71
67
  import {
72
68
  CliProviderQuotaError,
73
69
  executeCli,
@@ -79,11 +75,11 @@ import {
79
75
  import {
80
76
  inferCaptureIntent,
81
77
  resolveUserSkillRuntime
82
- } from "./chunk-OLMJR6UM.js";
78
+ } from "./chunk-PXKF5CV4.js";
83
79
  import {
84
80
  inlineImageUrlsForCustomProvider,
85
81
  prepareTools
86
- } from "./chunk-2COEG5ZV.js";
82
+ } from "./chunk-2SKTCNWO.js";
87
83
  import {
88
84
  getServerProviderSecret
89
85
  } from "./chunk-HS7MLR74.js";
@@ -106,7 +102,7 @@ import {
106
102
  resolveCliLocalSpawnDispatch,
107
103
  resolveRunContextFacts,
108
104
  resolveStartAgentRunCwd
109
- } from "./chunk-EJU6WCDH.js";
105
+ } from "./chunk-LXTC53TN.js";
110
106
  import {
111
107
  fetchWithTransientRetry,
112
108
  isTransientFetchError
@@ -114,16 +110,16 @@ import {
114
110
  import {
115
111
  deriveCredentialGroup,
116
112
  deriveCustomProviderCredentialGroup
117
- } from "./chunk-QZI44GWV.js";
113
+ } from "./chunk-F5AY2UZL.js";
118
114
  import {
119
115
  normalizeEnabledPromptSkills,
120
116
  resolveUserEnabledSkills
121
- } from "./chunk-GGKNJ42M.js";
117
+ } from "./chunk-GUVXQSFZ.js";
122
118
  import {
123
119
  prepareTokenUsageData,
124
120
  runKeyed,
125
121
  validateAskChoiceInput
126
- } from "./chunk-W772FYAQ.js";
122
+ } from "./chunk-PVAWNHP5.js";
127
123
  import {
128
124
  applyTokenUsageToDayStats,
129
125
  require_format
@@ -134,7 +130,54 @@ import {
134
130
  } from "./chunk-523DITKR.js";
135
131
  import {
136
132
  fetchServerSyncedCredential
137
- } from "./chunk-BLSNUIZD.js";
133
+ } from "./chunk-ABGULE7H.js";
134
+ import {
135
+ _readQueueEntriesLocked,
136
+ ackRunRecord,
137
+ appendRunQueue,
138
+ assertHostMemoryAdmission,
139
+ checkStaleRun,
140
+ claimRunRecord,
141
+ commitRunRecordClaim,
142
+ findRunRecord,
143
+ gcRunRecords,
144
+ isRunTerminalStatus,
145
+ listRunRecords,
146
+ localWriterRecovery,
147
+ queryRunRecords,
148
+ readHostMemory,
149
+ releaseRunRecordAck,
150
+ resolveLocalContinuation,
151
+ resolveRunsDir,
152
+ revokePreparedWriterLaunch,
153
+ serializeQueueEntries,
154
+ spawnLocalBackgroundRun,
155
+ terminateRunProcess,
156
+ transitionRunToTerminal,
157
+ withQueueLock
158
+ } from "./chunk-XIEYGCN6.js";
159
+ import {
160
+ remoteDialogSyncTimeout,
161
+ resolveRuntimeAuthToken,
162
+ resolveRuntimeServerUrl
163
+ } from "./chunk-UN7HIYMH.js";
164
+ import {
165
+ TASK_PREVIEW_MAX,
166
+ formatControlRunMessageCard,
167
+ formatDuration,
168
+ formatListRunsCard,
169
+ formatNotFoundRunCard,
170
+ formatRunAge,
171
+ formatStartRunCard,
172
+ formatStatusRunCard,
173
+ formatStopRunCard,
174
+ isAgentNameFallback,
175
+ isAgentRunTerminalStatus,
176
+ normalizeRunTitle,
177
+ resolveAgentRunName,
178
+ resolveRunLabel,
179
+ shortRunId
180
+ } from "./chunk-AXYH4734.js";
138
181
  import {
139
182
  getDefaultCliLocalRuntimeDb
140
183
  } from "./chunk-N5Z2V73W.js";
@@ -146,7 +189,7 @@ import {
146
189
  readDialogMessageRecords,
147
190
  readDialogMessages,
148
191
  resolveBuiltinLocalCliAgentConfig
149
- } from "./chunk-N5PQJKCY.js";
192
+ } from "./chunk-KMRKZNGT.js";
150
193
  import {
151
194
  LOCAL_CODEX_AGENT_KEY,
152
195
  isLocalCliAgentKey,
@@ -201,7 +244,7 @@ import {
201
244
  runExecShellGates,
202
245
  validateConfiguredRootExecutionLease,
203
246
  verifyOwnerRouteAck
204
- } from "./chunk-KC4SCKXO.js";
247
+ } from "./chunk-CVERLOJM.js";
205
248
  import {
206
249
  accumulateGeminiChunks,
207
250
  buildGeminiGenerateContentRequest,
@@ -213,7 +256,7 @@ import {
213
256
  resolveAntigravityFinishReason,
214
257
  resolveGeminiModelQuirks,
215
258
  shouldUseGeminiNativeToolRoute
216
- } from "./chunk-VFBVA3U2.js";
259
+ } from "./chunk-YPPKC6FL.js";
217
260
  import {
218
261
  PlatformStreamInterruptedError,
219
262
  buildPlatformChatCompletionRequest,
@@ -225,7 +268,7 @@ import {
225
268
  readPlatformChatSseCompletion,
226
269
  resolvePlatformChatProviderConfig,
227
270
  shouldUsePlatformChatProvider
228
- } from "./chunk-VV7TXWOC.js";
271
+ } from "./chunk-IX2BXN2K.js";
229
272
  import {
230
273
  readSseDataValues,
231
274
  readSseFrames
@@ -235,13 +278,13 @@ import {
235
278
  } from "./chunk-2WZXXAQD.js";
236
279
  import {
237
280
  resolveToolImagePolicy
238
- } from "./chunk-KNIIRXHF.js";
281
+ } from "./chunk-3HTP4WZQ.js";
239
282
  import {
240
283
  assertDispatchSelectionAdmission,
241
284
  buildNoloWorkspaceOpenAiTools,
242
285
  filterClientNoloWorkspaceToolNames,
243
286
  parseNoloWorkspaceToolArguments
244
- } from "./chunk-C4VAR65S.js";
287
+ } from "./chunk-YOT437BH.js";
245
288
  import {
246
289
  extractQuotaSnapshot,
247
290
  isCapacitySaturatedRateLimit,
@@ -252,14 +295,14 @@ import {
252
295
  import {
253
296
  HIGH_RISK_MUTATION_TOOL_NAMES,
254
297
  resolveRequestToolSurface
255
- } from "./chunk-SOF4OWDM.js";
298
+ } from "./chunk-IC2I373Q.js";
256
299
  import {
257
300
  collectStablePromptPrefix,
258
301
  convertMessagesToResponsesInput,
259
302
  findAgentStatePairingIssues,
260
303
  stablePromptCacheKey,
261
304
  toResponsesTools
262
- } from "./chunk-JM5C4EUA.js";
305
+ } from "./chunk-TOKPHZ55.js";
263
306
  import {
264
307
  EMPTY_TOOL_RESULT_TEXT,
265
308
  createToolImageBudget,
@@ -272,7 +315,7 @@ import {
272
315
  import {
273
316
  resolveAgentRequiredPackIds,
274
317
  resolveAgentSkillConfig
275
- } from "./chunk-EOWLBDY6.js";
318
+ } from "./chunk-X2KRQP7V.js";
276
319
  import {
277
320
  buildDialogFallbackTitleFromUserInput,
278
321
  normalizeDialogTitle
@@ -286,13 +329,13 @@ import {
286
329
  isCodexOAuthAgent,
287
330
  markCodexOAuthCatalogFailure,
288
331
  resolveCodexOAuthEffectiveModel
289
- } from "./chunk-LM2PS3YS.js";
332
+ } from "./chunk-YQETUZ5V.js";
290
333
  import {
291
334
  isDevinOAuthAgent
292
335
  } from "./chunk-5ZUL4CUO.js";
293
336
  import {
294
337
  normalizeUsage
295
- } from "./chunk-IZIN2UNJ.js";
338
+ } from "./chunk-T2BEPTAG.js";
296
339
  import {
297
340
  createProviderCallTimingTracker,
298
341
  finalizeProviderCallTiming,
@@ -310,19 +353,32 @@ import {
310
353
  resolveCurrentRunRuntimeToolPolicy,
311
354
  resolveLocalWorkspaceExecutorOptionsFromPolicy,
312
355
  resolveRequestedRuntimeToolNames
313
- } from "./chunk-47ITIXO7.js";
356
+ } from "./chunk-SSGTV4FC.js";
314
357
  import {
315
358
  asRecordOrEmpty
316
359
  } from "./chunk-KX6YBIHG.js";
317
360
  import {
318
361
  createFileCredentialBroker
319
- } from "./chunk-SNBZZPYH.js";
362
+ } from "./chunk-OQHIVPG4.js";
320
363
  import {
321
364
  compactWhitespace
322
365
  } from "./chunk-DWLEOOGR.js";
366
+ import {
367
+ withShellChildEnvironment
368
+ } from "./chunk-HVUDBOQG.js";
369
+ import {
370
+ estimateTokenCount
371
+ } from "./chunk-PSCNXBYA.js";
323
372
  import {
324
373
  isAntigravityOAuthAgent
325
- } from "./chunk-EWPDMS4N.js";
374
+ } from "./chunk-VPAZ6BEN.js";
375
+ import {
376
+ buildProviderSessionHeaders,
377
+ resolvePlatformAuthToken
378
+ } from "./chunk-6EDAMVG6.js";
379
+ import {
380
+ toErrorMessage
381
+ } from "./chunk-HNMXYYJR.js";
326
382
  import {
327
383
  FORCED_TOOLS,
328
384
  addDefaultLightWebToolsForConfiguredAgents,
@@ -334,104 +390,12 @@ import {
334
390
  expandEnabledPacks,
335
391
  resolveBuiltinSkillEntry,
336
392
  resolveEffectiveEnabledPacks
337
- } from "./chunk-GNHMRBYZ.js";
393
+ } from "./chunk-KRRE4A7D.js";
338
394
  import {
339
395
  CHROME_CONNECTOR_ACCEPTED_TOOL_NAMES,
340
396
  canonicalizeChromeConnectorToolNames,
341
397
  canonicalizeToolNames
342
398
  } from "./chunk-6OVNSQHN.js";
343
- import {
344
- createTokenDialogIndexKey,
345
- createTokenKey,
346
- createTokenStatsKey,
347
- createUserKey
348
- } from "./chunk-SYTHYBMI.js";
349
- import {
350
- dialogMessageKey
351
- } from "./chunk-OJKUU3LP.js";
352
- import {
353
- dialogIdFromKey
354
- } from "./chunk-YZMNK53S.js";
355
- import {
356
- classifyDialogSyncFailure,
357
- getLogger,
358
- startOwnedDialogSync
359
- } from "./chunk-YGMBIXCF.js";
360
- import {
361
- readPipeText,
362
- spawnProcess
363
- } from "./chunk-4O22PGNQ.js";
364
- import {
365
- agentRunCardLabels,
366
- t
367
- } from "./chunk-OB6DVWPF.js";
368
- import {
369
- _readQueueEntriesLocked,
370
- ackRunRecord,
371
- appendRunQueue,
372
- assertHostMemoryAdmission,
373
- checkStaleRun,
374
- claimRunRecord,
375
- commitRunRecordClaim,
376
- finalizeRunRecord,
377
- findRunRecord,
378
- gcRunRecords,
379
- isRunTerminalStatus,
380
- listRunRecords,
381
- localWriterRecovery,
382
- queryRunRecords,
383
- readHostMemory,
384
- readRunRecord,
385
- releaseRunRecordAck,
386
- resolveLocalContinuation,
387
- resolveRunsDir,
388
- revokePreparedWriterLaunch,
389
- serializeQueueEntries,
390
- spawnLocalBackgroundRun,
391
- stripResultFrontMatter,
392
- terminateRunProcess,
393
- transitionRunToTerminal,
394
- withQueueLock,
395
- writeRunRecord
396
- } from "./chunk-F7DU25CE.js";
397
- import {
398
- remoteDialogSyncTimeout,
399
- resolveRuntimeAuthToken,
400
- resolveRuntimeServerUrl
401
- } from "./chunk-SBVTHMEG.js";
402
- import {
403
- TASK_PREVIEW_MAX,
404
- formatControlRunMessageCard,
405
- formatDuration,
406
- formatListRunsCard,
407
- formatNotFoundRunCard,
408
- formatRunAge,
409
- formatStartRunCard,
410
- formatStatusRunCard,
411
- formatStopRunCard,
412
- isAgentNameFallback,
413
- isAgentRunTerminalStatus,
414
- normalizeRunTitle,
415
- resolveAgentRunName,
416
- resolveRunLabel,
417
- shortRunId
418
- } from "./chunk-VQUWV3YR.js";
419
- import {
420
- withShellChildEnvironment
421
- } from "./chunk-KEN3N2TN.js";
422
- import {
423
- estimateTokenCount
424
- } from "./chunk-PSCNXBYA.js";
425
- import {
426
- buildProviderSessionHeaders,
427
- resolvePlatformAuthToken
428
- } from "./chunk-4NA3YTBC.js";
429
- import {
430
- toErrorMessage
431
- } from "./chunk-HNMXYYJR.js";
432
- import {
433
- asTrimmedString
434
- } from "./chunk-3EUW3WEO.js";
435
399
  import {
436
400
  anthropicOAuthModelMaxOutputTokens,
437
401
  findModelConfig,
@@ -448,1402 +412,65 @@ import {
448
412
  asTrimmedLowercaseString
449
413
  } from "./chunk-QSJ3HFEF.js";
450
414
  import {
451
- asOptionalPositiveFiniteNumber
452
- } from "./chunk-U6VC4MU4.js";
453
- import {
454
- isCompiledBinary,
455
- parseUserIdFromAuthToken,
456
- resolveAuthToken,
457
- resolveServerUrl
458
- } from "./chunk-2THCNKE4.js";
459
- import {
460
- DEFAULT_NOLO_SERVER_URL
461
- } from "./chunk-OLZBQWZU.js";
462
- import {
463
- NOLO_CLUSTER_SERVERS
464
- } from "./chunk-LCBAMY2M.js";
465
- import {
466
- asOptionalTrimmedString
467
- } from "./chunk-G3SUCT4W.js";
468
- import {
469
- isLoopbackUrl
470
- } from "./chunk-4SN6J65J.js";
471
- import {
472
- normalizeServerOrigin
473
- } from "./chunk-CF7PE763.js";
474
- import {
475
- createOAuthTokenStore,
476
- isTokenExpired,
477
- readOAuthCredential,
478
- resolveFreshAccessToken
479
- } from "./chunk-G7Y4GXTY.js";
415
+ classifyDialogSyncFailure,
416
+ getLogger,
417
+ startOwnedDialogSync
418
+ } from "./chunk-YGMBIXCF.js";
480
419
  import {
481
- __toESM
482
- } from "./chunk-U67V476Y.js";
483
-
484
- // packages/agent-runtime/agentRunIsolation.ts
485
- var ORCHESTRATION_TOOL_NAMES = /* @__PURE__ */ new Set([
486
- "startAgentRun",
487
- "controlAgentRun",
488
- "requestTaskReview",
489
- "recordTaskReviewDecision",
490
- "listAgents",
491
- "readAgent",
492
- "runStreamingAgent"
493
- ]);
494
- var INTERACTION_REQUIRED_TOOL_NAMES = /* @__PURE__ */ new Set([
495
- "ask_user",
496
- // 凭据请求:需要宿主交互面板(Block 1a);desktop 无通道时同 ask_user 剥离。
497
- "secret-request"
498
- ]);
499
- var SELF_MUTATION_TOOL_NAMES = /* @__PURE__ */ new Set([
500
- "updateSelf",
501
- "updateAgent"
502
- ]);
503
- var SUBTASK_REMOVED_TOOL_NAMES = /* @__PURE__ */ new Set([
504
- ...ORCHESTRATION_TOOL_NAMES,
505
- ...INTERACTION_REQUIRED_TOOL_NAMES,
506
- ...SELF_MUTATION_TOOL_NAMES
507
- ]);
508
- function isSubtaskRun(env) {
509
- if (!env) return false;
510
- const value = env.NOLO_AGENT_RUN_CHILD;
511
- return typeof value === "string" && value.length > 0 && value !== "0";
512
- }
513
- var RUN_WAKE_CHANNEL_ENV = "NOLO_RUN_WAKE";
514
- function hasRunWakeChannel(env) {
515
- if (!env) return false;
516
- const value = env[RUN_WAKE_CHANNEL_ENV];
517
- return typeof value === "string" && value.length > 0 && value !== "0";
518
- }
519
- function filterToolNamesForRunKind(toolNames, isSubtask) {
520
- if (!isSubtask) return [...toolNames];
521
- return toolNames.filter((name) => !SUBTASK_REMOVED_TOOL_NAMES.has(name));
522
- }
523
-
524
- // packages/cli/client/hostReviewDispatch.ts
525
- import { AsyncLocalStorage } from "node:async_hooks";
526
- import { createHash as createHash4, randomUUID } from "node:crypto";
527
- import { appendFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, readdirSync as readdirSync2, renameSync, writeFileSync as writeFileSync2, lstatSync as lstatSync2, realpathSync as realpathSync2 } from "node:fs";
528
- import { join as join4, resolve as resolve4 } from "node:path";
529
-
530
- // packages/cli/client/reviewVerdict.ts
531
- var SEVERITIES = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];
532
- var BLOCKERS = ["CRITICAL", "HIGH"];
533
- var FIRST_LINE_RE = /^VERDICT: (APPROVE|BLOCK)(?:\s*[—–\-::]\s*.*)?$/;
534
- var VERDICT_DECL_RE = /^VERDICT\s*[::]/i;
535
- var CONFLICT_RE = /VERDICT\s*[::]\s*`{0,2}\*{0,2}(APPROVE|BLOCK)\b(?!\s*[|/])/gi;
536
- var HEADING_RE = /^(#{1,2})\s+(.*)$/;
537
- var HEADING_SEV_RE = /^[*`_\s]*(CRITICAL|HIGH|MEDIUM|LOW)\b/i;
538
- var TABLE_ROW_RE = /^\s*\|(.*)\|\s*$/;
539
- var FENCE_RE = /^\s*```/;
540
- var EMPTY_SECTION_RE = /^(?:无。?|None|0)$/i;
541
- function invalid(reason) {
542
- return { status: "INVALID", reason, exitCode: 2 };
543
- }
544
- function stripDecoration(line) {
545
- return line.replace(/^\s*(?:[-*+>]|\d+[.)])\s*/, "").replace(/[*_`]/g, "").trim();
546
- }
547
- function unwrap(line) {
548
- return line.trim().replace(/^\*\*(.*)\*\*$/, "$1").trim();
549
- }
550
- function isEmptySection(body) {
551
- const content = body.filter((line) => line.trim() !== "");
552
- return content.length === 1 && EMPTY_SECTION_RE.test(unwrap(content[0]));
553
- }
554
- function stripFrontmatter(markdown) {
555
- return markdown.replace(/^---[\r\n]+[\s\S]*?[\r\n]+---(?:\r?\n|$)/, "");
556
- }
557
- function parseStructuredReview(text) {
558
- const body = stripFrontmatter(text).trim();
559
- if (!body.startsWith("{")) return { kind: "legacy" };
560
- const nonempty2 = (v) => typeof v === "string" && v.trim().length > 0;
561
- try {
562
- const value = JSON.parse(body);
563
- const keys = ["schemaVersion", "revision", "status", "reason", "findings"];
564
- if (!value || value.schemaVersion !== 1 || Object.keys(value).some((k) => !keys.includes(k)) || !["completed", "incomplete"].includes(value.status) || !nonempty2(value.revision) || !Array.isArray(value.findings) || value.reason !== void 0 && (value.status !== "incomplete" || !nonempty2(value.reason)) || value.status === "incomplete" && !nonempty2(value.reason))
565
- return { kind: "invalid", reason: "\u7ED3\u6784\u5316\u5BA1\u67E5\u5B57\u6BB5\u65E0\u6548\u6216\u672A\u5B8C\u6210\u539F\u56E0\u7F3A\u5931" };
566
- const ids = /* @__PURE__ */ new Set();
567
- const findingKeys = ["id", "severity", "file", "line", "evidence", "impact"];
568
- for (const f of value.findings) {
569
- if (!f || Object.keys(f).some((k) => !findingKeys.includes(k)) || !nonempty2(f.id) || ids.has(f.id.trim()) || !SEVERITIES.includes(f.severity) || !nonempty2(f.file) || !Number.isSafeInteger(f.line) || f.line < 1 || !nonempty2(f.evidence) || !nonempty2(f.impact))
570
- return { kind: "invalid", reason: "\u7ED3\u6784\u5316 finding \u65E0\u6548\u6216 id \u91CD\u590D" };
571
- ids.add(f.id.trim());
572
- }
573
- return { kind: "structured", review: value };
574
- } catch {
575
- return { kind: "invalid", reason: "\u7ED3\u6784\u5316\u5BA1\u67E5 JSON \u65E0\u6548" };
576
- }
577
- }
578
- function structuredReviewVerdict(review) {
579
- return review.status === "completed" && !review.findings.some((f) => BLOCKERS.includes(f.severity)) ? "APPROVE" : "BLOCK";
580
- }
581
- function evaluateVerdict(markdown, expectedRevision) {
582
- const parsed = parseStructuredReview(markdown);
583
- if (parsed.kind === "invalid") return invalid(parsed.reason);
584
- if (parsed.kind === "structured") {
585
- if (expectedRevision !== void 0 && parsed.review.revision !== expectedRevision)
586
- return invalid("\u7ED3\u6784\u5316\u5BA1\u67E5\u7248\u672C\u4E0E\u5BBF\u4E3B\u53D7\u68C0\u7248\u672C\u4E0D\u5339\u914D");
587
- return { status: structuredReviewVerdict(parsed.review) === "APPROVE" ? "OK APPROVE" : "OK BLOCK", exitCode: 0 };
588
- }
589
- const stripped = stripFrontmatter(markdown);
590
- const lines = stripped.split(/\r?\n/);
591
- const firstIdx = lines.findIndex((line) => line.trim() !== "");
592
- if (firstIdx < 0) return invalid("\u6587\u4EF6\u4E3A\u7A7A\uFF1A\u627E\u4E0D\u5230\u9996\u884C VERDICT");
593
- const head = lines[firstIdx].trim();
594
- const matched = FIRST_LINE_RE.exec(head);
595
- if (!matched) {
596
- return invalid(
597
- `\u9996\u884C\u672A\u7CBE\u786E\u5339\u914D ^VERDICT: (APPROVE|BLOCK)$\uFF08\u5B9E\u9645\uFF1A${head.slice(0, 80)}\uFF09`
598
- );
599
- }
600
- const verdict = matched[1].toUpperCase();
601
- const suffix = head.replace(/^VERDICT\s*[::]\s*(?:APPROVE|BLOCK)\b/i, "");
602
- if (/\bVERDICT\s*[::]/i.test(suffix)) return invalid("\u9996\u884C\u540E\u7F00\u4E0D\u5F97\u5305\u542B\u7B2C\u4E8C\u4E2A VERDICT \u58F0\u660E");
603
- const declared = {};
604
- const nonEmpty = {};
605
- for (const sev of SEVERITIES) {
606
- declared[sev] = false;
607
- nonEmpty[sev] = false;
608
- }
609
- let inFence = false;
610
- for (let i = firstIdx + 1; i < lines.length; i++) {
611
- const raw = lines[i];
612
- if (FENCE_RE.test(raw)) {
613
- inFence = !inFence;
614
- continue;
615
- }
616
- if (inFence || !VERDICT_DECL_RE.test(stripDecoration(raw))) continue;
617
- for (const hit of raw.matchAll(CONFLICT_RE)) {
618
- const other = hit[1].toUpperCase();
619
- if (other !== verdict) {
620
- return invalid(
621
- `\u7B2C ${i + 1} \u884C\u51FA\u73B0\u4E0E\u9996\u884C\u77DB\u76FE\u7684\u7ED3\u8BBA\uFF08\u9996\u884C ${verdict}\uFF0C\u6B64\u5904 ${other}\uFF09\uFF1A${raw.trim().slice(0, 80)}`
622
- );
623
- }
624
- }
625
- }
626
- const record = (sev, body2) => {
627
- if (!sev) return;
628
- declared[sev] = true;
629
- if (!isEmptySection(body2)) nonEmpty[sev] = true;
630
- };
631
- let current = null;
632
- let body = [];
633
- inFence = false;
634
- for (let i = firstIdx + 1; i < lines.length; i++) {
635
- const raw = lines[i];
636
- if (FENCE_RE.test(raw)) {
637
- inFence = !inFence;
638
- continue;
639
- }
640
- if (inFence) continue;
641
- const heading = HEADING_RE.exec(raw);
642
- if (heading) {
643
- record(current, body);
644
- const sev = HEADING_SEV_RE.exec(heading[2]);
645
- current = sev ? sev[1].toUpperCase() : null;
646
- body = [];
647
- continue;
648
- }
649
- const row = TABLE_ROW_RE.exec(raw);
650
- if (row) {
651
- const cells = row[1].split("|");
652
- const severity = SEVERITIES.find(
653
- (s) => unwrap(cells[0] ?? "").toUpperCase() === s
654
- );
655
- if (!severity) continue;
656
- const rawCount = cells[1] ?? "";
657
- const count2 = unwrap(rawCount);
658
- if (!/^\d+$/.test(count2)) {
659
- return invalid(
660
- `\u8868\u683C ${severity} \u7684 Count \u5FC5\u987B\u4E3A\u7EAF\u6570\u5B57\uFF08\u5B9E\u9645\uFF1A${rawCount.trim() || "(\u7A7A)"}\uFF09`
661
- );
662
- }
663
- declared[severity] = true;
664
- if (Number(count2) !== 0) nonEmpty[severity] = true;
665
- continue;
666
- }
667
- if (current) body.push(raw);
668
- }
669
- record(current, body);
670
- const missing = BLOCKERS.filter((sev) => !declared[sev]);
671
- if (missing.length > 0) {
672
- return invalid(
673
- `\u7F3A\u5C11 ${missing.join("\u3001")} \u7EA7\u522B\u58F0\u660E\uFF08\u9700 "## CRITICAL"/"## HIGH" \u6BB5\u6216 "| CRITICAL | 0 |" \u8868\u683C\u884C\uFF09`
674
- );
675
- }
676
- const blockers = BLOCKERS.filter((sev) => nonEmpty[sev]);
677
- if (verdict === "APPROVE") {
678
- if (blockers.length > 0) {
679
- return invalid(
680
- `APPROVE \u4F46 ${blockers.join("\u3001")} \u975E\u7A7A\uFF08APPROVE \u8981\u6C42\u8FD9\u4E24\u6BB5\u5404\u53EA\u5199\u4E00\u884C\u300C\u65E0\u3002\u300D\uFF09`
681
- );
682
- }
683
- return { status: "OK APPROVE", exitCode: 0 };
684
- }
685
- if (blockers.length === 0) {
686
- return invalid(
687
- "BLOCK \u4F46 CRITICAL \u4E0E HIGH \u5747\u4E3A\u7A7A\uFF1A\u7ED3\u8BBA\u7F3A\u5C11\u963B\u65AD\u4F9D\u636E\uFF08\u82E5\u5B9E\u9645\u5E94\u653E\u884C\uFF0C\u9996\u884C\u8BF7\u5199 APPROVE\uFF09"
688
- );
689
- }
690
- return { status: "OK BLOCK", exitCode: 0 };
691
- }
692
-
693
- // packages/cli/client/taskRevisionEvidence.ts
694
- import { createHash } from "node:crypto";
695
- import { closeSync, lstatSync, openSync, readSync, readlinkSync, realpathSync } from "node:fs";
696
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
697
- var GIT_TIMEOUT_MS = 3e4;
698
- var BINARY_SNIFF_BYTES = 8e3;
699
- var HASH_CHUNK_BYTES = 1024 * 1024;
700
- var CREDENTIAL_PATTERNS = [
701
- /(^|\/)\.env(\.[^/]*)?$/i,
702
- /(^|\/)\.env[-_][^/]*$/i,
703
- /(^|\/)[^/]*\.env([-_.][^/]*)?$/i,
704
- /(^|\/)\.envrc$/i,
705
- /(^|\/)\.netrc$/i,
706
- /(^|\/)\.npmrc$/i,
707
- /(^|\/)\.pypirc$/i,
708
- /(^|\/)\.pgpass$/i,
709
- /(^|\/)\.git-credentials$/i,
710
- /(^|\/)\.htpasswd$/i,
711
- /(^|\/)\.docker\/config\.json$/i,
712
- /(^|\/)\.kube\/config$/i,
713
- /(^|\/)id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/i,
714
- /\.(pem|key|p12|pfx|jks|keystore|ppk|asc)$/i,
715
- /(^|\/)(credentials|secrets?|service[-_]?account|service[-_]?key|token|tokens|apikey|api[-_]?key)s?\.(json|ya?ml|toml)$/i,
716
- /(^|\/)\.aws\/credentials$/i,
717
- /(^|\/)\.config\/gcloud\/[^\/]*\.json$/i
718
- ];
719
- var GIT_ENV_DROP_KEYS = [
720
- "GIT_DIR",
721
- "GIT_WORK_TREE",
722
- "GIT_INDEX_FILE",
723
- "GIT_COMMON_DIR",
724
- "GIT_OBJECT_DIRECTORY",
725
- "GIT_ALTERNATE_OBJECT_DIRECTORIES",
726
- "GIT_CEILING_DIRECTORIES",
727
- "GIT_NAMESPACE",
728
- "GIT_CONFIG",
729
- "GIT_CONFIG_COUNT",
730
- "GIT_CONFIG_PARAMETERS",
731
- "GIT_CONFIG_KEY_0",
732
- "GIT_CONFIG_VALUE_0",
733
- "GIT_REPLACE_REF_BASE",
734
- "GIT_SHALLOW_FILE",
735
- "GIT_ATTR_NOSYSTEM"
736
- ];
737
- function isCredentialLikePath(repoRelativePath) {
738
- const normalized = repoRelativePath.replace(/\\/g, "/");
739
- return CREDENTIAL_PATTERNS.some((pattern) => pattern.test(normalized));
740
- }
741
- function toMessage(error) {
742
- if (error instanceof Error) return error.message;
743
- return String(error);
744
- }
745
- function errorCode(error) {
746
- const code = error?.code;
747
- return typeof code === "string" ? code : null;
748
- }
749
- function sha256(bytes) {
750
- return createHash("sha256").update(bytes).digest("hex");
751
- }
752
- function looksBinary(bytes) {
753
- const limit = Math.min(bytes.length, BINARY_SNIFF_BYTES);
754
- for (let index = 0; index < limit; index += 1) {
755
- if (bytes[index] === 0) return true;
756
- }
757
- return false;
758
- }
759
- function hashFileStreaming(absPath) {
760
- const fd = openSync(absPath, "r");
761
- try {
762
- const head = Buffer.alloc(BINARY_SNIFF_BYTES);
763
- const headRead = readSync(fd, head, 0, BINARY_SNIFF_BYTES, null);
764
- const sniff = head.subarray(0, headRead);
765
- const hash2 = createHash("sha256");
766
- hash2.update(sniff);
767
- let size = headRead;
768
- const chunk = Buffer.alloc(HASH_CHUNK_BYTES);
769
- for (; ; ) {
770
- const read = readSync(fd, chunk, 0, chunk.length, null);
771
- if (read <= 0) break;
772
- hash2.update(chunk.subarray(0, read));
773
- size += read;
774
- }
775
- return { hash: hash2.digest("hex"), binary: looksBinary(sniff), size };
776
- } finally {
777
- closeSync(fd);
778
- }
779
- }
780
- function gitEnv() {
781
- const env = {};
782
- for (const [key, value] of Object.entries(process.env)) {
783
- if (typeof value === "string") env[key] = value;
784
- }
785
- for (const key of GIT_ENV_DROP_KEYS) delete env[key];
786
- env.GIT_OPTIONAL_LOCKS = "0";
787
- env.GIT_TERMINAL_PROMPT = "0";
788
- env.GIT_CONFIG_GLOBAL = "/dev/null";
789
- env.GIT_CONFIG_SYSTEM = "/dev/null";
790
- env.LC_ALL = "C";
791
- return env;
792
- }
793
- function gitArgs(args) {
794
- return ["-c", "safe.directory=*", "-c", "diff.renames=copies", "-c", "diff.noprefix=false", ...args];
795
- }
796
- async function readPipeBytes(stream) {
797
- if (!stream) return Buffer.alloc(0);
798
- const anyStream = stream;
799
- const chunks = [];
800
- if (typeof anyStream[Symbol.asyncIterator] === "function") {
801
- for await (const chunk of anyStream) {
802
- if (typeof chunk === "string") chunks.push(Buffer.from(chunk, "utf8"));
803
- else if (chunk instanceof Uint8Array) chunks.push(Buffer.from(chunk));
804
- else chunks.push(Buffer.from(String(chunk ?? ""), "utf8"));
805
- }
806
- return Buffer.concat(chunks);
807
- }
808
- return new Promise((resolvePromise) => {
809
- let done = false;
810
- const finish = () => {
811
- if (done) return;
812
- done = true;
813
- resolvePromise(Buffer.concat(chunks));
814
- };
815
- stream.on("data", (chunk) => {
816
- chunks.push(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : Buffer.from(chunk));
817
- });
818
- stream.on("end", finish);
819
- stream.on("close", finish);
820
- stream.on("error", finish);
821
- });
822
- }
823
- async function runGit(args, cwd) {
824
- const proc = spawnProcess({
825
- cmd: ["git", ...gitArgs(args)],
826
- cwd,
827
- stdout: "pipe",
828
- stderr: "pipe",
829
- stdin: "ignore",
830
- env: gitEnv()
831
- });
832
- const [stdout, stderr, exitCode] = await Promise.all([
833
- readPipeBytes(proc.stdout),
834
- readPipeText(proc.stderr),
835
- new Promise((resolvePromise) => {
836
- const timer = setTimeout(() => {
837
- proc.kill();
838
- resolvePromise(-1);
839
- }, GIT_TIMEOUT_MS);
840
- void proc.exited.then((code) => {
841
- clearTimeout(timer);
842
- resolvePromise(code);
843
- });
844
- })
845
- ]);
846
- return { exitCode, stdout, stderr };
847
- }
848
- async function gitText(args, cwd) {
849
- const result = await runGit(args, cwd);
850
- if (result.exitCode !== 0) {
851
- throw new Error(`git ${args.join(" ")} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);
852
- }
853
- return result.stdout.toString("utf8");
854
- }
855
- function parseNameStatusZ(text) {
856
- const fields = text.split("\0");
857
- const out = [];
858
- let index = 0;
859
- while (index < fields.length) {
860
- const status = fields[index];
861
- if (!status) {
862
- index += 1;
863
- continue;
864
- }
865
- const letter = status[0];
866
- if (letter === "R" || letter === "C") {
867
- const previousPath = fields[index + 1];
868
- const path2 = fields[index + 2];
869
- if (!previousPath || !path2) break;
870
- out.push({ status: letter, path: path2, previousPath });
871
- index += 3;
872
- continue;
873
- }
874
- const path = fields[index + 1];
875
- if (!path) break;
876
- out.push({ status: letter, path });
877
- index += 2;
878
- }
879
- return out;
880
- }
881
- function parseLsTreeZ(text) {
882
- const map = /* @__PURE__ */ new Map();
883
- for (const record of text.split("\0")) {
884
- if (!record) continue;
885
- const tabIndex = record.indexOf(" ");
886
- if (tabIndex < 0) continue;
887
- const meta = record.slice(0, tabIndex).split(" ");
888
- const path = record.slice(tabIndex + 1);
889
- if (meta.length < 3 || !path) continue;
890
- map.set(path, { mode: meta[0], sha: meta[2] });
891
- }
892
- return map;
893
- }
894
- function parseLsFilesZ(text) {
895
- const map = /* @__PURE__ */ new Map();
896
- for (const record of text.split("\0")) {
897
- if (!record) continue;
898
- const tabIndex = record.indexOf(" ");
899
- if (tabIndex < 0) continue;
900
- const meta = record.slice(0, tabIndex).split(" ");
901
- const path = record.slice(tabIndex + 1);
902
- if (meta.length < 3 || !path) continue;
903
- if (meta[2] !== "0") continue;
904
- map.set(path, { mode: meta[0], sha: meta[1] });
905
- }
906
- return map;
907
- }
908
- function parseUnmergedPaths(text) {
909
- const paths = /* @__PURE__ */ new Set();
910
- for (const record of text.split("\0")) {
911
- if (!record) continue;
912
- const tabIndex = record.indexOf(" ");
913
- if (tabIndex < 0) continue;
914
- paths.add(record.slice(tabIndex + 1));
915
- }
916
- return paths;
917
- }
918
- function toPosixRelative(repoRoot, absolutePath) {
919
- const rel = relative(repoRoot, absolutePath);
920
- if (!rel || rel.startsWith("..")) return null;
921
- return rel.split("\\").join("/");
922
- }
923
- function isInsideDir(root, candidate) {
924
- if (candidate === root) return true;
925
- return candidate.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
926
- }
927
- function realpathBounded(absPath) {
928
- let current = resolve(absPath);
929
- const rest = [];
930
- for (; ; ) {
931
- try {
932
- const real = realpathSync(current);
933
- return rest.length ? join(real, ...rest) : real;
934
- } catch (error) {
935
- const code = errorCode(error);
936
- if (code !== "ENOENT" && code !== "ENOTDIR") return null;
937
- const parent = dirname(current);
938
- if (parent === current) return null;
939
- rest.unshift(basename(current));
940
- current = parent;
941
- }
942
- }
943
- }
944
- function modeType(mode) {
945
- if (!mode) return null;
946
- if (mode === "120000") return "symlink";
947
- if (mode === "160000") return "gitlink";
948
- if (mode === "040000") return "tree";
949
- if (mode.startsWith("100")) return "file";
950
- return "other";
951
- }
952
- function normalizeScopePaths(args) {
953
- const lexical = [];
954
- const real = [];
955
- for (const raw of args.taskPaths) {
956
- const trimmed = raw.trim();
957
- if (!trimmed) continue;
958
- const absolute = isAbsolute(trimmed) ? resolve(trimmed) : resolve(args.repoRoot, trimmed);
959
- const rel = relative(args.repoRoot, absolute);
960
- if (rel.startsWith("..")) {
961
- throw new Error(`task path escapes repository root: ${raw}`);
962
- }
963
- const relativePath = rel === "" ? "" : rel.split("\\").join("/");
964
- lexical.push(relativePath);
965
- const realPath = realpathBounded(absolute);
966
- real.push(realPath ?? absolute);
967
- }
968
- if (lexical.length === 0) {
969
- throw new Error("taskPaths allowlist is required: no task path given");
970
- }
971
- return { lexical, real };
972
- }
973
- function isWithinScope(repoRelativePath, scopes) {
974
- return scopes.some((scope) => {
975
- if (scope === "") return true;
976
- if (repoRelativePath === scope) return true;
977
- return repoRelativePath.startsWith(scope.endsWith("/") ? scope : `${scope}/`);
978
- });
979
- }
980
- function isWithinRealScope(realPath, scopes) {
981
- return scopes.some((scope) => isInsideDir(scope, realPath));
982
- }
983
- async function hashGitBlob(args) {
984
- const result = await runGit(["cat-file", "blob", args.sha], args.repoRoot);
985
- if (result.exitCode !== 0) {
986
- throw new Error(`git cat-file blob ${args.sha} failed: ${result.stderr.trim()}`);
987
- }
988
- return { hash: sha256(result.stdout), binary: looksBinary(result.stdout) };
989
- }
990
- function assertSafeBaseline(baseline) {
991
- if (baseline.startsWith("-")) {
992
- throw new Error(`baseline must not be parsed as a git option: ${baseline}`);
993
- }
994
- for (const char of baseline) {
995
- const code = char.codePointAt(0) ?? 0;
996
- if (code <= 32 || code === 127) {
997
- throw new Error("baseline must not contain control characters or whitespace");
998
- }
999
- }
1000
- }
1001
- function isHexSha(value) {
1002
- return /^[0-9a-f]{40}$/.test(value) || /^[0-9a-f]{64}$/.test(value);
1003
- }
1004
- function computeTaskRevisionEntriesDigest(entries, baselineSha, outcome) {
1005
- const canonicalEntries = entries.map((entry) => ({
1006
- path: entry.path,
1007
- previousPath: entry.previousPath ?? null,
1008
- changeKind: entry.changeKind,
1009
- staged: entry.staged,
1010
- unstaged: entry.unstaged,
1011
- untracked: entry.untracked,
1012
- baselineMode: entry.baselineMode,
1013
- indexMode: entry.indexMode,
1014
- worktreeMode: entry.worktreeMode,
1015
- baselineHash: entry.baselineHash,
1016
- indexHash: entry.indexHash,
1017
- worktreeHash: entry.worktreeHash,
1018
- linkTextHash: entry.linkTextHash ?? null,
1019
- symlinkTargetHash: entry.symlinkTargetHash ?? null,
1020
- binary: entry.binary,
1021
- error: entry.error ?? null,
1022
- hardLinkAlias: entry.hardLinkAlias ?? false,
1023
- credentialLike: entry.credentialLike ?? false,
1024
- outOfScopeSymlink: entry.outOfScopeSymlink ?? false,
1025
- symlinkTargetOutOfScope: entry.symlinkTargetOutOfScope ?? false,
1026
- followedSymlink: entry.followedSymlink ?? false
1027
- }));
1028
- return sha256(
1029
- JSON.stringify({
1030
- baselineSha,
1031
- complete: outcome.complete,
1032
- failures: outcome.failures.map((failure3) => ({ path: failure3.path, reason: failure3.reason })),
1033
- entries: canonicalEntries
1034
- })
1035
- );
1036
- }
1037
- async function collectTaskRevisionEvidence(options) {
1038
- const cwd = resolve(options.cwd);
1039
- const requestedBaseline = (options.baseline ?? "").trim();
1040
- if (!requestedBaseline) {
1041
- throw new Error("baseline is required: caller must pass an explicit baseline commit");
1042
- }
1043
- if (!Array.isArray(options.taskPaths) || options.taskPaths.length === 0) {
1044
- throw new Error("taskPaths allowlist is required: caller must pass the task-owned paths");
1045
- }
1046
- assertSafeBaseline(requestedBaseline);
1047
- const repoRootText = await gitText(["rev-parse", "--show-toplevel"], cwd);
1048
- const repoRoot = resolve(repoRootText.trim());
1049
- const repoRootReal = realpathSync(repoRoot);
1050
- const scopes = normalizeScopePaths({ repoRoot, repoRootReal, taskPaths: options.taskPaths });
1051
- const baselineSha = (await gitText(["rev-parse", "--verify", "--end-of-options", `${requestedBaseline}^{commit}`], cwd)).trim();
1052
- if (!isHexSha(baselineSha)) {
1053
- throw new Error(`baseline did not resolve to a commit object id: ${requestedBaseline}`);
1054
- }
1055
- const [baselineDiffText, stagedDiffText, unstagedDiffText, untrackedText, indexText, treeText, unmergedText] = await Promise.all([
1056
- gitText(["diff", "--no-ext-diff", "--no-textconv", "--find-copies-harder", "--name-status", "-z", baselineSha, "--"], cwd),
1057
- gitText(["diff", "--no-ext-diff", "--no-textconv", "--find-copies-harder", "--cached", "--name-status", "-z", baselineSha, "--"], cwd),
1058
- gitText(["diff", "--no-ext-diff", "--no-textconv", "--find-copies-harder", "--name-status", "-z"], cwd),
1059
- gitText(["ls-files", "--others", "--exclude-standard", "-z"], cwd),
1060
- gitText(["ls-files", "-s", "-z"], cwd),
1061
- gitText(["ls-tree", "-r", "-z", baselineSha], cwd),
1062
- gitText(["ls-files", "-u", "-z"], cwd)
1063
- ]);
1064
- const baselineDiff = parseNameStatusZ(baselineDiffText);
1065
- const stagedDiff = parseNameStatusZ(stagedDiffText);
1066
- const unstagedDiff = parseNameStatusZ(unstagedDiffText);
1067
- const indexEntries = parseLsFilesZ(indexText);
1068
- const baselineTree = parseLsTreeZ(treeText);
1069
- const unmergedPaths = parseUnmergedPaths(unmergedText);
1070
- const candidates = /* @__PURE__ */ new Map();
1071
- const ensure = (path) => {
1072
- const existing = candidates.get(path);
1073
- if (existing) return existing;
1074
- const created = { path, untracked: false };
1075
- candidates.set(path, created);
1076
- return created;
1077
- };
1078
- for (const item of baselineDiff) {
1079
- const candidate = ensure(item.path);
1080
- candidate.baselineStatus = item.status;
1081
- if (item.previousPath) candidate.previousPath = item.previousPath;
1082
- }
1083
- for (const item of stagedDiff) {
1084
- const candidate = ensure(item.path);
1085
- candidate.stagedStatus = item.status;
1086
- if (item.previousPath) candidate.previousPath = item.previousPath;
1087
- }
1088
- for (const item of unstagedDiff) {
1089
- const candidate = ensure(item.path);
1090
- candidate.unstagedStatus = item.status;
1091
- if (item.previousPath) candidate.previousPath = item.previousPath;
1092
- }
1093
- for (const path of untrackedText.split("\0")) {
1094
- if (!path) continue;
1095
- const candidate = ensure(path);
1096
- candidate.untracked = true;
1097
- }
1098
- for (const path of unmergedPaths) {
1099
- const candidate = ensure(path);
1100
- candidate.stagedStatus = candidate.stagedStatus ?? "U";
1101
- candidate.unstagedStatus = candidate.unstagedStatus ?? "U";
1102
- }
1103
- const failures = [];
1104
- const entries = [];
1105
- let excludedDirtyPathCount = 0;
1106
- const sortedPaths = [...candidates.keys()].sort();
1107
- for (const path of sortedPaths) {
1108
- const absolutePath = resolve(repoRoot, path);
1109
- const lexicalMatch = isWithinScope(path, scopes.lexical);
1110
- const realMatch = lexicalMatch ? true : isWithinRealScope(realpathBounded(absolutePath) ?? "", scopes.real);
1111
- if (!realMatch) {
1112
- excludedDirtyPathCount += 1;
1113
- continue;
1114
- }
1115
- const candidate = candidates.get(path);
1116
- const baselineEntry = baselineTree.get(path) ?? null;
1117
- const indexEntry = indexEntries.get(path) ?? null;
1118
- let worktreeMode = null;
1119
- let worktreeHash = null;
1120
- let worktreeBinary = false;
1121
- let linkTextHash;
1122
- let symlinkTargetHash;
1123
- let symlinkTarget;
1124
- let followedSymlink;
1125
- let outOfScopeSymlink;
1126
- let symlinkTargetOutOfScope;
1127
- let credentialTarget;
1128
- let credentialLike = false;
1129
- let hardLinkAlias;
1130
- let isGitlink = false;
1131
- let entryError;
1132
- let worktreeExists = false;
1133
- let worktreeIsSymlink = false;
1134
- let worktreeIsDirectory = false;
1135
- let worktreeLinks = 1;
1136
- try {
1137
- const stats = lstatSync(absolutePath);
1138
- worktreeExists = true;
1139
- worktreeIsSymlink = stats.isSymbolicLink();
1140
- worktreeIsDirectory = stats.isDirectory();
1141
- worktreeLinks = stats.nlink;
1142
- worktreeMode = worktreeIsSymlink ? "120000" : stats.isDirectory() ? "040000" : stats.mode & 73 ? "100755" : "100644";
1143
- } catch (error) {
1144
- const code = errorCode(error);
1145
- if (code !== "ENOENT") {
1146
- entryError = `worktree-stat-failed: ${code ?? toMessage(error)}`;
1147
- }
1148
- worktreeExists = false;
1149
- }
1150
- if (worktreeLinks > 1) hardLinkAlias = true;
1151
- if (unmergedPaths.has(path)) {
1152
- entryError = "unmerged-index-entry";
1153
- } else if (isCredentialLikePath(path)) {
1154
- credentialLike = true;
1155
- entryError = "credential-file-refused";
1156
- } else if (modeType(baselineEntry?.mode ?? null) === "gitlink" || modeType(indexEntry?.mode ?? null) === "gitlink") {
1157
- entryError = "gitlink-entry-not-hashable";
1158
- isGitlink = true;
1159
- } else if (worktreeIsDirectory) {
1160
- entryError = "worktree-directory-not-hashable";
1161
- } else if (worktreeIsSymlink) {
1162
- let linkTarget;
1163
- try {
1164
- linkTarget = readlinkSync(absolutePath);
1165
- } catch (error) {
1166
- linkTarget = void 0;
1167
- entryError = `symlink-read-failed: ${toMessage(error)}`;
1168
- }
1169
- if (linkTarget !== void 0) {
1170
- symlinkTarget = linkTarget;
1171
- const linkTextHashValue = sha256(Buffer.from(linkTarget, "utf8"));
1172
- linkTextHash = linkTextHashValue;
1173
- worktreeHash = linkTextHashValue;
1174
- const targetAbsolute = resolve(dirname(absolutePath), linkTarget);
1175
- const targetReal = realpathBounded(targetAbsolute);
1176
- if (!targetReal || !isInsideDir(repoRootReal, targetReal)) {
1177
- outOfScopeSymlink = true;
1178
- followedSymlink = false;
1179
- entryError = "out-of-scope-symlink";
1180
- } else {
1181
- const targetRelative = toPosixRelative(repoRootReal, targetReal);
1182
- if (!targetRelative || isCredentialLikePath(targetRelative)) {
1183
- credentialTarget = true;
1184
- followedSymlink = false;
1185
- entryError = "credential-target-refused";
1186
- } else if (!isWithinRealScope(targetReal, scopes.real)) {
1187
- symlinkTargetOutOfScope = true;
1188
- followedSymlink = false;
1189
- } else {
1190
- try {
1191
- const targetStats = lstatSync(targetReal);
1192
- if (targetStats.isDirectory()) {
1193
- followedSymlink = false;
1194
- entryError = "symlink-target-is-directory";
1195
- } else {
1196
- const hashed = hashFileStreaming(targetReal);
1197
- symlinkTargetHash = hashed.hash;
1198
- worktreeBinary = hashed.binary;
1199
- followedSymlink = true;
1200
- }
1201
- } catch (error) {
1202
- followedSymlink = false;
1203
- entryError = `symlink-target-unreadable: ${toMessage(error)}`;
1204
- }
1205
- }
1206
- }
1207
- }
1208
- } else if (worktreeExists) {
1209
- if (worktreeLinks > 1) {
1210
- entryError = "hard-link-alias-refused";
1211
- } else {
1212
- const realPath = realpathBounded(absolutePath);
1213
- if (!realPath || !isInsideDir(repoRootReal, realPath)) {
1214
- entryError = "out-of-repo-realpath";
1215
- } else if (!isWithinRealScope(realPath, scopes.real)) {
1216
- entryError = "out-of-scope-realpath";
1217
- } else {
1218
- try {
1219
- const hashed = hashFileStreaming(realPath);
1220
- worktreeHash = hashed.hash;
1221
- worktreeBinary = hashed.binary;
1222
- } catch (error) {
1223
- entryError = `worktree-unreadable: ${toMessage(error)}`;
1224
- }
1225
- }
1226
- }
1227
- }
1228
- const skipBlobRead = credentialLike || isGitlink;
1229
- const readBlob = async (sha3) => {
1230
- try {
1231
- const hashed = await hashGitBlob({ repoRoot, sha: sha3 });
1232
- return { hash: hashed.hash, binary: hashed.binary };
1233
- } catch (error) {
1234
- return { error };
1235
- }
1236
- };
1237
- const [baselineBlob, indexBlob] = await Promise.all([
1238
- baselineEntry && !skipBlobRead ? readBlob(baselineEntry.sha) : Promise.resolve(null),
1239
- indexEntry && !skipBlobRead ? readBlob(indexEntry.sha) : Promise.resolve(null)
1240
- ]);
1241
- let baselineHash = null;
1242
- let baselineBinary = false;
1243
- if (baselineBlob) {
1244
- if (baselineBlob.error !== void 0) {
1245
- entryError = entryError ?? `baseline-blob-unreadable: ${toMessage(baselineBlob.error)}`;
1246
- } else {
1247
- baselineHash = baselineBlob.hash ?? null;
1248
- baselineBinary = baselineBlob.binary ?? false;
1249
- }
1250
- }
1251
- let indexHash = null;
1252
- let indexBinary = false;
1253
- if (indexBlob) {
1254
- if (indexBlob.error !== void 0) {
1255
- entryError = entryError ?? `index-blob-unreadable: ${toMessage(indexBlob.error)}`;
1256
- } else {
1257
- indexHash = indexBlob.hash ?? null;
1258
- indexBinary = indexBlob.binary ?? false;
1259
- }
1260
- }
1261
- const staged = candidate.stagedStatus !== void 0;
1262
- const unstaged = candidate.unstagedStatus !== void 0 || candidate.untracked;
1263
- const baselineType = modeType(baselineEntry?.mode ?? null);
1264
- const worktreeType = modeType(worktreeMode);
1265
- let changeKind = "modified";
1266
- if (candidate.untracked && !baselineEntry && !indexEntry) {
1267
- changeKind = "untracked";
1268
- } else if (baselineEntry && !worktreeExists && worktreeType !== "tree") {
1269
- changeKind = "deleted";
1270
- } else if (candidate.previousPath) {
1271
- const renameStatus = candidate.stagedStatus ?? candidate.unstagedStatus ?? candidate.baselineStatus ?? "";
1272
- changeKind = renameStatus.startsWith("C") ? "copied" : "renamed";
1273
- } else if (!baselineEntry) {
1274
- changeKind = "added";
1275
- } else if (baselineType && worktreeType && baselineType !== worktreeType) {
1276
- changeKind = "type-changed";
1277
- } else if (!staged && !unstaged) {
1278
- changeKind = "unchanged";
1279
- }
1280
- const entry = {
1281
- path,
1282
- ...candidate.previousPath ? { previousPath: candidate.previousPath } : {},
1283
- changeKind,
1284
- staged,
1285
- unstaged,
1286
- untracked: candidate.untracked,
1287
- baselineMode: baselineEntry?.mode ?? null,
1288
- indexMode: indexEntry?.mode ?? null,
1289
- worktreeMode,
1290
- baselineHash,
1291
- indexHash,
1292
- worktreeHash,
1293
- binary: worktreeBinary || indexBinary || baselineBinary,
1294
- ...linkTextHash !== void 0 ? { linkTextHash } : {},
1295
- ...symlinkTargetHash !== void 0 ? { symlinkTargetHash } : {},
1296
- ...symlinkTarget !== void 0 ? { symlinkTarget } : {},
1297
- ...followedSymlink !== void 0 ? { followedSymlink } : {},
1298
- ...outOfScopeSymlink !== void 0 ? { outOfScopeSymlink } : {},
1299
- ...symlinkTargetOutOfScope !== void 0 ? { symlinkTargetOutOfScope } : {},
1300
- ...credentialTarget !== void 0 ? { credentialTarget } : {},
1301
- ...credentialLike ? { credentialLike: true } : {},
1302
- ...hardLinkAlias ? { hardLinkAlias: true } : {},
1303
- ...entryError ? { error: entryError } : {}
1304
- };
1305
- entries.push(entry);
1306
- if (entryError) {
1307
- failures.push({ path, reason: entryError });
1308
- }
1309
- }
1310
- const complete = failures.length === 0;
1311
- const entriesDigest = computeTaskRevisionEntriesDigest(entries, baselineSha, {
1312
- complete,
1313
- failures
1314
- });
1315
- return {
1316
- cwd,
1317
- repoRoot,
1318
- baseline: { requested: requestedBaseline, resolvedSha: baselineSha },
1319
- collectedAt: (/* @__PURE__ */ new Date()).toISOString(),
1320
- complete,
1321
- entries,
1322
- failures,
1323
- excludedDirtyPathCount,
1324
- entriesDigest
1325
- };
1326
- }
1327
-
1328
- // packages/cli/client/taskProgressEvidence.ts
1329
- import { execFile } from "node:child_process";
1330
- import { promisify } from "node:util";
1331
- import { createHash as createHash2 } from "node:crypto";
1332
-
1333
- // packages/cli/client/taskReviewEvidence.ts
1334
- import { join as join2, resolve as resolve2 } from "node:path";
1335
- function sameTaskScope(a, b) {
1336
- return a.taskId === b.taskId && a.dialogId === b.dialogId && resolve2(a.workspace) === resolve2(b.workspace);
1337
- }
1338
-
1339
- // packages/cli/client/taskProgressEvidence.ts
1340
- var exec = promisify(execFile);
1341
- var sha = (b) => createHash2("sha256").update(b).digest("hex");
1342
- function taskContentRevision(evidence) {
1343
- return sha(Buffer.from(JSON.stringify({
1344
- baseline: evidence.baseline.resolvedSha,
1345
- entries: evidence.entries.map((e) => ({ path: e.path, baselineMode: e.baselineMode, baselineHash: e.baselineHash, mode: e.worktreeMode, hash: e.worktreeHash })).sort((a, b) => a.path.localeCompare(b.path))
1346
- })));
1347
- }
1348
-
1349
- // packages/cli/client/hostTaskEvents.ts
1350
- import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
1351
- import { homedir } from "node:os";
1352
- import { join as join3, resolve as resolve3 } from "node:path";
1353
- import { createHash as createHash3 } from "node:crypto";
1354
- var nonempty = (v) => typeof v === "string" && v.trim().length > 0;
1355
- function scopeOf(ref) {
1356
- if (!nonempty(ref.taskId) || !nonempty(ref.workspace) || !nonempty(ref.dialogId)) throw new Error("Invalid host task scope");
1357
- return { taskId: ref.taskId, workspace: resolve3(ref.workspace), dialogId: ref.dialogId, ...ref.taskInstanceId ? { taskInstanceId: ref.taskInstanceId } : {} };
1358
- }
1359
- function same(a, b) {
1360
- return a.taskId === b.taskId && a.workspace === b.workspace && a.dialogId === b.dialogId && a.taskInstanceId === b.taskInstanceId;
1361
- }
1362
- function validChange(c) {
1363
- if (!c || typeof c !== "object") return false;
1364
- switch (c.type) {
1365
- case "admitted":
1366
- return ["owner", "implementation-leaf"].includes(c.role);
1367
- case "role":
1368
- return ["owner", "implementation-leaf"].includes(c.value);
1369
- case "authorization":
1370
- return ["active", "paused", "revoked"].includes(c.value);
1371
- case "acceptance":
1372
- return ["pending", "waived", "accepted", "unknown"].includes(c.value);
1373
- case "progress":
1374
- return !!c.value && ["complete", "incomplete", "unknown"].includes(c.value.implementation) && ["changed", "unchanged", "unknown"].includes(c.value.changes);
1375
- default:
1376
- return false;
1377
- }
1378
- }
1379
- function reduce(events, scope) {
1380
- let contract;
1381
- let taskStart;
1382
- for (let i = 0; i < events.length; i++) {
1383
- const e = events[i];
1384
- if (!e || !e.scope || !e.source) return { authorization: "unknown", reason: "invalid" };
1385
- if (!same(e.scope, scope)) return { authorization: "unknown", reason: "scope_mismatch" };
1386
- if (e.sequence !== i + 1 || !nonempty(e.source?.actorId) || !nonempty(e.source?.sourceId) || !["user-control", "trusted-host"].includes(e.source.kind) || !validChange(e.change)) return { authorization: "unknown", reason: "invalid" };
1387
- const c = e.change;
1388
- if (c.type === "admitted") {
1389
- if (contract) return { authorization: "unknown", reason: "invalid" };
1390
- if (e.source.kind === "user-control" && c.role !== "owner") return { authorization: "unknown", reason: "invalid" };
1391
- taskStart = c.taskStart;
1392
- if (taskStart && (e.source.kind !== "trusted-host" || taskStart.taskInstanceId !== scope.taskInstanceId || taskStart.userId !== e.source.actorId || !nonempty(taskStart.userMessageId) || !/^[a-f0-9]{64}$/.test(taskStart.contentSha256))) return { authorization: "unknown", reason: "invalid" };
1393
- contract = { taskId: scope.taskId, role: c.role, authorization: "active", acceptance: "unknown", implementation: "unknown", changes: "unknown" };
1394
- } else {
1395
- if (!contract) return { authorization: "unknown", reason: "invalid" };
1396
- if (contract.authorization === "revoked") return { authorization: "unknown", reason: "invalid" };
1397
- if (c.type === "progress") {
1398
- if (e.source.kind !== "trusted-host") return { authorization: "unknown", reason: "invalid" };
1399
- const { implementation, changes, revision, authorInstanceId, review, commit, localMerge } = c.value;
1400
- contract = { ...contract, implementation, changes, revision, authorInstanceId, review, commit, localMerge };
1401
- } else if (c.type === "authorization") contract.authorization = c.value;
1402
- else if (c.type === "acceptance") contract.acceptance = c.value;
1403
- else if (c.type === "role") {
1404
- if (e.source.kind !== "trusted-host") return { authorization: "unknown", reason: "invalid" };
1405
- contract.role = c.value;
1406
- }
1407
- }
1408
- }
1409
- return contract ? { authorization: contract.authorization, sequence: events.length, contract, ...taskStart ? { taskStart } : {} } : { authorization: "unknown", reason: "missing" };
1410
- }
1411
- function directory(root, ref) {
1412
- return join3(root, createHash3("sha256").update(JSON.stringify(ref)).digest("hex"));
1413
- }
1414
- function hostTaskEventsRoot(env) {
1415
- return join3(env.NOLO_HOME || join3(homedir(), ".nolo"), "host-task-events");
1416
- }
1417
- function readHostTask(root, reference) {
1418
- try {
1419
- const scope = scopeOf(reference);
1420
- const dir2 = directory(root, scope);
1421
- let names;
1422
- try {
1423
- names = readdirSync(dir2);
1424
- } catch (e) {
1425
- if (e.code === "ENOENT") return { authorization: "unknown", reason: "missing" };
1426
- throw e;
1427
- }
1428
- if (names.some((n) => !/^\d{12}\.json$/.test(n))) return { authorization: "unknown", reason: "invalid" };
1429
- return reduce(names.sort().map((n) => JSON.parse(readFileSync(join3(dir2, n), "utf8"))), scope);
1430
- } catch {
1431
- return { authorization: "unknown", reason: "invalid" };
1432
- }
1433
- }
1434
- function createHostTaskController(root, source) {
1435
- if (!nonempty(source.actorId) || !nonempty(source.sourceId) || !["user-control", "trusted-host"].includes(source.kind)) throw new Error("Invalid host source");
1436
- const boundSource = { ...source };
1437
- if (root.trim().length === 0) throw new Error("Invalid host event store root");
1438
- return {
1439
- append(reference, expectedSequence, change) {
1440
- const scope = scopeOf(reference);
1441
- const state = readHostTask(root, scope);
1442
- if (!Number.isSafeInteger(expectedSequence) || expectedSequence < 0 || (state.authorization === "unknown" ? state.reason !== "missing" || expectedSequence !== 0 : state.sequence !== expectedSequence)) throw new Error("Host task sequence conflict or invalid history");
1443
- const dir2 = directory(root, scope);
1444
- const previous = expectedSequence ? readdirSync(dir2).sort().map((n) => JSON.parse(readFileSync(join3(dir2, n), "utf8"))) : [];
1445
- const event = { scope, sequence: expectedSequence + 1, source: boundSource, change };
1446
- const next = reduce([...previous, event], scope);
1447
- if (next.authorization === "unknown") throw new Error("Invalid host task transition");
1448
- mkdirSync(dir2, { recursive: true, mode: 448 });
1449
- writeFileSync(join3(dir2, `${String(event.sequence).padStart(12, "0")}.json`), JSON.stringify(event), { flag: "wx", mode: 384 });
1450
- return next;
1451
- }
1452
- };
1453
- }
1454
- function unknownTaskCompletion(taskId) {
1455
- return { taskId, status: "blocked", reasons: ["invalid_contract"] };
1456
- }
1457
-
1458
- // packages/cli/client/hostReviewDispatch.ts
1459
- var context = new AsyncLocalStorage();
1460
- var currentHostReviewDispatch = () => context.getStore();
1461
- function withHostReviewDispatch(value, action) {
1462
- return context.run(value ? structuredClone(value) : void 0, action);
1463
- }
1464
- function matchesHostReviewDispatch(c, call, args) {
1465
- return !!c?.target && call.id === c.toolCallId && args.agentKey === c.target.agentKey && args.task === c.target.task;
1466
- }
1467
- function consumeHostReviewDispatch(c, env) {
1468
- if (!safe(c.dispatchId) || !c.toolCallId || !c.target.agentKey || !c.target.task) throw new Error("Invalid review dispatch identity");
1469
- mkdirSync2(dir(env), { recursive: true, mode: 448 });
1470
- writeFileSync2(join4(dir(env), `dispatch-${c.dispatchId}.consumed`), JSON.stringify(c), { flag: "wx", mode: 384 });
1471
- }
1472
- async function settleHostReviewsForScope(scope, env, accept) {
1473
- let names;
1474
- try {
1475
- names = readdirSync2(dir(env));
1476
- } catch {
1477
- return;
1478
- }
1479
- for (const name of names.filter((n) => n.endsWith(".json") && !n.startsWith("author-"))) {
1480
- try {
1481
- const intent = JSON.parse(readFileSync2(join4(dir(env), name), "utf8"));
1482
- if (intent.scope.taskId === scope.taskId && intent.scope.dialogId === scope.dialogId && resolve4(intent.scope.workspace) === resolve4(scope.workspace)) {
1483
- await settleHostReviewDispatch(intent.reviewerRunId, env, accept);
1484
- }
1485
- } catch {
1486
- }
1487
- }
1488
- }
1489
- var safe = (id) => /^[A-Za-z0-9._-]{1,128}$/.test(id);
1490
- function dir(env) {
1491
- const path = join4(resolveRunsDir(env), "host-review-dispatch");
1492
- try {
1493
- if (lstatSync2(path).isSymbolicLink() || realpathSync2(path) !== resolve4(path)) throw new Error("Unsafe review dispatch directory");
1494
- } catch (error) {
1495
- if (error.code !== "ENOENT") throw error;
1496
- }
1497
- return path;
1498
- }
1499
- function file(env, id) {
1500
- if (!safe(id)) throw new Error("Invalid review run id");
1501
- return join4(dir(env), `${id}.json`);
1502
- }
1503
- function createHostAuthorExecution(env, scope, turnId) {
1504
- const task = readHostTask(hostTaskEventsRoot(env), scope);
1505
- const executionId = task.authorization !== "unknown" && task.contract.authorInstanceId || randomUUID();
1506
- if (!safe(executionId)) throw new Error("Invalid author execution identity");
1507
- mkdirSync2(dir(env), { recursive: true, mode: 448 });
1508
- try {
1509
- writeFileSync2(join4(dir(env), `author-${executionId}.json`), JSON.stringify({ executionId, scope, turnId }), { flag: "wx", mode: 384 });
1510
- } catch (error) {
1511
- const existing = JSON.parse(readFileSync2(join4(dir(env), `author-${executionId}.json`), "utf8"));
1512
- if (existing.executionId !== executionId || JSON.stringify(existing.scope) !== JSON.stringify(scope)) throw error;
1513
- }
1514
- return executionId;
1515
- }
1516
- async function validateHostReviewDispatch(c, env, cwd) {
1517
- if (resolve4(c.scope.workspace) !== resolve4(cwd) || !safe(c.authorExecutionId) || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(c.baseline) || !c.taskPaths.length) throw new Error("Invalid trusted review context");
1518
- const task = readHostTask(hostTaskEventsRoot(env), c.scope);
1519
- if (task.authorization !== "active") throw new Error("Review task is not active");
1520
- if (task.contract.authorInstanceId && task.contract.authorInstanceId !== c.authorExecutionId) throw new Error("Author execution identity mismatch");
1521
- const author = JSON.parse(readFileSync2(join4(dir(env), `author-${c.authorExecutionId}.json`), "utf8"));
1522
- if (author.executionId !== c.authorExecutionId || JSON.stringify(author.scope) !== JSON.stringify(c.scope) || !author.turnId) throw new Error("Author turn binding missing");
1523
- const revision = await collectTaskRevisionEvidence({ cwd, baseline: c.baseline, taskPaths: c.taskPaths });
1524
- if (!revision.complete || taskContentRevision(revision) !== c.revision) throw new Error("Review revision changed or incomplete");
1525
- }
1526
- async function bindHostReviewRun(c, runId, env) {
1527
- if (runId === c.authorExecutionId) throw new Error("Self review rejected");
1528
- await validateHostReviewDispatch(c, env, c.scope.workspace);
1529
- mkdirSync2(dir(env), { recursive: true, mode: 448 });
1530
- const consumed = JSON.parse(readFileSync2(join4(dir(env), `dispatch-${c.dispatchId}.consumed`), "utf8"));
1531
- if (JSON.stringify(consumed) !== JSON.stringify(c)) throw new Error("Review dispatch not consumed by this invocation");
1532
- writeFileSync2(join4(dir(env), `dispatch-${c.dispatchId}.bound`), runId, { flag: "wx", mode: 384 });
1533
- const intent = { ...structuredClone(c), reviewerRunId: runId };
1534
- writeFileSync2(file(env, runId), JSON.stringify(intent), { flag: "wx", mode: 384 });
1535
- }
1536
- async function settleHostReviewDispatch(runId, env, accept, options) {
1537
- try {
1538
- const intentPath = file(env, runId);
1539
- if (lstatSync2(intentPath).isSymbolicLink() || realpathSync2(intentPath) !== resolve4(intentPath)) throw new Error("Unsafe intent path");
1540
- const intent = JSON.parse(readFileSync2(intentPath, "utf8"));
1541
- if (intent.reviewerRunId !== runId || intent.authorExecutionId === runId || readFileSync2(join4(dir(env), `dispatch-${intent.dispatchId}.bound`), "utf8") !== runId) throw new Error("Review identity mismatch");
1542
- await validateHostReviewDispatch(intent, env, intent.scope.workspace);
1543
- const storedDecision = readDecisionRecord(`${intentPath}.decision`);
1544
- if (!storedDecision) throw new Error("review_decision_missing");
1545
- if (storedDecision.state !== "committed" && !(storedDecision.state === "pending" && options?.allowPending)) throw new Error(`review_decision_${storedDecision.state === "pending" ? "pending" : "failed"}`);
1546
- if (storedDecision.action !== "continue") throw new Error("review_decision_does_not_continue");
1547
- if (storedDecision.dispatchId !== intent.dispatchId || storedDecision.runId !== runId || storedDecision.revision !== intent.revision) throw new Error("review_decision_binding_mismatch");
1548
- const run = readRunRecord(runId, { env });
1549
- const expected = join4(resolveRunsDir(env), `${runId}.result.md`);
1550
- if (!run || run.runId !== runId || run.status !== "done" || run.exitCode !== 0 || !run.resultFile || resolve4(run.resultFile) !== resolve4(expected)) throw new Error("Review not a successful canonical terminal");
1551
- if (lstatSync2(expected).isSymbolicLink() || !lstatSync2(expected).isFile() || lstatSync2(expected).size > 2 * 1024 * 1024 || realpathSync2(expected) !== resolve4(expected)) throw new Error("Unsafe result path");
1552
- const bytes = readFileSync2(expected);
1553
- const digest2 = createHash4("sha256").update(bytes).digest("hex");
1554
- if (storedDecision.resultSha256 !== digest2) throw new Error("review_decision_result_changed");
1555
- if (intent.resultSha256 && intent.resultSha256 !== digest2) throw new Error("Review result changed");
1556
- const text = stripResultFrontMatter(bytes.toString("utf8"));
1557
- const verdict = evaluateVerdict(text, intent.revision);
1558
- if (verdict.status !== "OK APPROVE") throw new Error("Review is not strict APPROVE");
1559
- const summary = summarizeReview(text);
1560
- await validateHostReviewDispatch(intent, env, intent.scope.workspace);
1561
- const pin = `${intentPath}.result-sha256`;
1562
- try {
1563
- writeFileSync2(pin, digest2, { flag: "wx", mode: 384 });
1564
- } catch {
1565
- if (readFileSync2(pin, "utf8") !== digest2) throw new Error("Review result changed");
1566
- }
1567
- const acknowledgement = `${intentPath}.content-accepted`;
1568
- let accepted = false;
1569
- try {
1570
- accepted = readFileSync2(acknowledgement, "utf8") === digest2;
1571
- } catch {
1572
- }
1573
- if (!accepted) {
1574
- if (!accept || !await accept({ runId, dispatchId: intent.dispatchId, revision: intent.revision, sha256: digest2, text })) throw new Error("Review content not acknowledged by host orchestration");
1575
- await validateHostReviewDispatch(intent, env, intent.scope.workspace);
1576
- if (createHash4("sha256").update(readFileSync2(expected)).digest("hex") !== digest2) throw new Error("Review result changed during acknowledgement");
1577
- try {
1578
- writeFileSync2(acknowledgement, digest2, { flag: "wx", mode: 384 });
1579
- } catch {
1580
- if (readFileSync2(acknowledgement, "utf8") !== digest2) throw new Error("Review acknowledgement mismatch");
1581
- }
1582
- }
1583
- await validateHostReviewDispatch(intent, env, intent.scope.workspace);
1584
- if (options?.allowPending) return { status: "validated" };
1585
- const committed = readDecisionRecord(`${intentPath}.decision`);
1586
- if (!committed || committed.state !== "committed" || committed.action !== "continue" || committed.resultSha256 !== digest2 || committed.dispatchId !== intent.dispatchId || committed.runId !== runId || committed.revision !== intent.revision) throw new Error("review_decision_not_committed");
1587
- const latest = readHostTask(hostTaskEventsRoot(env), intent.scope);
1588
- if (latest.authorization !== "active") throw new Error("Task no longer active");
1589
- if (latest.contract.review?.evidenceRef === `run:${runId}:sha256:${digest2}` && latest.contract.review.revision === intent.revision) return { status: "verified" };
1590
- createHostTaskController(hostTaskEventsRoot(env), { kind: "trusted-host", actorId: "review-settlement", sourceId: intent.dispatchId }).append(intent.scope, latest.sequence, {
1591
- type: "progress",
1592
- value: {
1593
- ...preservedProgress(latest.contract, intent.revision),
1594
- revision: intent.revision,
1595
- authorInstanceId: latest.contract.revision === intent.revision ? latest.contract.authorInstanceId ?? intent.authorExecutionId : intent.authorExecutionId,
1596
- review: { revision: intent.revision, reviewerInstanceId: runId, verdict: summary.verdict, hasCriticalOrHigh: summary.counts.critical > 0 || summary.counts.high > 0, evidenceRef: `run:${runId}:sha256:${digest2}` }
1597
- }
1598
- });
1599
- return { status: "verified" };
1600
- } catch (e) {
1601
- try {
1602
- const intent = JSON.parse(readFileSync2(file(env, runId), "utf8"));
1603
- const latest = readHostTask(hostTaskEventsRoot(env), intent.scope);
1604
- if (latest.authorization === "active" && latest.contract.review?.reviewerInstanceId === runId) {
1605
- const current = await collectTaskRevisionEvidence({ cwd: intent.scope.workspace, baseline: intent.baseline, taskPaths: intent.taskPaths });
1606
- createHostTaskController(hostTaskEventsRoot(env), { kind: "trusted-host", actorId: "review-settlement", sourceId: `invalidate-${intent.dispatchId}` }).append(intent.scope, latest.sequence, {
1607
- type: "progress",
1608
- value: { ...preservedProgress(latest.contract, current.complete ? taskContentRevision(current) : ""), review: void 0 }
1609
- });
1610
- }
1611
- } catch {
1612
- }
1613
- return { status: "unknown", reason: e instanceof Error ? e.message : "host binding missing" };
1614
- }
1615
- }
1616
- function preservedProgress(contract, revision) {
1617
- if (contract.revision !== revision) return { implementation: "unknown", changes: "unknown", revision: void 0, authorInstanceId: void 0, review: void 0, commit: void 0, localMerge: void 0 };
1618
- const { implementation, changes, authorInstanceId, review, commit, localMerge } = contract;
1619
- return { implementation, changes, revision, authorInstanceId, review, commit, localMerge };
1620
- }
1621
- async function recordHostTaskReviewDecision(scope, decision, env) {
1622
- const intentPath = file(env, decision.runId);
1623
- if (lstatSync2(intentPath).isSymbolicLink() || realpathSync2(intentPath) !== resolve4(intentPath)) throw new Error("Unsafe intent path");
1624
- const intent = JSON.parse(readFileSync2(intentPath, "utf8"));
1625
- if (JSON.stringify(intent.scope) !== JSON.stringify(scope) || intent.dispatchId !== decision.dispatchId || intent.reviewerRunId !== decision.runId || intent.revision !== decision.revision || readFileSync2(join4(dir(env), `dispatch-${intent.dispatchId}.bound`), "utf8") !== decision.runId) throw new Error("review_decision_binding_mismatch");
1626
- const run = readRunRecord(decision.runId, { env });
1627
- const resultPath = join4(resolveRunsDir(env), `${decision.runId}.result.md`);
1628
- if (!run || run.status !== "done" || run.exitCode !== 0 || resolve4(run.resultFile ?? "") !== resolve4(resultPath) || lstatSync2(resultPath).isSymbolicLink() || realpathSync2(resultPath) !== resolve4(resultPath) || !lstatSync2(resultPath).isFile() || lstatSync2(resultPath).size > 2 * 1024 * 1024) throw new Error("review_decision_result_unavailable");
1629
- const bytes = readFileSync2(resultPath);
1630
- if (createHash4("sha256").update(bytes).digest("hex") !== decision.resultSha256) throw new Error("review_decision_result_changed");
1631
- const decisionPath = `${intentPath}.decision`;
1632
- const auditPath = `${decisionPath}.audit`;
1633
- const pending = { ...structuredClone(decision), state: "pending" };
1634
- try {
1635
- writeFileSync2(decisionPath, JSON.stringify(pending), { flag: "wx", mode: 384 });
1636
- } catch (error) {
1637
- appendFileSync(auditPath, `${JSON.stringify({ ...pending, state: "failed", reason: "review_decision_already_claimed", at: (/* @__PURE__ */ new Date()).toISOString() })}
1638
- `, { mode: 384 });
1639
- throw new Error("review_decision_already_claimed", { cause: error });
1640
- }
1641
- try {
1642
- appendFileSync(auditPath, `${JSON.stringify(pending)}
1643
- `, { mode: 384 });
1644
- await validateHostReviewDispatch(intent, env, scope.workspace);
1645
- const text = stripResultFrontMatter(bytes.toString("utf8"));
1646
- const summary = summarizeReview(text);
1647
- pending.counts = summary.counts;
1648
- if (decision.action === "continue") {
1649
- if (evaluateVerdict(text, intent.revision).status !== "OK APPROVE") throw new Error("review_decision_not_approved");
1650
- if (decision.findings.some((f) => f.disposition === "fix")) throw new Error("review_decision_unresolved_findings");
1651
- assertFindingCoverage(decision.findings, summary);
1652
- }
1653
- if (decision.action === "continue") {
1654
- const validated = await settleHostReviewDispatch(decision.runId, env, (review) => Promise.resolve(review.dispatchId === decision.dispatchId && review.revision === decision.revision && review.sha256 === decision.resultSha256), { allowPending: true });
1655
- if (validated.status !== "validated") throw new Error(validated.reason ?? "review_decision_not_approved");
1656
- } else {
1657
- const latest = readHostTask(hostTaskEventsRoot(env), scope);
1658
- if (latest.authorization === "unknown") throw new Error("review_decision_task_unresolved");
1659
- createHostTaskController(hostTaskEventsRoot(env), { kind: "trusted-host", actorId: "review-decision", sourceId: intent.dispatchId }).append(scope, latest.sequence, {
1660
- type: "progress",
1661
- value: { ...preservedProgress(latest.contract, intent.revision), review: void 0 }
1662
- });
1663
- }
1664
- writeDecisionRecord(decisionPath, auditPath, { ...pending, state: "committed" }, "committed");
1665
- if (decision.action === "continue") {
1666
- const published = await settleHostReviewDispatch(decision.runId, env);
1667
- if (published.status !== "verified") throw new Error(published.reason ?? "review_decision_not_published");
1668
- }
1669
- } catch (error) {
1670
- writeDecisionRecord(decisionPath, auditPath, { ...pending, state: "failed", reason: error instanceof Error ? error.message : String(error) }, "failed");
1671
- await settleHostReviewDispatch(decision.runId, env);
1672
- throw error;
1673
- }
1674
- }
1675
- var FULL_TEXT_COVERAGE_ID = "full-text";
1676
- var SEVERITY_HEADING_RE = /^#{1,2}\s*[*`_\s]*(CRITICAL|HIGH|MEDIUM|LOW)\b/i;
1677
- var ANY_HEADING_RE = /^#{1,6}\s/;
1678
- var EMPTY_DECLARATION_RE = /^(?:无。?|None|0)$/i;
1679
- var BULLET_RE = /^[-*+]\s+(.*)$/;
1680
- function summarizeReview(text) {
1681
- const parsed = parseStructuredReview(text);
1682
- if (parsed.kind === "invalid") throw new Error(parsed.reason);
1683
- if (parsed.kind === "structured") {
1684
- const counts2 = { critical: 0, high: 0, medium: 0, low: 0 };
1685
- for (const finding of parsed.review.findings)
1686
- counts2[finding.severity.toLowerCase()]++;
1687
- return {
1688
- verdict: structuredReviewVerdict(parsed.review),
1689
- counts: counts2,
1690
- findingIds: parsed.review.findings.map((f) => f.id),
1691
- unlabelled: 0
1692
- };
1693
- }
1694
- const counts = { critical: 0, high: 0, medium: 0, low: 0 };
1695
- const findingIds = [];
1696
- let unlabelled = 0;
1697
- let section = null;
1698
- let declared = null;
1699
- for (const raw of text.split("\n")) {
1700
- const line = raw.trim();
1701
- if (!line) continue;
1702
- const verdict2 = line.match(/^VERDICT\s*[::]\s*(APPROVE|BLOCK)\b/);
1703
- if (verdict2) {
1704
- declared = verdict2[1];
1705
- continue;
1706
- }
1707
- const severity = line.match(SEVERITY_HEADING_RE);
1708
- if (severity) {
1709
- section = severity[1].toLowerCase();
1710
- continue;
1711
- }
1712
- if (ANY_HEADING_RE.test(line)) {
1713
- section = null;
1714
- continue;
1715
- }
1716
- if (!section) continue;
1717
- if (line.startsWith("|") || line.startsWith("```") || /^[-=]{3,}$/.test(line)) continue;
1718
- if (EMPTY_DECLARATION_RE.test(line.replace(/[*`_]/g, "").trim())) continue;
1719
- const bullet = line.match(BULLET_RE);
1720
- const body = bullet ? bullet[1] : line;
1721
- counts[section]++;
1722
- const id = bullet ? extractFindingId(body) : null;
1723
- if (id) findingIds.push(id);
1724
- else unlabelled++;
1725
- }
1726
- const verdict = declared === "APPROVE" ? "APPROVE" : declared === "BLOCK" ? "BLOCK" : "WARNING";
1727
- return { verdict, counts, findingIds, unlabelled };
1728
- }
1729
- var SEVERITY_LABEL_RE = /^(?:CRITICAL|HIGH|MEDIUM|LOW)$/i;
1730
- var LABELLED_FILE_LINE_RE = /(?:^|[\s*`])File\*{0,2}\s*[::]\s*`?([^\s`*:]+?\.[A-Za-z0-9]{1,8}):(\d+(?:-\d+)?)`?(?=$|[\s,;.)])/;
1731
- function extractFindingId(body) {
1732
- const bracket = body.match(/^\[([^\]]{1,64})\]/);
1733
- if (bracket && !SEVERITY_LABEL_RE.test(bracket[1].trim())) return bracket[1].trim();
1734
- const prefixed = body.match(/\b((?:CRITICAL|HIGH|MEDIUM|LOW|F)-[A-Za-z0-9._-]{1,32})\b/i);
1735
- if (prefixed) return prefixed[1];
1736
- const labelled = body.match(LABELLED_FILE_LINE_RE);
1737
- if (labelled) return `${labelled[1]}:${labelled[2]}`;
1738
- const reference = body.match(/`([^`\n]+?):(\d+(?:-\d+)?)`/);
1739
- if (reference) return `${reference[1]}:${reference[2]}`;
1740
- return null;
1741
- }
1742
- function normalizeFindingId(raw) {
1743
- let id = raw.trim();
1744
- id = id.replace(/^[`"'\u201c\u201d\u2018\u2019]+|[`"'\u201c\u201d\u2018\u2019]+$/g, "").trim();
1745
- id = id.replace(/^\[|\]$/g, "").trim();
1746
- id = id.replace(/\s+/g, " ");
1747
- id = id.replace(/[.,;]+$/, "").trim();
1748
- if (/^(?:critical|high|medium|low|f)-/i.test(id)) id = id.toLowerCase();
1749
- return id;
1750
- }
1751
- function assertFindingCoverage(findings, summary) {
1752
- const declared = findings.map((f) => normalizeFindingId(f.id)).filter((id) => id.length > 0);
1753
- const uncovered = summary.findingIds.filter((id) => !declared.includes(normalizeFindingId(id)));
1754
- if (uncovered.length > 0) throw new Error(`review_decision_findings_incomplete: ${uncovered.join(", ")}`);
1755
- if (summary.unlabelled > 0 && !declared.includes(FULL_TEXT_COVERAGE_ID)) throw new Error("review_decision_findings_incomplete: full-text disposition required");
1756
- }
1757
- function readDecisionRecord(path) {
1758
- try {
1759
- return JSON.parse(readFileSync2(path, "utf8"));
1760
- } catch {
1761
- return null;
1762
- }
1763
- }
1764
- function writeDecisionRecord(decisionPath, auditPath, record, transition) {
1765
- const tmp = `${decisionPath}.${randomUUID()}.tmp`;
1766
- writeFileSync2(tmp, JSON.stringify(record), { mode: 384 });
1767
- renameSync(tmp, decisionPath);
1768
- appendFileSync(auditPath, `${JSON.stringify({ state: transition, action: record.action, reason: record.reason, counts: record.counts, at: (/* @__PURE__ */ new Date()).toISOString() })}
1769
- `, { mode: 384 });
1770
- }
1771
-
1772
- // packages/cli/client/localRuntimeAdapter.ts
1773
- import { createHash as createHash14 } from "node:crypto";
1774
- import { resolve as resolveReviewWorkspace } from "node:path";
1775
-
1776
- // packages/cli/client/hostTaskWorkspace.ts
1777
- import { execFileSync } from "node:child_process";
1778
- import { createHash as createHash5 } from "node:crypto";
1779
- import { lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, realpathSync as realpathSync3, writeFileSync as writeFileSync3 } from "node:fs";
1780
- import { dirname as dirname2, join as join5, relative as relative2, resolve as resolve5 } from "node:path";
1781
- function git(cwd, args) {
1782
- const env = { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_NO_REPLACE_OBJECTS: "1" };
1783
- for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES"]) delete env[key];
1784
- return execFileSync("git", ["--no-optional-locks", ...args], { cwd, env, timeout: 15e3, maxBuffer: 8 * 1024 * 1024, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
1785
- }
1786
- function pathFor(scope, env) {
1787
- return join5(hostTaskEventsRoot(env), "workspace-snapshots", createHash5("sha256").update(JSON.stringify([scope.taskId, resolve5(scope.workspace), scope.dialogId])).digest("hex") + ".json");
1788
- }
1789
- function admitHostTaskWorkspace(scope, env) {
1790
- const path = pathFor(scope, env);
1791
- try {
1792
- return readHostTaskWorkspace(scope, env);
1793
- } catch (e) {
1794
- if (e.code !== "ENOENT") throw e;
1795
- }
1796
- const snapshot = { version: 1, scope: { ...scope, workspace: resolve5(scope.workspace) }, repoRoot: "", baseline: "", taskPaths: [], existingDirtyPaths: [], status: "blocked" };
1797
- try {
1798
- const cwd = realpathSync3(scope.workspace);
1799
- if (git(cwd, ["rev-parse", "--is-inside-work-tree"]).trim() !== "true") throw new Error("not_git_worktree");
1800
- snapshot.repoRoot = realpathSync3(git(cwd, ["rev-parse", "--show-toplevel"]).trim());
1801
- if (cwd !== resolve5(scope.workspace)) throw new Error("workspace_symlink_or_noncanonical");
1802
- snapshot.baseline = git(cwd, ["rev-parse", "--verify", "HEAD^{commit}"]).trim();
1803
- const sub = relative2(snapshot.repoRoot, cwd).replaceAll("\\", "/");
1804
- snapshot.taskPaths = [sub || "."];
1805
- const status = git(snapshot.repoRoot, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
1806
- const rows = status.split("\0").filter(Boolean);
1807
- for (let i = 0; i < rows.length; i++) {
1808
- const row = rows[i];
1809
- snapshot.existingDirtyPaths.push(row.slice(3));
1810
- if (row[0] === "R" || row[0] === "C" || row[1] === "R" || row[1] === "C") snapshot.existingDirtyPaths.push(rows[++i] ?? "");
1811
- }
1812
- if (snapshot.existingDirtyPaths.length) throw new Error("existing_dirty_paths_ownership_unknown");
1813
- if (git(cwd, ["rev-parse", "HEAD"]).trim() !== snapshot.baseline) throw new Error("head_changed_during_admission");
1814
- snapshot.status = "ready";
1815
- } catch (e) {
1816
- snapshot.reason = e instanceof Error ? e.message : "workspace_unavailable";
1817
- }
1818
- mkdirSync3(dirname2(path), { recursive: true, mode: 448 });
1819
- writeFileSync3(path, JSON.stringify(snapshot), { flag: "wx", mode: 384 });
1820
- return snapshot;
1821
- }
1822
- function readHostTaskWorkspace(scope, env) {
1823
- const path = pathFor(scope, env);
1824
- if (lstatSync3(path).isSymbolicLink() || realpathSync3(path) !== resolve5(path)) throw new Error("unsafe_workspace_snapshot_path");
1825
- const s = JSON.parse(readFileSync3(path, "utf8"));
1826
- if (s.version !== 1 || s.scope.taskId !== scope.taskId || s.scope.dialogId !== scope.dialogId || s.scope.workspace !== resolve5(scope.workspace) || s.scope.taskInstanceId !== scope.taskInstanceId) throw new Error("workspace_snapshot_scope_mismatch");
1827
- return s;
1828
- }
1829
- async function collectHostTaskWorkspace(scope, env) {
1830
- try {
1831
- const s = readHostTaskWorkspace(scope, env);
1832
- if (s.status !== "ready" || s.existingDirtyPaths.length) throw new Error(s.reason ?? "workspace_blocked");
1833
- if (realpathSync3(scope.workspace) !== s.scope.workspace || realpathSync3(git(scope.workspace, ["rev-parse", "--show-toplevel"]).trim()) !== s.repoRoot) throw new Error("workspace_identity_changed");
1834
- const paths = [relative2(s.repoRoot, s.scope.workspace).replaceAll("\\", "/") || "."];
1835
- if (JSON.stringify(paths) !== JSON.stringify(s.taskPaths)) throw new Error("workspace_scope_changed");
1836
- git(scope.workspace, ["merge-base", "--is-ancestor", s.baseline, "HEAD"]);
1837
- const evidence = await collectTaskRevisionEvidence({ cwd: scope.workspace, baseline: s.baseline, taskPaths: s.taskPaths });
1838
- if (!evidence.complete || evidence.baseline.resolvedSha !== s.baseline) throw new Error("revision_incomplete");
1839
- return { status: "ready", context: { scope, baseline: s.baseline, taskPaths: s.taskPaths, revision: taskContentRevision(evidence) } };
1840
- } catch (e) {
1841
- return { status: "blocked", reason: e instanceof Error ? e.message : "workspace_snapshot_missing" };
1842
- }
1843
- }
420
+ isCompiledBinary,
421
+ parseUserIdFromAuthToken,
422
+ resolveAuthToken,
423
+ resolveServerUrl
424
+ } from "./chunk-WACI5I6V.js";
425
+ import {
426
+ DEFAULT_NOLO_SERVER_URL
427
+ } from "./chunk-OLZBQWZU.js";
428
+ import {
429
+ NOLO_CLUSTER_SERVERS
430
+ } from "./chunk-LCBAMY2M.js";
431
+ import {
432
+ isLoopbackUrl
433
+ } from "./chunk-4SN6J65J.js";
434
+ import {
435
+ normalizeServerOrigin
436
+ } from "./chunk-CF7PE763.js";
437
+ import {
438
+ agentRunCardLabels,
439
+ t
440
+ } from "./chunk-OB6DVWPF.js";
441
+ import {
442
+ createOAuthTokenStore,
443
+ isTokenExpired,
444
+ readOAuthCredential,
445
+ resolveFreshAccessToken
446
+ } from "./chunk-G7Y4GXTY.js";
447
+ import {
448
+ createTokenDialogIndexKey,
449
+ createTokenKey,
450
+ createTokenStatsKey,
451
+ createUserKey
452
+ } from "./chunk-SYTHYBMI.js";
453
+ import {
454
+ dialogMessageKey
455
+ } from "./chunk-OJKUU3LP.js";
456
+ import {
457
+ dialogIdFromKey
458
+ } from "./chunk-YZMNK53S.js";
459
+ import {
460
+ asTrimmedString
461
+ } from "./chunk-3EUW3WEO.js";
462
+ import {
463
+ asOptionalPositiveFiniteNumber
464
+ } from "./chunk-U6VC4MU4.js";
465
+ import {
466
+ asOptionalTrimmedString
467
+ } from "./chunk-G3SUCT4W.js";
468
+ import {
469
+ __toESM
470
+ } from "./chunk-U67V476Y.js";
1844
471
 
1845
472
  // packages/agent-runtime/anthropicMessagesProvider.ts
1846
- import { randomUUID as randomUUID2 } from "node:crypto";
473
+ import { randomUUID } from "node:crypto";
1847
474
 
1848
475
  // packages/agent-runtime/anthropicMessagesStream.ts
1849
476
  var ANTHROPIC_STREAM_ERROR_STATUS = {
@@ -2308,7 +935,7 @@ function buildAnthropicMessagesBody(args) {
2308
935
  }
2309
936
  blocks.push({
2310
937
  type: "tool_use",
2311
- id: stringValue(call.id) ?? `toolu_${randomUUID2()}`,
938
+ id: stringValue(call.id) ?? `toolu_${randomUUID()}`,
2312
939
  name,
2313
940
  input
2314
941
  });
@@ -2403,7 +1030,7 @@ function mapAnthropicMessageToOpenAi(payload) {
2403
1030
  if (block.type === "thinking" && typeof block.thinking === "string") reasoning += block.thinking;
2404
1031
  if (block.type === "tool_use" && typeof block.name === "string") {
2405
1032
  toolCalls.push({
2406
- id: stringValue(block.id) ?? `toolu_${randomUUID2()}`,
1033
+ id: stringValue(block.id) ?? `toolu_${randomUUID()}`,
2407
1034
  type: "function",
2408
1035
  function: { name: block.name, arguments: JSON.stringify(block.input ?? {}) }
2409
1036
  });
@@ -2422,7 +1049,7 @@ function mapAnthropicMessageToOpenAi(payload) {
2422
1049
  (raw) => raw && typeof raw === "object" && typeof raw.type === "string" ? [String(raw.type)] : []
2423
1050
  );
2424
1051
  return {
2425
- id: stringValue(payload.id) ?? `chatcmpl_${randomUUID2()}`,
1052
+ id: stringValue(payload.id) ?? `chatcmpl_${randomUUID()}`,
2426
1053
  object: "chat.completion",
2427
1054
  model: stringValue(payload.model) ?? "claude",
2428
1055
  choices: [{
@@ -2630,33 +1257,43 @@ var REGISTRY_INJECTED_TOOL_NAMES = /* @__PURE__ */ new Set([
2630
1257
  "read_xhs_profile"
2631
1258
  ]);
2632
1259
 
2633
- // packages/ai/tools/agent/taskReviewTools.ts
2634
- var str = { type: "string", minLength: 1 };
2635
- var requestTaskReviewFunctionSchema = {
2636
- name: "requestTaskReview",
2637
- description: "Request an independent review of the registered task revision. Local host only; requires existing account auto-review authorization. Ordinary startAgentRun is not review.",
2638
- parameters: { type: "object", additionalProperties: false, properties: {
2639
- reviewerAgentKey: str,
2640
- revision: str
2641
- }, required: ["reviewerAgentKey", "revision"] }
2642
- };
2643
- var recordTaskReviewDecisionFunctionSchema = {
2644
- name: "recordTaskReviewDecision",
2645
- description: 'After reading the terminal review, record a reasoned continue/fix/stop decision bound to its dispatch, run, revision and result SHA256, with finding dispositions. APPROVE alone is not a decision. For continue, every finding the report enumerates with an explicit id (a file:line reference or a bracketed id) must appear in findings with its own disposition; an empty findings list cannot stand in for reported findings. If the report states findings the host cannot enumerate mechanically, add one finding with id "full-text" whose rationale dispositions the whole report text.',
2646
- parameters: { type: "object", additionalProperties: false, properties: {
2647
- dispatchId: str,
2648
- runId: str,
2649
- revision: str,
2650
- resultSha256: { type: "string", pattern: "^[a-f0-9]{64}$" },
2651
- action: { type: "string", enum: ["continue", "fix", "stop"] },
2652
- rationale: str,
2653
- findings: { type: "array", items: { type: "object", additionalProperties: false, properties: {
2654
- id: str,
2655
- disposition: { type: "string", enum: ["accepted", "fix", "disputed"] },
2656
- rationale: str
2657
- }, required: ["id", "disposition", "rationale"] } }
2658
- }, required: ["dispatchId", "runId", "revision", "resultSha256", "action", "rationale", "findings"] }
2659
- };
1260
+ // packages/agent-runtime/agentRunIsolation.ts
1261
+ var ORCHESTRATION_TOOL_NAMES = /* @__PURE__ */ new Set([
1262
+ "startAgentRun",
1263
+ "controlAgentRun",
1264
+ "listAgents",
1265
+ "readAgent",
1266
+ "runStreamingAgent"
1267
+ ]);
1268
+ var INTERACTION_REQUIRED_TOOL_NAMES = /* @__PURE__ */ new Set([
1269
+ "ask_user",
1270
+ // 凭据请求:需要宿主交互面板(Block 1a);desktop 无通道时同 ask_user 剥离。
1271
+ "secret-request"
1272
+ ]);
1273
+ var SELF_MUTATION_TOOL_NAMES = /* @__PURE__ */ new Set([
1274
+ "updateSelf",
1275
+ "updateAgent"
1276
+ ]);
1277
+ var SUBTASK_REMOVED_TOOL_NAMES = /* @__PURE__ */ new Set([
1278
+ ...ORCHESTRATION_TOOL_NAMES,
1279
+ ...INTERACTION_REQUIRED_TOOL_NAMES,
1280
+ ...SELF_MUTATION_TOOL_NAMES
1281
+ ]);
1282
+ function isSubtaskRun(env) {
1283
+ if (!env) return false;
1284
+ const value = env.NOLO_AGENT_RUN_CHILD;
1285
+ return typeof value === "string" && value.length > 0 && value !== "0";
1286
+ }
1287
+ var RUN_WAKE_CHANNEL_ENV = "NOLO_RUN_WAKE";
1288
+ function hasRunWakeChannel(env) {
1289
+ if (!env) return false;
1290
+ const value = env[RUN_WAKE_CHANNEL_ENV];
1291
+ return typeof value === "string" && value.length > 0 && value !== "0";
1292
+ }
1293
+ function filterToolNamesForRunKind(toolNames, isSubtask) {
1294
+ if (!isSubtask) return [...toolNames];
1295
+ return toolNames.filter((name) => !SUBTASK_REMOVED_TOOL_NAMES.has(name));
1296
+ }
2660
1297
 
2661
1298
  // packages/cli/client/localRuntimeTools.ts
2662
1299
  var CLI_CHROME_CONNECTOR_TOOL_NAME_SET = new Set(
@@ -2733,11 +1370,7 @@ function buildOrchestrationOpenAiTools(args) {
2733
1370
  const names = ["startAgentRun", "controlAgentRun"].filter(
2734
1371
  (name) => args.toolNameSet.has(name)
2735
1372
  );
2736
- const reviewTools = [
2737
- ...args.toolNameSet.has("requestTaskReview") ? [{ type: "function", function: requestTaskReviewFunctionSchema }] : [],
2738
- ...args.toolNameSet.has("recordTaskReviewDecision") ? [{ type: "function", function: recordTaskReviewDecisionFunctionSchema }] : []
2739
- ];
2740
- if (names.length === 0) return reviewTools;
1373
+ if (names.length === 0) return [];
2741
1374
  const waitCapableActions = CONTROL_AGENT_RUN_ACTIONS.filter(
2742
1375
  (action) => action !== "wait"
2743
1376
  );
@@ -2751,7 +1384,6 @@ function buildOrchestrationOpenAiTools(args) {
2751
1384
  wakeEnabled: wakeChannel
2752
1385
  });
2753
1386
  return [
2754
- ...reviewTools,
2755
1387
  ...prepareTools(names).map((tool) => {
2756
1388
  if (tool?.function?.name === "controlAgentRun") {
2757
1389
  return { ...tool, function: controlSchema };
@@ -3639,9 +2271,9 @@ function calculateDelegatedPayloadMetrics(task, input, delegatedContent) {
3639
2271
  }
3640
2272
  var isCliProviderAgent = isCliProviderAgentConfig;
3641
2273
  function resolveCliProviderName(agentConfig) {
3642
- const explicit2 = asTrimmedLowercaseString(agentConfig?.cliProvider);
3643
- if (explicit2) {
3644
- if (isCliProvider(explicit2)) return explicit2;
2274
+ const explicit = asTrimmedLowercaseString(agentConfig?.cliProvider);
2275
+ if (explicit) {
2276
+ if (isCliProvider(explicit)) return explicit;
3645
2277
  throw new Error(
3646
2278
  `Unknown CLI provider: "${agentConfig?.cliProvider}". Expected one of: ${CLI_PROVIDER_VALUES.join(", ")}`
3647
2279
  );
@@ -3774,14 +2406,14 @@ var resolveCliProviderTransport = async (ctx) => {
3774
2406
  };
3775
2407
 
3776
2408
  // packages/agent-runtime/codexResponsesProvider.ts
3777
- import { createHash as createHash6 } from "node:crypto";
3778
- import { randomUUID as randomUUID3 } from "node:crypto";
2409
+ import { createHash } from "node:crypto";
2410
+ import { randomUUID as randomUUID2 } from "node:crypto";
3779
2411
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
3780
2412
  var CODEX_CLIENT_VERSION = "0.162.1";
3781
2413
  var CODEX_ORIGINATOR = "codex_cli_rs";
3782
2414
  var CODEX_OPENAI_BETA = "responses=experimental";
3783
2415
  var OPENAI_AUTH_CLAIM = "https://api.openai.com/auth";
3784
- var CODEX_INSTALLATION_ID = randomUUID3();
2416
+ var CODEX_INSTALLATION_ID = randomUUID2();
3785
2417
  function decodeCodexAccountId(accessToken) {
3786
2418
  const parts = accessToken.split(".");
3787
2419
  if (parts.length < 2) return void 0;
@@ -3799,10 +2431,10 @@ function decodeCodexAccountId(accessToken) {
3799
2431
  var turnStartedAtByTurn = /* @__PURE__ */ new Map();
3800
2432
  function createCodexRequestIdentity(installationId = CODEX_INSTALLATION_ID, stable) {
3801
2433
  const key = stable?.sessionKey && isStableSessionIdentityEnabled() ? stable.sessionKey : void 0;
3802
- const sessionId = key ? deriveStableUuid(key, "session") : randomUUID3();
3803
- const threadId = key ? sessionId : randomUUID3();
3804
- const windowId = key ? deriveStableUuid(key, "window") : randomUUID3();
3805
- const turnId = key ? deriveStableUuid(key, `turn:${stable?.turnToken ?? ""}`) : randomUUID3();
2434
+ const sessionId = key ? deriveStableUuid(key, "session") : randomUUID2();
2435
+ const threadId = key ? sessionId : randomUUID2();
2436
+ const windowId = key ? deriveStableUuid(key, "window") : randomUUID2();
2437
+ const turnId = key ? deriveStableUuid(key, `turn:${stable?.turnToken ?? ""}`) : randomUUID2();
3806
2438
  let turnStartedAt = Date.now();
3807
2439
  if (key) {
3808
2440
  const tk = `${key}\0${stable?.turnToken ?? ""}`;
@@ -3961,7 +2593,7 @@ function throwIfAborted(signal) {
3961
2593
  }
3962
2594
  function waitBackoff(ms, signal, injectedSleep) {
3963
2595
  throwIfAborted(signal);
3964
- return new Promise((resolve15, reject) => {
2596
+ return new Promise((resolve7, reject) => {
3965
2597
  let timer;
3966
2598
  const cleanup = () => {
3967
2599
  signal?.removeEventListener("abort", onAbort);
@@ -3976,7 +2608,7 @@ function waitBackoff(ms, signal, injectedSleep) {
3976
2608
  injectedSleep(ms).then(
3977
2609
  () => {
3978
2610
  cleanup();
3979
- resolve15();
2611
+ resolve7();
3980
2612
  },
3981
2613
  (error) => {
3982
2614
  cleanup();
@@ -3986,7 +2618,7 @@ function waitBackoff(ms, signal, injectedSleep) {
3986
2618
  } else {
3987
2619
  timer = setTimeout(() => {
3988
2620
  cleanup();
3989
- resolve15();
2621
+ resolve7();
3990
2622
  }, ms);
3991
2623
  }
3992
2624
  });
@@ -3995,7 +2627,7 @@ async function callCodexResponsesOnce(args, accountId, timingTracker) {
3995
2627
  const fetchImpl = args.fetchImpl ?? fetch;
3996
2628
  const msgs = Array.isArray(args.openAiBody.messages) ? args.openAiBody.messages : [];
3997
2629
  const lastUser = [...msgs].reverse().find((m) => m && m.role === "user");
3998
- const turnToken = createHash6("sha256").update(JSON.stringify(lastUser?.content ?? "")).digest("hex").slice(0, 24);
2630
+ const turnToken = createHash("sha256").update(JSON.stringify(lastUser?.content ?? "")).digest("hex").slice(0, 24);
3999
2631
  const identity = createCodexRequestIdentity(
4000
2632
  void 0,
4001
2633
  args.sessionKey ? { sessionKey: args.sessionKey, turnToken } : void 0
@@ -4239,14 +2871,14 @@ function countCodexInputChars(messages) {
4239
2871
  }
4240
2872
  function abortableSleep(sleepFn, ms, signal) {
4241
2873
  let timer;
4242
- const waitOnce = () => sleepFn ? Promise.resolve(sleepFn(ms)) : new Promise((resolve15) => {
4243
- timer = setTimeout(resolve15, ms);
2874
+ const waitOnce = () => sleepFn ? Promise.resolve(sleepFn(ms)) : new Promise((resolve7) => {
2875
+ timer = setTimeout(resolve7, ms);
4244
2876
  });
4245
2877
  if (!signal) return waitOnce().then(() => void 0);
4246
2878
  if (signal.aborted) {
4247
2879
  return Promise.reject(signal.reason ?? new DOMException("aborted", "AbortError"));
4248
2880
  }
4249
- return new Promise((resolve15, reject) => {
2881
+ return new Promise((resolve7, reject) => {
4250
2882
  let settled = false;
4251
2883
  const finish = (settle) => {
4252
2884
  if (settled) return;
@@ -4260,7 +2892,7 @@ function abortableSleep(sleepFn, ms, signal) {
4260
2892
  );
4261
2893
  signal.addEventListener("abort", onAbort, { once: true });
4262
2894
  waitOnce().then(
4263
- () => finish(resolve15),
2895
+ () => finish(resolve7),
4264
2896
  (error) => finish(() => reject(error))
4265
2897
  );
4266
2898
  });
@@ -5163,7 +3795,7 @@ function waitWithAbort(ms, signal) {
5163
3795
  if (signal?.aborted) {
5164
3796
  return Promise.reject(signal.reason ?? new Error("owner-required proxy aborted"));
5165
3797
  }
5166
- return new Promise((resolve15, reject) => {
3798
+ return new Promise((resolve7, reject) => {
5167
3799
  let timer;
5168
3800
  const cleanup = () => {
5169
3801
  if (timer !== void 0) clearTimeout(timer);
@@ -5175,7 +3807,7 @@ function waitWithAbort(ms, signal) {
5175
3807
  };
5176
3808
  timer = setTimeout(() => {
5177
3809
  cleanup();
5178
- resolve15();
3810
+ resolve7();
5179
3811
  }, ms);
5180
3812
  signal?.addEventListener("abort", onAbort, { once: true });
5181
3813
  });
@@ -5692,14 +4324,14 @@ function resolveProviderResolveOverrides(agentConfig, options) {
5692
4324
  }
5693
4325
 
5694
4326
  // packages/cli/client/localRuntimePaths.ts
5695
- import { dirname as dirname3, extname, join as join6 } from "node:path";
4327
+ import { dirname, extname, join } from "node:path";
5696
4328
  import { fileURLToPath } from "node:url";
5697
4329
  function resolveLocalRuntimePaths(moduleUrl, compiled, execPath) {
5698
- if (compiled) return { cliDir: dirname3(execPath), cliEntrypoint: execPath };
4330
+ if (compiled) return { cliDir: dirname(execPath), cliEntrypoint: execPath };
5699
4331
  const modulePath = fileURLToPath(moduleUrl);
5700
4332
  const extension = extname(modulePath) === ".js" ? ".js" : ".ts";
5701
- const cliDir = extension === ".js" ? dirname3(modulePath) : dirname3(dirname3(modulePath));
5702
- return { cliDir, cliEntrypoint: join6(cliDir, `index${extension}`) };
4333
+ const cliDir = extension === ".js" ? dirname(modulePath) : dirname(dirname(modulePath));
4334
+ return { cliDir, cliEntrypoint: join(cliDir, `index${extension}`) };
5703
4335
  }
5704
4336
 
5705
4337
  // packages/cli/client/localRunExecutionIsolation.ts
@@ -5826,7 +4458,7 @@ function describeLocalRunExecutionIsolation(fact) {
5826
4458
  var emittedNoticeKeys = /* @__PURE__ */ new Set();
5827
4459
  function createLocalRunIsolationNoticeEmitter(args) {
5828
4460
  const seen = args.seen ?? emittedNoticeKeys;
5829
- return (fact, context2) => {
4461
+ return (fact, context) => {
5830
4462
  const notice = fact.notice;
5831
4463
  if (!notice) return false;
5832
4464
  const key = `${notice.platform}:${notice.sandboxBackend}:${notice.reason}`;
@@ -5844,7 +4476,7 @@ function createLocalRunIsolationNoticeEmitter(args) {
5844
4476
  reason: fact.reason,
5845
4477
  platform: fact.platform,
5846
4478
  sandboxBackend: fact.sandboxBackend,
5847
- ...context2 ?? {}
4479
+ ...context ?? {}
5848
4480
  }
5849
4481
  });
5850
4482
  return true;
@@ -5860,10 +4492,10 @@ function recordLocalRunExecutionIsolation(args) {
5860
4492
  );
5861
4493
  return path;
5862
4494
  }
5863
- function joinPath(dir2, name) {
5864
- if (!dir2) return name;
5865
- const sep3 = dir2.includes("\\") && !dir2.includes("/") ? "\\" : "/";
5866
- return dir2.endsWith(sep3) ? `${dir2}${name}` : `${dir2}${sep3}${name}`;
4495
+ function joinPath(dir, name) {
4496
+ if (!dir) return name;
4497
+ const sep2 = dir.includes("\\") && !dir.includes("/") ? "\\" : "/";
4498
+ return dir.endsWith(sep2) ? `${dir}${name}` : `${dir}${sep2}${name}`;
5867
4499
  }
5868
4500
 
5869
4501
  // packages/core/settingsSyncFreshness.ts
@@ -5930,7 +4562,7 @@ function isBusyProviderStreamError(error) {
5930
4562
  return BUSY_STREAM_ERROR_RE.test(toErrorMessage(error));
5931
4563
  }
5932
4564
  async function defaultSleep(ms) {
5933
- await new Promise((resolve15) => setTimeout(resolve15, ms));
4565
+ await new Promise((resolve7) => setTimeout(resolve7, ms));
5934
4566
  }
5935
4567
  function isRetryableProviderStreamError(error) {
5936
4568
  const message = toErrorMessage(error);
@@ -6464,7 +5096,7 @@ function buildLocalParentWakeMessage(args) {
6464
5096
  var EVIDENCE_WRITE_BATCH_SIZE = 4;
6465
5097
  var EVIDENCE_WRITE_BATCH_GAP_MS = 300;
6466
5098
  async function defaultEvidenceSleep(ms) {
6467
- await new Promise((resolve15) => setTimeout(resolve15, ms));
5099
+ await new Promise((resolve7) => setTimeout(resolve7, ms));
6468
5100
  }
6469
5101
  async function runThrottledBatches(items, run, options = {}) {
6470
5102
  const batchSize = options.batchSize ?? EVIDENCE_WRITE_BATCH_SIZE;
@@ -7334,8 +5966,8 @@ function createHostApprovalCardQueue() {
7334
5966
  return {
7335
5967
  /** Resolves with the user's answer once this card reaches the head of the queue. */
7336
5968
  present(card, present) {
7337
- return new Promise((resolve15) => {
7338
- waiting.push({ card, present, resolve: resolve15 });
5969
+ return new Promise((resolve7) => {
5970
+ waiting.push({ card, present, resolve: resolve7 });
7339
5971
  void Promise.resolve().then(drain);
7340
5972
  });
7341
5973
  },
@@ -7429,13 +6061,13 @@ async function createBrowserShellApprovalBridge(args) {
7429
6061
  },
7430
6062
  ...args.awaitHostApproval ? { awaitHostApproval: async (card) => {
7431
6063
  requireActive();
7432
- const decision = await new Promise((resolve15, reject) => {
6064
+ const decision = await new Promise((resolve7, reject) => {
7433
6065
  const abort = () => reject(new Error("Browser approval bridge revoked"));
7434
6066
  lifetime.signal.addEventListener("abort", abort, { once: true });
7435
6067
  Promise.resolve().then(() => {
7436
6068
  requireActive();
7437
6069
  return args.awaitHostApproval(card, lifetime.signal);
7438
- }).then(resolve15, reject).finally(() => lifetime.signal.removeEventListener("abort", abort));
6070
+ }).then(resolve7, reject).finally(() => lifetime.signal.removeEventListener("abort", abort));
7439
6071
  });
7440
6072
  requireActive();
7441
6073
  if (decision !== "allow_once" && decision !== "deny") throw new Error("Invalid host decision");
@@ -7458,17 +6090,17 @@ async function createBrowserShellApprovalBridge(args) {
7458
6090
  clearTimeout(timer);
7459
6091
  args.signal?.removeEventListener("abort", onAbort);
7460
6092
  bindings.clear();
7461
- closing = new Promise((resolve15) => {
7462
- server.close(() => resolve15());
6093
+ closing = new Promise((resolve7) => {
6094
+ server.close(() => resolve7());
7463
6095
  server.closeAllConnections();
7464
6096
  });
7465
6097
  return closing;
7466
6098
  }
7467
- await new Promise((resolve15, reject) => {
6099
+ await new Promise((resolve7, reject) => {
7468
6100
  server.once("error", reject);
7469
6101
  server.listen(0, "127.0.0.1", () => {
7470
6102
  server.removeListener("error", reject);
7471
- resolve15();
6103
+ resolve7();
7472
6104
  });
7473
6105
  });
7474
6106
  const address = server.address();
@@ -7559,559 +6191,6 @@ Expires: ${new Date(card.expiresAt).toISOString()}`;
7559
6191
  }
7560
6192
  }
7561
6193
 
7562
- // packages/cli/client/taskReviewTools.ts
7563
- import { lstatSync as lstatSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync5, realpathSync as realpathSync4 } from "node:fs";
7564
- import { join as join8, resolve as resolve8 } from "node:path";
7565
-
7566
- // packages/cli/tui/redactSecrets.ts
7567
- var REDACTED = "\u27E8redacted\u27E9";
7568
- function redactSecrets(text) {
7569
- return text.replace(/\b(?:sk|pk)-[A-Za-z0-9_-]{10,}/g, REDACTED).replace(/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{12,}/gi, `$1${REDACTED}`).replace(
7570
- /\b((?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|token|secret|password|passwd|credential)s?\s*[=:]\s*["']?)[^\s"',;]{8,}/gi,
7571
- `$1${REDACTED}`
7572
- ).replace(
7573
- /\b((?:--[a-z-]*(?:token|key|secret|password|credential)[a-z-]*)\s+)[^\s"']{8,}/gi,
7574
- `$1${REDACTED}`
7575
- );
7576
- }
7577
-
7578
- // packages/cli/tui/askTextSanitize.ts
7579
- var ASK_SECRET_PLACEHOLDER = "\u27E8redacted\u27E9";
7580
- var C0_C1_CONTROL_REGEX = /[\x00-\x1f\x7f-\x9f]/g;
7581
- var NORMAL_GIST_SECRET_PATTERNS = [
7582
- /\bbearer\s+[A-Za-z0-9._~+/=-]{8,}/i,
7583
- /\bsk-(?:ant-)?(?:api)?[0-9a-zA-Z-]{10,}/,
7584
- /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{10,}/,
7585
- /\bxox[baprs]-[A-Za-z0-9-]{10,}/
7586
- ];
7587
- function withholdIfSecretLike(gist) {
7588
- if (!gist) return "";
7589
- if (findPotentialSecrets(gist).length > 0) return "";
7590
- if (NORMAL_GIST_SECRET_PATTERNS.some((pattern) => pattern.test(gist))) return "";
7591
- return gist;
7592
- }
7593
- function toText(value) {
7594
- return typeof value === "string" ? value : String(value ?? "");
7595
- }
7596
- function cleanAskText(value) {
7597
- return stripAnsi(toText(value)).replace(/[\r\n]+/g, " ").replace(/\s+/g, " ").replace(C0_C1_CONTROL_REGEX, "").replace(/\s+/g, " ").trim();
7598
- }
7599
- function safeAskText(value, max) {
7600
- const cleaned = redactSecrets(cleanAskText(value));
7601
- if (!cleaned) return "";
7602
- const guarded = withholdIfSecretLike(cleaned) || ASK_SECRET_PLACEHOLDER;
7603
- return max === void 0 ? guarded : clipCompactText(guarded, max, "\u2026");
7604
- }
7605
- function safeApprovalMultilineText(value) {
7606
- const lines = stripAnsi(String(value ?? "")).replace(/\r\n?|\u2028|\u2029/g, "\n").split("\n");
7607
- return lines.map((line) => {
7608
- const cleaned = line.replace(/\t/g, " ").replace(C0_C1_CONTROL_REGEX, "");
7609
- const redacted = redactSecrets(cleaned);
7610
- return redacted ? withholdIfSecretLike(redacted) || ASK_SECRET_PLACEHOLDER : "";
7611
- }).join("\n");
7612
- }
7613
-
7614
- // packages/cli/client/hostTaskProgressProducer.ts
7615
- import { createHash as createHash8 } from "node:crypto";
7616
- import { lstatSync as lstatSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4, readdirSync as readdirSync3, writeFileSync as writeFileSync4 } from "node:fs";
7617
- import { join as join7, relative as relative3, resolve as resolve7 } from "node:path";
7618
-
7619
- // packages/cli/agentRunLocalWorkspace.ts
7620
- import { createHash as createHash7 } from "node:crypto";
7621
- import { constants } from "node:fs";
7622
- import { lstat, open } from "node:fs/promises";
7623
- import { resolve as resolve6 } from "node:path";
7624
- function unknownLocalRunAcceptance(cwd, base) {
7625
- return {
7626
- schemaVersion: 1,
7627
- source: "local-runtime",
7628
- capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
7629
- cwd,
7630
- base,
7631
- deliveryHead: null,
7632
- workspace: { status: "unknown", fingerprint: null, changedPaths: null, atomic: false },
7633
- checks: { status: "unknown", reason: "No version-bound command execution evidence collected" },
7634
- review: { status: "unknown" }
7635
- };
7636
- }
7637
- async function runGitForLocalSummary(args, deps = {}) {
7638
- const spawn = deps.spawnProcess ?? spawnProcess;
7639
- const read = deps.readPipeText ?? readPipeText;
7640
- const proc = spawn({
7641
- cmd: ["git", ...args.gitArgs],
7642
- cwd: args.cwd,
7643
- stdout: "pipe",
7644
- stderr: "pipe"
7645
- });
7646
- const [stdout, stderr, exitCode] = await Promise.all([
7647
- read(proc.stdout),
7648
- read(proc.stderr),
7649
- proc.exited
7650
- ]);
7651
- if (exitCode !== 0) {
7652
- throw new Error((stderr || stdout || `git ${args.gitArgs.join(" ")} failed`).trim());
7653
- }
7654
- return args.gitArgs.includes("-z") || args.gitArgs.includes("--binary") ? stdout : stdout.trim();
7655
- }
7656
- async function inspectLocalRunWorkspace(cwd, deps = {}, acceptanceBase) {
7657
- if (acceptanceBase !== void 0) {
7658
- const acceptance = unknownLocalRunAcceptance(cwd, acceptanceBase);
7659
- const sample = acceptanceBase === null ? null : await captureBoundedWorkspace(cwd, {
7660
- spawn: deps.spawnProcess,
7661
- signal: deps.signal,
7662
- limits: deps.sampleLimits,
7663
- base: acceptanceBase
7664
- });
7665
- if (sample) {
7666
- acceptance.deliveryHead = sample.head;
7667
- acceptance.workspace = {
7668
- status: "observed",
7669
- fingerprint: sample.fingerprint,
7670
- changedPaths: sample.changedPaths,
7671
- atomic: false
7672
- };
7673
- }
7674
- return {
7675
- cwd,
7676
- clean: sample ? sample.status.trim() === "" : false,
7677
- status: sample?.status ?? "workspace inspection unavailable (unknown)",
7678
- acceptance,
7679
- ...sample?.commit ? { commit: sample.commit } : {}
7680
- };
7681
- }
7682
- const run = (gitArgs2) => runGitForLocalSummary({ cwd, gitArgs: gitArgs2 }, deps);
7683
- const status = await run(["status", "--short"]);
7684
- const rawCommit = await run(["log", "-1", "--format=%h%x00%s"]).catch(() => "");
7685
- const [hash2, subject] = rawCommit.split("\0");
7686
- return {
7687
- cwd,
7688
- clean: status.trim() === "",
7689
- status,
7690
- ...hash2 ? { commit: { hash: hash2, subject: subject ?? "" } } : {}
7691
- };
7692
- }
7693
- function shouldPrintLocalRunSummary(args) {
7694
- return Boolean(args.localRuntimeCwd && args.parsed.runtimeMode === "local");
7695
- }
7696
- function formatLocalRunSummary(args) {
7697
- return [
7698
- "",
7699
- "[nolo] local run summary",
7700
- `workspace: ${args.inspection.cwd}`,
7701
- ...args.dialogId ? [`dialog: ${args.dialogId}`] : [],
7702
- ...args.inspection.commit ? [`commit: ${args.inspection.commit.hash} ${args.inspection.commit.subject}`] : [],
7703
- `dirty: ${args.inspection.clean ? "clean" : "dirty"}`,
7704
- ...!args.inspection.clean && args.inspection.status.trim() ? [`status:
7705
- ${args.inspection.status.trim()}`] : [],
7706
- ""
7707
- ].join("\n");
7708
- }
7709
- async function captureLocalRunBase(cwd, options = {}) {
7710
- if (options.signal?.aborted) return null;
7711
- const controller = new AbortController();
7712
- const abort = () => controller.abort();
7713
- options.signal?.addEventListener("abort", abort, { once: true });
7714
- const timer = setTimeout(abort, options.timeoutMs ?? 2e3);
7715
- let child;
7716
- let bytesRead = 0;
7717
- let onAbort;
7718
- const stop = () => {
7719
- child?.kill();
7720
- child?.stdout?.destroy();
7721
- child?.stderr?.destroy();
7722
- };
7723
- controller.signal.addEventListener("abort", stop, { once: true });
7724
- const work = async () => {
7725
- child = (options.spawn ?? spawnProcess)({
7726
- cmd: ["git", "rev-parse", "HEAD"],
7727
- cwd,
7728
- stdin: "ignore",
7729
- stdout: "pipe",
7730
- stderr: "pipe",
7731
- env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" }
7732
- });
7733
- const read = async (stream) => {
7734
- const chunks = [];
7735
- if (stream) for await (const chunk of stream) {
7736
- if (controller.signal.aborted) throw new Error("base capture cancelled");
7737
- const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
7738
- bytesRead += bytes.length;
7739
- if (bytesRead > (options.outputBytes ?? 4096)) {
7740
- controller.abort();
7741
- throw new Error("base output budget");
7742
- }
7743
- chunks.push(bytes);
7744
- }
7745
- return Buffer.concat(chunks).toString("utf8").trim();
7746
- };
7747
- const [head, , code] = await Promise.all([read(child.stdout), read(child.stderr), child.exited]);
7748
- if (controller.signal.aborted || code !== 0 || !/^[a-f0-9]{40,64}$/.test(head)) return null;
7749
- return head;
7750
- };
7751
- try {
7752
- return await Promise.race([work(), new Promise((resolve15) => {
7753
- onAbort = () => resolve15(null);
7754
- controller.signal.addEventListener("abort", onAbort, { once: true });
7755
- if (controller.signal.aborted) resolve15(null);
7756
- })]);
7757
- } catch {
7758
- return null;
7759
- } finally {
7760
- controller.abort();
7761
- clearTimeout(timer);
7762
- options.signal?.removeEventListener("abort", abort);
7763
- controller.signal.removeEventListener("abort", stop);
7764
- if (onAbort) controller.signal.removeEventListener("abort", onAbort);
7765
- }
7766
- }
7767
- function observeLocalCommandResult(event, cwd) {
7768
- if (event.type !== "tool-result" || event.toolName !== "execShell") return;
7769
- const meta = event.metadata;
7770
- 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;
7771
- return {
7772
- commandFingerprint: `sha256:${createHash7("sha256").update(meta.command).digest("hex")}`,
7773
- cwd,
7774
- cwdSource: "configured-workspace",
7775
- exitCode: meta.timedOut ? "timeout" : meta.exitCode,
7776
- // Settlement replaces this with the containing result-file JSON pointer.
7777
- evidence: "runtime-tool-result",
7778
- versionBinding: "unknown",
7779
- source: "execShell-tool-result",
7780
- toolCallId: event.toolCallId,
7781
- capturedAt: (/* @__PURE__ */ new Date()).toISOString()
7782
- };
7783
- }
7784
- function attachLocalCommandObservations(acceptance, observations, resultReference) {
7785
- if (!observations.length) return;
7786
- const existing = acceptance.checks.observations ?? [];
7787
- acceptance.checks.observations = [...existing, ...observations.map((observation, index) => ({
7788
- ...observation,
7789
- evidence: `${resultReference}#/acceptance/checks/observations/${existing.length + index}`
7790
- }))];
7791
- acceptance.checks.reason = "Command exits observed; execution cwd is configured only and execution-time version stability is unproven";
7792
- }
7793
- var COMMAND_WORKSPACE_SAMPLE_LIMITS = {
7794
- timeoutMs: 2e3,
7795
- gitOutputBytes: 1024 * 1024,
7796
- files: 128,
7797
- fileBytes: 1024 * 1024,
7798
- totalFileBytes: 4 * 1024 * 1024,
7799
- concurrentSamples: 1
7800
- };
7801
- var activeCommandWorkspaceSamples = 0;
7802
- async function captureBoundedWorkspace(cwd, options = {}) {
7803
- if (options.signal?.aborted || activeCommandWorkspaceSamples >= COMMAND_WORKSPACE_SAMPLE_LIMITS.concurrentSamples) return null;
7804
- activeCommandWorkspaceSamples++;
7805
- const limits = { ...COMMAND_WORKSPACE_SAMPLE_LIMITS, ...options.limits };
7806
- const controller = new AbortController();
7807
- const abort = () => controller.abort();
7808
- options.signal?.addEventListener("abort", abort, { once: true });
7809
- const timer = setTimeout(abort, limits.timeoutMs);
7810
- let outputBytes = 0;
7811
- let fileBytes = 0;
7812
- const check = () => {
7813
- if (controller.signal.aborted) throw new Error("sample cancelled");
7814
- };
7815
- const git2 = async (args) => {
7816
- check();
7817
- const child = (options.spawn ?? spawnProcess)({
7818
- cmd: ["git", ...args],
7819
- cwd,
7820
- stdin: "ignore",
7821
- stdout: "pipe",
7822
- stderr: "pipe",
7823
- env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" }
7824
- });
7825
- const stop = () => {
7826
- child.kill();
7827
- child.stdout?.destroy();
7828
- child.stderr?.destroy();
7829
- };
7830
- controller.signal.addEventListener("abort", stop, { once: true });
7831
- const read = async (stream) => {
7832
- const chunks = [];
7833
- if (stream) for await (const chunk of stream) {
7834
- check();
7835
- const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
7836
- outputBytes += bytes.length;
7837
- if (outputBytes > limits.gitOutputBytes) {
7838
- controller.abort();
7839
- throw new Error("git output budget");
7840
- }
7841
- chunks.push(bytes);
7842
- }
7843
- return Buffer.concat(chunks);
7844
- };
7845
- try {
7846
- const [stdout, , code] = await Promise.all([read(child.stdout), read(child.stderr), child.exited]);
7847
- check();
7848
- if (code !== 0) throw new Error("git inspection failed");
7849
- return stdout;
7850
- } finally {
7851
- controller.signal.removeEventListener("abort", stop);
7852
- stop();
7853
- }
7854
- };
7855
- const work = async () => {
7856
- const head = await git2(["rev-parse", "HEAD"]);
7857
- const root = (await git2(["rev-parse", "--show-toplevel"])).toString("utf8").trim();
7858
- const digest2 = createHash7("sha256").update(head);
7859
- const summary = options.base !== void 0 ? (await git2(["log", "-1", "--format=%h%x00%s"])).toString("utf8").trim() : "";
7860
- const paths = options.base !== void 0 ? (await git2(["-C", root, "diff", "--name-only", "-z", options.base, "--"])).toString("utf8").split("\0").filter(Boolean) : [];
7861
- if (paths.length > limits.files) throw new Error("base changed file count budget");
7862
- const status = await git2(["-C", root, "status", "--porcelain=v1", "-z", "--untracked-files=all"]);
7863
- if (status.toString("utf8").split("\0").filter(Boolean).length > limits.files) throw new Error("changed file count budget");
7864
- digest2.update(status);
7865
- for (const args of [
7866
- ["diff", "--no-ext-diff", "--no-textconv", "--binary", "HEAD", "--"],
7867
- ["diff", "--cached", "--no-ext-diff", "--no-textconv", "--binary", "HEAD", "--"]
7868
- ]) digest2.update(await git2(["-C", root, ...args]));
7869
- const names = (await git2(["-C", root, "ls-files", "--others", "--exclude-standard", "-z"])).toString("utf8").split("\0").filter(Boolean).sort();
7870
- if (names.length > limits.files) throw new Error("file count budget");
7871
- for (const name of names) {
7872
- check();
7873
- const path = resolve6(root, name);
7874
- const stat = await lstat(path);
7875
- check();
7876
- if (!stat.isFile() || stat.size > limits.fileBytes || fileBytes + stat.size > limits.totalFileBytes) throw new Error("file budget");
7877
- digest2.update(JSON.stringify([name, stat.mode, stat.size]));
7878
- if (stat.size === 0) {
7879
- const after2 = await lstat(path);
7880
- check();
7881
- if (!after2.isFile() || after2.size !== 0 || after2.ino !== stat.ino || after2.mtimeMs !== stat.mtimeMs) throw new Error("racing empty file");
7882
- continue;
7883
- }
7884
- let readBytes = 0;
7885
- const file2 = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
7886
- try {
7887
- check();
7888
- const opened = await file2.stat();
7889
- check();
7890
- if (!opened.isFile() || opened.ino !== stat.ino || opened.size !== stat.size) throw new Error("racing open");
7891
- const stream = file2.createReadStream({
7892
- autoClose: false,
7893
- highWaterMark: Math.min(32 * 1024, stat.size),
7894
- end: stat.size - 1,
7895
- signal: controller.signal
7896
- });
7897
- try {
7898
- for await (const chunk of stream) {
7899
- check();
7900
- const bytes = chunk;
7901
- readBytes += bytes.length;
7902
- fileBytes += bytes.length;
7903
- if (readBytes > limits.fileBytes || fileBytes > limits.totalFileBytes) throw new Error("read budget");
7904
- digest2.update(bytes);
7905
- }
7906
- } finally {
7907
- stream.destroy();
7908
- }
7909
- } finally {
7910
- await file2.close();
7911
- }
7912
- const after = await lstat(path);
7913
- check();
7914
- if (readBytes !== stat.size || after.size !== stat.size || after.mtimeMs !== stat.mtimeMs || after.ino !== stat.ino || !after.isFile()) throw new Error("racing file");
7915
- }
7916
- check();
7917
- const [hash2, subject] = summary.split("\0");
7918
- return {
7919
- fingerprint: `sha256:${digest2.digest("hex")}`,
7920
- head: head.toString("utf8").trim(),
7921
- status: status.toString("utf8").replace(/\0/g, "\n"),
7922
- changedPaths: [.../* @__PURE__ */ new Set([...paths, ...names])].sort(),
7923
- ...hash2 ? { commit: { hash: hash2, subject: subject ?? "" } } : {}
7924
- };
7925
- };
7926
- let onAbort;
7927
- try {
7928
- const pending = work().finally(() => {
7929
- activeCommandWorkspaceSamples--;
7930
- });
7931
- return await Promise.race([pending, new Promise((resolve15) => {
7932
- onAbort = () => resolve15(null);
7933
- controller.signal.addEventListener("abort", onAbort, { once: true });
7934
- if (controller.signal.aborted) resolve15(null);
7935
- })]);
7936
- } catch {
7937
- return null;
7938
- } finally {
7939
- controller.abort();
7940
- clearTimeout(timer);
7941
- options.signal?.removeEventListener("abort", abort);
7942
- if (onAbort) controller.signal.removeEventListener("abort", onAbort);
7943
- }
7944
- }
7945
- async function captureCommandWorkspaceFingerprint(cwd, options = {}) {
7946
- return (await captureBoundedWorkspace(cwd, options))?.fingerprint ?? null;
7947
- }
7948
- function wrapLocalCommandWorkspaceObservation(adapter, cwd, bindings, capture = captureCommandWorkspaceFingerprint, signal) {
7949
- const safeCapture = (callSignal) => capture(cwd, { signal: signal ?? callSignal }).catch(() => null);
7950
- return {
7951
- ...adapter,
7952
- async executeTool(call, options) {
7953
- if (call.name !== "execShell") return adapter.executeTool.call(adapter, call, options);
7954
- try {
7955
- if (JSON.parse(call.arguments).background === true) return adapter.executeTool.call(adapter, call, options);
7956
- } catch {
7957
- }
7958
- const before = await safeCapture(options?.abortSignal);
7959
- const result = await adapter.executeTool.call(adapter, call, options);
7960
- if (result.metadata?.executionState === "synchronous-complete" && result.metadata.detached !== true && result.metadata.aborted !== true) {
7961
- const after = await safeCapture(options?.abortSignal);
7962
- bindings.set(call.id, {
7963
- versionBinding: !before || !after ? "unknown" : before === after ? "observed-unchanged" : "stale",
7964
- executionWorkspace: {
7965
- before,
7966
- after,
7967
- atomic: false,
7968
- limitation: "ABA and external concurrent writes are not excluded"
7969
- }
7970
- });
7971
- }
7972
- return result;
7973
- }
7974
- };
7975
- }
7976
-
7977
- // packages/cli/client/hostTaskProgressProducer.ts
7978
- var digest = (text) => createHash8("sha256").update(text).digest("hex");
7979
- var explicit = (paths) => paths.length > 0 && paths.every((p) => typeof p === "string" && p !== "." && !p.startsWith("/") && !p.includes("\\") && !p.includes("\0") && p.split("/").every((s) => s && s !== "." && s !== ".."));
7980
- var planPath = (scope, env) => join7(hostTaskEventsRoot(env), "plans", `${digest(JSON.stringify(scope))}.json`);
7981
- function readHostTaskAcceptancePlan(scope, env) {
7982
- try {
7983
- const path = planPath(scope, env);
7984
- if (lstatSync4(path).isSymbolicLink()) return;
7985
- const saved = JSON.parse(readFileSync4(path, "utf8"));
7986
- if (sameTaskScope(saved.scope, scope) && saved.scope.taskInstanceId === scope.taskInstanceId) return saved.plan;
7987
- } catch {
7988
- }
7989
- }
7990
- function readHostTaskUserAssignment(scope, env) {
7991
- const path = join7(hostTaskEventsRoot(env), "assignments", `${digest(JSON.stringify(scope))}.json`);
7992
- try {
7993
- if (lstatSync4(path).isSymbolicLink()) return;
7994
- const evidence = JSON.parse(readFileSync4(path, "utf8"));
7995
- if (!sameTaskScope(evidence.scope, scope) || evidence.scope.taskInstanceId !== scope.taskInstanceId || digest(evidence.body) !== evidence.bodySha256 || evidence.complete && evidence.bodySha256 !== evidence.source.contentSha256) return;
7996
- return { path, source: evidence.source, complete: evidence.complete, bodySha256: evidence.bodySha256 };
7997
- } catch {
7998
- return;
7999
- }
8000
- }
8001
- function readHostTaskReviewPlanEvidence(scope, env) {
8002
- const plan = readHostTaskAcceptancePlan(scope, env);
8003
- if (!plan) throw new Error("task_acceptance_plan_required_continue_author");
8004
- const planFile = planPath(scope, env);
8005
- const saved = JSON.parse(readFileSync4(planFile, "utf8"));
8006
- const observationFile = join7(hostTaskEventsRoot(env), "producer", `${digest(JSON.stringify(scope))}.json`);
8007
- let observations = [];
8008
- try {
8009
- if (lstatSync4(observationFile).isSymbolicLink()) throw new Error("unsafe_observation_file");
8010
- const record = JSON.parse(readFileSync4(observationFile, "utf8"));
8011
- if (sameTaskScope(record.scope, scope) && JSON.stringify(record.plan) === JSON.stringify(plan)) observations = record.observations;
8012
- } catch {
8013
- }
8014
- return { plan, assignment: readHostTaskUserAssignment(scope, env), source: saved.source, planFile, observationFile: observations.length ? observationFile : void 0, observations };
8015
- }
8016
- async function collectHostTaskPlannedWorkspace(scope, env) {
8017
- const plan = readHostTaskAcceptancePlan(scope, env);
8018
- if (!plan || !explicit(plan.taskPaths)) throw new Error("task_acceptance_plan_required_continue_author");
8019
- const evidence = await collectTaskRevisionEvidence({ cwd: scope.workspace, baseline: plan.baseline, taskPaths: plan.taskPaths });
8020
- if (!evidence.complete) throw new Error("task_revision_incomplete");
8021
- return { scope, baseline: plan.baseline, taskPaths: plan.taskPaths, revision: taskContentRevision(evidence) };
8022
- }
8023
-
8024
- // packages/cli/client/taskReviewTools.ts
8025
- import { createHash as createHash9, randomUUID as randomUUID4 } from "node:crypto";
8026
- function createTaskReviewExecutors(deps) {
8027
- const host = async () => {
8028
- if (!deps.host) throw Object.assign(new Error("Task review requires a registered local host scope and account authorization binding"), { code: "task_review_host_unavailable" });
8029
- await deps.host.authorize();
8030
- return deps.host;
8031
- };
8032
- const argsOf = (call) => {
8033
- const value = call.arguments ?? call.args;
8034
- return typeof value === "string" ? JSON.parse(value) : value;
8035
- };
8036
- return {
8037
- requestTaskReview: async (call) => {
8038
- const h = await host();
8039
- const a = argsOf(call);
8040
- if (!a || typeof a.reviewerAgentKey !== "string" || !a.reviewerAgentKey.trim()) throw new Error("reviewerAgentKey required");
8041
- if (!readHostTaskAcceptancePlan(h.scope, deps.env)) throw new Error("task_plan_required");
8042
- const workspace = await collectHostTaskWorkspace(h.scope, deps.env);
8043
- if (workspace.status !== "ready") throw new Error(`task_review_workspace_unavailable: ${workspace.reason}`);
8044
- const c = readHostTaskAcceptancePlan(h.scope, deps.env) ? await collectHostTaskPlannedWorkspace(h.scope, deps.env) : workspace.context;
8045
- if (c.taskPaths.includes(".")) throw new Error("task_acceptance_plan_required_continue_author");
8046
- if (a.revision !== c.revision) throw new Error("task_review_revision_changed");
8047
- const facts = readHostTaskReviewPlanEvidence(h.scope, deps.env);
8048
- if (!facts.assignment || facts.assignment.source.messageId !== facts.source?.messageId || facts.assignment.source.contentSha256 !== facts.source?.contentSha256) throw new Error("task_assignment_evidence_unavailable");
8049
- const dispatchId = randomUUID4();
8050
- const evidenceRoot = join8(resolveRunsDir(deps.env), "host-review-dispatch");
8051
- mkdirSync5(evidenceRoot, { recursive: true, mode: 448 });
8052
- const evidenceFile = join8(evidenceRoot, `plan-${dispatchId}.json`);
8053
- const checks = facts.plan.commands.map((command) => {
8054
- const fingerprint = `sha256:${createHash9("sha256").update(command.command).digest("hex")}`;
8055
- const index = facts.observations.findLastIndex((o) => o.commandFingerprint === fingerprint && o.revision === c.revision);
8056
- const observation = facts.observations[index];
8057
- return {
8058
- ...command,
8059
- status: observation ? "observed (not a semantic pass)" : "not executed / evidence unavailable",
8060
- ...observation ? { observation, evidenceRef: `${evidenceFile}#/checks/${facts.plan.commands.indexOf(command)}/observation`, originalEvidenceRef: `${facts.observationFile}#/observations/${index}` } : {}
8061
- };
8062
- });
8063
- writeFileSync5(evidenceFile, JSON.stringify({
8064
- scope: h.scope,
8065
- baseline: c.baseline,
8066
- revision: c.revision,
8067
- taskPaths: c.taskPaths,
8068
- planId: facts.plan.planId,
8069
- userSource: facts.source,
8070
- assignment: facts.assignment,
8071
- planFile: facts.planFile,
8072
- checks
8073
- }), { flag: "wx", mode: 384 });
8074
- const task = `Read-only review of worktree ${h.scope.workspace}. Files/scope: ${JSON.stringify(c.taskPaths)}. Revision: ${c.revision}. Host planId: ${facts.plan.planId}. Host evidence: ${evidenceFile}.
8075
- All acceptanceCommands: ${JSON.stringify(checks.map(({ commandId, command, status, evidenceRef }) => ({ commandId, command, status, evidenceRef })))}.
8076
- Read the host-captured user assignment JSON at ${facts.assignment.path} using readFile. Verify SHA-256 of its body equals ${facts.assignment.bodySha256}; original source hash: ${facts.source.contentSha256}. Assignment completeness: ${facts.assignment.complete ? "complete; body hash must also equal original source hash" : "INCOMPLETE credential-filtered projection; original source hash cannot be verified from the redacted body; do not claim full evidence"}; the frozen plan is a model proposal, not proof of task completeness. Verify that the explicit files and ALL planned checks cover the user's assigned scope and that checks meaningfully exercise the required behavior. Inspect host observations in the evidence file (toolCallId, revision, exit/status, workspace before/after). Exit 0, including true, does not prove implementation complete. If coverage/check effectiveness is insufficient, record a concrete finding; if required assignment/evidence is unavailable, return status incomplete with reason. Return one JSON object, no fence: {"schemaVersion":1,"revision":"${c.revision}","status":"completed" or "incomplete","findings":[{"id":"M-1","severity":"MEDIUM","file":"path","line":1,"evidence":"observable evidence or reproduction","impact":"concrete consequence"}]}. Use findings:[] if none. incomplete requires a nonempty reason; completed must not contain reason. No verdict or separate report; put every issue in findings. The host computes approval. Do not invent findings to fill the schema. Do not edit files.`;
8077
- const dispatch = {
8078
- ...c,
8079
- authorExecutionId: h.authorExecutionId,
8080
- dispatchId,
8081
- planId: facts.plan.planId,
8082
- planEvidenceFile: evidenceFile,
8083
- toolCallId: call.id || randomUUID4(),
8084
- target: { agentKey: a.reviewerAgentKey, task }
8085
- };
8086
- await validateHostReviewDispatch(dispatch, deps.env, h.scope.workspace);
8087
- const selectionReason = `Host review dispatch: reviewer ${a.reviewerAgentKey} is fixed by the host task-review seam and was validated as an agent other than the author ${h.authorExecutionId} (review independence), so the reviewer's own model tier is used as-is rather than swapping to a difficulty-matched agent.`;
8088
- const result = await withHostReviewDispatch(dispatch, () => deps.start({ ...call, id: dispatch.toolCallId, name: "startAgentRun", arguments: JSON.stringify({
8089
- agentKey: a.reviewerAgentKey,
8090
- title: "Task review",
8091
- task,
8092
- readOnly: true,
8093
- parentDialogId: h.scope.dialogId,
8094
- cwd: h.scope.workspace,
8095
- selectionReason
8096
- }) }));
8097
- return { ...result, content: JSON.stringify({ dispatchId: dispatch.dispatchId, revision: dispatch.revision, launch: result.content }) };
8098
- },
8099
- recordTaskReviewDecision: async (call) => {
8100
- const h = await host();
8101
- const a = argsOf(call);
8102
- if (!a || !["continue", "fix", "stop"].includes(a.action) || !["dispatchId", "runId", "revision", "rationale"].every((k) => typeof a[k] === "string" && a[k].trim()) || !/^[a-f0-9]{64}$/.test(a.resultSha256) || !Array.isArray(a.findings) || a.findings.some((f) => !f || typeof f.id !== "string" || !f.id.trim() || !["accepted", "fix", "disputed"].includes(f.disposition) || typeof f.rationale !== "string" || !f.rationale.trim())) throw new Error("invalid_task_review_decision");
8103
- if (!/^[A-Za-z0-9._-]{1,128}$/.test(a.runId)) throw new Error("review_decision_binding_mismatch");
8104
- const intentPath = join8(resolveRunsDir(deps.env), "host-review-dispatch", `${a.runId}.json`);
8105
- if (lstatSync5(intentPath).isSymbolicLink() || realpathSync4(intentPath) !== resolve8(intentPath)) throw new Error("unsafe_review_plan_binding");
8106
- const intent = JSON.parse(readFileSync5(intentPath, "utf8"));
8107
- const plan = readHostTaskAcceptancePlan(h.scope, deps.env);
8108
- if (!plan || intent.planId !== plan.planId) throw new Error("review_decision_plan_mismatch");
8109
- await recordHostTaskReviewDecision(h.scope, a, deps.env);
8110
- return { content: JSON.stringify({ recorded: true, action: a.action, dispatchId: a.dispatchId }) };
8111
- }
8112
- };
8113
- }
8114
-
8115
6194
  // packages/core/fetchWebpageShaping.ts
8116
6195
  var FETCH_WEBPAGE_PREVIEW_LENGTH = 1200;
8117
6196
  var FETCH_WEBPAGE_MAX_CONTENT_LENGTH = 12 * 1024;
@@ -8217,7 +6296,7 @@ async function fetchWebpageLocally(args) {
8217
6296
  }
8218
6297
 
8219
6298
  // packages/cli/client/cliServerPlatformToolExecutors.ts
8220
- import { createHash as createHash10 } from "node:crypto";
6299
+ import { createHash as createHash2 } from "node:crypto";
8221
6300
  function buildServerPlatformToolExecutors(args) {
8222
6301
  const postServer = async (path, body, opts) => {
8223
6302
  const serverUrl = resolveRuntimeServerUrl(args.env);
@@ -8354,7 +6433,7 @@ function buildServerPlatformToolExecutors(args) {
8354
6433
  }
8355
6434
  ])
8356
6435
  );
8357
- const shortHash = (value, len) => createHash10("sha256").update(value).digest("hex").slice(0, len);
6436
+ const shortHash = (value, len) => createHash2("sha256").update(value).digest("hex").slice(0, len);
8358
6437
  const localMemoryContext = async () => {
8359
6438
  const openCliLocalRuntimeDb = async () => {
8360
6439
  const { getDefaultCliLocalRuntimeDb: getDefaultCliLocalRuntimeDb2 } = await import("./localRuntimeDb-N7KHDXS2.js");
@@ -8735,8 +6814,8 @@ function buildServerPlatformToolExecutors(args) {
8735
6814
  }
8736
6815
 
8737
6816
  // packages/cli/agentRunArgs.ts
8738
- import { readFileSync as readFileSync6 } from "node:fs";
8739
- import { isAbsolute as isAbsolute2 } from "node:path";
6817
+ import { readFileSync } from "node:fs";
6818
+ import { isAbsolute } from "node:path";
8740
6819
  function readFlagValue(args, flag) {
8741
6820
  const index = args.indexOf(flag);
8742
6821
  if (index < 0) return void 0;
@@ -8877,7 +6956,7 @@ function parseAgentRunArgs(args, options = {}) {
8877
6956
  const agentKey = rawAgentKey ? resolveCliAgentKeyInput(rawAgentKey) : void 0;
8878
6957
  const explicitMsg = readFlagValue(args, "--msg");
8879
6958
  const msgFile = readFlagValue(args, "--msg-file");
8880
- const fileMessage = msgFile ? (options.readTextFile ?? ((path) => readFileSync6(path, "utf8")))(msgFile) : void 0;
6959
+ const fileMessage = msgFile ? (options.readTextFile ?? ((path) => readFileSync(path, "utf8")))(msgFile) : void 0;
8881
6960
  const rawMessage = explicitMsg ?? fileMessage ?? positional.slice(isNoLoginRunShorthand ? 0 : 1).join(" ");
8882
6961
  if (!agentKey || !rawMessage.trim()) return null;
8883
6962
  const message = rawMessage.trim();
@@ -8938,7 +7017,7 @@ function parseAgentRunArgs(args, options = {}) {
8938
7017
  if (!rawInstaboxArtifactDir) {
8939
7018
  throw new Error("--runtime-key instabox \u5FC5\u987B\u6307\u5B9A --instabox-artifact-dir <\u7EDD\u5BF9\u8DEF\u5F84>");
8940
7019
  }
8941
- if (!isAbsolute2(rawInstaboxArtifactDir) || rawInstaboxArtifactDir.includes("\0") || rawInstaboxArtifactDir.split("/").includes("..")) {
7020
+ if (!isAbsolute(rawInstaboxArtifactDir) || rawInstaboxArtifactDir.includes("\0") || rawInstaboxArtifactDir.split("/").includes("..")) {
8942
7021
  throw new Error(`--instabox-artifact-dir \u5FC5\u987B\u4E3A\u5408\u6CD5\u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u4E14\u4E0D\u80FD\u5305\u542B .. \u6216\u7A7A\u5B57\u7B26: "${rawInstaboxArtifactDir}"`);
8943
7022
  }
8944
7023
  if (rawInstaboxWorkspace === "snapshot" && !rawInstaboxManifest) {
@@ -9043,8 +7122,8 @@ function parseAgentRunArgs(args, options = {}) {
9043
7122
  }
9044
7123
 
9045
7124
  // packages/cli/client/cliAgentRunToolExecutors.ts
9046
- import { join as join10, resolve as resolve11 } from "node:path";
9047
- import { randomUUID as randomUUID5 } from "node:crypto";
7125
+ import { join as join3, resolve as resolve3 } from "node:path";
7126
+ import { randomUUID as randomUUID3 } from "node:crypto";
9048
7127
  import * as nodeFs2 from "node:fs";
9049
7128
 
9050
7129
  // packages/agent-runtime/waitForRunTerminal.ts
@@ -9107,7 +7186,7 @@ function waitForRunTerminal(args) {
9107
7186
  }
9108
7187
 
9109
7188
  // packages/cli/client/cliAgentRunToolExecutors.ts
9110
- import { existsSync as existsSync2, readFileSync as readFileSync9 } from "node:fs";
7189
+ import { existsSync as existsSync2, readFileSync as readFileSync4 } from "node:fs";
9111
7190
 
9112
7191
  // packages/cli/client/agentRunSnapshot.ts
9113
7192
  function readString(value) {
@@ -9353,24 +7432,24 @@ function deriveAgentRunTodoStatus(input) {
9353
7432
  }
9354
7433
 
9355
7434
  // packages/cli/client/fileSystemStores.ts
9356
- import { existsSync, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync6 } from "node:fs";
7435
+ import { existsSync, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
9357
7436
  import { homedir as nodeHomedir } from "node:os";
9358
- import { dirname as dirname4, join as join9 } from "node:path";
7437
+ import { dirname as dirname2, join as join2 } from "node:path";
9359
7438
  var nodeFs = {
9360
- mkdirSync: mkdirSync6,
9361
- writeFileSync: writeFileSync6,
9362
- readFileSync: readFileSync7,
7439
+ mkdirSync,
7440
+ writeFileSync,
7441
+ readFileSync: readFileSync2,
9363
7442
  existsSync
9364
7443
  };
9365
- function resolveNoloHome(env, homedir3) {
7444
+ function resolveNoloHome(env, homedir2) {
9366
7445
  const custom = env?.NOLO_HOME;
9367
7446
  if (custom && custom.trim()) return custom.trim();
9368
7447
  const ambient = process.env.NOLO_HOME?.trim();
9369
7448
  if (ambient) return ambient;
9370
- return join9(homedir3(), ".nolo");
7449
+ return join2(homedir2(), ".nolo");
9371
7450
  }
9372
- function ensureDir(dir2, fs) {
9373
- fs.mkdirSync(dir2, { recursive: true });
7451
+ function ensureDir(dir, fs) {
7452
+ fs.mkdirSync(dir, { recursive: true });
9374
7453
  }
9375
7454
  function readJson(path, fs) {
9376
7455
  if (!fs.existsSync(path)) return void 0;
@@ -9386,11 +7465,11 @@ function writeJson(path, data, fs) {
9386
7465
  }
9387
7466
  function createFileSystemTodoStore(opts = {}) {
9388
7467
  const env = opts.env ?? process.env;
9389
- const homedir3 = opts.homedir ?? nodeHomedir;
7468
+ const homedir2 = opts.homedir ?? nodeHomedir;
9390
7469
  const fs = opts.fs ?? nodeFs;
9391
- const noloHome = resolveNoloHome(env, homedir3);
9392
- const filePath = opts.filePath ?? join9(noloHome, "agent_run_todos.json");
9393
- const oldFilePath = join9(noloHome, "todos.json");
7470
+ const noloHome = resolveNoloHome(env, homedir2);
7471
+ const filePath = opts.filePath ?? join2(noloHome, "agent_run_todos.json");
7472
+ const oldFilePath = join2(noloHome, "todos.json");
9394
7473
  const loadMap = () => {
9395
7474
  if (!opts.filePath && !fs.existsSync(filePath) && fs.existsSync(oldFilePath)) {
9396
7475
  const oldData = readJson(oldFilePath, fs);
@@ -9415,7 +7494,7 @@ function createFileSystemTodoStore(opts = {}) {
9415
7494
  }
9416
7495
  }
9417
7496
  }
9418
- ensureDir(dirname4(filePath), fs);
7497
+ ensureDir(dirname2(filePath), fs);
9419
7498
  writeJson(filePath, { todos: [...map2.values()] }, fs);
9420
7499
  return map2;
9421
7500
  }
@@ -9429,7 +7508,7 @@ function createFileSystemTodoStore(opts = {}) {
9429
7508
  return map;
9430
7509
  };
9431
7510
  const persist = (map) => {
9432
- ensureDir(dirname4(filePath), fs);
7511
+ ensureDir(dirname2(filePath), fs);
9433
7512
  writeJson(filePath, { todos: [...map.values()] }, fs);
9434
7513
  };
9435
7514
  return {
@@ -9460,13 +7539,13 @@ function createFileSystemTodoStore(opts = {}) {
9460
7539
  }
9461
7540
 
9462
7541
  // packages/cli/client/instaboxRunConfig.ts
9463
- import { lstatSync as lstatSync6, readFileSync as readFileSync8, realpathSync as realpathSync5 } from "node:fs";
9464
- import { isAbsolute as isAbsolute3, normalize, resolve as resolve10 } from "node:path";
7542
+ import { lstatSync, readFileSync as readFileSync3, realpathSync } from "node:fs";
7543
+ import { isAbsolute as isAbsolute2, normalize, resolve as resolve2 } from "node:path";
9465
7544
 
9466
7545
  // packages/cli/client/localInstaboxWorkspaceDelivery.ts
9467
- import { constants as constants2 } from "node:fs";
9468
- import { open as open2, realpath } from "node:fs/promises";
9469
- import { createHash as createHash11 } from "node:crypto";
7546
+ import { constants } from "node:fs";
7547
+ import { open, realpath } from "node:fs/promises";
7548
+ import { createHash as createHash3 } from "node:crypto";
9470
7549
 
9471
7550
  // packages/agent-runtime/instaboxBackend.ts
9472
7551
  var INSTABOX_BACKEND_ID = "instabox";
@@ -9640,7 +7719,7 @@ var InstaboxBackend = class {
9640
7719
  ...rawBody === void 0 ? {} : { body: rawBody }
9641
7720
  });
9642
7721
  });
9643
- this.#sleep = options.sleepImpl ?? ((ms) => new Promise((resolve15) => setTimeout(resolve15, ms)));
7722
+ this.#sleep = options.sleepImpl ?? ((ms) => new Promise((resolve7) => setTimeout(resolve7, ms)));
9644
7723
  this.#machineTimeoutSeconds = options.machineTimeoutSeconds ?? 1800;
9645
7724
  this.#createTimeoutMs = options.createTimeoutMs ?? 18e4;
9646
7725
  this.#deleteTimeoutMs = options.deleteTimeoutMs ?? 12e4;
@@ -9669,15 +7748,15 @@ var InstaboxBackend = class {
9669
7748
  * 成功时刻(不采信 202 响应时间,那是「已受理」不是「可用」)。
9670
7749
  */
9671
7750
  async prepare(ticket) {
9672
- const context2 = {};
7751
+ const context = {};
9673
7752
  try {
9674
- return await this.#prepare(ticket, context2);
7753
+ return await this.#prepare(ticket, context);
9675
7754
  } catch (error) {
9676
- if (context2.record) throw this.#withRecovery(error, context2.record);
7755
+ if (context.record) throw this.#withRecovery(error, context.record);
9677
7756
  throw error;
9678
7757
  }
9679
7758
  }
9680
- async #prepare(ticket, context2) {
7759
+ async #prepare(ticket, context) {
9681
7760
  if (ticket.version !== 1 || !ticket.ticketId || !ticket.grantId) {
9682
7761
  throw new InstaboxBackendError("instabox_invalid_ticket");
9683
7762
  }
@@ -9711,7 +7790,7 @@ var InstaboxBackend = class {
9711
7790
  const expectedSpec = this.#freeOrgObservation.allowedSpecs.find(
9712
7791
  (s) => s.vcpus === plan.vcpus && s.memMiB === plan.memMiB
9713
7792
  );
9714
- context2.record = {
7793
+ context.record = {
9715
7794
  version: 1,
9716
7795
  recordId: crypto.randomUUID(),
9717
7796
  revision: 0,
@@ -9732,7 +7811,7 @@ var InstaboxBackend = class {
9732
7811
  },
9733
7812
  stop: { intent: false, accepted: false }
9734
7813
  };
9735
- await this.#saveRecovery(context2.record);
7814
+ await this.#saveRecovery(context.record);
9736
7815
  }
9737
7816
  const created = await this.#call({
9738
7817
  method: "POST",
@@ -9740,11 +7819,11 @@ var InstaboxBackend = class {
9740
7819
  idempotencyKey: createKey2,
9741
7820
  body: createBody
9742
7821
  });
9743
- if (context2.record) {
9744
- context2.record.machineId = readString2(asRecord(created.payload)?.machineId) ?? void 0;
9745
- context2.record.createOperationId = readString2(asRecord(created.payload)?.id) ?? void 0;
9746
- if (isSuccess(created.status)) context2.record.create.state = "responded";
9747
- await this.#saveRecovery(context2.record);
7822
+ if (context.record) {
7823
+ context.record.machineId = readString2(asRecord(created.payload)?.machineId) ?? void 0;
7824
+ context.record.createOperationId = readString2(asRecord(created.payload)?.id) ?? void 0;
7825
+ if (isSuccess(created.status)) context.record.create.state = "responded";
7826
+ await this.#saveRecovery(context.record);
9748
7827
  }
9749
7828
  if (!isSuccess(created.status)) {
9750
7829
  const upstreamCode = extractInstaboxErrorCode(created.payload);
@@ -9864,7 +7943,7 @@ var InstaboxBackend = class {
9864
7943
  const usageBaselineRunningMs = baseline === null ? null : Math.round(baseline.runningSeconds * 1e3);
9865
7944
  const leaseId = `${machineId}:${ticket.ticketId}`;
9866
7945
  this.#leases.set(leaseId, {
9867
- recovery: context2.record,
7946
+ recovery: context.record,
9868
7947
  machineId,
9869
7948
  ticketId: ticket.ticketId,
9870
7949
  grantId: ticket.grantId,
@@ -9886,7 +7965,7 @@ var InstaboxBackend = class {
9886
7965
  readableRoots: [...ticket.filesystem.readableRoots],
9887
7966
  writableRoots: [...ticket.filesystem.writableRoots],
9888
7967
  metadata: {
9889
- ...context2.record ? { recoveryRecordId: context2.record.recordId } : {},
7968
+ ...context.record ? { recoveryRecordId: context.record.recordId } : {},
9890
7969
  machineId,
9891
7970
  machineName,
9892
7971
  templateId: this.#templateId,
@@ -10158,8 +8237,8 @@ var InstaboxBackend = class {
10158
8237
  try {
10159
8238
  await Promise.race([
10160
8239
  this.#sleep(Math.min(this.#pollIntervalMs, remaining())),
10161
- new Promise((resolve15) => {
10162
- timer = setTimeout(resolve15, remaining());
8240
+ new Promise((resolve7) => {
8241
+ timer = setTimeout(resolve7, remaining());
10163
8242
  })
10164
8243
  ]);
10165
8244
  } finally {
@@ -10461,8 +8540,8 @@ var InstaboxBackend = class {
10461
8540
  try {
10462
8541
  return await Promise.race([
10463
8542
  this.#call({ ...args, timeoutMs: void 0 }),
10464
- new Promise((resolve15) => {
10465
- timer = setTimeout(() => resolve15({ status: 0, payload: null, transportError: "Timeout" }), args.timeoutMs);
8543
+ new Promise((resolve7) => {
8544
+ timer = setTimeout(() => resolve7({ status: 0, payload: null, transportError: "Timeout" }), args.timeoutMs);
10466
8545
  })
10467
8546
  ]);
10468
8547
  } finally {
@@ -10600,7 +8679,7 @@ function extractInstaboxErrorCode(payload) {
10600
8679
 
10601
8680
  // packages/cli/client/localInstaboxWorkspaceDelivery.ts
10602
8681
  var SNAPSHOT_LIMITS = { files: 256, fileBytes: 8 * 1024 * 1024, totalBytes: 32 * 1024 * 1024, chunkBytes: 384 * 1024 };
10603
- var hash = (bytes) => createHash11("sha256").update(bytes).digest("hex");
8682
+ var hash = (bytes) => createHash3("sha256").update(bytes).digest("hex");
10604
8683
  var fail = (code) => {
10605
8684
  throw new Error(`instabox_workspace_delivery:${code}`);
10606
8685
  };
@@ -10645,10 +8724,10 @@ function validateInstaboxWorkspaceSelection(selection) {
10645
8724
  async function readApprovedFiles(m) {
10646
8725
  if (process.platform !== "linux") fail("secure_host_reader_unavailable");
10647
8726
  if (await realpath(m.hostRoot) !== m.hostRoot) fail("host_root_not_canonical");
10648
- let root = await open2("/", constants2.O_RDONLY | constants2.O_DIRECTORY | constants2.O_NOFOLLOW);
8727
+ let root = await open("/", constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
10649
8728
  try {
10650
8729
  for (const part of m.hostRoot.split("/").filter(Boolean)) {
10651
- const next = await open2(`/proc/self/fd/${root.fd}/${part}`, constants2.O_RDONLY | constants2.O_DIRECTORY | constants2.O_NOFOLLOW);
8730
+ const next = await open(`/proc/self/fd/${root.fd}/${part}`, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
10652
8731
  await root.close();
10653
8732
  root = next;
10654
8733
  }
@@ -10664,30 +8743,30 @@ async function readApprovedFiles(m) {
10664
8743
  try {
10665
8744
  const parts = entry.path.split("/");
10666
8745
  for (const part of parts.slice(0, -1)) {
10667
- const dir2 = await open2(`/proc/self/fd/${parent.fd}/${part}`, constants2.O_RDONLY | constants2.O_DIRECTORY | constants2.O_NOFOLLOW);
10668
- dirs.push(dir2);
10669
- parent = dir2;
8746
+ const dir = await open(`/proc/self/fd/${parent.fd}/${part}`, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
8747
+ dirs.push(dir);
8748
+ parent = dir;
10670
8749
  }
10671
- const file2 = await open2(`/proc/self/fd/${parent.fd}/${parts.at(-1)}`, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
8750
+ const file = await open(`/proc/self/fd/${parent.fd}/${parts.at(-1)}`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
10672
8751
  try {
10673
- const before = await file2.stat();
8752
+ const before = await file.stat();
10674
8753
  if (!before.isFile() || before.nlink !== 1 || before.size !== entry.sizeBytes) fail("file_metadata_mismatch");
10675
8754
  const bytes = Buffer.alloc(entry.sizeBytes);
10676
8755
  let offset = 0;
10677
8756
  while (offset < bytes.length) {
10678
- const { bytesRead } = await file2.read(bytes, offset, bytes.length - offset, offset);
8757
+ const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
10679
8758
  if (!bytesRead) fail("file_changed");
10680
8759
  offset += bytesRead;
10681
8760
  }
10682
- const after = await file2.stat();
8761
+ const after = await file.stat();
10683
8762
  if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs || hash(bytes) !== entry.sha256) fail("file_hash_mismatch");
10684
8763
  if (/-----BEGIN [A-Z ]*PRIVATE KEY-----|(?:api[_-]?key|access[_-]?token|password)\s*[:=]\s*["']?[A-Za-z0-9_+\/-]{12,}/i.test(bytes.toString("utf8"))) fail("sensitive_content");
10685
8764
  result.push(bytes);
10686
8765
  } finally {
10687
- await file2.close();
8766
+ await file.close();
10688
8767
  }
10689
8768
  } finally {
10690
- for (const dir2 of dirs.reverse()) await dir2.close();
8769
+ for (const dir of dirs.reverse()) await dir.close();
10691
8770
  }
10692
8771
  }
10693
8772
  } finally {
@@ -10822,14 +8901,14 @@ function resolveInstaboxRunConfigPath(options) {
10822
8901
  fail2("missing_path", `\u73AF\u5883\u53D8\u91CF ${INSTABOX_RUN_CONFIG_ENV} \u672A\u8BBE\u7F6E\u6216\u4E3A\u7A7A`);
10823
8902
  }
10824
8903
  const runsDir = options?.runsDir ?? resolveRunsDir(env);
10825
- const normalizedRunsDir = normalize(resolve10(runsDir));
10826
- const resolvedTarget = isAbsolute3(explicitPath) ? normalize(explicitPath) : normalize(resolve10(normalizedRunsDir, explicitPath));
8904
+ const normalizedRunsDir = normalize(resolve2(runsDir));
8905
+ const resolvedTarget = isAbsolute2(explicitPath) ? normalize(explicitPath) : normalize(resolve2(normalizedRunsDir, explicitPath));
10827
8906
  if (resolvedTarget !== normalizedRunsDir && !resolvedTarget.startsWith(normalizedRunsDir.endsWith("/") ? normalizedRunsDir : `${normalizedRunsDir}/`)) {
10828
8907
  fail2("path_traversal", `\u914D\u7F6E\u8DEF\u5F84 "${explicitPath}" \u8D8A\u51FA\u4E86\u9650\u5B9A\u7684 runs \u76EE\u5F55 "${normalizedRunsDir}"`);
10829
8908
  }
10830
8909
  let stats;
10831
8910
  try {
10832
- stats = lstatSync6(resolvedTarget);
8911
+ stats = lstatSync(resolvedTarget);
10833
8912
  } catch (err) {
10834
8913
  fail2("file_unreadable", `\u914D\u7F6E\u6587\u4EF6\u4E0D\u53EF\u8BFB\u6216\u4E0D\u5B58\u5728: ${resolvedTarget}`);
10835
8914
  }
@@ -10843,8 +8922,8 @@ function resolveInstaboxRunConfigPath(options) {
10843
8922
  fail2("file_too_large", `\u914D\u7F6E\u6587\u4EF6\u5927\u5C0F (${stats.size} \u5B57\u8282) \u8D85\u8FC7\u4E0A\u9650 (${INSTABOX_RUN_CONFIG_MAX_BYTES} \u5B57\u8282)`);
10844
8923
  }
10845
8924
  try {
10846
- const realTarget = realpathSync5(resolvedTarget);
10847
- const realRuns = realpathSync5(normalizedRunsDir);
8925
+ const realTarget = realpathSync(resolvedTarget);
8926
+ const realRuns = realpathSync(normalizedRunsDir);
10848
8927
  if (realTarget !== realRuns && !realTarget.startsWith(realRuns.endsWith("/") ? realRuns : `${realRuns}/`)) {
10849
8928
  fail2("symlink_traversal", `\u914D\u7F6E\u771F\u5B9E\u8DEF\u5F84 "${realTarget}" \u8D8A\u51FA runs \u771F\u5B9E\u76EE\u5F55 "${realRuns}"`);
10850
8929
  }
@@ -10856,7 +8935,7 @@ function loadInstaboxRunConfig(options) {
10856
8935
  const { resolvedPath } = resolveInstaboxRunConfigPath(options);
10857
8936
  let rawText;
10858
8937
  try {
10859
- rawText = readFileSync8(resolvedPath, "utf8");
8938
+ rawText = readFileSync3(resolvedPath, "utf8");
10860
8939
  } catch (err) {
10861
8940
  fail2("file_read_failed", `\u8BFB\u53D6\u914D\u7F6E\u6587\u4EF6\u5931\u8D25: ${err instanceof Error ? err.message : String(err)}`);
10862
8941
  }
@@ -10905,7 +8984,7 @@ function loadInstaboxRunConfig(options) {
10905
8984
  if (!artifactRootRaw) {
10906
8985
  fail2("missing_artifact_root", "artifactRoot (artifact\u76EE\u7684\u76EE\u5F55) \u5FC5\u987B\u4E3A\u975E\u7A7A\u5B57\u7B26\u4E32\uFF0C\u672A\u914D\u7F6E\u6216\u9ED8\u8BA4\u5747\u88AB\u62D2\u7EDD");
10907
8986
  }
10908
- if (!isAbsolute3(artifactRootRaw) || artifactRootRaw.includes("\0") || artifactRootRaw.split("/").includes("..")) {
8987
+ if (!isAbsolute2(artifactRootRaw) || artifactRootRaw.includes("\0") || artifactRootRaw.split("/").includes("..")) {
10909
8988
  fail2("invalid_artifact_root", `artifactRoot \u5FC5\u987B\u4E3A\u5408\u6CD5\u7EDD\u5BF9\u8DEF\u5F84: "${artifactRootRaw}"`);
10910
8989
  }
10911
8990
  const artifactRoot = normalize(artifactRootRaw);
@@ -11138,7 +9217,7 @@ var parseCallArgs = (call) => {
11138
9217
  return {};
11139
9218
  }
11140
9219
  };
11141
- var resolveFs = (deps) => deps.fs ?? { existsSync: existsSync2, readFileSync: readFileSync9 };
9220
+ var resolveFs = (deps) => deps.fs ?? { existsSync: existsSync2, readFileSync: readFileSync4 };
11142
9221
  var probeRunCwd = (deps) => {
11143
9222
  const fs = deps.fs;
11144
9223
  const stat = fs?.statSync ?? nodeFs2.statSync;
@@ -11312,13 +9391,13 @@ function createCliStartAgentRunExecutor(deps = {}) {
11312
9391
  if (previousRecord && previousCacheHitRatio === void 0 && previousRecord.resultFile) {
11313
9392
  try {
11314
9393
  const fs = deps.fs ?? nodeFs2;
11315
- const runsDir = resolve11(resolveRunsDir(deps.env, deps.homedir));
11316
- const expected = resolve11(runsDir, `${previousRecord.runId}.result.md`);
11317
- if (previousRecord.runId.includes("/") || previousRecord.runId.includes("\\") || resolve11(previousRecord.resultFile) !== expected || !fs.realpathSync || !fs.lstatSync) throw new Error("Unverified result path");
9394
+ const runsDir = resolve3(resolveRunsDir(deps.env, deps.homedir));
9395
+ const expected = resolve3(runsDir, `${previousRecord.runId}.result.md`);
9396
+ if (previousRecord.runId.includes("/") || previousRecord.runId.includes("\\") || resolve3(previousRecord.resultFile) !== expected || !fs.realpathSync || !fs.lstatSync) throw new Error("Unverified result path");
11318
9397
  const stat = fs.lstatSync(expected);
11319
9398
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Non-regular result file");
11320
9399
  const canonicalDir = String(fs.realpathSync(runsDir));
11321
- if (String(fs.realpathSync(expected)) !== join10(canonicalDir, `${previousRecord.runId}.result.md`)) throw new Error("Result escapes runs directory");
9400
+ if (String(fs.realpathSync(expected)) !== join3(canonicalDir, `${previousRecord.runId}.result.md`)) throw new Error("Result escapes runs directory");
11322
9401
  if ((deps.platform ?? process.platform) !== "linux" || !fs.fstatSync || !fs.readSync || !fs.closeSync || !nodeFs2.constants.O_NOFOLLOW || !nodeFs2.constants.O_DIRECTORY) throw new Error("FD proof unavailable");
11323
9402
  let dirFd;
11324
9403
  let resultFd;
@@ -11327,7 +9406,7 @@ function createCliStartAgentRunExecutor(deps = {}) {
11327
9406
  dirFd = fs.openSync(runsDir, nodeFs2.constants.O_RDONLY | nodeFs2.constants.O_DIRECTORY | nodeFs2.constants.O_NOFOLLOW);
11328
9407
  if (!fs.fstatSync(dirFd).isDirectory() || String(fs.realpathSync(`/proc/self/fd/${dirFd}`)) !== canonicalDir) throw new Error("Unverified directory fd");
11329
9408
  resultFd = fs.openSync(`/proc/self/fd/${dirFd}/${previousRecord.runId}.result.md`, nodeFs2.constants.O_RDONLY | nodeFs2.constants.O_NOFOLLOW | nodeFs2.constants.O_NONBLOCK);
11330
- if (!fs.fstatSync(resultFd).isFile() || String(fs.realpathSync(`/proc/self/fd/${resultFd}`)) !== join10(canonicalDir, `${previousRecord.runId}.result.md`)) throw new Error("Unverified result fd");
9409
+ if (!fs.fstatSync(resultFd).isFile() || String(fs.realpathSync(`/proc/self/fd/${resultFd}`)) !== join3(canonicalDir, `${previousRecord.runId}.result.md`)) throw new Error("Unverified result fd");
11331
9410
  const bytes = Buffer.alloc(16 * 1024);
11332
9411
  let offset = 0;
11333
9412
  while (offset < bytes.length) {
@@ -11432,10 +9511,10 @@ function createCliStartAgentRunExecutor(deps = {}) {
11432
9511
  const manifest = typeof args.instaboxManifest === "string" ? args.instaboxManifest.trim() : "";
11433
9512
  if (workspace === "snapshot" && !manifest) throw new Error("instaboxWorkspace=snapshot \u5FC5\u987B\u63D0\u4F9B instaboxManifest");
11434
9513
  if (workspace === "empty" && args.instaboxManifest !== void 0) throw new Error("instaboxWorkspace=empty \u4E0D\u5F97\u63D0\u4F9B instaboxManifest");
11435
- const artifactDir = args.instaboxArtifactDir ?? join10(
9514
+ const artifactDir = args.instaboxArtifactDir ?? join3(
11436
9515
  resolveRunsDir(deps.env, deps.homedir),
11437
9516
  "instabox-artifacts",
11438
- randomUUID5()
9517
+ randomUUID3()
11439
9518
  );
11440
9519
  if (typeof artifactDir !== "string" || !artifactDir.startsWith("/") || artifactDir.includes("\0") || artifactDir.split("/").includes("..")) {
11441
9520
  throw new Error("instaboxArtifactDir \u5FC5\u987B\u4E3A\u5408\u6CD5\u7EDD\u5BF9\u8DEF\u5F84\uFF0C\u4E0D\u80FD\u5305\u542B .. \u6216\u7A7A\u5B57\u7B26");
@@ -11483,13 +9562,6 @@ function createCliStartAgentRunExecutor(deps = {}) {
11483
9562
  allowCredentialConcurrency: effectiveAllowCredentialConcurrency
11484
9563
  });
11485
9564
  const dodCommands = Array.isArray(args.dodCommands) ? args.dodCommands.filter((c) => typeof c === "string" && c.trim().length > 0).map((c) => c.trim()) : typeof args.dod === "string" && args.dod.trim().length > 0 ? [args.dod.trim()] : Array.isArray(args.dod) ? args.dod.filter((c) => typeof c === "string" && c.trim().length > 0).map((c) => c.trim()) : void 0;
11486
- const candidateReview = deps.reviewDispatchContext ?? currentHostReviewDispatch();
11487
- const reviewContext = matchesHostReviewDispatch(candidateReview, call, args) ? candidateReview : void 0;
11488
- if (reviewContext) {
11489
- if (continueDialogId || args.readOnly !== true) throw new Error("Typed review requires a fresh readOnly run");
11490
- await validateHostReviewDispatch(reviewContext, deps.env ?? process.env, requestedCwd ?? deps.cwd ?? process.cwd());
11491
- consumeHostReviewDispatch(reviewContext, deps.env ?? process.env);
11492
- }
11493
9565
  const childPolicy = parseAgentRunArgs(rawArgs, { readTextFile: () => message });
11494
9566
  const { runId, batchId: resolvedBatchId } = await spawnLocalBackgroundRun(
11495
9567
  {
@@ -11529,24 +9601,6 @@ function createCliStartAgentRunExecutor(deps = {}) {
11529
9601
  },
11530
9602
  { ...deps, shellApprovalHost: deps.shellApprovalHostForAgent ? await deps.shellApprovalHostForAgent(agentKey) : deps.shellApprovalHost }
11531
9603
  );
11532
- if (reviewContext) {
11533
- try {
11534
- await bindHostReviewRun(reviewContext, runId, deps.env ?? process.env);
11535
- } catch (error) {
11536
- const record = readRunRecord(runId, deps);
11537
- let stopped = false;
11538
- try {
11539
- if (record) stopped = await (deps.terminateRunProcess ?? terminateRunProcess)(record, "SIGTERM", deps);
11540
- } catch {
11541
- }
11542
- if (stopped) finalizeRunRecord(runId, { status: "killed", note: "Host review binding failed; newly created run cancelled" }, deps);
11543
- else {
11544
- const latest = readRunRecord(runId, deps);
11545
- if (latest) writeRunRecord({ ...latest, note: "Host review binding failed; cancellation unconfirmed" }, deps);
11546
- }
11547
- throw new Error(`Host review binding failed for ${runId}; cancellation=${stopped ? "confirmed" : "unconfirmed"}: ${error instanceof Error ? error.message : String(error)}`);
11548
- }
11549
- }
11550
9604
  const displayName = resolveRunLabel({ agentName, agentKey, runId });
11551
9605
  const labels = agentRunCardLabels();
11552
9606
  const taskPreview = typeof args.task === "string" ? args.task.replace(/\s+/g, " ").trim().slice(0, TASK_PREVIEW_MAX) : "";
@@ -11934,7 +9988,7 @@ ${entry.text}`).join("\n\n");
11934
9988
  const transferred = new Set(remainingEntries.map((entry) => entry.id));
11935
9989
  const current = _readQueueEntriesLocked(queuePath, fs);
11936
9990
  if (typeof fs.renameSync !== "function") throw new Error("atomic queue replacement requires renameSync");
11937
- const pendingQueue = `${queuePath}.${randomUUID5()}.tmp`;
9991
+ const pendingQueue = `${queuePath}.${randomUUID3()}.tmp`;
11938
9992
  fs.writeFileSync(pendingQueue, serializeQueueEntries(current.filter((entry) => !transferred.has(entry.id))), { encoding: "utf8", flag: "wx" });
11939
9993
  fs.renameSync(pendingQueue, queuePath);
11940
9994
  return result;
@@ -12225,7 +10279,8 @@ function buildCliWorkspaceToolExecutors(args) {
12225
10279
  return buildNoloWorkspaceCliToolExecutors({
12226
10280
  cliEntrypoint: args.cliEntrypoint ?? process.argv[1] ?? "",
12227
10281
  env: args.env,
12228
- metadataKind: "cliWorkspaceTool"
10282
+ metadataKind: "cliWorkspaceTool",
10283
+ planningCaller: args.planningCaller
12229
10284
  });
12230
10285
  }
12231
10286
  function buildLocalToolExecutors(args) {
@@ -12249,6 +10304,7 @@ function buildLocalToolExecutors(args) {
12249
10304
  agentKey: args.agentKey
12250
10305
  }),
12251
10306
  ...buildCliWorkspaceToolExecutors({
10307
+ planningCaller: args.planningCaller,
12252
10308
  env: args.env,
12253
10309
  cliEntrypoint: args.cliEntrypoint
12254
10310
  }),
@@ -12392,18 +10448,8 @@ function buildLocalToolExecutors(args) {
12392
10448
  metadata: { uiAskChoice: true }
12393
10449
  };
12394
10450
  },
12395
- ...createTaskReviewExecutors({
12396
- env: args.env,
12397
- host: args.taskReviewHost,
12398
- start: createCliStartAgentRunExecutor({
12399
- shellApprovalHostForAgent: args.shellApprovalHostForAgent,
12400
- ...pickAgentRunResolverDeps(args),
12401
- env: args.env,
12402
- cliEntrypoint: args.cliEntrypoint,
12403
- cwd: args.workspaceRoot,
12404
- currentAgentKey: args.agentKey
12405
- })
12406
- }),
10451
+ // typed review executor(requestTaskReview / recordTaskReviewDecision)已移除;
10452
+ // 这两个工具随之从工具面消失(2026-11-15 owner 决定放弃 typed review)。
12407
10453
  // agent-orchestration 能力包:startAgentRun / controlAgentRun 本地 --bg 执行器
12408
10454
  // (复用 ~/.nolo/runs/ 注册表,MED-1 修复)。
12409
10455
  startAgentRun: createCliStartAgentRunExecutor({
@@ -12414,7 +10460,6 @@ function buildLocalToolExecutors(args) {
12414
10460
  env: args.env,
12415
10461
  cliEntrypoint: args.cliEntrypoint,
12416
10462
  cwd: args.workspaceRoot,
12417
- reviewDispatchContext: args.reviewDispatchContext,
12418
10463
  currentAgentKey: args.agentKey
12419
10464
  }),
12420
10465
  controlAgentRun: createCliControlAgentRunExecutor({
@@ -12601,7 +10646,7 @@ function createOAuthApiKeyRefResolver(options = {}) {
12601
10646
 
12602
10647
  // packages/agent-runtime/localSandboxWorkload.ts
12603
10648
  import { existsSync as existsSync3 } from "node:fs";
12604
- import { resolve as resolve13 } from "node:path";
10649
+ import { resolve as resolve5 } from "node:path";
12605
10650
 
12606
10651
  // packages/agent-runtime/executionChannel.ts
12607
10652
  var EXECUTION_SHELL_TOOL = "execShell";
@@ -12680,19 +10725,19 @@ function createExecutionChannel(args) {
12680
10725
 
12681
10726
  // packages/agent-runtime/linuxBubblewrapBackend.ts
12682
10727
  import {
12683
- closeSync as closeSync2,
10728
+ closeSync,
12684
10729
  constants as fsConstants,
12685
10730
  fstatSync,
12686
10731
  mkdtempSync,
12687
- openSync as openSync2,
12688
- readlinkSync as readlinkSync2,
10732
+ openSync,
10733
+ readlinkSync,
12689
10734
  rmdirSync,
12690
10735
  unlinkSync,
12691
10736
  writeSync
12692
10737
  } from "node:fs";
12693
10738
  import { access } from "node:fs/promises";
12694
10739
  import { tmpdir } from "node:os";
12695
- import { isAbsolute as isAbsolute4, join as join11, relative as relative4, resolve as resolve12 } from "node:path";
10740
+ import { isAbsolute as isAbsolute3, join as join4, relative, resolve as resolve4 } from "node:path";
12696
10741
 
12697
10742
  // packages/agent-runtime/linuxSandboxSeccomp.ts
12698
10743
  var AUDIT_ARCH_X86_64 = 3221225534;
@@ -12785,45 +10830,45 @@ var MAX_OUTPUT_BYTES = 1024 * 1024;
12785
10830
  var PSEUDO_FS = ["/proc", "/sys", "/dev", "/run"];
12786
10831
  var SANDBOX_MOUNTS = ["/", "/usr", "/bin", "/lib", "/lib64", "/tmp"];
12787
10832
  var inside = (parent, child) => {
12788
- const rel = relative4(parent, child);
12789
- return rel === "" || rel !== ".." && !rel.startsWith("../") && !isAbsolute4(rel);
10833
+ const rel = relative(parent, child);
10834
+ return rel === "" || rel !== ".." && !rel.startsWith("../") && !isAbsolute3(rel);
12790
10835
  };
12791
10836
  function openRootHandle(path) {
12792
- if (typeof path !== "string" || !isAbsolute4(path) || path.includes("\0")) {
10837
+ if (typeof path !== "string" || !isAbsolute3(path) || path.includes("\0")) {
12793
10838
  throw new Error("Sandbox root must be absolute");
12794
10839
  }
12795
- const expected = resolve12(path);
10840
+ const expected = resolve4(path);
12796
10841
  if (SANDBOX_MOUNTS.includes(expected) || PSEUDO_FS.some((reserved) => inside(reserved, expected))) {
12797
10842
  throw new Error("Sandbox root overlaps a reserved sandbox/pseudo filesystem path");
12798
10843
  }
12799
10844
  let fd;
12800
10845
  try {
12801
- fd = openSync2(expected, fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW);
10846
+ fd = openSync(expected, fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW);
12802
10847
  } catch {
12803
10848
  throw new Error("Sandbox root must be an existing directory without symlinks");
12804
10849
  }
12805
10850
  try {
12806
- if (readlinkSync2(`/proc/self/fd/${fd}`) !== expected) {
10851
+ if (readlinkSync(`/proc/self/fd/${fd}`) !== expected) {
12807
10852
  throw new Error("Sandbox root cannot contain symlinks");
12808
10853
  }
12809
10854
  const st = fstatSync(fd);
12810
10855
  if (!st.isDirectory()) throw new Error("Sandbox root must be a directory");
12811
10856
  return { fd, identity: { path: expected, dev: st.dev, ino: st.ino } };
12812
10857
  } catch (error) {
12813
- closeSync2(fd);
10858
+ closeSync(fd);
12814
10859
  throw error;
12815
10860
  }
12816
10861
  }
12817
10862
  var SECCOMP_TEMP_DIR_PREFIX = "nolo-bwrap-seccomp-";
12818
10863
  function openSeccompFd(program) {
12819
- const dir2 = mkdtempSync(join11(tmpdir(), SECCOMP_TEMP_DIR_PREFIX));
12820
- const file2 = join11(dir2, "filter.bpf");
10864
+ const dir = mkdtempSync(join4(tmpdir(), SECCOMP_TEMP_DIR_PREFIX));
10865
+ const file = join4(dir, "filter.bpf");
12821
10866
  let writer = -1;
12822
10867
  let reader = -1;
12823
10868
  try {
12824
- writer = openSync2(file2, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 384);
10869
+ writer = openSync(file, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 384);
12825
10870
  if (writeSync(writer, program) !== program.byteLength) throw new Error("Short seccomp write");
12826
- reader = openSync2(file2, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
10871
+ reader = openSync(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
12827
10872
  const w = fstatSync(writer);
12828
10873
  const r = fstatSync(reader);
12829
10874
  if (w.ino !== r.ino || w.dev !== r.dev || r.size !== program.byteLength) {
@@ -12831,29 +10876,29 @@ function openSeccompFd(program) {
12831
10876
  }
12832
10877
  return reader;
12833
10878
  } catch (error) {
12834
- if (reader >= 0) closeSync2(reader);
10879
+ if (reader >= 0) closeSync(reader);
12835
10880
  throw new Error(`Cannot prepare seccomp policy; refusing sandbox (${error.message})`);
12836
10881
  } finally {
12837
- if (writer >= 0) closeSync2(writer);
10882
+ if (writer >= 0) closeSync(writer);
12838
10883
  try {
12839
- unlinkSync(file2);
10884
+ unlinkSync(file);
12840
10885
  } catch {
12841
10886
  }
12842
10887
  try {
12843
- rmdirSync(dir2);
10888
+ rmdirSync(dir);
12844
10889
  } catch {
12845
10890
  }
12846
10891
  }
12847
10892
  }
12848
10893
  function identifyRoot(path) {
12849
10894
  const { fd, identity } = openRootHandle(path);
12850
- closeSync2(fd);
10895
+ closeSync(fd);
12851
10896
  return identity;
12852
10897
  }
12853
10898
  function reopenAuthorizedRoot(expected) {
12854
10899
  const { fd, identity } = openRootHandle(expected.path);
12855
10900
  if (identity.dev !== expected.dev || identity.ino !== expected.ino) {
12856
- closeSync2(fd);
10901
+ closeSync(fd);
12857
10902
  throw new Error("Sandbox root identity changed since prepare");
12858
10903
  }
12859
10904
  return fd;
@@ -12975,7 +11020,7 @@ var LinuxBubblewrapBackend = class {
12975
11020
  if (request.timeoutMs !== void 0 && (!Number.isFinite(request.timeoutMs) || request.timeoutMs <= 0)) {
12976
11021
  throw new Error("Sandbox timeout must be finite and positive");
12977
11022
  }
12978
- if (request.cwd && !active.writable.some(({ path: root }) => isAbsolute4(request.cwd) && inside(root, resolve12(request.cwd)))) {
11023
+ if (request.cwd && !active.writable.some(({ path: root }) => isAbsolute3(request.cwd) && inside(root, resolve4(request.cwd)))) {
12979
11024
  throw new Error("Command cwd outside writable sandbox roots");
12980
11025
  }
12981
11026
  if (!validateConfiguredRootExecutionLease(active.ticket, active.lease)) {
@@ -12987,7 +11032,7 @@ var LinuxBubblewrapBackend = class {
12987
11032
  for (const root of [...active.readable, ...active.writable]) rootFds.push(reopenAuthorizedRoot(root));
12988
11033
  rootFds.push(openSeccompFd(active.seccomp));
12989
11034
  } catch (error) {
12990
- for (const fd of rootFds) closeSync2(fd);
11035
+ for (const fd of rootFds) closeSync(fd);
12991
11036
  throw error;
12992
11037
  }
12993
11038
  const seccompChildFd = 3 + active.readable.length + active.writable.length;
@@ -13016,10 +11061,10 @@ var LinuxBubblewrapBackend = class {
13016
11061
  "--tmpfs",
13017
11062
  "/tmp"
13018
11063
  ];
13019
- for (const dir2 of ["/bin", "/lib", "/lib64"]) {
11064
+ for (const dir of ["/bin", "/lib", "/lib64"]) {
13020
11065
  try {
13021
- await access(dir2);
13022
- args.push("--ro-bind", dir2, dir2);
11066
+ await access(dir);
11067
+ args.push("--ro-bind", dir, dir);
13023
11068
  } catch {
13024
11069
  }
13025
11070
  }
@@ -13035,7 +11080,7 @@ var LinuxBubblewrapBackend = class {
13035
11080
  env: { PATH: "/usr/bin:/bin" }
13036
11081
  });
13037
11082
  } finally {
13038
- for (const fd of rootFds) closeSync2(fd);
11083
+ for (const fd of rootFds) closeSync(fd);
13039
11084
  }
13040
11085
  active.running.add(processHandle);
13041
11086
  onEvent?.({ type: "started", executionId, at: Date.now() });
@@ -13132,7 +11177,7 @@ async function createLocalSandboxWorkload(args) {
13132
11177
  const envRoots = typeof env.NOLO_LOCAL_SANDBOX_ROOTS === "string" ? env.NOLO_LOCAL_SANDBOX_ROOTS.split(":").map((entry) => entry.trim()) : [];
13133
11178
  const readableRoots = normalizeRoots(
13134
11179
  args.readableRoots && args.readableRoots.length > 0 ? args.readableRoots : [...DEFAULT_SANDBOX_READABLE_ROOTS, ...envRoots]
13135
- ).filter((root) => !FORBIDDEN_EXTRA_ROOTS.has(resolve13(root)));
11180
+ ).filter((root) => !FORBIDDEN_EXTRA_ROOTS.has(resolve5(root)));
13136
11181
  const backend = args.backend ?? new LinuxBubblewrapBackend();
13137
11182
  const ticket = {
13138
11183
  version: 1,
@@ -13180,7 +11225,7 @@ async function createLocalSandboxWorkload(args) {
13180
11225
  if (canonicalToolName(toolName) !== EXECUTION_SHELL_TOOL) return null;
13181
11226
  const callArgs = toolArgs ?? {};
13182
11227
  const command = typeof callArgs.command === "string" ? callArgs.command : "";
13183
- const mountedBins = readableRoots.map((root) => `${root}/bin`).filter((dir2) => existsSync3(dir2));
11228
+ const mountedBins = readableRoots.map((root) => `${root}/bin`).filter((dir) => existsSync3(dir));
13184
11229
  const sandboxPath = [
13185
11230
  ...mountedBins,
13186
11231
  process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin"
@@ -13715,10 +11760,10 @@ async function applyDockerWorkspaceDelivery(runtime, selection) {
13715
11760
 
13716
11761
  // packages/cli/client/localWorkspaceArchive.ts
13717
11762
  import { spawnSync } from "node:child_process";
13718
- import { mkdtempSync as mkdtempSync2, statSync as statSync2, writeFileSync as writeFileSync7 } from "node:fs";
11763
+ import { mkdtempSync as mkdtempSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "node:fs";
13719
11764
  import { rm } from "node:fs/promises";
13720
11765
  import { tmpdir as tmpdir2 } from "node:os";
13721
- import { join as join12 } from "node:path";
11766
+ import { join as join5 } from "node:path";
13722
11767
  var runHostCommand = (argv, { cwd }) => {
13723
11768
  const result = spawnSync(argv[0], argv.slice(1), {
13724
11769
  cwd,
@@ -13778,11 +11823,11 @@ function prepareHostWorkspaceDelivery(args) {
13778
11823
  `\u5DE5\u4F5C\u533A\u6587\u4EF6\u6570 ${tracked.length} \u8D85\u8FC7\u4E0A\u9650 ${MAX_DELIVERY_FILE_COUNT}\uFF1A\u7591\u4F3C\u628A node_modules / \u6784\u5EFA\u4EA7\u7269\u6253\u8FDB\u4E86\u5F52\u6863\uFF08\u5F52\u6863\u53EA\u53D6 git ls-files\uFF09\u3002`
13779
11824
  );
13780
11825
  }
13781
- const stagingDir = mkdtempSync2(join12(args.tmpDir ?? tmpdir2(), "nolo-workspace-delivery-"));
11826
+ const stagingDir = mkdtempSync2(join5(args.tmpDir ?? tmpdir2(), "nolo-workspace-delivery-"));
13782
11827
  const stamp = `${process.pid}-${Date.now()}`;
13783
- const archivePath = join12(stagingDir, `workspace-${stamp}.tar.gz`);
13784
- const bundlePath = join12(stagingDir, `workspace-${stamp}.bundle`);
13785
- const listPath = join12(stagingDir, `filelist-${stamp}.z`);
11828
+ const archivePath = join5(stagingDir, `workspace-${stamp}.tar.gz`);
11829
+ const bundlePath = join5(stagingDir, `workspace-${stamp}.bundle`);
11830
+ const listPath = join5(stagingDir, `filelist-${stamp}.z`);
13786
11831
  const removeFile = args.removeFile ?? (async (filePath) => {
13787
11832
  await rm(filePath, { force: true });
13788
11833
  });
@@ -13844,7 +11889,7 @@ function prepareHostWorkspaceDelivery(args) {
13844
11889
  fallbackReason = bundled.reason;
13845
11890
  }
13846
11891
  try {
13847
- writeFileSync7(listPath, listed.stdout, "utf8");
11892
+ writeFileSync2(listPath, listed.stdout, "utf8");
13848
11893
  const tarred = run(
13849
11894
  ["tar", "-czf", archivePath, "-C", root, "--null", "-T", listPath],
13850
11895
  { cwd: root }
@@ -14122,28 +12167,28 @@ async function createLocalDockerWorkload(args) {
14122
12167
  };
14123
12168
  let rejectReady = () => {
14124
12169
  };
14125
- const ready = new Promise((resolve15, reject) => {
14126
- resolveReady = resolve15;
12170
+ const ready = new Promise((resolve7, reject) => {
12171
+ resolveReady = resolve7;
14127
12172
  rejectReady = reject;
14128
12173
  });
14129
12174
  let releaseRun = () => {
14130
12175
  };
14131
- const releaseGate = new Promise((resolve15) => {
14132
- releaseRun = resolve15;
12176
+ const releaseGate = new Promise((resolve7) => {
12177
+ releaseRun = resolve7;
14133
12178
  });
14134
12179
  const waitForReleaseOrAbort = () => {
14135
12180
  const signal = args.signal;
14136
12181
  if (!signal) return releaseGate;
14137
12182
  if (signal.aborted) return Promise.resolve();
14138
- return new Promise((resolve15) => {
12183
+ return new Promise((resolve7) => {
14139
12184
  const onAbort = () => {
14140
12185
  signal.removeEventListener("abort", onAbort);
14141
- resolve15();
12186
+ resolve7();
14142
12187
  };
14143
12188
  signal.addEventListener("abort", onAbort, { once: true });
14144
12189
  void releaseGate.then(() => {
14145
12190
  signal.removeEventListener("abort", onAbort);
14146
- resolve15();
12191
+ resolve7();
14147
12192
  });
14148
12193
  });
14149
12194
  };
@@ -14468,7 +12513,7 @@ function buildInstaboxBridgeBootstrapScript(root, probeId) {
14468
12513
  return `printf 'NOLO_BRIDGE_REASON=helper_source_invalid
14469
12514
  '`;
14470
12515
  }
14471
- const dir2 = INSTABOX_HELPER_PATH.slice(0, INSTABOX_HELPER_PATH.lastIndexOf("/"));
12516
+ const dir = INSTABOX_HELPER_PATH.slice(0, INSTABOX_HELPER_PATH.lastIndexOf("/"));
14472
12517
  return [
14473
12518
  `root=${posixQuote(root)}`,
14474
12519
  `mkdir -p "$root" 2>/dev/null || true`,
@@ -14478,7 +12523,7 @@ function buildInstaboxBridgeBootstrapScript(root, probeId) {
14478
12523
  `for cand in bun node; do if command -v "$cand" >/dev/null 2>&1; then rt="$cand"; break; fi; done`,
14479
12524
  `printf 'NOLO_BRIDGE_RUNTIME=%s\\n' "\${rt:-none}"`,
14480
12525
  `if [ -z "$rt" ]; then printf 'NOLO_BRIDGE_REASON=runtime_missing\\n'; exit 0; fi`,
14481
- `mkdir -p ${posixQuote(dir2)} 2>/dev/null || true`,
12526
+ `mkdir -p ${posixQuote(dir)} 2>/dev/null || true`,
14482
12527
  `if ! printf %s ${posixQuote(helperPayload)} | base64 -d > ${posixQuote(INSTABOX_HELPER_PATH)}; then printf 'NOLO_BRIDGE_REASON=upload_failed\\n'; exit 0; fi`,
14483
12528
  `chmod 0644 ${posixQuote(INSTABOX_HELPER_PATH)} 2>/dev/null || true`,
14484
12529
  // 探针文件名带本次 run 的唯一 id:**只创建自己的**,绝不覆盖/删除同名既有文件
@@ -14635,14 +12680,14 @@ function describeInstaboxBridgeUnavailable(bridge) {
14635
12680
  }
14636
12681
 
14637
12682
  // packages/cli/client/localInstaboxWorkspaceRecovery.ts
14638
- import { constants as constants4 } from "node:fs";
14639
- import { open as open3 } from "node:fs/promises";
14640
- import { createHash as createHash13, randomUUID as randomUUID6 } from "node:crypto";
12683
+ import { constants as constants3 } from "node:fs";
12684
+ import { open as open2 } from "node:fs/promises";
12685
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
14641
12686
 
14642
12687
  // packages/agent-runtime/artifactStore.ts
14643
- import { createHash as createHash12, createHmac } from "node:crypto";
12688
+ import { createHash as createHash4, createHmac } from "node:crypto";
14644
12689
  import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
14645
- import { dirname as dirname5, resolve as resolve14, sep as sep2 } from "node:path";
12690
+ import { dirname as dirname3, resolve as resolve6, sep } from "node:path";
14646
12691
  var ArtifactStoreError = class extends Error {
14647
12692
  code;
14648
12693
  key;
@@ -14692,12 +12737,12 @@ function isNotFoundError(error) {
14692
12737
  return error?.code === "ENOENT";
14693
12738
  }
14694
12739
  function createLocalArtifactStore(options) {
14695
- const root = resolve14(options.rootDir);
12740
+ const root = resolve6(options.rootDir);
14696
12741
  const now = options.now ?? Date.now;
14697
- const pathFor2 = (key) => {
12742
+ const pathFor = (key) => {
14698
12743
  assertArtifactKey(key);
14699
- const target = resolve14(root, key);
14700
- if (target !== root && !target.startsWith(`${root}${sep2}`)) {
12744
+ const target = resolve6(root, key);
12745
+ if (target !== root && !target.startsWith(`${root}${sep}`)) {
14701
12746
  throw new ArtifactStoreError(
14702
12747
  "invalid_key",
14703
12748
  `artifact key \u89E3\u6790\u540E\u8D8A\u51FA rootDir\uFF1A${describeKey(key)}`,
@@ -14709,9 +12754,9 @@ function createLocalArtifactStore(options) {
14709
12754
  return {
14710
12755
  async put(key, data, opts) {
14711
12756
  const bytes = toBytes(data);
14712
- const target = pathFor2(key);
12757
+ const target = pathFor(key);
14713
12758
  try {
14714
- await mkdir(dirname5(target), { recursive: true });
12759
+ await mkdir(dirname3(target), { recursive: true });
14715
12760
  await writeFile(target, bytes);
14716
12761
  } catch (error) {
14717
12762
  if (error instanceof ArtifactStoreError) throw error;
@@ -14729,7 +12774,7 @@ function createLocalArtifactStore(options) {
14729
12774
  };
14730
12775
  },
14731
12776
  async get(key) {
14732
- const target = pathFor2(key);
12777
+ const target = pathFor(key);
14733
12778
  try {
14734
12779
  return new Uint8Array(await readFile(target));
14735
12780
  } catch (error) {
@@ -14748,7 +12793,7 @@ function createLocalArtifactStore(options) {
14748
12793
  }
14749
12794
  },
14750
12795
  async delete(key) {
14751
- const target = pathFor2(key);
12796
+ const target = pathFor(key);
14752
12797
  try {
14753
12798
  await unlink(target);
14754
12799
  } catch (error) {
@@ -14767,12 +12812,12 @@ function createLocalArtifactStore(options) {
14767
12812
  };
14768
12813
  }
14769
12814
  function sha256Hex2(data) {
14770
- return createHash12("sha256").update(data).digest("hex");
12815
+ return createHash4("sha256").update(data).digest("hex");
14771
12816
  }
14772
12817
  var EMPTY_SHA256 = sha256Hex2("");
14773
12818
 
14774
12819
  // packages/cli/client/localInstaboxWorkspaceRecovery.ts
14775
- var sha2 = (b) => createHash13("sha256").update(b).digest("hex");
12820
+ var sha = (b) => createHash5("sha256").update(b).digest("hex");
14776
12821
  function fail4(code) {
14777
12822
  throw Object.assign(new Error(`instabox_workspace_recovery:${code}; cleanup_pending`), { code: "instabox_cleanup_pending", cleanupPending: true });
14778
12823
  }
@@ -14815,14 +12860,14 @@ async function captureInstaboxBaseline(args) {
14815
12860
  return fail4("baseline_failed");
14816
12861
  }
14817
12862
  };
14818
- let digest2 = "", count2 = -1;
12863
+ let digest = "", count2 = -1;
14819
12864
  const files = [];
14820
12865
  const skipped = [];
14821
12866
  do {
14822
12867
  const r = await call({ op: "scan", offset: files.length });
14823
- if (!/^[a-f0-9]{64}$/.test(r.manifestSha256) || !Number.isInteger(r.total) || r.total < 0 || r.total > SNAPSHOT_LIMITS.files || !Array.isArray(r.files) || r.files.length !== Math.min(8, r.total - files.length) || r.skipped !== void 0 && (!Array.isArray(r.skipped) || r.skipped.length > SNAPSHOT_LIMITS.files) || count2 !== -1 && (count2 !== r.total || digest2 !== r.manifestSha256)) fail4("baseline_failed");
12868
+ if (!/^[a-f0-9]{64}$/.test(r.manifestSha256) || !Number.isInteger(r.total) || r.total < 0 || r.total > SNAPSHOT_LIMITS.files || !Array.isArray(r.files) || r.files.length !== Math.min(8, r.total - files.length) || r.skipped !== void 0 && (!Array.isArray(r.skipped) || r.skipped.length > SNAPSHOT_LIMITS.files) || count2 !== -1 && (count2 !== r.total || digest !== r.manifestSha256)) fail4("baseline_failed");
14824
12869
  count2 = r.total;
14825
- digest2 = r.manifestSha256;
12870
+ digest = r.manifestSha256;
14826
12871
  files.push(...r.files);
14827
12872
  if (Array.isArray(r.skipped)) {
14828
12873
  for (const s of r.skipped) {
@@ -14837,8 +12882,8 @@ async function captureInstaboxBaseline(args) {
14837
12882
  seen.add(f.path);
14838
12883
  total += f.sizeBytes;
14839
12884
  }
14840
- if (total > SNAPSHOT_LIMITS.totalBytes || sha2(JSON.stringify(files)) !== digest2) fail4("baseline_failed");
14841
- return { files, digest: digest2, skipped };
12885
+ if (total > SNAPSHOT_LIMITS.totalBytes || sha(JSON.stringify(files)) !== digest) fail4("baseline_failed");
12886
+ return { files, digest, skipped };
14842
12887
  }
14843
12888
  async function recoverInstaboxWorkspace(args) {
14844
12889
  const policy = args.policy;
@@ -14853,14 +12898,14 @@ async function recoverInstaboxWorkspace(args) {
14853
12898
  }
14854
12899
  };
14855
12900
  const scan = async () => {
14856
- let digest2 = "", count2 = -1;
12901
+ let digest = "", count2 = -1;
14857
12902
  const files = [];
14858
12903
  const skipped = [];
14859
12904
  do {
14860
12905
  const r = await call({ op: "scan", offset: files.length });
14861
- if (!/^[a-f0-9]{64}$/.test(r.manifestSha256) || !Number.isInteger(r.total) || r.total < 0 || r.total > SNAPSHOT_LIMITS.files || !Array.isArray(r.files) || r.files.length !== Math.min(8, r.total - files.length) || r.skipped !== void 0 && (!Array.isArray(r.skipped) || r.skipped.length > SNAPSHOT_LIMITS.files) || count2 !== -1 && (count2 !== r.total || digest2 !== r.manifestSha256)) fail4("manifest_changed");
12906
+ if (!/^[a-f0-9]{64}$/.test(r.manifestSha256) || !Number.isInteger(r.total) || r.total < 0 || r.total > SNAPSHOT_LIMITS.files || !Array.isArray(r.files) || r.files.length !== Math.min(8, r.total - files.length) || r.skipped !== void 0 && (!Array.isArray(r.skipped) || r.skipped.length > SNAPSHOT_LIMITS.files) || count2 !== -1 && (count2 !== r.total || digest !== r.manifestSha256)) fail4("manifest_changed");
14862
12907
  count2 = r.total;
14863
- digest2 = r.manifestSha256;
12908
+ digest = r.manifestSha256;
14864
12909
  files.push(...r.files);
14865
12910
  if (Array.isArray(r.skipped)) {
14866
12911
  for (const s of r.skipped) {
@@ -14875,11 +12920,11 @@ async function recoverInstaboxWorkspace(args) {
14875
12920
  seen.add(f.path);
14876
12921
  total += f.sizeBytes;
14877
12922
  }
14878
- if (total > SNAPSHOT_LIMITS.totalBytes || sha2(JSON.stringify(files)) !== digest2) fail4("manifest_mismatch");
12923
+ if (total > SNAPSHOT_LIMITS.totalBytes || sha(JSON.stringify(files)) !== digest) fail4("manifest_mismatch");
14879
12924
  for (const s of skipped) {
14880
12925
  if (policy.allowedPaths.includes(s)) fail4("allowed_path_unreadable");
14881
12926
  }
14882
- return { files, digest: digest2, skipped };
12927
+ return { files, digest, skipped };
14883
12928
  };
14884
12929
  await policy.quiesce();
14885
12930
  const initial = await scan();
@@ -14899,12 +12944,12 @@ async function recoverInstaboxWorkspace(args) {
14899
12944
  const r = await call({ op: "read", path: f.path, offset, manifestSha256: initial.digest });
14900
12945
  if (typeof r.data !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(r.data)) fail4("invalid_chunk");
14901
12946
  const b = Buffer.from(r.data, "base64");
14902
- if (b.length !== Math.min(49152, f.sizeBytes - offset) || sha2(b) !== r.sha256) fail4("chunk_mismatch");
12947
+ if (b.length !== Math.min(49152, f.sizeBytes - offset) || sha(b) !== r.sha256) fail4("chunk_mismatch");
14903
12948
  chunks.push(b);
14904
12949
  offset += b.length;
14905
12950
  }
14906
12951
  const bytes2 = Buffer.concat(chunks);
14907
- if (sha2(bytes2) !== f.sha256 || sensitive(bytes2)) fail4("unsafe_content");
12952
+ if (sha(bytes2) !== f.sha256 || sensitive(bytes2)) fail4("unsafe_content");
14908
12953
  output.push({ path: f.path, data: bytes2.toString("base64") });
14909
12954
  }
14910
12955
  if ((await scan()).digest !== initial.digest) fail4("workspace_changed");
@@ -14919,37 +12964,37 @@ async function recoverInstaboxWorkspace(args) {
14919
12964
  deletedPaths,
14920
12965
  output
14921
12966
  }));
14922
- let root = await open3("/", constants4.O_RDONLY | constants4.O_DIRECTORY | constants4.O_NOFOLLOW);
12967
+ let root = await open2("/", constants3.O_RDONLY | constants3.O_DIRECTORY | constants3.O_NOFOLLOW);
14923
12968
  try {
14924
12969
  for (const part of policy.artifactRoot.split("/").filter(Boolean)) {
14925
12970
  if (part === "." || part === "..") fail4("invalid_destination");
14926
- const next = await open3(`/proc/self/fd/${root.fd}/${part}`, constants4.O_RDONLY | constants4.O_DIRECTORY | constants4.O_NOFOLLOW);
12971
+ const next = await open2(`/proc/self/fd/${root.fd}/${part}`, constants3.O_RDONLY | constants3.O_DIRECTORY | constants3.O_NOFOLLOW);
14927
12972
  await root.close();
14928
12973
  root = next;
14929
12974
  }
14930
12975
  const { mkdir: mkdir2, rename } = await import("node:fs/promises");
14931
- const id = `instabox-${randomUUID6()}`;
12976
+ const id = `instabox-${randomUUID4()}`;
14932
12977
  const namespace = `/proc/self/fd/${root.fd}/${id}`;
14933
12978
  await mkdir2(namespace, { mode: 448 });
14934
- const dir2 = await open3(namespace, constants4.O_RDONLY | constants4.O_DIRECTORY | constants4.O_NOFOLLOW);
12979
+ const dir = await open2(namespace, constants3.O_RDONLY | constants3.O_DIRECTORY | constants3.O_NOFOLLOW);
14935
12980
  try {
14936
- const prefix = `/proc/self/fd/${dir2.fd}`;
14937
- const file2 = await open3(`${prefix}/snapshot.pending`, constants4.O_WRONLY | constants4.O_CREAT | constants4.O_EXCL | constants4.O_NOFOLLOW, 384);
12981
+ const prefix = `/proc/self/fd/${dir.fd}`;
12982
+ const file = await open2(`${prefix}/snapshot.pending`, constants3.O_WRONLY | constants3.O_CREAT | constants3.O_EXCL | constants3.O_NOFOLLOW, 384);
14938
12983
  try {
14939
- await file2.writeFile(bytes);
14940
- await file2.sync();
12984
+ await file.writeFile(bytes);
12985
+ await file.sync();
14941
12986
  } finally {
14942
- await file2.close();
12987
+ await file.close();
14943
12988
  }
14944
12989
  await rename(`${prefix}/snapshot.pending`, `${prefix}/snapshot.json`);
14945
- await dir2.sync();
12990
+ await dir.sync();
14946
12991
  await root.sync();
14947
12992
  const stored = await createLocalArtifactStore({ rootDir: prefix }).get("snapshot.json");
14948
- if (sha2(stored) !== sha2(bytes)) fail4("artifact_readback_mismatch");
12993
+ if (sha(stored) !== sha(bytes)) fail4("artifact_readback_mismatch");
14949
12994
  if ((await scan()).digest !== initial.digest) fail4("workspace_changed_after_persist");
14950
- return { artifact: { id: `${id}/snapshot.json`, sizeBytes: bytes.length, contentType: "application/json", createdAt: Date.now() }, sha256: sha2(bytes), files: changed, deletedPaths };
12995
+ return { artifact: { id: `${id}/snapshot.json`, sizeBytes: bytes.length, contentType: "application/json", createdAt: Date.now() }, sha256: sha(bytes), files: changed, deletedPaths };
14951
12996
  } finally {
14952
- await dir2.close();
12997
+ await dir.close();
14953
12998
  }
14954
12999
  } finally {
14955
13000
  await root.close();
@@ -14960,13 +13005,13 @@ async function recoverInstaboxWorkspace(args) {
14960
13005
  function sanitizeReleaseError(error) {
14961
13006
  const raw = error instanceof Error ? error.message : String(error);
14962
13007
  const sanitized = raw.replace(/(?:api[_-]?key|bearer|token|password|secret)[=:\s]+[A-Za-z0-9_\-\.]{8,}/gi, "[REDACTED]").replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "[REDACTED]").slice(0, 500);
14963
- const safe2 = new Error(sanitized);
13008
+ const safe = new Error(sanitized);
14964
13009
  if (error instanceof Error) {
14965
- safe2.name = error.name;
14966
- if (error.code) safe2.code = error.code;
14967
- if (error.cleanupPending !== void 0) safe2.cleanupPending = error.cleanupPending;
13010
+ safe.name = error.name;
13011
+ if (error.code) safe.code = error.code;
13012
+ if (error.cleanupPending !== void 0) safe.cleanupPending = error.cleanupPending;
14968
13013
  }
14969
- return safe2;
13014
+ return safe;
14970
13015
  }
14971
13016
  var LOCAL_INSTABOX_BACKEND_ID = INSTABOX_BACKEND_ID;
14972
13017
  function resolveInstaboxApiKey(env) {
@@ -15017,8 +13062,8 @@ async function prepareFileBridge(execDirect, root, probeId) {
15017
13062
  return verdict.ready ? { root: pinned.root, runtime: pinned.runtime, ready: true, probeId, probePath: parsed.probePath } : { root: pinned.root, runtime: pinned.runtime, ready: false, reason: verdict.reason ?? "probe_failed", probeId, probePath: parsed.probePath };
15018
13063
  }
15019
13064
  function resolveInstaboxTemplateId(options) {
15020
- const explicit2 = options.templateId?.trim();
15021
- if (explicit2) return explicit2;
13065
+ const explicit = options.templateId?.trim();
13066
+ if (explicit) return explicit;
15022
13067
  const envOverride = options.env?.INSTABOX_TEMPLATE_ID?.trim();
15023
13068
  if (envOverride) return envOverride;
15024
13069
  const tier = options.orgTier?.trim().toLowerCase();
@@ -15277,8 +13322,8 @@ async function createLocalInstaboxWorkload(args) {
15277
13322
  }
15278
13323
 
15279
13324
  // packages/cli/client/localRunArtifactExport.ts
15280
- import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync8 } from "node:fs";
15281
- import { dirname as dirname6, join as join13 } from "node:path";
13325
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "node:fs";
13326
+ import { dirname as dirname4, join as join6 } from "node:path";
15282
13327
 
15283
13328
  // packages/agent-runtime/runArtifactExport.ts
15284
13329
  var RUN_DIFF_COMMAND = "git add -A && git diff --cached --binary";
@@ -15317,8 +13362,8 @@ var UNSAFE_WORKTREE_NAME = /[^A-Za-z0-9._-]+/g;
15317
13362
  function worktreeArtifactName(path) {
15318
13363
  const trimmed = String(path ?? "").replace(/[/\\]+$/, "");
15319
13364
  const base = trimmed.split(/[/\\]/).pop() ?? "";
15320
- const safe2 = base.replace(UNSAFE_WORKTREE_NAME, "-").replace(/^[-.]+|[-.]+$/g, "");
15321
- return safe2 || "worktree";
13365
+ const safe = base.replace(UNSAFE_WORKTREE_NAME, "-").replace(/^[-.]+|[-.]+$/g, "");
13366
+ return safe || "worktree";
15322
13367
  }
15323
13368
  function worktreeDiffArtifactKey(runId, name) {
15324
13369
  return `runs/${runId}/worktrees/${name}.patch`;
@@ -15486,11 +13531,11 @@ function serializeRunArtifactAudit(record) {
15486
13531
  // packages/cli/client/localRunArtifactExport.ts
15487
13532
  function resolveRunArtifactsRootDir(runsDir) {
15488
13533
  const normalized = runsDir.replace(/[/\\]+$/, "");
15489
- return join13(dirname6(normalized || runsDir), "artifacts");
13534
+ return join6(dirname4(normalized || runsDir), "artifacts");
15490
13535
  }
15491
13536
  function writeRunArtifactAudit(args) {
15492
- const fs = args.fs ?? { mkdirSync: mkdirSync7, writeFileSync: writeFileSync8 };
15493
- const path = join13(args.runsDir, `${args.record.runId}.artifacts.json`);
13537
+ const fs = args.fs ?? { mkdirSync: mkdirSync2, writeFileSync: writeFileSync3 };
13538
+ const path = join6(args.runsDir, `${args.record.runId}.artifacts.json`);
15494
13539
  fs.mkdirSync?.(args.runsDir, { recursive: true });
15495
13540
  fs.writeFileSync(path, serializeRunArtifactAudit(args.record));
15496
13541
  return path;
@@ -15842,9 +13887,9 @@ function buildTokenDialogIndexOps(args) {
15842
13887
 
15843
13888
  // packages/cli/client/localRuntimeDialog.ts
15844
13889
  var import_format = __toESM(require_format(), 1);
15845
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync8 } from "fs";
15846
- import { homedir as homedir2 } from "os";
15847
- import { join as join14 } from "path";
13890
+ import { appendFileSync, mkdirSync as mkdirSync3 } from "fs";
13891
+ import { homedir } from "os";
13892
+ import { join as join7 } from "path";
15848
13893
  var diagLog = {
15849
13894
  warn: (msg) => getLogger("cli.localRuntimeDialog").warn(msg),
15850
13895
  info: (msg) => getLogger("cli.localRuntimeDialog").info(msg)
@@ -15895,11 +13940,11 @@ function projectRawUsage(usage) {
15895
13940
  function debugCaptureRawUsage(item) {
15896
13941
  if (!process.env.NOLO_DEBUG_RAW_USAGE) return;
15897
13942
  try {
15898
- const noloHome = process.env.NOLO_HOME?.trim() || join14(homedir2(), ".nolo");
15899
- const dir2 = join14(noloHome, "logs");
15900
- mkdirSync8(dir2, { recursive: true });
15901
- appendFileSync2(
15902
- join14(dir2, "raw-usage.jsonl"),
13943
+ const noloHome = process.env.NOLO_HOME?.trim() || join7(homedir(), ".nolo");
13944
+ const dir = join7(noloHome, "logs");
13945
+ mkdirSync3(dir, { recursive: true });
13946
+ appendFileSync(
13947
+ join7(dir, "raw-usage.jsonl"),
15903
13948
  JSON.stringify({
15904
13949
  ts: Date.now(),
15905
13950
  model: item.model,
@@ -16738,15 +14783,15 @@ function createCliLocalRuntimeAdapter(deps) {
16738
14783
  const runId = asOptionalTrimmedString(deps.env?.NOLO_AGENT_RUN_ID) ?? "interactive";
16739
14784
  emitRunIsolationNotice(fact, { runId });
16740
14785
  try {
16741
- const { writeFileSync: writeFileSync9, mkdirSync: mkdirSync9 } = await import("node:fs");
16742
- const { resolveRunsDir: resolveRunsDir2 } = await import("./agentRunControl-DFEEOFC7.js");
14786
+ const { writeFileSync: writeFileSync4, mkdirSync: mkdirSync4 } = await import("node:fs");
14787
+ const { resolveRunsDir: resolveRunsDir2 } = await import("./agentRunControl-SNZZ5XP4.js");
16743
14788
  recordLocalRunExecutionIsolation({
16744
14789
  runId,
16745
14790
  runsDir: resolveRunsDir2(deps.env),
16746
14791
  fact,
16747
14792
  fs: {
16748
- writeFileSync: (path, data) => writeFileSync9(path, data),
16749
- mkdirSync: (path, options) => mkdirSync9(path, options)
14793
+ writeFileSync: (path, data) => writeFileSync4(path, data),
14794
+ mkdirSync: (path, options) => mkdirSync4(path, options)
16750
14795
  }
16751
14796
  });
16752
14797
  getLogger("cli.localRuntimeAdapter").info(
@@ -16764,7 +14809,7 @@ function createCliLocalRuntimeAdapter(deps) {
16764
14809
  dockerWorkloadReleased = true;
16765
14810
  dockerWorkloadLoad = null;
16766
14811
  if (loaded) {
16767
- const { resolveRunsDir: resolveRunsDir2 } = await import("./agentRunControl-DFEEOFC7.js");
14812
+ const { resolveRunsDir: resolveRunsDir2 } = await import("./agentRunControl-SNZZ5XP4.js");
16768
14813
  const exportRunDiff = deps.exportDockerRunDiffArtifact ?? exportDockerRunDiffArtifact;
16769
14814
  const warn = (message) => process.stderr.write(`[nolo] ${message}
16770
14815
  `);
@@ -16846,8 +14891,8 @@ function createCliLocalRuntimeAdapter(deps) {
16846
14891
  };
16847
14892
  let runtimeToolExecutionLimits = {};
16848
14893
  const skillPolicyFingerprint = (source) => JSON.stringify(Object.entries(resolveAgentSkillConfig(source)).sort(([a], [b]) => a.localeCompare(b)));
16849
- let installedTaskReviewHost;
16850
14894
  let reviewAgentConfig;
14895
+ let planningCaller = {};
16851
14896
  const isCanonicalAutoReviewAdmitted = (visits) => {
16852
14897
  const canonical = resolveBuiltinSkillEntry("auto-review");
16853
14898
  if (!canonical || !visits) return false;
@@ -16855,36 +14900,7 @@ function createCliLocalRuntimeAdapter(deps) {
16855
14900
  (visit) => visit.dbKey === canonical.skillId && visit.meta?.skillConfig?.id === canonical.skillId
16856
14901
  );
16857
14902
  };
16858
- const accountReviewScope = (dialogId, taskInstanceId) => ({
16859
- taskId: `tui-local-alpha-v1-${createHash14("sha256").update(JSON.stringify([userId, dialogId, resolveReviewWorkspace(workspaceRoot), "local-alpha-v1", ...taskInstanceId ? [taskInstanceId] : []])).digest("hex")}`,
16860
- dialogId,
16861
- workspace: resolveReviewWorkspace(workspaceRoot),
16862
- ...taskInstanceId ? { taskInstanceId } : {}
16863
- });
16864
- const requireAccountReview = async (scope) => {
16865
- if (!userId || userId === "local" || !scope.dialogId?.trim()) throw new Error("task_review_authenticated_user_missing");
16866
- if (scope.taskId !== accountReviewScope(scope.dialogId, scope.taskInstanceId).taskId || resolveReviewWorkspace(scope.workspace) !== resolveReviewWorkspace(workspaceRoot)) throw new Error("task_review_user_scope_mismatch");
16867
- const store = await getOrCreateSharedStore(deps);
16868
- const dialog = await store.read(`dialog-${userId}-${scope.dialogId}`);
16869
- if (dialog?.userId && dialog.userId !== userId) throw new Error("task_review_user_scope_mismatch");
16870
- const settings = await store.read(createUserKey.settings(userId));
16871
- const skills = await resolveUserSkillRuntime(reviewAgentConfig, settings && typeof settings === "object" ? settings : {});
16872
- if (!isCanonicalAutoReviewAdmitted(skills.visits)) throw new Error("task_review_account_optin_required");
16873
- };
16874
- const authorizedReviewHost = () => {
16875
- const host = installedTaskReviewHost ?? deps.taskReviewHost;
16876
- if (!host) return void 0;
16877
- return { ...host, authorize: async () => {
16878
- await host.authorize();
16879
- await requireAccountReview(host.scope);
16880
- const task = readHostTask(hostTaskEventsRoot(deps.env), host.scope);
16881
- if (task.authorization !== "active") throw new Error(`task_review_authorization_${task.authorization}`);
16882
- const workspace = await collectHostTaskWorkspace(host.scope, deps.env);
16883
- if (workspace.status !== "ready") throw new Error(`task_review_workspace_unavailable: ${workspace.reason}`);
16884
- } };
16885
- };
16886
14903
  const buildCurrentToolExecutors = (agentConfig) => buildLocalToolExecutors({
16887
- taskReviewHost: authorizedReviewHost(),
16888
14904
  workspaceRoot,
16889
14905
  sourceParentDialogId: deps.parentDialogId,
16890
14906
  env: deps.env,
@@ -16936,6 +14952,11 @@ function createCliLocalRuntimeAdapter(deps) {
16936
14952
  ...deps.requestUserChoice ? { requestUserChoice: deps.requestUserChoice } : {},
16937
14953
  ...deps.pastedTextStore ? { pastedTextStore: deps.pastedTextStore } : {},
16938
14954
  agentKey: agentConfig?.key,
14955
+ planningCaller: planningCaller = {
14956
+ agentKey: agentConfig?.key,
14957
+ effectiveModel: agentConfig?.model,
14958
+ runKind: deps.env.NOLO_AGENT_RUN_CHILD === "1" || agentConfig?.toolSurface?.runKind === "subtask" ? "subtask" : "interactive"
14959
+ },
16939
14960
  agentSkillSource: agentConfig?.rawRecord,
16940
14961
  ...agentConfig ? { resolveAgentSkillSource: async () => {
16941
14962
  const store = await getOrCreateSharedStore(deps);
@@ -17598,38 +15619,6 @@ function createCliLocalRuntimeAdapter(deps) {
17598
15619
  };
17599
15620
  return {
17600
15621
  ...adapterBase,
17601
- async admitAccountReviewTurn(dialogId, turnId, taskStart) {
17602
- if (taskStart && (taskStart.userId !== userId || !taskStart.taskInstanceId?.trim() || !taskStart.userMessageId?.trim() || !/^[a-f0-9]{64}$/.test(taskStart.contentSha256))) throw new Error("task_review_user_turn_source_invalid");
17603
- if (isSubtaskRun(deps.env) || !activeAgentToolNames.some((name) => ["requestTaskReview", "recordTaskReviewDecision"].includes(name))) throw new Error("task_review_outside_final_run_surface");
17604
- const scope = accountReviewScope(dialogId, taskStart?.taskInstanceId);
17605
- await requireAccountReview(scope);
17606
- const root = hostTaskEventsRoot(deps.env);
17607
- const current = readHostTask(root, scope);
17608
- if (current.authorization !== "unknown" && taskStart && (current.taskStart?.taskInstanceId !== taskStart.taskInstanceId || current.taskStart?.userId !== taskStart.userId || current.taskStart?.userMessageId !== taskStart.userMessageId || current.taskStart?.contentSha256 !== taskStart.contentSha256)) throw new Error("task_review_user_turn_source_mismatch");
17609
- if (current.authorization === "unknown") {
17610
- if (current.reason !== "missing") throw new Error("task_review_task_history_invalid");
17611
- if (!taskStart) throw new Error("task_review_explicit_task_start_required");
17612
- const snapshot = admitHostTaskWorkspace(scope, deps.env);
17613
- if (snapshot.status !== "ready") throw new Error(`task_review_workspace_unavailable: ${snapshot.reason}`);
17614
- createHostTaskController(root, { kind: "trusted-host", actorId: userId, sourceId: taskStart ? `account-task-start:${taskStart.userMessageId}:${taskStart.contentSha256}` : `account-auto-review-admission:${turnId}` }).append(scope, 0, { type: "admitted", role: "owner", ...taskStart ? { taskStart } : {} });
17615
- } else if (current.authorization !== "active") throw new Error(`task_review_authorization_${current.authorization}`);
17616
- const workspace = await collectHostTaskWorkspace(scope, deps.env);
17617
- if (workspace.status !== "ready") throw new Error(`task_review_workspace_unavailable: ${workspace.reason}`);
17618
- const host = { scope, authorExecutionId: createHostAuthorExecution(deps.env, scope, turnId), authorize: async () => {
17619
- } };
17620
- installedTaskReviewHost = host;
17621
- localToolExecutors = buildCurrentToolExecutors(reviewAgentConfig);
17622
- return scope;
17623
- },
17624
- async authorizeAccountTask(scope) {
17625
- await requireAccountReview(scope);
17626
- const current = readHostTask(hostTaskEventsRoot(deps.env), scope);
17627
- if (current.authorization !== "active") throw new Error(`task_review_authorization_${current.authorization}`);
17628
- },
17629
- installTaskReviewHost(host) {
17630
- installedTaskReviewHost = host;
17631
- localToolExecutors = buildCurrentToolExecutors(reviewAgentConfig);
17632
- },
17633
15622
  releaseLocalSandboxWorkload,
17634
15623
  prepareLocalRuntimeWorkload,
17635
15624
  // Session override or host-owned default; headless receives the same paid admission.
@@ -17642,6 +15631,9 @@ function createCliLocalRuntimeAdapter(deps) {
17642
15631
  agentConfig,
17643
15632
  options
17644
15633
  );
15634
+ if (!options?.textOnly && planningCaller.agentKey === agentConfig.key) {
15635
+ planningCaller.effectiveModel = provider.model;
15636
+ }
17645
15637
  const retryingProvider = shouldUsePlatformChatProvider(deps.env, agentConfig) ? withProviderStreamRetry(provider, {
17646
15638
  ...deps,
17647
15639
  retryOnly: isBusyProviderStreamError
@@ -17663,20 +15655,9 @@ function createCliLocalRuntimeAdapter(deps) {
17663
15655
  }
17664
15656
 
17665
15657
  export {
17666
- hostTaskEventsRoot,
17667
- readHostTask,
17668
- createHostTaskController,
17669
- unknownTaskCompletion,
17670
- sameTaskScope,
17671
- admitHostTaskWorkspace,
17672
- collectHostTaskWorkspace,
17673
15658
  readTimestamp,
17674
15659
  parseAgentRunEvent,
17675
15660
  isLiveAgentRunObservation,
17676
- redactSecrets,
17677
- withholdIfSecretLike,
17678
- safeAskText,
17679
- safeApprovalMultilineText,
17680
15661
  formatApprovalRemaining,
17681
15662
  createHostApprovalCardQueue,
17682
15663
  registerHostApprovalRenderer,
@@ -17712,18 +15693,6 @@ export {
17712
15693
  loadCliDialogSummary,
17713
15694
  saveCliDialogSummary,
17714
15695
  loadCliDialogLastContextUsage,
17715
- withHostReviewDispatch,
17716
- matchesHostReviewDispatch,
17717
- settleHostReviewsForScope,
17718
- createHostAuthorExecution,
17719
- unknownLocalRunAcceptance,
17720
- inspectLocalRunWorkspace,
17721
- shouldPrintLocalRunSummary,
17722
- formatLocalRunSummary,
17723
- captureLocalRunBase,
17724
- observeLocalCommandResult,
17725
- attachLocalCommandObservations,
17726
- wrapLocalCommandWorkspaceObservation,
17727
15696
  LOCAL_SERVER_TABLE_TOOL_NAMES,
17728
15697
  LOCAL_SERVER_TABLE_TOOL_NAME_SET,
17729
15698
  LOCAL_SERVER_WEB_TOOL_NAMES,
@@ -17744,8 +15713,6 @@ export {
17744
15713
  resolveBoundMachineId,
17745
15714
  isCliProviderAgentConfig,
17746
15715
  detectCurrentMachineId,
17747
- readHostTaskAcceptancePlan,
17748
- collectHostTaskPlannedWorkspace,
17749
15716
  readFlagValue,
17750
15717
  isFullstackCodingAgentRef,
17751
15718
  positionalArgs,