nolo-cli 0.1.26 → 0.1.29

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 (897) hide show
  1. package/agent-runtime/dialogStatus.ts +139 -0
  2. package/agent-runtime/index.ts +8 -0
  3. package/agentAliases.ts +11 -14
  4. package/agentCommandSupport.ts +2 -2
  5. package/agentCreateCustomCommands.ts +273 -0
  6. package/agentDialogsCommands.ts +226 -0
  7. package/agentDoctorCommands.ts +203 -0
  8. package/agentInternalCommandEntries.ts +11 -2
  9. package/agentListCommands.ts +27 -18
  10. package/agentMachineCommands.ts +97 -23
  11. package/agentPullCommand.ts +9 -9
  12. package/agentRecordHelpers.ts +61 -4
  13. package/agentRunCommand.ts +35 -410
  14. package/agentRunLocalWorkspace.ts +182 -0
  15. package/agentRunParsing.ts +279 -0
  16. package/agentSuperviseCommands.ts +8 -0
  17. package/agentUnpublishCommands.ts +112 -0
  18. package/ai/agent/_executeModel.ts +14 -14
  19. package/ai/agent/agentSlice.ts +8 -8
  20. package/ai/agent/appWorkingMemory.ts +2 -2
  21. package/ai/agent/avatarUtils.ts +1 -1
  22. package/ai/agent/buildEditingContext.ts +3 -3
  23. package/ai/agent/buildSystemPrompt.ts +16 -7
  24. package/ai/agent/cleanAgentMessages.ts +1 -1
  25. package/ai/agent/cliChatClient.ts +3 -3
  26. package/ai/agent/cliExecutor.ts +4 -2
  27. package/ai/agent/createAgentSchema.ts +1 -1
  28. package/ai/agent/executeToolCall.ts +2 -2
  29. package/ai/agent/fetchAgentContexts.ts +3 -3
  30. package/ai/agent/getFullChatContextKeys.ts +4 -4
  31. package/ai/agent/guidedCreation/draft.ts +1 -1
  32. package/ai/agent/guidedCreation/types.ts +1 -1
  33. package/ai/agent/hooks/fetchPublicAgents.ts +6 -6
  34. package/ai/agent/hooks/useAgentConfig.ts +49 -21
  35. package/ai/agent/hooks/useAgentDialog.ts +1 -1
  36. package/ai/agent/hooks/useAgentFormValidation.ts +9 -9
  37. package/ai/agent/hooks/usePublicAgents.ts +9 -9
  38. package/ai/agent/persistMessageWithFixedId.ts +4 -4
  39. package/ai/agent/planSlice.ts +1 -1
  40. package/ai/agent/referenceUtils.ts +4 -4
  41. package/ai/agent/runAgentBackground.ts +3 -3
  42. package/ai/agent/runAgentClientLoop.ts +12 -12
  43. package/ai/agent/runtimeGuidance.ts +1 -1
  44. package/ai/agent/server/fetchPublicAgents.ts +6 -6
  45. package/ai/agent/startParallelAgentStreams.ts +12 -12
  46. package/ai/agent/streamAgentChatTurn.ts +21 -21
  47. package/ai/agent/streamAgentChatTurnUtils.ts +22 -22
  48. package/ai/agent/utils/imageOutput.ts +2 -2
  49. package/ai/agent/utils/publicImageAgentMode.ts +1 -1
  50. package/ai/agent/utils/sortUtils.ts +1 -1
  51. package/ai/agent/web/useGuidedAgentCreation.ts +29 -8
  52. package/ai/chat/fetchUtils.native.ts +2 -2
  53. package/ai/chat/fetchUtils.ts +2 -2
  54. package/ai/chat/sendOpenAICompletionsRequest.native.ts +11 -11
  55. package/ai/chat/sendOpenAICompletionsRequest.ts +12 -12
  56. package/ai/chat/sendOpenAIResponseRequest.ts +14 -14
  57. package/ai/chat/shouldUseServerProxy.ts +1 -1
  58. package/ai/chat/updateTotalUsage.ts +1 -1
  59. package/ai/context/buildReferenceContext.ts +14 -14
  60. package/ai/context/calculateContextUsage.ts +1 -1
  61. package/ai/llm/generateRequestBody.ts +3 -3
  62. package/ai/llm/getPricing.ts +4 -4
  63. package/ai/llm/hooks/useModelPricing.ts +2 -2
  64. package/ai/llm/imagePricing.ts +1 -1
  65. package/ai/llm/models.ts +3 -3
  66. package/ai/llm/providers.ts +8 -8
  67. package/ai/memory/capture.ts +1 -1
  68. package/ai/memory/consolidate.ts +1 -1
  69. package/ai/memory/delete.ts +2 -2
  70. package/ai/memory/query.ts +1 -1
  71. package/ai/memory/queryShared.ts +1 -1
  72. package/ai/memory/recentRelationshipRecap.ts +2 -2
  73. package/ai/memory/remember.ts +1 -1
  74. package/ai/memory/store.ts +1 -1
  75. package/ai/memory/storeShared.ts +2 -2
  76. package/ai/memory/understanding.ts +1 -1
  77. package/ai/messages/type.ts +1 -1
  78. package/ai/policy/personalizationDialog.ts +6 -6
  79. package/ai/policy/runtimePolicy.ts +1 -1
  80. package/ai/skills/referenceRuntime.ts +1 -1
  81. package/ai/skills/skillDiagnostics.ts +1 -1
  82. package/ai/skills/skillDocBuilder.ts +1 -1
  83. package/ai/skills/skillReferenceSummary.ts +1 -1
  84. package/ai/skills/skillSummaryMarker.ts +1 -1
  85. package/ai/token/calculatePrice.ts +5 -5
  86. package/ai/token/db.ts +3 -3
  87. package/ai/token/externalToolCost.ts +4 -4
  88. package/ai/token/hooks/useRecords.ts +3 -3
  89. package/ai/token/modelUsageQuery.ts +2 -2
  90. package/ai/token/openaiImageGenerationUsage.ts +2 -2
  91. package/ai/token/prepareTokenUsageData.ts +1 -1
  92. package/ai/token/query.ts +1 -1
  93. package/ai/token/queryUserTokens.ts +1 -1
  94. package/ai/token/resolveBillingTarget.ts +1 -1
  95. package/ai/token/saveTokenRecord.ts +5 -5
  96. package/ai/token/serverDialogProjection.ts +4 -4
  97. package/ai/token/serverTokenWriter.ts +3 -3
  98. package/ai/token/tokenThunks.ts +1 -1
  99. package/ai/tools/agent/agentUpdateShared.ts +4 -4
  100. package/ai/tools/agent/callAgentTool.ts +3 -3
  101. package/ai/tools/agent/createAgentTool.ts +12 -12
  102. package/ai/tools/agent/createDialogTool.ts +3 -3
  103. package/ai/tools/agent/parallelBudget.ts +2 -2
  104. package/ai/tools/agent/prepareAgentDraftTool.ts +18 -4
  105. package/ai/tools/agent/presets/appBuilderPreset.ts +1 -1
  106. package/ai/tools/agent/runLlmTool.ts +1 -1
  107. package/ai/tools/agent/skillAgentPreset.ts +6 -6
  108. package/ai/tools/agent/updateAgentTool.ts +4 -4
  109. package/ai/tools/agent/updateSelfTool.ts +8 -8
  110. package/ai/tools/appTools.ts +3 -3
  111. package/ai/tools/category/createCategoryTool.ts +2 -2
  112. package/ai/tools/category/queryContentsByCategoryTool.ts +2 -2
  113. package/ai/tools/category/updateContentCategoryTool.ts +2 -2
  114. package/ai/tools/createDocTool.ts +3 -3
  115. package/ai/tools/createPlanTool.ts +9 -9
  116. package/ai/tools/createSkillDocTool.ts +4 -4
  117. package/ai/tools/createWorkflowTool.ts +2 -2
  118. package/ai/tools/deleteSpacesTool.ts +5 -5
  119. package/ai/tools/deleteSpacesToolModel.ts +1 -1
  120. package/ai/tools/doctorSkillTool.ts +3 -3
  121. package/ai/tools/evalSkillTool.ts +3 -3
  122. package/ai/tools/execShellTool.ts +1 -1
  123. package/ai/tools/executeSqlTool.ts +1 -1
  124. package/ai/tools/geminiImagePreviewTool.ts +9 -9
  125. package/ai/tools/importDataTool.ts +2 -2
  126. package/ai/tools/importSkillTool.ts +4 -4
  127. package/ai/tools/index.ts +37 -0
  128. package/ai/tools/listUserSpacesTool.ts +2 -2
  129. package/ai/tools/localFilesTool.ts +85 -9
  130. package/ai/tools/openaiImageTool.ts +9 -9
  131. package/ai/tools/readDocTool.ts +3 -3
  132. package/ai/tools/readTool.ts +9 -9
  133. package/ai/tools/rememberMemoryTool.ts +3 -3
  134. package/ai/tools/remotionVideoTool.ts +7 -7
  135. package/ai/tools/searchDialogMessagesTool.ts +2 -2
  136. package/ai/tools/searchWorkspaceTool.ts +4 -4
  137. package/ai/tools/table/addTableRowTool.ts +2 -2
  138. package/ai/tools/table/createTableTool.ts +2 -2
  139. package/ai/tools/table/rowTools.ts +2 -2
  140. package/ai/tools/table/schemaTools.ts +3 -3
  141. package/ai/tools/table/shareTableTool.ts +5 -5
  142. package/ai/tools/table/toolShared.ts +6 -6
  143. package/ai/tools/toolApiClient.ts +15 -6
  144. package/ai/tools/toolRunSlice.ts +2 -2
  145. package/ai/tools/updateContentTitleTool.ts +2 -2
  146. package/ai/tools/updateDocTool.ts +7 -7
  147. package/ai/tools/updateUserPreferenceProfileTool.ts +3 -3
  148. package/ai/workflow/workflowExecutor.ts +3 -3
  149. package/ai/workflow/workflowSlice.ts +1 -1
  150. package/app/actions/syncAppRecord.ts +73 -0
  151. package/app/admin/adminPages.ts +13 -0
  152. package/app/colors.ts +1 -0
  153. package/app/constants/animationSets.ts +21 -0
  154. package/app/constants/appEditor.ts +99 -0
  155. package/app/constants/clientDownloads.ts +54 -0
  156. package/app/constants/desktopReleaseManifest.ts +68 -0
  157. package/app/constants/homeTabs.ts +15 -0
  158. package/app/constants/routePaths.ts +15 -0
  159. package/app/email/emailApiRoutes.ts +14 -0
  160. package/app/favorite/favoriteSlice.ts +690 -0
  161. package/app/favorite/type.ts +43 -0
  162. package/app/favorite/useAgentFavorite.ts +43 -0
  163. package/app/favorite/useContentFavorite.ts +41 -0
  164. package/app/fetchOwnedApps.ts +269 -0
  165. package/app/guide/quickStartGuide.ts +128 -0
  166. package/app/hooks/deleteDbKey.ts +233 -0
  167. package/app/hooks/index.ts +4 -0
  168. package/app/hooks/useAppDetail.ts +208 -0
  169. package/app/hooks/useAppVersions.ts +52 -0
  170. package/app/hooks/useAutoResizeTextarea.ts +29 -0
  171. package/app/hooks/useChatPageTitle.ts +85 -0
  172. package/app/hooks/useClipboardFiles.ts +20 -0
  173. package/app/hooks/useDesktopLocalConnectorAutostart.ts +38 -0
  174. package/app/hooks/useDragResize.ts +91 -0
  175. package/app/hooks/useElementSizeVar.ts +24 -0
  176. package/app/hooks/useFileDropZone.ts +52 -0
  177. package/app/hooks/useHasMounted.ts +11 -0
  178. package/app/hooks/useImageLoadFallback.ts +19 -0
  179. package/app/hooks/useIsMobile.ts +46 -0
  180. package/app/hooks/useMyApps.ts +375 -0
  181. package/app/hooks/useMyContentItems.ts +91 -0
  182. package/app/hooks/useNewMessageNotification.ts +81 -0
  183. package/app/hooks/usePageMeta.ts +107 -0
  184. package/app/hooks/useRecentlyOpened.ts +84 -0
  185. package/app/hooks/useUnifiedStore.ts +11 -0
  186. package/app/hooks/useUserNotifications.ts +197 -0
  187. package/app/hooks.ts +55 -0
  188. package/app/i18n/clientResources.ts +65 -0
  189. package/app/i18n/i18n.base.ts +14 -0
  190. package/app/i18n/i18n.config.ts +62 -0
  191. package/app/i18n/i18n.server.ts +13 -0
  192. package/app/i18n/index.ts +15 -0
  193. package/app/i18n/mapLanguage.ts +11 -0
  194. package/app/i18n/translations/appBuilder.locale.ts +453 -0
  195. package/app/i18n/translations/error.locale.ts +246 -0
  196. package/app/i18n/translations/interface.locale.ts +2174 -0
  197. package/app/i18n/translations/seo.locale.ts +129 -0
  198. package/app/i18n/types.ts +6 -0
  199. package/app/notifications/formatNotification.ts +134 -0
  200. package/app/notifications/model.ts +77 -0
  201. package/app/notifications/notificationSlice.ts +141 -0
  202. package/app/notifications/useNotificationActions.ts +67 -0
  203. package/app/pages/homeTabState.ts +57 -0
  204. package/app/pages/quickChatFlow.ts +109 -0
  205. package/app/pages/rechargeCheckout.ts +23 -0
  206. package/app/pages/usePageArt.ts +91 -0
  207. package/app/realtime/sharedSse.ts +182 -0
  208. package/app/reducer.ts +36 -0
  209. package/app/seo/pageMeta.ts +123 -0
  210. package/app/settings/config.ts +54 -0
  211. package/app/settings/dbActionThunks.ts +34 -0
  212. package/app/settings/defaultSpacePreference.ts +87 -0
  213. package/app/settings/navItems.ts +73 -0
  214. package/app/settings/prepareUserSetting.ts +11 -0
  215. package/app/settings/settingsRecord.ts +8 -0
  216. package/app/settings/web/chat-config/useAutoSaveGlobalPrompt.ts +59 -0
  217. package/app/settings/web/machineStatus.ts +23 -0
  218. package/app/settings/web/useSettingsStylesheet.ts +28 -0
  219. package/app/settings/web/userSecurityUtils.ts +21 -0
  220. package/app/stateViews/runtime.ts +86 -0
  221. package/app/store.ts +53 -0
  222. package/app/theme/colors.ts +280 -0
  223. package/app/theme/fontPreference.ts +77 -0
  224. package/app/theme/index.ts +7 -0
  225. package/app/theme/theme.config.ts +120 -0
  226. package/app/theme/themeModeBootstrap.ts +123 -0
  227. package/app/theme/useSystemTheme.ts +33 -0
  228. package/app/types/appSummary.ts +114 -0
  229. package/app/types.ts +358 -0
  230. package/app/utils/appDeploySource.ts +50 -0
  231. package/app/utils/appKeys.ts +55 -0
  232. package/app/utils/appRuntimeUrl.ts +51 -0
  233. package/app/utils/async.ts +28 -0
  234. package/app/utils/asyncMapStatus.ts +31 -0
  235. package/app/utils/clipboard.ts +86 -0
  236. package/app/utils/credits.ts +12 -0
  237. package/app/utils/desktopAgentRuntimeStatusClient.ts +42 -0
  238. package/app/utils/desktopAgentRuntimeTurnClient.ts +70 -0
  239. package/app/utils/desktopLocalConnectorClient.ts +83 -0
  240. package/app/utils/env.ts +12 -0
  241. package/app/utils/excelToSlate.ts +430 -0
  242. package/app/utils/fileReaders.ts +12 -0
  243. package/app/utils/fileUtils.ts +229 -0
  244. package/app/utils/imageUtils.native.ts +96 -0
  245. package/app/utils/imageUtils.ts +244 -0
  246. package/app/utils/ime.ts +43 -0
  247. package/app/utils/myContentItems.ts +290 -0
  248. package/app/utils/processDateRange.ts +30 -0
  249. package/app/utils/retryFetch.ts +61 -0
  250. package/app/utils/slateToExcel.ts +58 -0
  251. package/app/utils/toast.native.ts +42 -0
  252. package/app/utils/toast.ts +3 -0
  253. package/app/web/spaceInitGuard.ts +28 -0
  254. package/auth/action/signOutAction.ts +0 -0
  255. package/auth/action/signUpAction.ts +227 -0
  256. package/auth/actor.ts +16 -0
  257. package/auth/authSlice.ts +517 -0
  258. package/auth/billing.ts +130 -0
  259. package/auth/client/deleteUserRequest.ts +86 -0
  260. package/auth/client/loginRequest.ts +14 -0
  261. package/auth/hooks/useAuth.ts +9 -0
  262. package/auth/hooks/useDeleteOwnAccount.ts +50 -0
  263. package/auth/hooks/useDeleteOwnAccountFlow.ts +66 -0
  264. package/auth/hooks/useDeleteUser.ts +45 -0
  265. package/auth/hooks/useEnableUser.ts +50 -0
  266. package/auth/hooks/useFetchUsers.ts +77 -0
  267. package/auth/hooks/useRechargeUser.ts +82 -0
  268. package/auth/index.ts +1 -0
  269. package/auth/invite.ts +19 -0
  270. package/auth/locale.ts +84 -0
  271. package/auth/resetAuthScopedClientState.ts +27 -0
  272. package/auth/rn/tokenManager.ts +72 -0
  273. package/auth/routes.ts +127 -0
  274. package/auth/server/accessActivity.ts +143 -0
  275. package/auth/server/billingFullChainSimulator.ts +325 -0
  276. package/auth/server/billingUsageReport.ts +192 -0
  277. package/auth/server/cliLogin.ts +198 -0
  278. package/auth/server/creatorEarningCreditConversion.ts +515 -0
  279. package/auth/server/creatorEarningsLedger.ts +165 -0
  280. package/auth/server/creatorEarningsReport.ts +299 -0
  281. package/auth/server/creatorSettlementLedger.ts +386 -0
  282. package/auth/server/creatorSettlementReport.ts +442 -0
  283. package/auth/server/creatorSplitConfig.ts +191 -0
  284. package/auth/server/deduct.ts +270 -0
  285. package/auth/server/delete.ts +887 -0
  286. package/auth/server/disable.ts +61 -0
  287. package/auth/server/emailAutomation.ts +358 -0
  288. package/auth/server/emailAutomationConfig.ts +88 -0
  289. package/auth/server/emailAutomationRules.ts +94 -0
  290. package/auth/server/emailAutomationTemplates.ts +131 -0
  291. package/auth/server/emailAutomationTypes.ts +38 -0
  292. package/auth/server/emailDbConfig.ts +147 -0
  293. package/auth/server/emailDelivery.ts +960 -0
  294. package/auth/server/emailDeliveryGuards.ts +282 -0
  295. package/auth/server/emailPolicy.ts +43 -0
  296. package/auth/server/emailPreferences.ts +117 -0
  297. package/auth/server/emailProvider.ts +277 -0
  298. package/auth/server/emailReport.ts +439 -0
  299. package/auth/server/emailRuntimeConfig.ts +86 -0
  300. package/auth/server/emailScenarioNotifications.ts +340 -0
  301. package/auth/server/enable.ts +61 -0
  302. package/auth/server/getRechargeHistory.ts +110 -0
  303. package/auth/server/getUser.ts +71 -0
  304. package/auth/server/inviteReward.ts +295 -0
  305. package/auth/server/inviteRewardEmail.ts +1 -0
  306. package/auth/server/ledger.ts +422 -0
  307. package/auth/server/ledgerAudit.ts +424 -0
  308. package/auth/server/ledgerWitness.ts +472 -0
  309. package/auth/server/listusers.ts +154 -0
  310. package/auth/server/locks.ts +32 -0
  311. package/auth/server/login.ts +184 -0
  312. package/auth/server/productBillingSplits.ts +166 -0
  313. package/auth/server/productEntitlements.ts +139 -0
  314. package/auth/server/productPurchase.ts +382 -0
  315. package/auth/server/recharge.ts +284 -0
  316. package/auth/server/revenueShareLedger.ts +389 -0
  317. package/auth/server/revenueShareReport.ts +258 -0
  318. package/auth/server/revenueSplitPolicy.ts +119 -0
  319. package/auth/server/revokeSessions.ts +59 -0
  320. package/auth/server/route.ts +195 -0
  321. package/auth/server/sendEmail.ts +176 -0
  322. package/auth/server/shared.ts +51 -0
  323. package/auth/server/signup.ts +423 -0
  324. package/auth/server/signupIpQuota.ts +44 -0
  325. package/auth/server/token.ts +109 -0
  326. package/auth/server/tokenUsageBilling.ts +312 -0
  327. package/auth/server/transfer.ts +40 -0
  328. package/auth/server/utils.ts +200 -0
  329. package/auth/sessionTokenVersion.ts +38 -0
  330. package/auth/token.ts +63 -0
  331. package/auth/tokenCookie.ts +1 -0
  332. package/auth/types.ts +28 -0
  333. package/auth/utils.ts +108 -0
  334. package/auth/web/bootstrapAuthState.ts +60 -0
  335. package/auth/web/tokenManager.ts +61 -0
  336. package/auth/web/useRegister.ts +70 -0
  337. package/build.ts +16 -0
  338. package/buildPublish.ts +133 -0
  339. package/buildPublishArtifactAssembly.ts +346 -0
  340. package/buildPublishImportAnalysis.ts +237 -0
  341. package/chat/chat.locale.ts +804 -0
  342. package/chat/dialog/actions/addCybotAction.ts +52 -0
  343. package/chat/dialog/actions/addReferenceKeysAction.ts +62 -0
  344. package/chat/dialog/actions/builtinDialogLlm.ts +35 -0
  345. package/chat/dialog/actions/cleanupCliSession.ts +40 -0
  346. package/chat/dialog/actions/compactDialogAndForkAction.ts +47 -0
  347. package/chat/dialog/actions/createDialogAction.ts +372 -0
  348. package/chat/dialog/actions/createScheduledTaskAction.ts +78 -0
  349. package/chat/dialog/actions/handleSendMessageAction.ts +197 -0
  350. package/chat/dialog/actions/handleSendMessageResolver.ts +29 -0
  351. package/chat/dialog/actions/removeCybotAction.ts +6 -0
  352. package/chat/dialog/actions/removeDialogAgentAction.ts +44 -0
  353. package/chat/dialog/actions/replacePrimaryCybotAction.ts +6 -0
  354. package/chat/dialog/actions/setPrimaryDialogAgentAction.ts +52 -0
  355. package/chat/dialog/actions/updateDialogSummaryAction.ts +405 -0
  356. package/chat/dialog/actions/updateDialogTitleAction.ts +151 -0
  357. package/chat/dialog/actions/updateDialogTitlePolicy.ts +30 -0
  358. package/chat/dialog/actions/updateTokensAction.ts +233 -0
  359. package/chat/dialog/dialogAgents.ts +54 -0
  360. package/chat/dialog/dialogPageRenderMode.ts +182 -0
  361. package/chat/dialog/dialogSlice.ts +872 -0
  362. package/chat/dialog/dialogTitle.ts +81 -0
  363. package/chat/dialog/dialogTokenStats.ts +12 -0
  364. package/chat/dialog/dialogUrl.ts +6 -0
  365. package/chat/dialog/ensureDialogSpaceAction.ts +208 -0
  366. package/chat/dialog/goal.ts +108 -0
  367. package/chat/dialog/hooks/useStreamingSymbol.ts +63 -0
  368. package/chat/dialog/objectAssistantRegistry.ts +286 -0
  369. package/chat/dialog/schedule.ts +17 -0
  370. package/chat/dialog/useCreateDialog.ts +52 -0
  371. package/chat/hooks/sendPermissionResolver.ts +128 -0
  372. package/chat/hooks/useChatInput.ts +99 -0
  373. package/chat/hooks/useChatInputSeed.ts +31 -0
  374. package/chat/hooks/useMessageInteraction.ts +412 -0
  375. package/chat/hooks/useSendPermission.ts +92 -0
  376. package/chat/hooks/useThinkingVisibility.ts +27 -0
  377. package/chat/messages/browserImageUrl.ts +48 -0
  378. package/chat/messages/deleteMessages.ts +47 -0
  379. package/chat/messages/fetchAndCacheMessages.ts +119 -0
  380. package/chat/messages/fetchConvMsgs.ts +51 -0
  381. package/chat/messages/fetchMessages.ts +84 -0
  382. package/chat/messages/fileUrl.ts +13 -0
  383. package/chat/messages/generateMessageKey.ts +21 -0
  384. package/chat/messages/hooks/useBase64Migration.ts +115 -0
  385. package/chat/messages/messageAgent.ts +8 -0
  386. package/chat/messages/messageContent.ts +199 -0
  387. package/chat/messages/messageContract.ts +88 -0
  388. package/chat/messages/messageSlice.ts +1191 -0
  389. package/chat/messages/pendingAttachmentParts.ts +117 -0
  390. package/chat/messages/sendFirstMessage.ts +193 -0
  391. package/chat/messages/toolPresentation.ts +212 -0
  392. package/chat/messages/toolThunks.ts +625 -0
  393. package/chat/messages/types.ts +176 -0
  394. package/chat/messages/web/ChatDisplayContext.ts +14 -0
  395. package/chat/messages/web/ToolMessageTypes.ts +23 -0
  396. package/chat/messages/web/diffViewerModel.ts +61 -0
  397. package/chat/messages/web/groupToolEntries.ts +44 -0
  398. package/chat/messages/web/groupToolMessages.ts +35 -0
  399. package/chat/messages/web/inlineReactArtifactParser.ts +63 -0
  400. package/chat/messages/web/toolDisplayName.ts +22 -0
  401. package/chat/messages/web/useLoopStopReason.ts +43 -0
  402. package/chat/messages/ziweiChartDoc.ts +94 -0
  403. package/chat/web/docxToSlate.ts +597 -0
  404. package/chat/web/fileProcessor.ts +442 -0
  405. package/chat/web/hooks/useProgressiveDisplayCount.ts +102 -0
  406. package/chat/web/messageInputAgentUi.ts +189 -0
  407. package/chat/web/messageInputKeyBehavior.ts +53 -0
  408. package/chat/web/messageInputMention.ts +102 -0
  409. package/chat/web/messageInputSendResolver.ts +51 -0
  410. package/chat/web/messageSlashCommands.ts +10 -0
  411. package/chat/web/pdfOcrProcessor.ts +131 -0
  412. package/chat/web/sidebar/allViewSearch.ts +87 -0
  413. package/chat/web/sidebar/types.ts +12 -0
  414. package/chat/web/sidebar/useChatSidebarFilteredData.ts +141 -0
  415. package/chat/web/sidebar/useSidebarDragAndDrop.ts +56 -0
  416. package/cliCommandFactories.ts +32 -0
  417. package/cliEnvHelpers.ts +96 -10
  418. package/cliIoTypes.ts +3 -0
  419. package/client/agentRun.ts +26 -229
  420. package/client/agentRunLocalExecution.test.ts +123 -0
  421. package/client/agentRunLocalExecution.ts +124 -0
  422. package/client/agentRunRuntimeSelection.test.ts +158 -0
  423. package/client/agentRunRuntimeSelection.ts +155 -0
  424. package/client/profileConfig.test.ts +66 -0
  425. package/client/profileConfig.ts +41 -0
  426. package/client/streamingOutput.ts +1 -3
  427. package/client/taskRunPrompt.ts +7 -24
  428. package/commandRegistry.ts +2 -2
  429. package/connector-experimental/daemonLauncher.ts +189 -0
  430. package/core/builtinAgents.ts +58 -0
  431. package/core/coin.ts +42 -0
  432. package/core/config.ts +15 -0
  433. package/core/crypto.ts +51 -0
  434. package/core/events/types.ts +145 -0
  435. package/core/generateKeyPairFromSeedV1.ts +15 -0
  436. package/core/generateMainKey.ts +22 -0
  437. package/core/init.ts +41 -0
  438. package/core/localOrigins.ts +8 -0
  439. package/core/password.ts +13 -0
  440. package/core/prefix.ts +23 -0
  441. package/create/editor/blockCommands.ts +118 -0
  442. package/create/editor/highlightExample.ts +66 -0
  443. package/create/editor/imageUpload.ts +66 -0
  444. package/create/editor/mark.ts +15 -0
  445. package/create/editor/plugins/normalizeChineseTypography.ts +85 -0
  446. package/create/editor/plugins/withBlockStructure.ts +53 -0
  447. package/create/editor/plugins/withChineseTypography.ts +61 -0
  448. package/create/editor/plugins/withLayout.ts +30 -0
  449. package/create/editor/plugins/withLinks.ts +13 -0
  450. package/create/editor/plugins/withMentions.ts +15 -0
  451. package/create/editor/plugins/withTables.ts +52 -0
  452. package/create/editor/tableCommands.ts +270 -0
  453. package/create/editor/theme/prism/default.ts +145 -0
  454. package/create/editor/theme/prism/githubDark.ts +139 -0
  455. package/create/editor/theme/prism/githubLight.ts +139 -0
  456. package/create/editor/theme/prism/index.ts +23 -0
  457. package/create/editor/theme/prism/okaidia.ts +197 -0
  458. package/create/editor/toolMentionOptions.ts +19 -0
  459. package/create/editor/transforms/fromMarkdown/index.ts +260 -0
  460. package/create/editor/transforms/fromMarkdown/inline.ts +285 -0
  461. package/create/editor/transforms/fromMarkdown/table.ts +130 -0
  462. package/create/editor/transforms/markdownToSlate.ts +24 -0
  463. package/create/editor/transforms/slateToRenderMarkdown.ts +218 -0
  464. package/create/editor/transforms/slateToSimplifiedMarkdown.ts +224 -0
  465. package/create/editor/transforms/slateToText.ts +33 -0
  466. package/create/editor/types.ts +120 -0
  467. package/create/editor/utils/editorFactory.ts +54 -0
  468. package/create/editor/utils/hasPlainCodeBlock.ts +39 -0
  469. package/create/editor/utils/linkCommands.ts +63 -0
  470. package/create/editor/utils/pdfToSlate.ts +706 -0
  471. package/create/editor/utils/slateUtils.ts +233 -0
  472. package/create/editor/utils/txtToSlate.ts +40 -0
  473. package/create/hooks/category.ts +82 -0
  474. package/create/routePaths.ts +5 -0
  475. package/create/space/addSpaceAction.ts +193 -0
  476. package/create/space/category/categoryActions.ts +427 -0
  477. package/create/space/changeSpaceAction.ts +36 -0
  478. package/create/space/constants.ts +8 -0
  479. package/create/space/content/addContentAction.ts +116 -0
  480. package/create/space/content/contentThunks.ts +90 -0
  481. package/create/space/content/deleteContentFromSpaceAction.ts +187 -0
  482. package/create/space/content/deleteMultipleContentAction.ts +112 -0
  483. package/create/space/content/moveContentAction.ts +285 -0
  484. package/create/space/content/updateContentCategoryAction.ts +154 -0
  485. package/create/space/content/updateContentTitleAction.ts +106 -0
  486. package/create/space/content/uploadAndAddFileToSpaceAction.ts +98 -0
  487. package/create/space/contentKeyUtils.ts +117 -0
  488. package/create/space/contentLabels.ts +56 -0
  489. package/create/space/contentTypeMeta.ts +169 -0
  490. package/create/space/deleteSpaceAction.ts +276 -0
  491. package/create/space/fetchSpaceAction.ts +70 -0
  492. package/create/space/fetchSpaceSidebarStateAction.ts +26 -0
  493. package/create/space/hooks/agentFetchRetry.ts +19 -0
  494. package/create/space/hooks/useAgentFetcher.ts +149 -0
  495. package/create/space/hooks/useGroupedContent.ts +118 -0
  496. package/create/space/hooks/useSpaceEvents.ts +43 -0
  497. package/create/space/initialSpace.ts +78 -0
  498. package/create/space/loadDefaultSpaceAction.ts +57 -0
  499. package/create/space/member/addMemberAction.ts +79 -0
  500. package/create/space/member/fetchUserSpaceMembershipsAction.ts +386 -0
  501. package/create/space/member/memberThunks.ts +47 -0
  502. package/create/space/member/removeMemberAction.ts +67 -0
  503. package/create/space/publicCatalogSpace.ts +39 -0
  504. package/create/space/resolvePreferredSpaceId.ts +113 -0
  505. package/create/space/sidebarVisibleTypes.ts +214 -0
  506. package/create/space/space.locale.ts +981 -0
  507. package/create/space/spaceAccess.ts +182 -0
  508. package/create/space/spaceCollapsedState.ts +54 -0
  509. package/create/space/spaceKeys.ts +65 -0
  510. package/create/space/spaceSlice.ts +328 -0
  511. package/create/space/spaceThunks.ts +410 -0
  512. package/create/space/types.ts +27 -0
  513. package/create/space/updateSpaceAction.ts +107 -0
  514. package/create/space/utils/permissions.ts +47 -0
  515. package/create/space/validateSpacePermission.ts +38 -0
  516. package/create/types.ts +21 -0
  517. package/create/version/appVersionReplication.ts +160 -0
  518. package/create/version/versionApi.ts +142 -0
  519. package/customCodingAgentFlow.ts +208 -0
  520. package/customCodingAgentRecord.ts +179 -0
  521. package/database/actions/agentReadResolution.ts +33 -0
  522. package/database/actions/cacheMergedUserData.ts +1 -1
  523. package/database/actions/common.ts +44 -8
  524. package/database/actions/fetchUserData.ts +1 -1
  525. package/database/actions/fileContent.ts +3 -3
  526. package/database/actions/patch.ts +3 -3
  527. package/database/actions/read.ts +115 -76
  528. package/database/actions/readAndWait.ts +54 -86
  529. package/database/actions/readOutcome.ts +45 -0
  530. package/database/actions/readResolution.ts +102 -0
  531. package/database/actions/remove.ts +2 -2
  532. package/database/actions/upload.ts +4 -4
  533. package/database/actions/upsert.ts +2 -2
  534. package/database/actions/write.ts +4 -4
  535. package/database/client/handleError.ts +1 -1
  536. package/database/client/queryRequest.ts +1 -1
  537. package/database/dbSlice.ts +2 -2
  538. package/database/email.ts +1 -1
  539. package/database/hooks/useUserData.ts +4 -4
  540. package/database/keys.ts +2 -2
  541. package/database/runtimeServerContext.ts +3 -3
  542. package/database/server/actorAccess.ts +1 -1
  543. package/database/server/cybotReadonly.ts +1 -1
  544. package/database/server/dataHandlers.ts +1 -1
  545. package/database/server/delete.ts +8 -8
  546. package/database/server/emailRepository.ts +7 -7
  547. package/database/server/fileService.ts +1 -1
  548. package/database/server/handleTransaction.ts +2 -2
  549. package/database/server/patch.ts +3 -3
  550. package/database/server/read.ts +5 -5
  551. package/database/server/resourceAccess.ts +2 -2
  552. package/database/server/routes.ts +3 -3
  553. package/database/server/write.ts +5 -5
  554. package/database/table/deleteTable.ts +1 -1
  555. package/database/userPreferenceRegister.ts +2 -2
  556. package/dialogDataAccess.ts +186 -0
  557. package/dialogInternalCommandEntries.ts +11 -0
  558. package/dialogReadCommands.ts +179 -0
  559. package/dialogReadHelpers.ts +226 -0
  560. package/dialogStatusCommands.ts +122 -0
  561. package/docInternalCommandEntries.ts +20 -0
  562. package/hybridReadHelpers.ts +109 -0
  563. package/index.ts +2 -6
  564. package/integrations/anthropic/anthropicModels.ts +47 -0
  565. package/integrations/anthropic/type.ts +41 -0
  566. package/integrations/deepseek/models.ts +67 -0
  567. package/integrations/google/models.ts +298 -0
  568. package/integrations/openai/chatCompletionStreamMode.ts +10 -0
  569. package/integrations/openai/filterAndCleanMessages.ts +284 -0
  570. package/integrations/openai/flexTier.ts +102 -0
  571. package/integrations/openai/generateOpenAIRequestBody.ts +274 -0
  572. package/integrations/openai/generateResponseRequestBody.ts +77 -0
  573. package/integrations/openai/models.ts +271 -0
  574. package/integrations/openai/providerBodyCompatibility.ts +23 -0
  575. package/integrations/openai/responsesHelpers.ts +297 -0
  576. package/integrations/postmark/index.ts +57 -0
  577. package/integrations/resend/index.ts +353 -0
  578. package/integrations/weather/getWeather.ts +24 -0
  579. package/integrations/weather/index.ts +6 -0
  580. package/integrations/weather/routes.ts +31 -0
  581. package/integrations/weather/weatherApi.ts +27 -0
  582. package/integrations/weather/weatherConstants.ts +2 -0
  583. package/integrations/weather/weatherI18n.ts +50 -0
  584. package/integrations/weather/weatherService.ts +50 -0
  585. package/integrations/weather/weatherTypes.ts +140 -0
  586. package/integrations/weather/weatherUtils.ts +46 -0
  587. package/integrations/x-reader/backends/localBrowser.ts +215 -0
  588. package/integrations/x-reader/backends/publicFallback.ts +31 -0
  589. package/integrations/x-reader/backends/rawCdp.ts +218 -0
  590. package/integrations/x-reader/bridge/chromeBridgeManager.ts +235 -0
  591. package/integrations/x-reader/bridge/readXPostWithBridge.ts +73 -0
  592. package/integrations/x-reader/fixtureParser.ts +101 -0
  593. package/integrations/x-reader/index.ts +9 -0
  594. package/integrations/x-reader/redaction.ts +27 -0
  595. package/integrations/x-reader/types.ts +109 -0
  596. package/integrations/x-reader/visibleTextParser.ts +108 -0
  597. package/integrations/xai/models.ts +13 -0
  598. package/internalCommandEntries.ts +8 -0
  599. package/machineCommandPrompts.ts +77 -0
  600. package/machineCommandResolution.ts +43 -0
  601. package/machineCommands.ts +89 -1107
  602. package/machineDaemonCommands.ts +29 -0
  603. package/machineHeartbeatCommands.ts +29 -0
  604. package/machineStatusCommands.ts +95 -0
  605. package/machineWatchCommands.ts +41 -0
  606. package/machineWsPromptMaterialization.ts +89 -0
  607. package/machineWsRunDispatch.ts +570 -0
  608. package/machineWsSession.ts +148 -0
  609. package/package.json +109 -5
  610. package/pageCreateCommands.ts +219 -0
  611. package/pageDeleteCommands.ts +167 -0
  612. package/pageReadCommands.ts +151 -0
  613. package/pageUpdateCommands.ts +249 -0
  614. package/pageWriteHelpers.ts +209 -0
  615. package/publishPackage.ts +36 -0
  616. package/render/canvas/canvasEditContext.ts +1 -1
  617. package/render/layout/mainLayoutViewMode.ts +1 -1
  618. package/render/page/createPageAction.ts +12 -12
  619. package/render/page/docSlice.ts +8 -8
  620. package/render/page/server/createPage.ts +7 -7
  621. package/render/page/server/handleCreatePage.ts +2 -2
  622. package/render/page/types.ts +2 -2
  623. package/render/surf/utils/groupedWeatherData.ts +1 -1
  624. package/render/table/createTableAction.ts +7 -7
  625. package/render/table/deleteTableAction.ts +4 -4
  626. package/render/table/fetchAndCacheTableRows.ts +2 -2
  627. package/render/table/tableSlice.ts +6 -6
  628. package/render/table/types.ts +1 -1
  629. package/render/table/useCreateTable.ts +2 -2
  630. package/render/table/useTable.ts +2 -2
  631. package/render/table/utils/tableSerialization.ts +1 -1
  632. package/runtimeInternalCommandEntries.ts +15 -0
  633. package/runtimePassthroughCommands.ts +22 -0
  634. package/scriptCommandEntries.ts +5 -45
  635. package/scriptPassthroughHelpers.ts +28 -0
  636. package/secretScanHelpers.ts +31 -0
  637. package/server/agentEmailRegistrationRoutes.ts +29 -0
  638. package/server/agentRunRouteContract.ts +9 -0
  639. package/server/agentRunRoutes.ts +10 -0
  640. package/server/api/methods.ts +333 -0
  641. package/server/api/tableHandlers.ts +55 -0
  642. package/server/api/types.ts +27 -0
  643. package/server/apiContract.ts +88 -0
  644. package/server/apiRouteAdapter.ts +218 -0
  645. package/server/appBundler.ts +90 -0
  646. package/server/appRoutes.ts +92 -0
  647. package/server/artifactIconsRoute.ts +89 -0
  648. package/server/artifactRuntimeRoute.ts +136 -0
  649. package/server/authenticateToken.ts +73 -0
  650. package/server/billingLedgerRoutes.ts +48 -0
  651. package/server/cliChatRoutes.ts +5 -0
  652. package/server/cloudflareRoutes.ts +35 -0
  653. package/server/coreHeaders.ts +29 -0
  654. package/server/coreReadiness.ts +39 -0
  655. package/server/coreRoutes.ts +65 -0
  656. package/server/coreRuntime.ts +93 -0
  657. package/server/createResponse.ts +68 -0
  658. package/server/cryptoPaymentRoutes.ts +8 -0
  659. package/server/databaseRoutes.ts +225 -0
  660. package/server/desktopRuntimeRoutes.ts +120 -0
  661. package/server/devBuildInfo.ts +51 -0
  662. package/server/devReload.ts +161 -0
  663. package/server/devToolPathPolicy.ts +59 -0
  664. package/server/devToolRoutes.ts +274 -0
  665. package/server/email/cloudflareEmailProvider.ts +119 -0
  666. package/server/email/cloudflareInboundBridge.ts +121 -0
  667. package/server/email/cloudflareInboundWorker.ts +28 -0
  668. package/server/email/provider.ts +149 -0
  669. package/server/email/providerRegistry.ts +22 -0
  670. package/server/emailInboundRoutes.ts +17 -0
  671. package/server/entry.ts +211 -0
  672. package/server/handleRPCRequest.ts +117 -0
  673. package/server/handlers/activityStatsHandler.ts +74 -0
  674. package/server/handlers/agentEmailRegistrationE2EHandler.ts +406 -0
  675. package/server/handlers/agentEmailRegistrationE2ERoutes.ts +6 -0
  676. package/server/handlers/agentRun/agentLookup.ts +77 -0
  677. package/server/handlers/agentRun/autonomousRuntime.ts +355 -0
  678. package/server/handlers/agentRun/backgroundRunDialog.ts +31 -0
  679. package/server/handlers/agentRun/builtinAgents.ts +347 -0
  680. package/server/handlers/agentRun/continueDialogContext.ts +90 -0
  681. package/server/handlers/agentRun/debugContext.ts +58 -0
  682. package/server/handlers/agentRun/dialogLookup.ts +67 -0
  683. package/server/handlers/agentRun/foregroundStreamDialog.ts +13 -0
  684. package/server/handlers/agentRun/index.ts +1630 -0
  685. package/server/handlers/agentRun/inheritedDialogPrompt.ts +111 -0
  686. package/server/handlers/agentRun/localRuntimeBootstrap.ts +69 -0
  687. package/server/handlers/agentRun/loop.ts +2210 -0
  688. package/server/handlers/agentRun/machineConnector.ts +235 -0
  689. package/server/handlers/agentRun/machineRunAudit.ts +49 -0
  690. package/server/handlers/agentRun/modelUsageToolHandlers.ts +368 -0
  691. package/server/handlers/agentRun/referenceRuntime.ts +50 -0
  692. package/server/handlers/agentRun/requestContext.ts +86 -0
  693. package/server/handlers/agentRun/response.ts +27 -0
  694. package/server/handlers/agentRun/runBilling.ts +108 -0
  695. package/server/handlers/agentRun/runDialogPreparation.ts +55 -0
  696. package/server/handlers/agentRun/runtimeBinding.ts +61 -0
  697. package/server/handlers/agentRun/runtimeContext.ts +143 -0
  698. package/server/handlers/agentRun/runtimeExecutionContext.ts +153 -0
  699. package/server/handlers/agentRun/runtimePreparation.ts +193 -0
  700. package/server/handlers/agentRun/runtimeRouting.ts +88 -0
  701. package/server/handlers/agentRun/runtimeSystemMessages.ts +165 -0
  702. package/server/handlers/agentRun/saveDialog.ts +1373 -0
  703. package/server/handlers/agentRun/syncRunDialog.ts +90 -0
  704. package/server/handlers/agentRun/tableActivityProjection.ts +132 -0
  705. package/server/handlers/agentRun/taskRunControlPrompt.ts +122 -0
  706. package/server/handlers/agentRun/taskRunToolHandler.ts +579 -0
  707. package/server/handlers/agentRun/toolExecutor.ts +2909 -0
  708. package/server/handlers/agentRun/toolPolicyGuards.ts +295 -0
  709. package/server/handlers/agentRun/types.ts +94 -0
  710. package/server/handlers/agentRun/workspaceLease.ts +58 -0
  711. package/server/handlers/alphaTestRouteGuard.ts +30 -0
  712. package/server/handlers/apifyActorHandler.ts +170 -0
  713. package/server/handlers/appDeployFlow.ts +876 -0
  714. package/server/handlers/appDeployHandler.ts +4 -0
  715. package/server/handlers/appDeployMutationHandlers.ts +133 -0
  716. package/server/handlers/appDeployReadHandlers.ts +321 -0
  717. package/server/handlers/appDeployShared.ts +230 -0
  718. package/server/handlers/appDeployStatusStore.ts +178 -0
  719. package/server/handlers/appDomainHandler.ts +476 -0
  720. package/server/handlers/appLegacyInfraCleanup.ts +7 -0
  721. package/server/handlers/appSandboxHandler.ts +1055 -0
  722. package/server/handlers/appSourceReadiness.ts +75 -0
  723. package/server/handlers/appSpaceAccess.ts +179 -0
  724. package/server/handlers/applyEditHandler.ts +544 -0
  725. package/server/handlers/applyLineEditsHandler.ts +1058 -0
  726. package/server/handlers/billingLedgerAuditHandler.ts +82 -0
  727. package/server/handlers/billingLedgerWitnessHandler.ts +161 -0
  728. package/server/handlers/billingUsageReportHandler.ts +90 -0
  729. package/server/handlers/browserToolHandler.ts +450 -0
  730. package/server/handlers/cfTextToSpeechHandler.ts +137 -0
  731. package/server/handlers/cfWhisperHandler.ts +206 -0
  732. package/server/handlers/chatBillingSse.ts +79 -0
  733. package/server/handlers/chatHandler.ts +797 -0
  734. package/server/handlers/chatProxyRouting.ts +404 -0
  735. package/server/handlers/chatUpstreamRetry.ts +162 -0
  736. package/server/handlers/checkEnvHandler.ts +250 -0
  737. package/server/handlers/cliChatHandler.ts +266 -0
  738. package/server/handlers/cloudflareBrowserHandler.ts +275 -0
  739. package/server/handlers/cloudflareCrawlHandler.ts +260 -0
  740. package/server/handlers/codeSearchHandler.ts +484 -0
  741. package/server/handlers/connector/connectorConnectionRegistry.ts +192 -0
  742. package/server/handlers/connector/connectorWebSocket.ts +117 -0
  743. package/server/handlers/creatorEarningsReportHandler.ts +97 -0
  744. package/server/handlers/creatorSettlementReportHandler.ts +98 -0
  745. package/server/handlers/deepseekOcrHandler.ts +114 -0
  746. package/server/handlers/deleteMemoryHandler.ts +115 -0
  747. package/server/handlers/desktopAgentRuntimeAdapter.ts +307 -0
  748. package/server/handlers/desktopAgentRuntimeHostFacts.ts +40 -0
  749. package/server/handlers/desktopAgentRuntimeStatusHandler.ts +54 -0
  750. package/server/handlers/desktopAgentRuntimeTurnHandler.ts +165 -0
  751. package/server/handlers/desktopAgentRuntimeTurnService.ts +352 -0
  752. package/server/handlers/desktopClipboardHandler.ts +104 -0
  753. package/server/handlers/desktopFiles/handler.ts +159 -0
  754. package/server/handlers/desktopFiles/operations.ts +202 -0
  755. package/server/handlers/desktopFiles/sandbox.ts +62 -0
  756. package/server/handlers/desktopFiles/store.ts +81 -0
  757. package/server/handlers/desktopLlamaRuntimeHandler.ts +360 -0
  758. package/server/handlers/desktopLocalConnectorHandler.ts +101 -0
  759. package/server/handlers/desktopUpdaterHandler.ts +132 -0
  760. package/server/handlers/dialogEvents.ts +10 -0
  761. package/server/handlers/emailInboundHandler.ts +65 -0
  762. package/server/handlers/eventBus.ts +160 -0
  763. package/server/handlers/exaSearchHandler.ts +73 -0
  764. package/server/handlers/execShellHandler.ts +661 -0
  765. package/server/handlers/favoriteHandlers.ts +417 -0
  766. package/server/handlers/fetchWebpageHandler.ts +117 -0
  767. package/server/handlers/fileOutlineHandler.ts +107 -0
  768. package/server/handlers/geminiImagePreviewHandler.ts +612 -0
  769. package/server/handlers/getDialogBillingHandler.ts +151 -0
  770. package/server/handlers/getTransactionsHandler.ts +107 -0
  771. package/server/handlers/googleNativeChat.ts +572 -0
  772. package/server/handlers/listFilesHandler.ts +139 -0
  773. package/server/handlers/machines/machineAuth.ts +149 -0
  774. package/server/handlers/machines/machineBinding.ts +59 -0
  775. package/server/handlers/machines/machineHandlers.ts +279 -0
  776. package/server/handlers/machines/machineInstallAssets.ts +563 -0
  777. package/server/handlers/machines/machineRegistry.ts +89 -0
  778. package/server/handlers/notificationEmitter.ts +189 -0
  779. package/server/handlers/notificationsHandler.ts +91 -0
  780. package/server/handlers/olmOcrHandler.ts +115 -0
  781. package/server/handlers/openaiImageHandler.ts +500 -0
  782. package/server/handlers/providerHealthHandler.ts +36 -0
  783. package/server/handlers/publicHandler.ts +209 -0
  784. package/server/handlers/readFileHandler.ts +300 -0
  785. package/server/handlers/readXPostHandler.ts +180 -0
  786. package/server/handlers/rememberMemoryHandler.ts +69 -0
  787. package/server/handlers/remotionRenderHandler.ts +236 -0
  788. package/server/handlers/renderMarkdownHandler.ts +66 -0
  789. package/server/handlers/revenueShareReportHandler.ts +96 -0
  790. package/server/handlers/searchRepoHandler.ts +159 -0
  791. package/server/handlers/tableAccess.ts +34 -0
  792. package/server/handlers/tableToolHandlers.ts +741 -0
  793. package/server/handlers/typecheckWorker.ts +54 -0
  794. package/server/handlers/userEvents.ts +6 -0
  795. package/server/handlers/userSecretsHandler.ts +210 -0
  796. package/server/handlers/versionHandler.ts +281 -0
  797. package/server/handlers/versionStore.ts +176 -0
  798. package/server/handlers/wereadGatewayHandler.ts +48 -0
  799. package/server/handlers/whisperHandler.ts +158 -0
  800. package/server/handlers/writeFileHandler.ts +168 -0
  801. package/server/html/desktopReleaseManifest.server.ts +17 -0
  802. package/server/html/generateErrorResponse.ts +22 -0
  803. package/server/html/serializeState.ts +9 -0
  804. package/server/html/ssrPreload.ts +247 -0
  805. package/server/html/template.ts +275 -0
  806. package/server/httpCompression.ts +102 -0
  807. package/server/index.ts +0 -0
  808. package/server/liveReloadScript.ts +105 -0
  809. package/server/luIconNames.ts +14 -0
  810. package/server/machineRoutes.ts +44 -0
  811. package/server/mediaRoutes.ts +25 -0
  812. package/server/memoryRoutes.ts +14 -0
  813. package/server/normalizedStatusRoutes.ts +23 -0
  814. package/server/payments/crypto/cryptoUsdcBaseAddressPool.ts +49 -0
  815. package/server/payments/crypto/cryptoUsdcBaseConfig.ts +120 -0
  816. package/server/payments/crypto/cryptoUsdcBasePaymentProvider.ts +134 -0
  817. package/server/payments/crypto/cryptoUsdcBaseScanner.ts +267 -0
  818. package/server/payments/crypto/cryptoUsdcBaseWatcher.ts +40 -0
  819. package/server/payments/crypto/cryptoUsdtTronAddressPool.ts +49 -0
  820. package/server/payments/crypto/cryptoUsdtTronConfig.ts +120 -0
  821. package/server/payments/crypto/cryptoUsdtTronPaymentProvider.ts +132 -0
  822. package/server/payments/crypto/cryptoUsdtTronScanner.ts +313 -0
  823. package/server/payments/crypto/cryptoUsdtTronWatcher.ts +40 -0
  824. package/server/payments/paymentProvider.ts +6 -0
  825. package/server/payments/paymentRoutes.ts +27 -0
  826. package/server/payments/rechargeCredits.ts +69 -0
  827. package/server/payments/waffo/waffoPaymentProvider.ts +341 -0
  828. package/server/preview/previewCapability.ts +90 -0
  829. package/server/preview/previewConfig.ts +54 -0
  830. package/server/preview/previewGateway.ts +71 -0
  831. package/server/preview/previewRealtime.ts +33 -0
  832. package/server/providerHealthProbe.ts +198 -0
  833. package/server/providerHealthRoutes.ts +19 -0
  834. package/server/publicPaths.ts +12 -0
  835. package/server/publicRequestHandler.ts +15 -0
  836. package/server/reactAppBuilder.ts +416 -0
  837. package/server/realtimeRoutes.ts +69 -0
  838. package/server/renderStream.ts +20 -0
  839. package/server/routeFactory.ts +45 -0
  840. package/server/routes.ts +125 -0
  841. package/server/safeTempFile.ts +48 -0
  842. package/server/scheduler/scheduledTaskRuntime.ts +228 -0
  843. package/server/scheduler/schedulerService.ts +290 -0
  844. package/server/serverDrain.ts +129 -0
  845. package/server/services/browserSessionManager.ts +354 -0
  846. package/server/shareRoutes.ts +86 -0
  847. package/server/sqliteRoutes.ts +141 -0
  848. package/server/taskRunBridgeRoutes.ts +95 -0
  849. package/server/tasks.ts +113 -0
  850. package/server/waffoPaymentRoutes.ts +5 -0
  851. package/server/webUtilityRoutes.ts +50 -0
  852. package/server/workerValidator.ts +224 -0
  853. package/share/action.ts +225 -0
  854. package/share/clientTableReplication.ts +160 -0
  855. package/share/helpers.ts +302 -0
  856. package/share/keys.ts +243 -0
  857. package/share/link.ts +40 -0
  858. package/share/loadOwnerShares.ts +154 -0
  859. package/share/paidAccess.ts +32 -0
  860. package/share/publicSharePolicy.ts +27 -0
  861. package/share/server/fetchCommunityShares.ts +45 -0
  862. package/share/server/helpers.ts +202 -0
  863. package/share/server/importShare.ts +148 -0
  864. package/share/server/listCommunityShares.ts +167 -0
  865. package/share/server/purchaseDoc.ts +224 -0
  866. package/share/server/readCommunityShareCover.ts +73 -0
  867. package/share/server/readSharedTable.ts +139 -0
  868. package/share/server/tableReplication.ts +351 -0
  869. package/share/shareSlice.ts +53 -0
  870. package/share/tableShareState.ts +74 -0
  871. package/share/types.ts +100 -0
  872. package/spaceCategoryCommands.ts +263 -0
  873. package/spaceCommands.ts +295 -0
  874. package/spaceDeleteCommands.ts +312 -0
  875. package/spaceInternalCommandEntries.ts +19 -0
  876. package/spaceMutationHelpers.ts +135 -0
  877. package/spaceReadCommands.ts +323 -0
  878. package/systemInternalCommandEntries.ts +16 -22
  879. package/tableCommands.ts +33 -133
  880. package/tableDataOutput.ts +41 -0
  881. package/tableDataSafety.ts +26 -0
  882. package/tableMetaCommands.ts +307 -0
  883. package/tableMutationCommands.ts +266 -0
  884. package/tableQueryParsing.ts +90 -0
  885. package/tableQueryRequest.ts +53 -0
  886. package/taskRunActions.ts +122 -0
  887. package/taskRunCommand.ts +8 -214
  888. package/taskRunParsing.ts +86 -0
  889. package/taskRunPromptShared.ts +55 -0
  890. package/tui/session.ts +43 -372
  891. package/tui/tuiCatalog.ts +22 -0
  892. package/tui/tuiCommandInterpreter.test.ts +169 -0
  893. package/tui/tuiCommandInterpreter.ts +253 -0
  894. package/tui/tuiPresentation.test.ts +154 -0
  895. package/tui/tuiPresentation.ts +146 -0
  896. package/workflowInternalCommandEntries.ts +20 -0
  897. package/offlineMarxistsAgentCommand.ts +0 -314
@@ -0,0 +1,2909 @@
1
+ // packages/server/handlers/agentRun/toolExecutor.ts
2
+ //
3
+ // 服务端 tool 执行器。
4
+ // 直接调用本机 API(无需 Redux),结果以字符串返回给 LLM。
5
+ // 不持久化任何内容。
6
+
7
+ import { markdownToSlate } from "../../../create/editor/transforms/markdownToSlate";
8
+ import { slateToRenderMarkdown } from "../../../create/editor/transforms/slateToRenderMarkdown";
9
+ import { extractMentionsFromSlate } from "../../../create/editor/utils/slateUtils";
10
+ import { WEB_AUTH_TOKEN_COOKIE } from "../../../auth/tokenCookie";
11
+ import { DataType } from "../../../create/types";
12
+ import { NOLO_CLUSTER_SERVERS } from "../../../database/config";
13
+ import { createAgentKey, createKey, createUserKey } from "../../../database/keys";
14
+ import { ulid } from "../../../database/utils/ulid";
15
+ import { saveBufferAsFile } from "../../../database/server/fileService";
16
+ import { shareKey } from "../../../share/keys";
17
+ import { DEFAULT_MODEL, getApiEndpoint } from "../../../ai/llm/providers";
18
+ import type { AssistantToolCall, ToolExecutionContext } from "./types";
19
+ import {
20
+ buildSkillDocMarkdown,
21
+ resolvePageSkillMetadata,
22
+ parseSkillDocProtocol,
23
+ parseExternalSkillMarkdown,
24
+ type SkillDocConfig,
25
+ } from "../../../ai/skills/skillDocProtocol";
26
+ import {
27
+ buildSkillDocFromArgs,
28
+ type CreateSkillDocArgs,
29
+ } from "../../../ai/skills/skillDocBuilder";
30
+ import {
31
+ diagnoseSkillDocument,
32
+ evaluateSkillDocument,
33
+ } from "../../../ai/skills/skillDiagnostics";
34
+ import {
35
+ buildSkillAgentRecord,
36
+ type CreateSkillAgentToolArgs,
37
+ } from "../../../ai/tools/agent/skillAgentPreset";
38
+ import {
39
+ prepareAgentDraftToolFunc,
40
+ type PrepareAgentDraftToolArgs,
41
+ } from "../../../ai/tools/agent/prepareAgentDraftTool";
42
+ import type { CreateAgentToolArgs } from "../../../ai/tools/agent/createAgentTool";
43
+ import {
44
+ guardDestructiveAction,
45
+ guardPublicTableShare,
46
+ guardKnowledgeCapture,
47
+ isDestructiveShellCommand,
48
+ guardWorkspaceRead,
49
+ recordKnowledgeCapture,
50
+ recordWorkspaceRead,
51
+ } from "./toolPolicyGuards";
52
+ import { buildReadDocResult } from "../../../ai/tools/readDocTool";
53
+ import { buildSkillFollowupResult } from "../../../ai/tools/skillFollowup";
54
+ import { runZiweiChart } from "../../../ai/tools/ziweiChartTool";
55
+ import { evaluateSmallVisualEditGuard } from "../../../ai/tools/appEditGuard";
56
+ import {
57
+ analyzeAppStyleSystem,
58
+ buildAppStyleSystemHint,
59
+ } from "../../../ai/tools/appReadSnapshot";
60
+ import {
61
+ calculateParallelBranchPricing,
62
+ normalizeBudgetCredits,
63
+ summarizeParallelBudget,
64
+ summarizeParallelCosts,
65
+ } from "../../../ai/tools/agent/parallelBudget";
66
+ import {
67
+ extractAgentRuntimeServerBase,
68
+ normalizeServerOrigin,
69
+ } from "../../../ai/agent/runtimeServerBase";
70
+ import { extractEmailVerificationArtifacts } from "../../../ai/tools/emailTools";
71
+ import { convertMarxistsBookToOfflineHtml } from "../../../ai/tools/marxistsOfflineBook";
72
+ import { formatMarxistsOfflineBookDisplayData } from "../../../ai/tools/convertMarxistsBookTool";
73
+ import {
74
+ formatJdProductDisplayData,
75
+ getKnownJdProductFallback,
76
+ hasSparseJdSpecifications,
77
+ isIncompleteProductData,
78
+ jdProductScraperFunc,
79
+ mergeJdProductData,
80
+ parseJdBrowserExtractedData,
81
+ } from "../../../ai/tools/jdProductScraperTool";
82
+ import {
83
+ buildDialogMessageSearchResults,
84
+ clampDialogSearchNumber,
85
+ normalizeDialogSearchText,
86
+ } from "../../../ai/tools/dialogMessageSearch";
87
+ import serverDb from "../../../database/server/db";
88
+ import { createSpaceKey } from "../../../create/space/spaceKeys";
89
+ import {
90
+ buildDeleteSpacesPreview,
91
+ filterSpaceDeletionCandidates,
92
+ resolveConfirmedSpaceDeletionTargets,
93
+ type SpaceMembershipLike,
94
+ type SpaceRecordLike,
95
+ } from "../../../ai/tools/deleteSpacesToolModel";
96
+ import { canonicalizeToolName } from "../../../ai/tools/toolNameAliases";
97
+ import {
98
+ runCompleteDialogGoalTool,
99
+ runCreateDialogGoalTool,
100
+ runCreateScheduledTaskTool,
101
+ runGetDialogGoalTool,
102
+ runNotifyUserTool,
103
+ runQueryModelUsageTool,
104
+ } from "./modelUsageToolHandlers";
105
+ import { runTaskRunTool } from "./taskRunToolHandler";
106
+ import { projectDialogActivityToSubjectRows } from "./tableActivityProjection";
107
+ import { resolveExistingDialogRef } from "./dialogLookup";
108
+
109
+ const APP_DEPLOY_POLL_INTERVAL_MS = 250;
110
+ const APP_DEPLOY_POLL_TIMEOUT_MS = 60_000;
111
+ const DEFAULT_PARALLEL_AGENT_BRANCH_TIMEOUT_MS = 10 * 60 * 1000;
112
+ const configuredParallelAgentBranchTimeoutMs = Number(
113
+ process.env.PARALLEL_AGENT_BRANCH_TIMEOUT_MS,
114
+ );
115
+ const PARALLEL_AGENT_BRANCH_TIMEOUT_MS =
116
+ Number.isFinite(configuredParallelAgentBranchTimeoutMs) &&
117
+ configuredParallelAgentBranchTimeoutMs > 0
118
+ ? configuredParallelAgentBranchTimeoutMs
119
+ : DEFAULT_PARALLEL_AGENT_BRANCH_TIMEOUT_MS;
120
+ const IMAGE_GENERATION_TOOL_NAMES = new Set([
121
+ "geminiFlashImage",
122
+ "geminiProImagePreview",
123
+ "openAIGptImageGenerate",
124
+ "openAIGptImageEdit",
125
+ "openAIGptImage",
126
+ ]);
127
+ const FEEDBACK_AGENT_ID = "01NOLOFEEDBACKA000000000R1";
128
+
129
+ const trimString = (value: unknown): string =>
130
+ typeof value === "string" ? value.trim() : "";
131
+
132
+ const normalizeStringArray = (value: unknown): string[] => {
133
+ if (Array.isArray(value)) {
134
+ return value.map(trimString).filter(Boolean);
135
+ }
136
+ if (typeof value === "string") {
137
+ return value.split(",").map((item) => item.trim()).filter(Boolean);
138
+ }
139
+ return [];
140
+ };
141
+
142
+ const normalizeAgentReferencesForServerCreate = (value: unknown) =>
143
+ Array.isArray(value)
144
+ ? value
145
+ .filter((item): item is Record<string, unknown> =>
146
+ !!item && typeof item === "object" && !Array.isArray(item)
147
+ )
148
+ .map((item) => ({
149
+ dbKey: trimString(item.dbKey),
150
+ title: trimString(item.title),
151
+ type: trimString(item.type) || "knowledge",
152
+ }))
153
+ .filter((item) => item.dbKey)
154
+ : [];
155
+
156
+ const normalizeRunnableAgentModel = (provider: string, model: string) => {
157
+ try {
158
+ getApiEndpoint({ provider, model } as any);
159
+ return { provider, model };
160
+ } catch (error) {
161
+ if (
162
+ error instanceof Error &&
163
+ (error.message.includes("Unsupported provider") ||
164
+ error.message.includes("Custom provider URL is required"))
165
+ ) {
166
+ return {
167
+ provider: DEFAULT_MODEL.provider,
168
+ model: DEFAULT_MODEL.name,
169
+ };
170
+ }
171
+ throw error;
172
+ }
173
+ };
174
+
175
+ const buildServerCreatedAgentRecord = (
176
+ userId: string,
177
+ args: CreateAgentToolArgs,
178
+ currentSpaceId?: string | null,
179
+ ) => {
180
+ const name = trimString(args.name);
181
+ const model = trimString(args.model);
182
+ const provider = trimString(args.provider);
183
+ if (!name) throw new Error("createAgent: name is required");
184
+ if (!model) throw new Error("createAgent: model is required");
185
+ if (!provider) throw new Error("createAgent: provider is required");
186
+ const runnableModel = normalizeRunnableAgentModel(provider, model);
187
+
188
+ const now = Date.now();
189
+ const id = ulid();
190
+ const greeting =
191
+ typeof args.greeting === "string"
192
+ ? args.greeting.trim()
193
+ : args.greeting && typeof args.greeting === "object"
194
+ ? args.greeting
195
+ : undefined;
196
+ return {
197
+ id,
198
+ type: DataType.AGENT,
199
+ userId,
200
+ createdAt: now,
201
+ updatedAt: now,
202
+ dialogCount: 0,
203
+ messageCount: 0,
204
+ tokenCount: 0,
205
+ spaceId: currentSpaceId || undefined,
206
+ name,
207
+ model: runnableModel.model,
208
+ provider: runnableModel.provider,
209
+ prompt: trimString(args.prompt),
210
+ introduction: trimString(args.introduction),
211
+ ...(greeting ? { greeting } : {}),
212
+ isPublic: args.isPublic === true,
213
+ tags: normalizeStringArray(args.tags),
214
+ tools: normalizeStringArray(args.tools),
215
+ references: normalizeAgentReferencesForServerCreate(args.references),
216
+ linkedSpaces: normalizeStringArray(args.linkedSpaces),
217
+ ...(typeof args.temperature === "number" ? { temperature: args.temperature } : {}),
218
+ ...(typeof args.top_p === "number" ? { top_p: args.top_p } : {}),
219
+ ...(typeof args.frequency_penalty === "number"
220
+ ? { frequency_penalty: args.frequency_penalty }
221
+ : {}),
222
+ ...(typeof args.presence_penalty === "number"
223
+ ? { presence_penalty: args.presence_penalty }
224
+ : {}),
225
+ ...(typeof args.max_tokens === "number" ? { max_tokens: args.max_tokens } : {}),
226
+ ...(args.reasoning_effort ? { reasoning_effort: args.reasoning_effort } : {}),
227
+ whitelist: args.isPublic === true ? [] : [],
228
+ };
229
+ };
230
+ const FEEDBACK_TABLE_ID = "01NOLOFEEDBACKT000000000R1";
231
+ const TASK_BOARD_TABLE_ID = "NOLOTASKBOARD";
232
+ const TASK_RUN_PRIMITIVE_TOOL_NAMES = new Set([
233
+ "readTaskContext",
234
+ "queryReadyWorkItems",
235
+ "upsertWorkItem",
236
+ "claimWorkItem",
237
+ "openDialog",
238
+ "recordArtifact",
239
+ "setBlocker",
240
+ "clearBlocker",
241
+ "requestReview",
242
+ "recordReview",
243
+ "submitOutcome",
244
+ "closeWorkItem",
245
+ ]);
246
+ const SEARCH_DIALOG_MESSAGES_SCAN_LIMIT = 500;
247
+ const SEARCH_DIALOG_MESSAGES_RESULT_LIMIT = 10;
248
+ const SEARCH_DIALOG_MESSAGES_CONTEXT_LIMIT = 3;
249
+ const SEARCH_DIALOG_MESSAGES_CLIP_CHARS = 1800;
250
+ const SEARCH_DIALOG_MESSAGES_CONTEXT_CLIP_CHARS = 600;
251
+
252
+ const sanitizeGeneratedHtmlFileName = (value: unknown, fallback: string): string => {
253
+ const raw = typeof value === "string" && value.trim() ? value.trim() : fallback;
254
+ const sanitized =
255
+ raw
256
+ .replace(/[\\/:*?"<>|]+/g, "-")
257
+ .replace(/\s+/g, "-")
258
+ .replace(/-+/g, "-")
259
+ .replace(/^-|-$/g, "")
260
+ .slice(0, 100) || fallback;
261
+ return /\.html?$/i.test(sanitized) ? sanitized : `${sanitized}.html`;
262
+ };
263
+
264
+ const buildFileContentUrl = (base: string, fileDbKey: string): string =>
265
+ `${base}/api/v1/db/file/content/${encodeURIComponent(fileDbKey)}`;
266
+
267
+ const normalizeBase = (base: string): string => base.replace(/\/+$/, "");
268
+
269
+ const normalizeSubjectRefs = (value: unknown): Array<{ kind: string; id: string; role?: string }> => {
270
+ if (!Array.isArray(value)) return [];
271
+ return value
272
+ .map((item) => {
273
+ if (!item || typeof item !== "object") return null;
274
+ const raw = item as Record<string, unknown>;
275
+ const kind = typeof raw.kind === "string" ? raw.kind.trim() : "";
276
+ const id = typeof raw.id === "string" ? raw.id.trim() : "";
277
+ if (!kind || !id) return null;
278
+ const role = typeof raw.role === "string" && raw.role.trim() ? raw.role.trim() : undefined;
279
+ return { kind, id, ...(role ? { role } : {}) };
280
+ })
281
+ .filter((item): item is { kind: string; id: string; role?: string } => Boolean(item));
282
+ };
283
+
284
+ function mergeSubjectRefs(
285
+ ...refGroups: unknown[]
286
+ ): Array<{ kind: string; id: string; role?: string }> {
287
+ const merged: Array<{ kind: string; id: string; role?: string }> = [];
288
+ const seen = new Set<string>();
289
+ for (const ref of refGroups.flatMap((group) => normalizeSubjectRefs(group))) {
290
+ const key = `${ref.kind}\u0000${ref.id}\u0000${ref.role ?? ""}`;
291
+ if (seen.has(key)) continue;
292
+ seen.add(key);
293
+ merged.push(ref);
294
+ }
295
+ return merged;
296
+ }
297
+
298
+ const resolveSameOriginChildRunBase = (targetBase: string, mainBase: string) => {
299
+ if (normalizeServerOrigin(targetBase) !== normalizeServerOrigin(mainBase)) {
300
+ return targetBase;
301
+ }
302
+ const port = process.env.HTTP_PORT;
303
+ if (!port) return targetBase;
304
+ const host = process.env.PLATFORM_SERVER_HOST || "127.0.0.1";
305
+ const loopbackHost =
306
+ host === "0.0.0.0" || host === "::" || host === "[::]" ? "127.0.0.1" : host;
307
+ return `http://${loopbackHost}:${port}`;
308
+ };
309
+
310
+ const generateShareToken = (): string => {
311
+ const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
312
+ const charsLen = chars.length;
313
+ const maxValid = 252;
314
+ let token = "";
315
+ while (token.length < 10) {
316
+ const bytes = new Uint8Array(16);
317
+ crypto.getRandomValues(bytes);
318
+ for (let i = 0; i < bytes.length && token.length < 10; i += 1) {
319
+ if (bytes[i] < maxValid) {
320
+ token += chars.charAt(bytes[i] % charsLen);
321
+ }
322
+ }
323
+ }
324
+ return token;
325
+ };
326
+ const normalizeTaskRunPrimitiveArgs = (
327
+ toolName: string,
328
+ args: Record<string, any>,
329
+ ): Record<string, any> | null => {
330
+ if (!TASK_RUN_PRIMITIVE_TOOL_NAMES.has(toolName)) return null;
331
+ const dbKey = args.dbKey ?? args.rowDbKey;
332
+ const baseArgs = {
333
+ action: toolName,
334
+ ...(typeof dbKey === "string" && dbKey.trim() ? { dbKey: dbKey.trim() } : {}),
335
+ ...(typeof args.tenantId === "string" && args.tenantId.trim() ? { tenantId: args.tenantId.trim() } : {}),
336
+ ...(typeof args.tableId === "string" && args.tableId.trim() ? { tableId: args.tableId.trim() } : {}),
337
+ ...(typeof args.rowId === "string" && args.rowId.trim() ? { rowId: args.rowId.trim() } : {}),
338
+ };
339
+
340
+ if (toolName !== "upsertWorkItem" || Array.isArray(args.workItems)) {
341
+ return {
342
+ ...baseArgs,
343
+ ...args,
344
+ action: toolName,
345
+ ...(typeof dbKey === "string" && dbKey.trim() ? { dbKey: dbKey.trim() } : {}),
346
+ rowDbKey: undefined,
347
+ };
348
+ }
349
+
350
+ const id = args.workItemId ?? args.itemId ?? args.id;
351
+ const title = args.title ?? args.summary ?? args.description;
352
+ return {
353
+ ...baseArgs,
354
+ workItems: [
355
+ {
356
+ ...(typeof id === "string" && id.trim() ? { id: id.trim() } : {}),
357
+ ...(typeof args.kind === "string" && args.kind.trim()
358
+ ? { kind: args.kind.trim() }
359
+ : typeof args.type === "string" && args.type.trim()
360
+ ? { kind: args.type.trim() }
361
+ : {}),
362
+ ...(typeof args.ownerAgent === "string" && args.ownerAgent.trim()
363
+ ? { ownerAgent: args.ownerAgent.trim() }
364
+ : typeof args.owner === "string" && args.owner.trim()
365
+ ? { ownerAgent: args.owner.trim() }
366
+ : typeof args.agentKey === "string" && args.agentKey.trim()
367
+ ? { ownerAgent: args.agentKey.trim() }
368
+ : {}),
369
+ ...(typeof title === "string" && title.trim() ? { title: title.trim() } : {}),
370
+ ...(typeof args.status === "string" && args.status.trim()
371
+ ? { status: args.status.trim() }
372
+ : {}),
373
+ ...(Array.isArray(args.dependsOn) ? { dependsOn: args.dependsOn } : {}),
374
+ ...(Array.isArray(args.writeScope) ? { writeScope: args.writeScope } : {}),
375
+ ...(typeof args.reviewPolicy === "string" && args.reviewPolicy.trim()
376
+ ? { reviewPolicy: args.reviewPolicy.trim() }
377
+ : {}),
378
+ },
379
+ ],
380
+ };
381
+ };
382
+ const getAllowedRemoteServerBases = (): string[] =>
383
+ (process.env.AGENT_TOOL_ALLOWED_SERVER_BASES ?? "")
384
+ .split(",")
385
+ .map((base) => normalizeServerOrigin(base.trim()))
386
+ .filter((base): base is string => !!base);
387
+
388
+ const buildFanoutServerList = (
389
+ originServer: string,
390
+ syncServers: unknown,
391
+ ): string[] => {
392
+ const normalizedOrigin = normalizeServerOrigin(originServer);
393
+ const candidates = Array.isArray(syncServers) ? syncServers : [];
394
+ const shouldIncludeNoloCluster =
395
+ !!normalizedOrigin &&
396
+ (/^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/i.test(normalizedOrigin) ||
397
+ NOLO_CLUSTER_SERVERS.some(
398
+ (server) => normalizeServerOrigin(server) === normalizedOrigin,
399
+ ));
400
+ return Array.from(
401
+ new Set(
402
+ [
403
+ normalizedOrigin,
404
+ ...candidates,
405
+ ...(shouldIncludeNoloCluster ? NOLO_CLUSTER_SERVERS : []),
406
+ ]
407
+ .map((value) =>
408
+ typeof value === "string" ? normalizeServerOrigin(value) : null,
409
+ )
410
+ .filter((value): value is string => !!value),
411
+ ),
412
+ );
413
+ };
414
+
415
+ export const resolveDelegatedServerBase = (
416
+ requestedBase: unknown,
417
+ mainBase: string,
418
+ ): { ok: true; base: string } | { ok: false; error: string } => {
419
+ if (typeof requestedBase !== "string" || !requestedBase.trim()) {
420
+ return { ok: true, base: mainBase };
421
+ }
422
+
423
+ const requestedOrigin = normalizeServerOrigin(requestedBase.trim());
424
+ if (!requestedOrigin) {
425
+ return {
426
+ ok: false,
427
+ error: `Invalid serverBase: ${String(requestedBase)}`,
428
+ };
429
+ }
430
+
431
+ const mainOrigin = normalizeServerOrigin(mainBase);
432
+ const isLocalMain =
433
+ !!mainOrigin &&
434
+ /^https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?$/i.test(mainOrigin);
435
+ const isNoloClusterTarget = NOLO_CLUSTER_SERVERS.some(
436
+ (server) => normalizeServerOrigin(server) === requestedOrigin,
437
+ );
438
+ if (
439
+ requestedOrigin === mainOrigin ||
440
+ getAllowedRemoteServerBases().includes(requestedOrigin) ||
441
+ (isLocalMain && isNoloClusterTarget)
442
+ ) {
443
+ return { ok: true, base: requestedOrigin };
444
+ }
445
+
446
+ return {
447
+ ok: false,
448
+ error:
449
+ `serverBase "${requestedOrigin}" is not allowed. ` +
450
+ "Add it to AGENT_TOOL_ALLOWED_SERVER_BASES before delegating current auth to a remote nolo server.",
451
+ };
452
+ };
453
+
454
+ export { extractAgentRuntimeServerBase, normalizeServerOrigin };
455
+
456
+ const buildDelegatedAgentInput = (task: string, input: unknown): string => {
457
+ if (input === undefined || input === null) return task;
458
+ if (typeof input === "string") {
459
+ return `${task}\n\n--- INPUT (text) ---\n${input}`;
460
+ }
461
+ return `${task}\n\n--- INPUT (json) ---\n${JSON.stringify(input, null, 2)}`;
462
+ };
463
+
464
+ const isHttpImageData = (value: unknown): boolean =>
465
+ typeof value === "string" && /^https?:\/\//i.test(value.trim());
466
+
467
+ const collectLatestImageUrlsFromMessages = (messages: unknown): string[] => {
468
+ if (!Array.isArray(messages)) return [];
469
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
470
+ const content = (messages[index] as any)?.content;
471
+ if (!Array.isArray(content)) continue;
472
+ const urls = content
473
+ .map((part) =>
474
+ part?.type === "image_url" && typeof part.image_url?.url === "string"
475
+ ? part.image_url.url.trim()
476
+ : "",
477
+ )
478
+ .filter((url): url is string => isHttpImageData(url));
479
+ if (urls.length > 0) return [...new Set(urls)];
480
+ }
481
+ return [];
482
+ };
483
+
484
+ const fetchPersistedDialogImageUrls = async (
485
+ mainBase: string,
486
+ authToken: string,
487
+ dialogId?: string | null,
488
+ ): Promise<string[]> => {
489
+ if (!dialogId) return [];
490
+ try {
491
+ const res = await fetch(`${mainBase}/rpc/getConvMsgs`, {
492
+ method: "POST",
493
+ headers: {
494
+ "Content-Type": "application/json",
495
+ ...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
496
+ },
497
+ body: JSON.stringify({ dialogId, limit: 80 }),
498
+ });
499
+ if (!res.ok) return [];
500
+ const messages = await res.json().catch(() => []);
501
+ return collectLatestImageUrlsFromMessages(messages);
502
+ } catch {
503
+ return [];
504
+ }
505
+ };
506
+
507
+ const resolveImageToolArgs = async (
508
+ toolName: string,
509
+ args: Record<string, any>,
510
+ mainBase: string,
511
+ authToken: string,
512
+ context?: ToolExecutionContext,
513
+ ): Promise<Record<string, any>> => {
514
+ if (!IMAGE_GENERATION_TOOL_NAMES.has(toolName)) return args;
515
+
516
+ const images = Array.isArray(args.images) ? args.images : [];
517
+ if (images.some((image: any) => isHttpImageData(image?.data))) {
518
+ return args;
519
+ }
520
+
521
+ let fallbackUrls = Array.isArray(context?.imageUrls)
522
+ ? context.imageUrls.filter((url) => isHttpImageData(url))
523
+ : [];
524
+ if (fallbackUrls.length === 0) {
525
+ fallbackUrls = await fetchPersistedDialogImageUrls(
526
+ mainBase,
527
+ authToken,
528
+ context?.dialogId,
529
+ );
530
+ }
531
+ if (fallbackUrls.length === 0) return args;
532
+
533
+ return {
534
+ ...args,
535
+ images: fallbackUrls.slice(0, Math.max(1, images.length)).map((url) => ({
536
+ data: url,
537
+ })),
538
+ };
539
+ };
540
+
541
+ const normalizeSkillImportUrl = (rawUrl: string): string => {
542
+ const trimmed = rawUrl.trim();
543
+ const githubBlobMatch = trimmed.match(
544
+ /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/blob\/([^/]+)\/(.+)$/,
545
+ );
546
+ if (githubBlobMatch) {
547
+ const [, owner, repo, ref, path] = githubBlobMatch;
548
+ return `https://raw.githubusercontent.com/${owner}/${repo}/${ref}/${path}`;
549
+ }
550
+ return trimmed;
551
+ };
552
+
553
+ const withTaskRunContext = (
554
+ args: Record<string, any>,
555
+ context?: ToolExecutionContext,
556
+ ): Record<string, any> => {
557
+ const hasExplicitRowTarget =
558
+ (typeof args.dbKey === "string" && args.dbKey.trim()) ||
559
+ (typeof args.tenantId === "string" && args.tenantId.trim() &&
560
+ typeof args.tableId === "string" && args.tableId.trim() &&
561
+ typeof args.rowId === "string" && args.rowId.trim());
562
+ if (hasExplicitRowTarget) return args;
563
+ const rowDbKey =
564
+ typeof context?.runtimeContext?.taskRun?.rowDbKey === "string" &&
565
+ context.runtimeContext.taskRun.rowDbKey.trim()
566
+ ? context.runtimeContext.taskRun.rowDbKey.trim()
567
+ : "";
568
+ return rowDbKey ? { ...args, dbKey: rowDbKey } : args;
569
+ };
570
+
571
+ function buildAgentHandoffUserInput(args: {
572
+ message: string;
573
+ parentDialogId?: string;
574
+ subjectRefs?: Array<{ kind: string; id: string; role?: string }>;
575
+ subjectEvidenceLines?: string[];
576
+ runtimeContext?: Record<string, any>;
577
+ }): string {
578
+ const taskRun = args.runtimeContext?.taskRun;
579
+ const rowDbKey =
580
+ typeof taskRun?.rowDbKey === "string" && taskRun.rowDbKey.trim()
581
+ ? taskRun.rowDbKey.trim()
582
+ : "";
583
+ const workItemId =
584
+ typeof taskRun?.workItemId === "string" && taskRun.workItemId.trim()
585
+ ? taskRun.workItemId.trim()
586
+ : "";
587
+ const artifactIds = Array.isArray(taskRun?.artifactIds)
588
+ ? taskRun.artifactIds.filter((item: unknown): item is string => typeof item === "string" && Boolean(item.trim()))
589
+ : [];
590
+ const subjectRefs = args.subjectRefs?.filter((ref) => ref?.kind && ref?.id) ?? [];
591
+ const subjectEvidenceLines = args.subjectEvidenceLines?.filter(Boolean) ?? [];
592
+ if (!args.parentDialogId && !rowDbKey && !workItemId && artifactIds.length === 0 && subjectRefs.length === 0 && subjectEvidenceLines.length === 0) {
593
+ return args.message;
594
+ }
595
+ return [
596
+ "--- Nolo agent handoff context ---",
597
+ "This block is orientation for the receiving agent. It is not a workflow decision, review result, or replacement for inspecting durable records.",
598
+ ...(args.parentDialogId ? [`- parentDialogId: ${args.parentDialogId}`] : []),
599
+ ...(rowDbKey ? [`- task row: ${rowDbKey}`] : []),
600
+ ...(workItemId ? [`- workItemId: ${workItemId}`] : []),
601
+ ...(artifactIds.length ? [`- artifactIds: ${artifactIds.join(",")}`] : []),
602
+ ...(subjectRefs.length
603
+ ? [
604
+ "- subjectRefs:",
605
+ ...subjectRefs.map((ref) => ` - ${ref.kind}:${ref.id}${ref.role ? ` (${ref.role})` : ""}`),
606
+ ]
607
+ : []),
608
+ ...(subjectEvidenceLines.length
609
+ ? [
610
+ "- referenced evidence snapshot (server-read durable facts at handoff time):",
611
+ ...subjectEvidenceLines.map((line) => ` - ${line}`),
612
+ ]
613
+ : []),
614
+ "- Start by reading the durable task context when task-run is available.",
615
+ "- To find the work evidence, inspect the task row fields that already exist: workItems.dialogIds, workItems.outcome, review.dialogId, activityRefs, agentRuns.dialogId/resultSummary, and artifactRefs.",
616
+ "- Use dialog read/search tools for exact wording or tool traces; do not infer completion or review status from this handoff text alone.",
617
+ "- Durable result channels include taskRun primitives such as submitOutcome, setBlocker, requestReview, recordReview, or closeWorkItem when they are available.",
618
+ "--- Handoff task ---",
619
+ args.message,
620
+ ].join("\n");
621
+ }
622
+
623
+ const asPlainRecord = (value: unknown): Record<string, any> =>
624
+ value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, any> : {};
625
+
626
+ const summarizeStringArray = (value: unknown, max = 6): string[] => {
627
+ if (!Array.isArray(value)) return [];
628
+ const items = value
629
+ .filter((item): item is string => typeof item === "string" && Boolean(item.trim()))
630
+ .map((item) => item.trim());
631
+ return items.length > max ? [...items.slice(0, max), `+${items.length - max} more`] : items;
632
+ };
633
+
634
+ const clipEvidenceText = (value: unknown, max = 220): string => {
635
+ if (typeof value !== "string") return "";
636
+ const compact = value.replace(/\s+/g, " ").trim();
637
+ return compact.length > max ? `${compact.slice(0, max - 3)}...` : compact;
638
+ };
639
+
640
+ async function buildReferencedDialogEvidenceLines(args: {
641
+ subjectRefs: Array<{ kind: string; id: string; role?: string }>;
642
+ userId?: string | null;
643
+ }): Promise<string[]> {
644
+ const lines: string[] = [];
645
+ const seenDialogIds = new Set<string>();
646
+ for (const ref of args.subjectRefs) {
647
+ if (ref.kind !== "dialog" || !ref.id.trim()) continue;
648
+ const dialogId = ref.id.trim();
649
+ if (seenDialogIds.has(dialogId)) continue;
650
+ seenDialogIds.add(dialogId);
651
+ try {
652
+ const resolved = await resolveExistingDialogRef({
653
+ dialogId,
654
+ preferredUserId: args.userId,
655
+ });
656
+ if (!resolved?.dialogRecord) {
657
+ lines.push(`dialog:${dialogId}${ref.role ? ` (${ref.role})` : ""} not found`);
658
+ continue;
659
+ }
660
+ const dialog = asPlainRecord(resolved.dialogRecord);
661
+ const runtimeCheckpoint = asPlainRecord(dialog.runtimeCheckpoint);
662
+ const artifacts = asPlainRecord(dialog.artifacts);
663
+ const workspaceProgress = asPlainRecord(runtimeCheckpoint.workspaceProgress);
664
+ const workspaceLease = asPlainRecord(dialog.workspaceLease ?? runtimeCheckpoint.workspaceLease);
665
+ const messageCount = await countDialogMessages(dialogId);
666
+ const changedFiles = summarizeStringArray(
667
+ artifacts.changedFiles ?? workspaceProgress.changedFiles ?? workspaceLease.changedFiles,
668
+ );
669
+ const workspaceRoot = typeof workspaceLease.workspaceRoot === "string" && workspaceLease.workspaceRoot.trim()
670
+ ? workspaceLease.workspaceRoot.trim()
671
+ : typeof workspaceProgress.workspaceRoot === "string" && workspaceProgress.workspaceRoot.trim()
672
+ ? workspaceProgress.workspaceRoot.trim()
673
+ : "";
674
+ const status = typeof dialog.status === "string" && dialog.status.trim()
675
+ ? dialog.status.trim()
676
+ : "unknown";
677
+ const runtimeStatus = typeof runtimeCheckpoint.status === "string" && runtimeCheckpoint.status.trim()
678
+ ? runtimeCheckpoint.status.trim()
679
+ : "none";
680
+ const summary = clipEvidenceText(
681
+ dialog.resultSummary ?? runtimeCheckpoint.lastAssistantText ?? dialog.title,
682
+ );
683
+ lines.push(
684
+ [
685
+ `dialog:${dialogId}${ref.role ? ` (${ref.role})` : ""}`,
686
+ `status=${status}`,
687
+ `runtimeStatus=${runtimeStatus}`,
688
+ `messagesCount=${messageCount.count}${messageCount.truncated ? "+" : ""}`,
689
+ `artifacts=${Object.keys(artifacts).length ? "present" : "none"}`,
690
+ ...(workspaceRoot ? [`workspace=${workspaceRoot}`] : []),
691
+ `changedFiles=${changedFiles.length ? changedFiles.join(",") : "none"}`,
692
+ ...(summary ? [`summary="${summary}"`] : []),
693
+ ].join(" "),
694
+ );
695
+ } catch (error) {
696
+ const detail = error instanceof Error && error.message ? error.message : "read failed";
697
+ lines.push(`dialog:${dialogId}${ref.role ? ` (${ref.role})` : ""} unavailable: ${detail}`);
698
+ }
699
+ }
700
+ return lines;
701
+ }
702
+
703
+ async function countDialogMessages(dialogId: string, max = 200): Promise<{ count: number; truncated: boolean }> {
704
+ let count = 0;
705
+ const gte = createKey(DataType.DIALOG, dialogId, "msg", "");
706
+ const lte = createKey(DataType.DIALOG, dialogId, "msg", "\uffff");
707
+ for await (const _ of serverDb.iterator({ gte, lte })) {
708
+ count += 1;
709
+ if (count > max) return { count: max, truncated: true };
710
+ }
711
+ return { count, truncated: false };
712
+ }
713
+
714
+ const looksLikeLocalFilePath = (value: unknown): value is string => {
715
+ if (typeof value !== "string") return false;
716
+ const trimmed = value.trim();
717
+ if (!trimmed) return false;
718
+ return (
719
+ trimmed.startsWith("/") ||
720
+ trimmed.startsWith("./") ||
721
+ trimmed.startsWith("../") ||
722
+ trimmed.includes("/") ||
723
+ /\.[A-Za-z0-9_-]{1,12}$/.test(trimmed)
724
+ );
725
+ };
726
+
727
+ const normalizeToolExecutionArgs = (
728
+ toolName: string,
729
+ args: Record<string, any>,
730
+ ): Record<string, any> => {
731
+ if (toolName === "execShell") {
732
+ const command =
733
+ args.command ??
734
+ args.runCommand ??
735
+ args.run_command ??
736
+ args.terminalCommand ??
737
+ args.terminal_command ??
738
+ args.runInBash ??
739
+ args.run_in_bash ??
740
+ args.executeCommand ??
741
+ args.execute_command ??
742
+ args.execShell ??
743
+ args.bash ??
744
+ args.cmd;
745
+ return command == null ? args : { ...args, command };
746
+ }
747
+
748
+ if (toolName === "readFile") {
749
+ const filePath = args.filePath ?? args.path ?? args.filename ?? args.file;
750
+ return filePath == null ? args : { ...args, filePath };
751
+ }
752
+
753
+ if (toolName === "read") {
754
+ const filePath = args.filePath ?? args.path ?? args.filename ?? args.file;
755
+ if (filePath != null) return { ...args, filePath };
756
+ if (process.env.NOLO_DESKTOP === "1" && looksLikeLocalFilePath(args.dbKey)) {
757
+ return { ...args, filePath: args.dbKey };
758
+ }
759
+ }
760
+
761
+ return args;
762
+ };
763
+
764
+ export async function executeToolOnServer(
765
+ toolCall: AssistantToolCall,
766
+ serverBase: string,
767
+ authToken: string,
768
+ context?: ToolExecutionContext,
769
+ ): Promise<string> {
770
+ const mainBase = normalizeBase(serverBase);
771
+ const rawToolName = (toolCall.function.name || "").replace(/^functions\./, "").trim();
772
+ const toolName = canonicalizeToolName(rawToolName);
773
+ let args: Record<string, any> = {};
774
+ try {
775
+ args = JSON.parse(toolCall.function.arguments || "{}");
776
+ } catch {
777
+ return JSON.stringify({ error: "Invalid tool arguments JSON" });
778
+ }
779
+ args = normalizeToolExecutionArgs(toolName, args);
780
+ args = await resolveImageToolArgs(toolName, args, mainBase, authToken, context);
781
+
782
+ const currentAgentKey =
783
+ typeof context?.agentKey === "string" && context.agentKey.trim()
784
+ ? context.agentKey.trim()
785
+ : "";
786
+ const buildAuthHeaders = (): Record<string, string> => {
787
+ const headers: Record<string, string> = {};
788
+ if (authToken) {
789
+ headers.Authorization = `Bearer ${authToken}`;
790
+ headers.Cookie = `${WEB_AUTH_TOKEN_COOKIE}=${encodeURIComponent(authToken)}`;
791
+ }
792
+ if (currentAgentKey) {
793
+ headers["X-Nolo-Agent-Key"] = currentAgentKey;
794
+ }
795
+ return headers;
796
+ };
797
+
798
+ const post = async (
799
+ base: string,
800
+ path: string,
801
+ body: object
802
+ ): Promise<string> => {
803
+ const headers: Record<string, string> = {
804
+ "Content-Type": "application/json",
805
+ ...buildAuthHeaders(),
806
+ };
807
+
808
+ const res = await fetch(`${base}${path}`, {
809
+ method: "POST",
810
+ headers,
811
+ body: JSON.stringify(body),
812
+ });
813
+ if (!res.ok) {
814
+ return JSON.stringify({ error: `HTTP ${res.status}`, detail: await res.text() });
815
+ }
816
+ return res.text();
817
+ };
818
+
819
+ const postJson = async (
820
+ base: string,
821
+ path: string,
822
+ body: object,
823
+ ): Promise<{
824
+ ok: boolean;
825
+ status: number;
826
+ text: string;
827
+ data: any;
828
+ }> => {
829
+ const headers: Record<string, string> = {
830
+ "Content-Type": "application/json",
831
+ ...buildAuthHeaders(),
832
+ };
833
+
834
+ const res = await fetch(`${base}${path}`, {
835
+ method: "POST",
836
+ headers,
837
+ body: JSON.stringify(body),
838
+ });
839
+ const text = await res.text();
840
+ let data: any = null;
841
+ try {
842
+ data = text ? JSON.parse(text) : null;
843
+ } catch {
844
+ data = null;
845
+ }
846
+ return {
847
+ ok: res.ok,
848
+ status: res.status,
849
+ text,
850
+ data,
851
+ };
852
+ };
853
+
854
+ const postMain = async (path: string, body: object): Promise<string> =>
855
+ post(resolveSameOriginChildRunBase(mainBase, mainBase), path, body);
856
+
857
+ const sleep = (ms: number) =>
858
+ new Promise((resolve) => setTimeout(resolve, ms));
859
+
860
+ const withDialogId = (body: Record<string, any>): Record<string, any> => {
861
+ if (!context?.dialogId || "dialogId" in body) return body;
862
+ return {
863
+ ...body,
864
+ dialogId: context.dialogId,
865
+ };
866
+ };
867
+
868
+ const withFeedbackSubmitterUserId = (args: Record<string, any>): Record<string, any> => {
869
+ const agentKey = typeof context?.agentKey === "string" ? context.agentKey.trim() : "";
870
+ const userId = typeof context?.userId === "string" ? context.userId.trim() : "";
871
+ if (
872
+ !userId ||
873
+ !(
874
+ agentKey === `agent-pub-${FEEDBACK_AGENT_ID}` ||
875
+ agentKey.endsWith(`-${FEEDBACK_AGENT_ID}`)
876
+ )
877
+ ) {
878
+ return args;
879
+ }
880
+
881
+ const tableId = typeof args.tableId === "string" ? args.tableId.trim() : "";
882
+ const values =
883
+ args.values && typeof args.values === "object" && !Array.isArray(args.values)
884
+ ? args.values
885
+ : {};
886
+ if (tableId === FEEDBACK_TABLE_ID) {
887
+ return {
888
+ ...args,
889
+ values: {
890
+ ...values,
891
+ submitterUserId: values.submitterUserId || userId,
892
+ },
893
+ };
894
+ }
895
+ if (tableId === TASK_BOARD_TABLE_ID) {
896
+ return {
897
+ ...args,
898
+ values: {
899
+ ...values,
900
+ feedbackSubmitterUserId: values.feedbackSubmitterUserId || userId,
901
+ },
902
+ };
903
+ }
904
+ return args;
905
+ };
906
+
907
+ const deleteDbKey = async (dbKey: string): Promise<{ ok: boolean; status: number; text: string }> => {
908
+ const res = await fetch(`${mainBase}/api/v1/db/delete/${encodeURIComponent(dbKey)}`, {
909
+ method: "DELETE",
910
+ headers: buildAuthHeaders(),
911
+ });
912
+ return {
913
+ ok: res.ok,
914
+ status: res.status,
915
+ text: await res.text(),
916
+ };
917
+ };
918
+
919
+ const spaceMemberKeysForDelete = (spaceId: string, record: SpaceRecordLike): string[] => {
920
+ const memberIds = new Set<string>();
921
+ if (context?.userId) memberIds.add(context.userId);
922
+ if (Array.isArray(record.members)) {
923
+ for (const memberId of record.members) {
924
+ if (typeof memberId === "string" && memberId.trim()) {
925
+ memberIds.add(memberId.trim());
926
+ }
927
+ }
928
+ } else if (record.members && typeof record.members === "object") {
929
+ for (const memberId of Object.keys(record.members)) {
930
+ if (memberId.trim()) memberIds.add(memberId.trim());
931
+ }
932
+ }
933
+ return Array.from(memberIds).map((memberId) => createSpaceKey.member(memberId, spaceId));
934
+ };
935
+ const requireCurrentAgentKey = () => {
936
+ if (!currentAgentKey) {
937
+ return JSON.stringify({
938
+ error: "Current agent key is unavailable in server-side agent mode.",
939
+ });
940
+ }
941
+ return null;
942
+ };
943
+ const includesCaseInsensitive = (haystack: unknown, needle: unknown): boolean => {
944
+ const normalizedNeedle =
945
+ typeof needle === "string" && needle.trim() ? needle.trim().toLowerCase() : "";
946
+ if (!normalizedNeedle) return true;
947
+ const normalizedHaystack =
948
+ typeof haystack === "string" ? haystack.toLowerCase() : String(haystack || "").toLowerCase();
949
+ return normalizedHaystack.includes(normalizedNeedle);
950
+ };
951
+ const participantText = (participants: any): string =>
952
+ Array.isArray(participants)
953
+ ? participants
954
+ .map((participant) =>
955
+ [participant?.name, participant?.email]
956
+ .filter((value) => typeof value === "string" && value.trim())
957
+ .join(" "),
958
+ )
959
+ .join("\n")
960
+ : "";
961
+ const EMAIL_WAIT_GRACE_MS = 10_000;
962
+ const parseEmailTimestamp = (value: unknown): number | null => {
963
+ if (typeof value === "number" && Number.isFinite(value)) {
964
+ return value;
965
+ }
966
+ if (typeof value === "string" && value.trim()) {
967
+ const parsed = Date.parse(value);
968
+ return Number.isFinite(parsed) ? parsed : null;
969
+ }
970
+ return null;
971
+ };
972
+ const emailReceivedAtMs = (email: any): number | null =>
973
+ parseEmailTimestamp(email?.meta?.provider?.receivedAt) ??
974
+ parseEmailTimestamp(email?.receivedAt) ??
975
+ parseEmailTimestamp(email?.createdAt) ??
976
+ parseEmailTimestamp(email?.updatedAt);
977
+ const emailMatchesWaitFilters = (email: any, waitArgs: Record<string, any>): boolean =>
978
+ includesCaseInsensitive(email?.subject, waitArgs.subjectContains) &&
979
+ includesCaseInsensitive(email?.from?.email, waitArgs.fromContains) &&
980
+ includesCaseInsensitive(participantText(email?.to), waitArgs.toContains) &&
981
+ includesCaseInsensitive(
982
+ [email?.subject, email?.text, email?.html].filter(Boolean).join("\n"),
983
+ waitArgs.bodyContains,
984
+ );
985
+ const emailIsFreshForWait = (email: any, waitStartedAtMs: number): boolean => {
986
+ const receivedAtMs = emailReceivedAtMs(email);
987
+ if (receivedAtMs == null) return true;
988
+ return receivedAtMs >= waitStartedAtMs - EMAIL_WAIT_GRACE_MS;
989
+ };
990
+
991
+ const runChildAgent = async (
992
+ agentKey: string,
993
+ userInput: string,
994
+ requestedServerBase?: unknown,
995
+ requestedTimeoutMs?: unknown,
996
+ options?: {
997
+ background?: boolean;
998
+ parentDialogId?: string;
999
+ subjectRefs?: Array<{ kind: string; id: string; role?: string }>;
1000
+ idempotencyKey?: string;
1001
+ },
1002
+ ) => {
1003
+ let effectiveRequestedServerBase = requestedServerBase;
1004
+ let autoRouted = false;
1005
+ const allowedRemoteServerBases = getAllowedRemoteServerBases();
1006
+ if (
1007
+ allowedRemoteServerBases.length > 0 &&
1008
+ (typeof requestedServerBase !== "string" || !requestedServerBase.trim())
1009
+ ) {
1010
+ try {
1011
+ const res = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(agentKey)}`, {
1012
+ headers: buildAuthHeaders(),
1013
+ });
1014
+ if (res.ok) {
1015
+ const raw = await res.json();
1016
+ const agentRecord = raw?.data ?? raw;
1017
+ const runtimeServerBase = extractAgentRuntimeServerBase(agentRecord);
1018
+ const runtimeOrigin = runtimeServerBase
1019
+ ? normalizeServerOrigin(runtimeServerBase)
1020
+ : null;
1021
+ const mainOrigin = normalizeServerOrigin(mainBase);
1022
+ if (runtimeOrigin && runtimeOrigin !== mainOrigin) {
1023
+ effectiveRequestedServerBase = runtimeOrigin;
1024
+ autoRouted = true;
1025
+ }
1026
+ }
1027
+ } catch {
1028
+ // Best effort only. If metadata cannot be read, run on the current server.
1029
+ }
1030
+ }
1031
+
1032
+ const target = resolveDelegatedServerBase(effectiveRequestedServerBase, mainBase);
1033
+ if (!target.ok) {
1034
+ return {
1035
+ ok: false as const,
1036
+ status: 400,
1037
+ error: autoRouted
1038
+ ? `${target.error} Target agent declares this runtime serverBase in its delegation metadata.`
1039
+ : target.error,
1040
+ };
1041
+ }
1042
+
1043
+ const childRunBase = resolveSameOriginChildRunBase(target.base, mainBase);
1044
+ const childSubjectRefs = mergeSubjectRefs(
1045
+ context?.runtimeContext?.subjectRefs,
1046
+ options?.subjectRefs,
1047
+ );
1048
+ const childRuntimeContext = options?.background || childSubjectRefs.length || options?.idempotencyKey
1049
+ ? {
1050
+ ...(context?.runtimeContext ?? {}),
1051
+ surface: context?.runtimeContext?.surface ?? "server-script",
1052
+ entrypoint:
1053
+ options?.background
1054
+ ? "agent-tool:startAgentDialog"
1055
+ : context?.runtimeContext?.entrypoint ?? "agent-tool:callAgent",
1056
+ ...(childSubjectRefs.length ? { subjectRefs: childSubjectRefs } : {}),
1057
+ ...(options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),
1058
+ }
1059
+ : context?.runtimeContext;
1060
+ const res = await fetch(`${childRunBase}/api/agent/run`, {
1061
+ method: "POST",
1062
+ headers: { "Content-Type": "application/json", ...buildAuthHeaders() },
1063
+ body: JSON.stringify({
1064
+ agentKey,
1065
+ userInput,
1066
+ stream: false,
1067
+ ...(options?.background ? { background: true } : {}),
1068
+ spaceId: context?.currentSpaceId ?? undefined,
1069
+ ...(options?.parentDialogId ? { parentDialogId: options.parentDialogId } : {}),
1070
+ ...(childRuntimeContext ? { runtimeContext: childRuntimeContext } : {}),
1071
+ ...(typeof requestedTimeoutMs === "number" &&
1072
+ Number.isFinite(requestedTimeoutMs) &&
1073
+ requestedTimeoutMs > 0
1074
+ ? { timeoutMs: requestedTimeoutMs }
1075
+ : {}),
1076
+ }),
1077
+ });
1078
+ if (!res.ok) {
1079
+ return {
1080
+ ok: false as const,
1081
+ status: res.status,
1082
+ error: await res.text(),
1083
+ };
1084
+ }
1085
+ const payload = await res.json();
1086
+ return {
1087
+ ok: true as const,
1088
+ payload,
1089
+ ...(typeof effectiveRequestedServerBase === "string" && effectiveRequestedServerBase.trim()
1090
+ ? { serverBase: target.base }
1091
+ : {}),
1092
+ ...(autoRouted ? { autoRouted: true } : {}),
1093
+ };
1094
+ };
1095
+
1096
+ const waitForAppDeployResult = async (jobId: string) => {
1097
+ const deadline = Date.now() + APP_DEPLOY_POLL_TIMEOUT_MS;
1098
+ let latestPayload: any = null;
1099
+
1100
+ while (Date.now() < deadline) {
1101
+ const statusResult = await postJson(
1102
+ mainBase,
1103
+ "/api/app/deploy/status",
1104
+ { jobId },
1105
+ );
1106
+
1107
+ if (!statusResult.ok) {
1108
+ return JSON.stringify(
1109
+ statusResult.data ?? {
1110
+ error: `appDeploy status: HTTP ${statusResult.status}`,
1111
+ detail: statusResult.text,
1112
+ },
1113
+ );
1114
+ }
1115
+
1116
+ latestPayload = statusResult.data;
1117
+ if (
1118
+ latestPayload?.status === "succeeded" ||
1119
+ latestPayload?.status === "failed"
1120
+ ) {
1121
+ if (latestPayload.status === "succeeded" && latestPayload.result) {
1122
+ const result = latestPayload.result;
1123
+ return JSON.stringify({
1124
+ ...result,
1125
+ jobId: latestPayload.jobId,
1126
+ status: latestPayload.status,
1127
+ summary: latestPayload.summary,
1128
+ steps: latestPayload.steps,
1129
+ appUrl: result.customUrl ?? result.url,
1130
+ });
1131
+ }
1132
+ return JSON.stringify(latestPayload);
1133
+ }
1134
+
1135
+ await sleep(APP_DEPLOY_POLL_INTERVAL_MS);
1136
+ }
1137
+
1138
+ return JSON.stringify({
1139
+ ...(latestPayload && typeof latestPayload === "object"
1140
+ ? latestPayload
1141
+ : {
1142
+ success: true,
1143
+ jobId,
1144
+ status: "pending",
1145
+ summary: "部署任务仍在进行中",
1146
+ }),
1147
+ timeout: true,
1148
+ nextAction:
1149
+ "部署任务还未完成。请稍后再次查询该 jobId,或等待服务端完成后再继续向用户确认最终访问链接。",
1150
+ });
1151
+ };
1152
+
1153
+ const normalizeAppFiles = () => {
1154
+ if (Array.isArray(args.files) && args.files.length > 0) return args.files;
1155
+ if (Array.isArray(args.pages) && args.pages.length > 0) return args.pages;
1156
+ return undefined;
1157
+ };
1158
+ const serverToolName = toolName;
1159
+ const taskRunPrimitiveArgs = normalizeTaskRunPrimitiveArgs(serverToolName, args);
1160
+ if (taskRunPrimitiveArgs) {
1161
+ return runTaskRunTool(withTaskRunContext(taskRunPrimitiveArgs, context), authToken);
1162
+ }
1163
+
1164
+ switch (serverToolName) {
1165
+ // ── 网络/外部 API(同构,前后端都能调,这里走服务端代理)──
1166
+ case "fetchWebpage":
1167
+ return postMain("/api/fetch-webpage", withDialogId({ url: args.url }));
1168
+ case "convertMarxistsBookToOfflineHtml": {
1169
+ const result = await convertMarxistsBookToOfflineHtml({
1170
+ startUrl: args.startUrl,
1171
+ encoding: args.encoding,
1172
+ maxPages: args.maxPages,
1173
+ fetchImpl: fetch,
1174
+ });
1175
+ const fileName = sanitizeGeneratedHtmlFileName(
1176
+ args.singleFileName,
1177
+ `${result.title || "marxists-offline-book"}.html`,
1178
+ );
1179
+ const rawData: Record<string, unknown> = {
1180
+ title: result.title,
1181
+ startUrl: result.startUrl,
1182
+ indexUrl: result.indexUrl,
1183
+ stylesheetUrl: result.stylesheetUrl,
1184
+ pages: result.pages,
1185
+ validation: result.validation,
1186
+ fileName,
1187
+ };
1188
+ if (args.saveAsFile !== false) {
1189
+ if (!context?.userId) {
1190
+ rawData.saveWarning =
1191
+ "saveAsFile was requested, but the server tool execution context has no userId.";
1192
+ } else {
1193
+ const { fileId, metadata } = await saveBufferAsFile(
1194
+ Buffer.from(result.html, "utf8"),
1195
+ {
1196
+ tenantId: context.userId,
1197
+ originalName: fileName,
1198
+ mimeType: "text/html; charset=utf-8",
1199
+ ownerType: "user",
1200
+ ownerId: context.userId,
1201
+ uploadedBy: context.userId,
1202
+ source: "ai-generated",
1203
+ model: "convertMarxistsBookToOfflineHtml",
1204
+ prompt: result.startUrl,
1205
+ tags: ["offline-book", "marxists-org", "html"],
1206
+ clientMetadata: {
1207
+ fileCategory: "document",
1208
+ sourceUrl: result.startUrl,
1209
+ indexUrl: result.indexUrl,
1210
+ stylesheetUrl: result.stylesheetUrl,
1211
+ pageCount: result.validation.pageCount,
1212
+ },
1213
+ },
1214
+ );
1215
+ const fileDbKey =
1216
+ typeof (metadata as any).dbKey === "string"
1217
+ ? (metadata as any).dbKey
1218
+ : `file-${context.userId}-${fileId}`;
1219
+ rawData.fileId = fileId;
1220
+ rawData.fileDbKey = fileDbKey;
1221
+ rawData.fileUrl = buildFileContentUrl(mainBase, fileDbKey);
1222
+ }
1223
+ }
1224
+ if (args.outputMode === "html") {
1225
+ rawData.html = result.html;
1226
+ }
1227
+ return JSON.stringify({
1228
+ rawData,
1229
+ displayData: formatMarxistsOfflineBookDisplayData({
1230
+ ...rawData,
1231
+ htmlIncluded: args.outputMode === "html",
1232
+ }),
1233
+ });
1234
+ }
1235
+ case "read_x_post":
1236
+ return postMain(
1237
+ "/api/read-x-post",
1238
+ withDialogId({
1239
+ url: args.url,
1240
+ keepOpen: args.keepOpen,
1241
+ profileDir: args.profileDir,
1242
+ headless: args.headless,
1243
+ }),
1244
+ );
1245
+ case "wereadGateway":
1246
+ return postMain(
1247
+ "/api/weread/gateway",
1248
+ withDialogId(args),
1249
+ );
1250
+ case "exa_search":
1251
+ return postMain(
1252
+ "/api/exa-search",
1253
+ withDialogId({
1254
+ query: args.query,
1255
+ numResults: args.numResults ?? 5,
1256
+ contents: args.contents,
1257
+ }),
1258
+ );
1259
+ case "youtubeScraper":
1260
+ case "ecommerceScraper":
1261
+ case "amazonProductScraper":
1262
+ return postMain(
1263
+ "/api/apify-actor",
1264
+ withDialogId({ actorId: args.actorId ?? serverToolName, input: args }),
1265
+ );
1266
+ case "taobaoTmallProductScraper":
1267
+ return postMain(
1268
+ "/api/apify-actor",
1269
+ withDialogId({
1270
+ actorId: "sian.agency~taobao-tmall-product-scraper",
1271
+ input: {
1272
+ operation: "productDetail",
1273
+ itemId: args.itemId,
1274
+ detailDepth: args.detailDepth ?? "full",
1275
+ },
1276
+ resultType: "datasetItems",
1277
+ }),
1278
+ );
1279
+ case "jdProductScraper": {
1280
+ const result = await jdProductScraperFunc({
1281
+ skuId: args.skuId,
1282
+ url: args.url,
1283
+ });
1284
+ const skuId = typeof result.rawData?.skuId === "string" ? result.rawData.skuId : "";
1285
+ if (
1286
+ skuId &&
1287
+ (isIncompleteProductData(result.rawData) ||
1288
+ hasSparseJdSpecifications(result.rawData))
1289
+ ) {
1290
+ const mobileUrl = `https://item.m.jd.com/product/${skuId}.html`;
1291
+ const apifyText = await postMain(
1292
+ "/api/apify-actor",
1293
+ withDialogId({
1294
+ actorId: "apify~web-scraper",
1295
+ input: {
1296
+ startUrls: [{ url: mobileUrl }],
1297
+ maxPagesPerCrawl: 1,
1298
+ maxRequestRetries: 1,
1299
+ maxConcurrency: 1,
1300
+ proxyConfiguration: { useApifyProxy: true },
1301
+ pageFunction: `async function pageFunction(context) {
1302
+ await new Promise((resolve) => setTimeout(resolve, 1500));
1303
+ return {
1304
+ url: context.request.url,
1305
+ itemOnly: window._itemOnly || null,
1306
+ itemInfo: window._itemInfo || null,
1307
+ priceInfo: window.__price || window._price || null,
1308
+ title: document.title,
1309
+ html: document.documentElement ? document.documentElement.innerHTML : ""
1310
+ };
1311
+ }`,
1312
+ },
1313
+ resultType: "datasetItems",
1314
+ }),
1315
+ );
1316
+ let apifyData: any = null;
1317
+ try {
1318
+ apifyData = JSON.parse(apifyText || "null");
1319
+ } catch {
1320
+ apifyData = null;
1321
+ }
1322
+ const browserItem = Array.isArray(apifyData) ? apifyData[0] : null;
1323
+ if (browserItem && typeof browserItem === "object" && !("error" in browserItem)) {
1324
+ const browserFallback = parseJdBrowserExtractedData(browserItem, {
1325
+ skuId,
1326
+ url: mobileUrl,
1327
+ });
1328
+ result.rawData = mergeJdProductData(result.rawData, browserFallback);
1329
+ }
1330
+ }
1331
+ if (skuId && isIncompleteProductData(result.rawData)) {
1332
+ const knownFallback = getKnownJdProductFallback(skuId);
1333
+ if (knownFallback) {
1334
+ result.rawData = mergeJdProductData(result.rawData, knownFallback);
1335
+ }
1336
+ }
1337
+ result.displayData = formatJdProductDisplayData(result.rawData);
1338
+ return JSON.stringify(result);
1339
+ }
1340
+ case "geminiFlashImage":
1341
+ case "geminiProImagePreview":
1342
+ return postMain("/api/gemini-image-preview", withDialogId(args));
1343
+ case "openAIGptImageGenerate":
1344
+ return postMain(
1345
+ "/api/openai-image",
1346
+ withDialogId({
1347
+ ...args,
1348
+ operation: "generate",
1349
+ model: "gpt-image-2",
1350
+ })
1351
+ );
1352
+ case "openAIGptImageEdit":
1353
+ return postMain(
1354
+ "/api/openai-image",
1355
+ withDialogId({
1356
+ ...args,
1357
+ operation: "edit",
1358
+ model: "gpt-image-2",
1359
+ })
1360
+ );
1361
+ case "openAIGptImage":
1362
+ return postMain("/api/openai-image", withDialogId(args));
1363
+ case "remotionRenderVideo":
1364
+ return postMain("/api/remotion/render", withDialogId(args));
1365
+ case "ui_ask_choice": {
1366
+ const question =
1367
+ typeof args.question === "string" ? args.question.trim() : "";
1368
+ const choices = Array.isArray(args.choices) ? args.choices : [];
1369
+ const blocking = args.blocking !== false;
1370
+ if (!question || choices.length === 0) {
1371
+ return JSON.stringify({
1372
+ error: "ui_ask_choice",
1373
+ detail: "ui_ask_choice 需要 question 和至少一个 choice。",
1374
+ });
1375
+ }
1376
+ return JSON.stringify({
1377
+ type: "ui_ask_choice",
1378
+ question,
1379
+ choices,
1380
+ blocking,
1381
+ });
1382
+ }
1383
+ case "queryModelUsage": {
1384
+ try {
1385
+ return JSON.stringify(await runQueryModelUsageTool(args, context));
1386
+ } catch (err: any) {
1387
+ return JSON.stringify({
1388
+ error: "queryModelUsage",
1389
+ detail: err?.message ?? String(err),
1390
+ });
1391
+ }
1392
+ }
1393
+ case "createScheduledTask": {
1394
+ try {
1395
+ return JSON.stringify(await runCreateScheduledTaskTool(args, context));
1396
+ } catch (err: any) {
1397
+ return JSON.stringify({
1398
+ error: "createScheduledTask",
1399
+ detail: err?.message ?? String(err),
1400
+ });
1401
+ }
1402
+ }
1403
+ case "createDialogGoal": {
1404
+ try {
1405
+ return JSON.stringify(await runCreateDialogGoalTool(args, context));
1406
+ } catch (err: any) {
1407
+ return JSON.stringify({
1408
+ error: "createDialogGoal",
1409
+ detail: err?.message ?? String(err),
1410
+ });
1411
+ }
1412
+ }
1413
+ case "getDialogGoal": {
1414
+ try {
1415
+ return JSON.stringify(await runGetDialogGoalTool(args, context));
1416
+ } catch (err: any) {
1417
+ return JSON.stringify({
1418
+ error: "getDialogGoal",
1419
+ detail: err?.message ?? String(err),
1420
+ });
1421
+ }
1422
+ }
1423
+ case "completeDialogGoal": {
1424
+ try {
1425
+ return JSON.stringify(await runCompleteDialogGoalTool(args, context));
1426
+ } catch (err: any) {
1427
+ return JSON.stringify({
1428
+ error: "completeDialogGoal",
1429
+ detail: err?.message ?? String(err),
1430
+ });
1431
+ }
1432
+ }
1433
+ case "taskRun":
1434
+ return runTaskRunTool(withTaskRunContext(args, context), authToken);
1435
+ case "notifyUser": {
1436
+ try {
1437
+ return JSON.stringify(await runNotifyUserTool(args, context));
1438
+ } catch (err: any) {
1439
+ return JSON.stringify({
1440
+ error: "notifyUser",
1441
+ detail: err?.message ?? String(err),
1442
+ });
1443
+ }
1444
+ }
1445
+ case "rememberMemory":
1446
+ return postMain("/api/memory/remember", withDialogId({
1447
+ content: args.content,
1448
+ scope: args.scope,
1449
+ spaceId: context?.currentSpaceId ?? undefined,
1450
+ }));
1451
+ case "callAgent": {
1452
+ const agentKey = typeof args.agentKey === "string" ? args.agentKey.trim() : "";
1453
+ const task = typeof args.task === "string" ? args.task.trim() : "";
1454
+ if (!agentKey) {
1455
+ return JSON.stringify({ error: "callAgent: agentKey is required" });
1456
+ }
1457
+ if (!task) {
1458
+ return JSON.stringify({ error: "callAgent: task is required" });
1459
+ }
1460
+ const childRun = await runChildAgent(
1461
+ agentKey,
1462
+ buildDelegatedAgentInput(task, args.input),
1463
+ args.serverBase,
1464
+ );
1465
+ if (!childRun.ok) {
1466
+ return JSON.stringify({
1467
+ error: `callAgent: HTTP ${childRun.status}`,
1468
+ detail: childRun.error,
1469
+ });
1470
+ }
1471
+ const payload = childRun.payload;
1472
+ return JSON.stringify({
1473
+ success: true,
1474
+ agentKey,
1475
+ ...(childRun.serverBase ? { serverBase: childRun.serverBase } : {}),
1476
+ ...(childRun.autoRouted ? { autoRouted: true } : {}),
1477
+ dialogId: payload?.dialogId ?? null,
1478
+ model: payload?.model ?? null,
1479
+ provider: payload?.provider ?? null,
1480
+ content: typeof payload?.content === "string" ? payload.content : "",
1481
+ usage: payload?.usage ?? null,
1482
+ artifacts: payload?.artifacts ?? null,
1483
+ });
1484
+ }
1485
+ case "runStreamingAgent": {
1486
+ const agentKey = typeof args.agentKey === "string" ? args.agentKey.trim() : "";
1487
+ const userInput = typeof args.userInput === "string" ? args.userInput.trim() : "";
1488
+ if (!agentKey) {
1489
+ return JSON.stringify({ error: "runStreamingAgent: agentKey is required" });
1490
+ }
1491
+ if (!userInput) {
1492
+ return JSON.stringify({ error: "runStreamingAgent: userInput is required" });
1493
+ }
1494
+ const childRun = await runChildAgent(agentKey, userInput, args.serverBase);
1495
+ if (!childRun.ok) {
1496
+ return JSON.stringify({
1497
+ error: `runStreamingAgent: HTTP ${childRun.status}`,
1498
+ detail: childRun.error,
1499
+ });
1500
+ }
1501
+ const payload = childRun.payload;
1502
+ return JSON.stringify({
1503
+ success: true,
1504
+ handoff: true,
1505
+ agentKey,
1506
+ ...(childRun.serverBase ? { serverBase: childRun.serverBase } : {}),
1507
+ ...(childRun.autoRouted ? { autoRouted: true } : {}),
1508
+ dialogId: payload?.dialogId ?? null,
1509
+ ...(payload?.dialogKey ? { dialogKey: payload.dialogKey } : {}),
1510
+ model: payload?.model ?? null,
1511
+ content: typeof payload?.content === "string" ? payload.content : "",
1512
+ usage: payload?.usage ?? null,
1513
+ artifacts: payload?.artifacts ?? null,
1514
+ });
1515
+ }
1516
+ case "startAgentDialog": {
1517
+ const targetAgentKey =
1518
+ typeof args.targetAgentKey === "string"
1519
+ ? args.targetAgentKey.trim()
1520
+ : typeof args.agentKey === "string"
1521
+ ? args.agentKey.trim()
1522
+ : "";
1523
+ const message =
1524
+ typeof args.message === "string"
1525
+ ? args.message.trim()
1526
+ : typeof args.userInput === "string"
1527
+ ? args.userInput.trim()
1528
+ : "";
1529
+ if (!targetAgentKey) {
1530
+ return JSON.stringify({ error: "startAgentDialog: targetAgentKey is required" });
1531
+ }
1532
+ if (!message) {
1533
+ return JSON.stringify({ error: "startAgentDialog: message is required" });
1534
+ }
1535
+ const parentDialogId =
1536
+ typeof args.parentDialogId === "string" && args.parentDialogId.trim()
1537
+ ? args.parentDialogId.trim()
1538
+ : typeof context?.dialogId === "string" && context.dialogId.trim()
1539
+ ? context.dialogId.trim()
1540
+ : undefined;
1541
+ const timeoutMs =
1542
+ typeof args.timeoutMs === "number" && Number.isFinite(args.timeoutMs) && args.timeoutMs > 0
1543
+ ? args.timeoutMs
1544
+ : undefined;
1545
+ const subjectRefs = normalizeSubjectRefs(args.subjectRefs);
1546
+ const childSubjectRefs = mergeSubjectRefs(
1547
+ context?.runtimeContext?.subjectRefs,
1548
+ subjectRefs,
1549
+ );
1550
+ const subjectEvidenceLines = await buildReferencedDialogEvidenceLines({
1551
+ subjectRefs: childSubjectRefs,
1552
+ userId: context?.userId,
1553
+ });
1554
+ const childMessage = buildAgentHandoffUserInput({
1555
+ message,
1556
+ parentDialogId,
1557
+ subjectRefs: childSubjectRefs,
1558
+ subjectEvidenceLines,
1559
+ runtimeContext: context?.runtimeContext,
1560
+ });
1561
+ const childRun = await runChildAgent(
1562
+ targetAgentKey,
1563
+ childMessage,
1564
+ args.serverBase,
1565
+ timeoutMs,
1566
+ {
1567
+ background: true,
1568
+ parentDialogId,
1569
+ subjectRefs: childSubjectRefs,
1570
+ ...(typeof args.idempotencyKey === "string" && args.idempotencyKey.trim()
1571
+ ? { idempotencyKey: args.idempotencyKey.trim() }
1572
+ : {}),
1573
+ },
1574
+ );
1575
+ if (!childRun.ok) {
1576
+ return JSON.stringify({
1577
+ error: `startAgentDialog: HTTP ${childRun.status}`,
1578
+ detail: childRun.error,
1579
+ });
1580
+ }
1581
+ const payload = childRun.payload;
1582
+ const childDialogId = typeof payload?.dialogId === "string" && payload.dialogId.trim()
1583
+ ? payload.dialogId.trim()
1584
+ : "";
1585
+ const childDialogKey = typeof payload?.dialogKey === "string" && payload.dialogKey.trim()
1586
+ ? payload.dialogKey.trim()
1587
+ : undefined;
1588
+ const activityProjection = childDialogId
1589
+ ? await projectDialogActivityToSubjectRows({
1590
+ db: serverDb,
1591
+ subjectRefs: childSubjectRefs,
1592
+ activityRef: {
1593
+ type: "dialog",
1594
+ dialogId: childDialogId,
1595
+ ...(childDialogKey ? { dialogKey: childDialogKey } : {}),
1596
+ role: "child-dialog",
1597
+ agentKey: targetAgentKey,
1598
+ ...(parentDialogId ? { parentDialogId } : {}),
1599
+ status: typeof payload?.status === "string" && payload.status.trim()
1600
+ ? payload.status.trim()
1601
+ : "pending",
1602
+ updatedAt: new Date().toISOString(),
1603
+ },
1604
+ })
1605
+ : undefined;
1606
+ return JSON.stringify({
1607
+ success: true,
1608
+ status: payload?.status ?? "pending",
1609
+ targetAgentKey,
1610
+ childDialogId: childDialogId || null,
1611
+ childDialogKey: childDialogKey ?? null,
1612
+ ...(parentDialogId ? { parentDialogId } : {}),
1613
+ ...(childRun.serverBase ? { serverBase: childRun.serverBase } : {}),
1614
+ ...(childRun.autoRouted ? { autoRouted: true } : {}),
1615
+ ...(activityProjection && activityProjection.updatedRowDbKeys.length
1616
+ ? {
1617
+ activityProjection: {
1618
+ updatedRowDbKeys: activityProjection.updatedRowDbKeys,
1619
+ },
1620
+ }
1621
+ : {}),
1622
+ });
1623
+ }
1624
+ case "streamParallelAgents": {
1625
+ const task = typeof args.task === "string" ? args.task.trim() : "";
1626
+ const agents = Array.isArray(args.agents) ? args.agents : [];
1627
+ const returnMode = args.returnMode === "continue" ? "continue" : "handoff";
1628
+ const displayMode = "inline";
1629
+ const defaultServerBase = args.serverBase;
1630
+ const parallelSessionId = `parallel-${Date.now()}-${Math.random()
1631
+ .toString(36)
1632
+ .slice(2, 10)}`;
1633
+ const timeoutMs =
1634
+ typeof args.timeoutMs === "number" && Number.isFinite(args.timeoutMs) && args.timeoutMs > 0
1635
+ ? args.timeoutMs
1636
+ : PARALLEL_AGENT_BRANCH_TIMEOUT_MS;
1637
+ const budgetCredits = normalizeBudgetCredits(args.budgetCredits);
1638
+ if (!task) {
1639
+ return JSON.stringify({ error: "streamParallelAgents: task is required" });
1640
+ }
1641
+ if (agents.length === 0) {
1642
+ return JSON.stringify({ error: "streamParallelAgents: agents is required" });
1643
+ }
1644
+
1645
+ const results = await Promise.all(
1646
+ agents.map(async (agent: Record<string, any>, index: number) => {
1647
+ const agentKey =
1648
+ typeof agent?.agentKey === "string" ? agent.agentKey.trim() : "";
1649
+ const label =
1650
+ typeof agent?.label === "string" && agent.label.trim()
1651
+ ? agent.label.trim()
1652
+ : `Agent ${index + 1}`;
1653
+ const branchId =
1654
+ typeof agent?.branchId === "string" && agent.branchId.trim()
1655
+ ? agent.branchId.trim()
1656
+ : `branch-${index + 1}`;
1657
+ if (!agentKey) {
1658
+ return {
1659
+ ok: false,
1660
+ label,
1661
+ branchId,
1662
+ agentKey,
1663
+ error: "missing agentKey",
1664
+ spentCredits: null,
1665
+ };
1666
+ }
1667
+
1668
+ const childRun = await Promise.race([
1669
+ runChildAgent(agentKey, task, agent?.serverBase ?? defaultServerBase, timeoutMs),
1670
+ sleep(timeoutMs).then(() => ({
1671
+ ok: false as const,
1672
+ status: 408,
1673
+ error: `branch timeout after ${timeoutMs}ms`,
1674
+ })),
1675
+ ]);
1676
+ if (!childRun.ok) {
1677
+ return {
1678
+ ok: false,
1679
+ label,
1680
+ branchId,
1681
+ agentKey,
1682
+ error: childRun.error,
1683
+ status: childRun.status,
1684
+ authForwarded: Boolean(authToken),
1685
+ spentCredits: null,
1686
+ };
1687
+ }
1688
+
1689
+ const payload = childRun.payload;
1690
+ const pricing = calculateParallelBranchPricing({
1691
+ usage: payload?.usage,
1692
+ agentKey,
1693
+ dialogId: payload?.dialogId ?? null,
1694
+ agentConfig: {
1695
+ id: agentKey,
1696
+ model:
1697
+ typeof payload?.model === "string" ? payload.model : null,
1698
+ provider:
1699
+ typeof payload?.provider === "string"
1700
+ ? payload.provider
1701
+ : null,
1702
+ inputPrice:
1703
+ typeof payload?.inputPrice === "number"
1704
+ ? payload.inputPrice
1705
+ : null,
1706
+ outputPrice:
1707
+ typeof payload?.outputPrice === "number"
1708
+ ? payload.outputPrice
1709
+ : null,
1710
+ },
1711
+ });
1712
+ return {
1713
+ ok: true,
1714
+ label,
1715
+ branchId,
1716
+ parallelSessionId,
1717
+ parallelIndex: index,
1718
+ agentKey,
1719
+ agentName: label,
1720
+ ...(childRun.serverBase ? { serverBase: childRun.serverBase } : {}),
1721
+ ...(childRun.autoRouted ? { autoRouted: true } : {}),
1722
+ dialogId: payload?.dialogId ?? null,
1723
+ model: payload?.model ?? null,
1724
+ provider: payload?.provider ?? null,
1725
+ content:
1726
+ typeof payload?.content === "string" ? payload.content.trim() : "",
1727
+ usage: payload?.usage ?? null,
1728
+ artifacts: payload?.artifacts ?? null,
1729
+ spentCredits: pricing.spentCredits,
1730
+ billedModel: pricing.billedModel,
1731
+ billedProvider: pricing.billedProvider,
1732
+ billingServiceTier: pricing.billingServiceTier,
1733
+ pricingError: pricing.pricingError,
1734
+ };
1735
+ }),
1736
+ );
1737
+
1738
+ const successful = results.filter((item) => item.ok);
1739
+ const costSummary = summarizeParallelCosts(results);
1740
+ const budget = summarizeParallelBudget({
1741
+ budgetCredits,
1742
+ results,
1743
+ });
1744
+ const stats = {
1745
+ total: results.length,
1746
+ succeeded: successful.length,
1747
+ failed: results.length - successful.length,
1748
+ };
1749
+ const mergedContent = successful
1750
+ .map((item) => `## ${item.label}\n\n${item.content || "(无内容)"}`)
1751
+ .join("\n\n");
1752
+
1753
+ return JSON.stringify({
1754
+ success: true,
1755
+ handoff: returnMode === "handoff",
1756
+ returnMode,
1757
+ displayMode,
1758
+ toolName: "streamParallelAgents",
1759
+ content: mergedContent,
1760
+ summary: `并行调用 ${stats.total} 个 Agent · ${stats.succeeded} 成功 · ${stats.failed} 失败`,
1761
+ stats,
1762
+ costSummary,
1763
+ ...(budget ? { budget } : {}),
1764
+ parallelSessionId,
1765
+ results,
1766
+ timeoutMs,
1767
+ usage: successful.map((item) => item.usage).filter(Boolean),
1768
+ });
1769
+ }
1770
+ case "ziweiChart":
1771
+ return JSON.stringify(runZiweiChart(args));
1772
+
1773
+ // ── LevelDB 读写(同构,前后端均可用)──
1774
+ case "read": {
1775
+ if (looksLikeLocalFilePath(args.filePath)) {
1776
+ return postMain("/api/read-file", {
1777
+ filePath: args.filePath,
1778
+ startLine: args.startLine,
1779
+ endLine: args.endLine,
1780
+ });
1781
+ }
1782
+ const dbKey = args.dbKey;
1783
+ if (!dbKey) return JSON.stringify({ error: "read: dbKey is required" });
1784
+ const blockedReadResult = guardWorkspaceRead(dbKey, context);
1785
+ if (blockedReadResult) return blockedReadResult;
1786
+ const res = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(dbKey)}`, {
1787
+ headers: { Authorization: `Bearer ${authToken}` },
1788
+ });
1789
+ if (!res.ok) return JSON.stringify({ error: `read: HTTP ${res.status}`, detail: await res.text() });
1790
+ recordWorkspaceRead(dbKey, context);
1791
+ return res.text();
1792
+ }
1793
+ case "searchDialogMessages": {
1794
+ const dialogKey = normalizeDialogSearchText(args.dialogKey);
1795
+ const query = normalizeDialogSearchText(args.query);
1796
+ if (!dialogKey.startsWith("dialog-")) {
1797
+ return JSON.stringify({ error: "searchDialogMessages: dialogKey must be a dialog-* dbKey" });
1798
+ }
1799
+ if (!query) {
1800
+ return JSON.stringify({ error: "searchDialogMessages: query is required" });
1801
+ }
1802
+ const blockedReadResult = guardWorkspaceRead(dialogKey, context);
1803
+ if (blockedReadResult) return blockedReadResult;
1804
+ const dialogId = dialogKey.split("-").at(-1) || dialogKey;
1805
+ const scanLimit = clampDialogSearchNumber(
1806
+ args.scanLimit,
1807
+ SEARCH_DIALOG_MESSAGES_SCAN_LIMIT,
1808
+ 1,
1809
+ SEARCH_DIALOG_MESSAGES_SCAN_LIMIT,
1810
+ );
1811
+ const resultLimit = clampDialogSearchNumber(args.limit, 5, 1, SEARCH_DIALOG_MESSAGES_RESULT_LIMIT);
1812
+ const contextMessages = clampDialogSearchNumber(
1813
+ args.contextMessages,
1814
+ 1,
1815
+ 0,
1816
+ SEARCH_DIALOG_MESSAGES_CONTEXT_LIMIT,
1817
+ );
1818
+ const res = await fetch(`${mainBase}/rpc/getConvMsgs`, {
1819
+ method: "POST",
1820
+ headers: {
1821
+ Authorization: `Bearer ${authToken}`,
1822
+ "Content-Type": "application/json",
1823
+ },
1824
+ body: JSON.stringify({ dialogId, limit: scanLimit }),
1825
+ });
1826
+ if (!res.ok) {
1827
+ return JSON.stringify({ error: `searchDialogMessages: HTTP ${res.status}`, detail: await res.text() });
1828
+ }
1829
+ const newestFirst = await res.json();
1830
+ const messages = Array.isArray(newestFirst) ? [...newestFirst].reverse() : [];
1831
+ const matches = buildDialogMessageSearchResults({
1832
+ messages,
1833
+ query,
1834
+ limit: resultLimit,
1835
+ contextMessages,
1836
+ role: typeof args.role === "string" ? args.role : undefined,
1837
+ includeTools: args.includeTools,
1838
+ contentClipChars: SEARCH_DIALOG_MESSAGES_CLIP_CHARS,
1839
+ contextClipChars: SEARCH_DIALOG_MESSAGES_CONTEXT_CLIP_CHARS,
1840
+ });
1841
+ recordWorkspaceRead(dialogKey, context);
1842
+ return JSON.stringify({
1843
+ success: true,
1844
+ dialogKey,
1845
+ query,
1846
+ scannedMessages: messages.length,
1847
+ matches,
1848
+ });
1849
+ }
1850
+ case "readDoc":
1851
+ case "readPage": {
1852
+ const id = typeof args.id === "string" ? args.id.trim() : "";
1853
+ if (!id) return JSON.stringify({ error: `${serverToolName}: id is required` });
1854
+ const blockedReadResult = guardWorkspaceRead(id, context);
1855
+ if (blockedReadResult) return blockedReadResult;
1856
+ const res = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(id)}`, {
1857
+ headers: { Authorization: `Bearer ${authToken}` },
1858
+ });
1859
+ if (!res.ok) {
1860
+ return JSON.stringify({
1861
+ error: `${serverToolName}: HTTP ${res.status}`,
1862
+ detail: await res.text(),
1863
+ });
1864
+ }
1865
+ const page = await res.json();
1866
+ recordWorkspaceRead(id, context);
1867
+ return JSON.stringify(buildReadDocResult(page).rawData);
1868
+ }
1869
+ case "deleteSpaces": {
1870
+ if (!context?.userId) {
1871
+ return JSON.stringify({ error: "deleteSpaces: userId is required" });
1872
+ }
1873
+
1874
+ const query = typeof args.query === "string" ? args.query.trim() : "";
1875
+ if (!query) {
1876
+ return JSON.stringify({ error: "deleteSpaces: query is required" });
1877
+ }
1878
+
1879
+ const membershipsRes = await postJson(mainBase, "/rpc/getUserSpaceMemberships", {
1880
+ userId: context.userId,
1881
+ });
1882
+ if (!membershipsRes.ok || !Array.isArray(membershipsRes.data)) {
1883
+ return JSON.stringify({
1884
+ error: `deleteSpaces: membership HTTP ${membershipsRes.status}`,
1885
+ detail: membershipsRes.text,
1886
+ });
1887
+ }
1888
+
1889
+ const candidates = filterSpaceDeletionCandidates(
1890
+ membershipsRes.data as SpaceMembershipLike[],
1891
+ {
1892
+ query,
1893
+ matchMode: args.matchMode,
1894
+ }
1895
+ );
1896
+ const spaceRecordsById: Record<string, SpaceRecordLike | null> = {};
1897
+ for (const candidate of candidates) {
1898
+ const spaceId = String(candidate.spaceId ?? "").replace(/^space-/, "");
1899
+ if (!spaceId) continue;
1900
+ const readRes = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(createSpaceKey.space(spaceId))}`, {
1901
+ headers: buildAuthHeaders(),
1902
+ });
1903
+ if (!readRes.ok) {
1904
+ spaceRecordsById[spaceId] = null;
1905
+ continue;
1906
+ }
1907
+ try {
1908
+ spaceRecordsById[spaceId] = await readRes.json();
1909
+ } catch {
1910
+ spaceRecordsById[spaceId] = null;
1911
+ }
1912
+ }
1913
+
1914
+ const preview = buildDeleteSpacesPreview({
1915
+ currentUserId: context.userId,
1916
+ candidates,
1917
+ spaceRecordsById,
1918
+ });
1919
+
1920
+ const confirmedSpaceIds = Array.isArray(args.confirmedSpaceIds)
1921
+ ? args.confirmedSpaceIds.filter((id: unknown): id is string => typeof id === "string" && id.trim())
1922
+ : [];
1923
+ if (confirmedSpaceIds.length === 0) {
1924
+ return JSON.stringify({
1925
+ requiresConfirmation: true,
1926
+ message:
1927
+ "请让用户确认后,再带 confirmedSpaceIds 调用 deleteSpaces。只会删除 Space 壳和成员关系,不删除挂载内容。",
1928
+ ...preview,
1929
+ });
1930
+ }
1931
+
1932
+ const { targets, missingConfirmedSpaceIds } =
1933
+ resolveConfirmedSpaceDeletionTargets(preview, confirmedSpaceIds);
1934
+ const deletedSpaceIds: string[] = [];
1935
+ const deletedKeys: string[] = [];
1936
+ const failures: Array<{ dbKey: string; status: number; detail: string }> = [];
1937
+
1938
+ for (const target of targets) {
1939
+ const record = spaceRecordsById[target.spaceId];
1940
+ if (!record) continue;
1941
+ const keys = [
1942
+ ...spaceMemberKeysForDelete(target.spaceId, record),
1943
+ createSpaceKey.space(target.spaceId),
1944
+ ];
1945
+ let targetFailed = false;
1946
+ for (const key of keys) {
1947
+ const result = await deleteDbKey(key);
1948
+ if (!result.ok) {
1949
+ targetFailed = true;
1950
+ failures.push({ dbKey: key, status: result.status, detail: result.text });
1951
+ } else {
1952
+ deletedKeys.push(key);
1953
+ }
1954
+ }
1955
+ if (!targetFailed) deletedSpaceIds.push(target.spaceId);
1956
+ }
1957
+
1958
+ return JSON.stringify({
1959
+ deletedSpaceIds,
1960
+ deletedKeys,
1961
+ missingConfirmedSpaceIds,
1962
+ skipped: preview.skipped,
1963
+ failures,
1964
+ });
1965
+ }
1966
+ case "createDoc":
1967
+ case "createPage": {
1968
+ const blockedKnowledgeResult = guardKnowledgeCapture({
1969
+ context,
1970
+ target: "doc",
1971
+ });
1972
+ if (blockedKnowledgeResult) return blockedKnowledgeResult;
1973
+ const res = await fetch(`${mainBase}/api/page/create`, {
1974
+ method: "POST",
1975
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
1976
+ body: JSON.stringify({
1977
+ title: args.title ?? "新文档",
1978
+ content: args.content ?? "",
1979
+ spaceId: args.spaceId,
1980
+ categoryId: args.categoryId,
1981
+ }),
1982
+ });
1983
+ if (!res.ok) return JSON.stringify({ error: `createDoc: HTTP ${res.status}`, detail: await res.text() });
1984
+ recordKnowledgeCapture(context);
1985
+ return res.text();
1986
+ }
1987
+ case "createSkillDoc": {
1988
+ let title = "New Skill";
1989
+ let content = "";
1990
+ try {
1991
+ const built = buildSkillDocFromArgs(args as CreateSkillDocArgs);
1992
+ title = built.title;
1993
+ content = built.content;
1994
+ } catch (error: any) {
1995
+ return JSON.stringify({
1996
+ error: "createSkillDoc",
1997
+ detail: typeof error?.message === "string" ? error.message : String(error),
1998
+ });
1999
+ }
2000
+
2001
+ const blockedKnowledgeResult = guardKnowledgeCapture({
2002
+ context,
2003
+ target: "doc",
2004
+ });
2005
+ if (blockedKnowledgeResult) return blockedKnowledgeResult;
2006
+
2007
+ const res = await fetch(`${mainBase}/api/page/create`, {
2008
+ method: "POST",
2009
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
2010
+ body: JSON.stringify({
2011
+ title,
2012
+ content,
2013
+ spaceId: args.spaceId,
2014
+ categoryId: args.categoryId,
2015
+ }),
2016
+ });
2017
+ if (!res.ok) {
2018
+ return JSON.stringify({ error: `createSkillDoc: HTTP ${res.status}`, detail: await res.text() });
2019
+ }
2020
+ recordKnowledgeCapture(context);
2021
+ const created = await res.json();
2022
+ return JSON.stringify(
2023
+ buildSkillFollowupResult({
2024
+ dbKey: created?.dbKey ?? created?.id ?? "",
2025
+ title: created?.title ?? title,
2026
+ skillId: (args as CreateSkillDocArgs).name || undefined,
2027
+ spaceId: created?.spaceId ?? args.spaceId ?? null,
2028
+ toolNames: Array.isArray((args as CreateSkillDocArgs).toolNames)
2029
+ ? (args as CreateSkillDocArgs).toolNames
2030
+ : [],
2031
+ hasEvalConfig: Array.isArray((args as CreateSkillDocArgs).evalCases)
2032
+ && (args as CreateSkillDocArgs).evalCases!.length > 0,
2033
+ }).rawData
2034
+ );
2035
+ }
2036
+ case "doctorSkill": {
2037
+ let page: any = null;
2038
+ if (typeof args.id === "string" && args.id.trim()) {
2039
+ const res = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(args.id.trim())}`, {
2040
+ headers: { Authorization: `Bearer ${authToken}` },
2041
+ });
2042
+ if (!res.ok) {
2043
+ return JSON.stringify({ error: `doctorSkill: HTTP ${res.status}`, detail: await res.text() });
2044
+ }
2045
+ page = await res.json();
2046
+ }
2047
+ const result = await diagnoseSkillDocument(
2048
+ {
2049
+ id: page?.dbKey ?? args.id,
2050
+ title: page?.title,
2051
+ content: typeof args.content === "string" ? args.content : page?.content ?? "",
2052
+ meta: resolvePageSkillMetadata(page),
2053
+ tools: page?.tools,
2054
+ },
2055
+ );
2056
+ return JSON.stringify(result);
2057
+ }
2058
+ case "evalSkill": {
2059
+ let page: any = null;
2060
+ const loadPage = async (dbKey: string) => {
2061
+ const res = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(dbKey)}`, {
2062
+ headers: { Authorization: `Bearer ${authToken}` },
2063
+ });
2064
+ if (!res.ok) return undefined;
2065
+ return res.json();
2066
+ };
2067
+ if (typeof args.id === "string" && args.id.trim()) {
2068
+ page = await loadPage(args.id.trim());
2069
+ if (!page) {
2070
+ return JSON.stringify({ error: `evalSkill: 未找到 ${args.id}` });
2071
+ }
2072
+ }
2073
+ const result = await evaluateSkillDocument(
2074
+ {
2075
+ id: page?.dbKey ?? args.id,
2076
+ title: page?.title,
2077
+ content: typeof args.content === "string" ? args.content : page?.content ?? "",
2078
+ meta: resolvePageSkillMetadata(page),
2079
+ tools: page?.tools,
2080
+ },
2081
+ {
2082
+ loadPage,
2083
+ },
2084
+ );
2085
+ return JSON.stringify(result);
2086
+ }
2087
+ case "createSkillAgent": {
2088
+ if (!context?.userId) {
2089
+ return JSON.stringify({ error: "createSkillAgent: missing userId in execution context" });
2090
+ }
2091
+
2092
+ const agent = buildSkillAgentRecord({
2093
+ userId: context.userId,
2094
+ currentSpaceId: context.currentSpaceId ?? undefined,
2095
+ args: args as CreateSkillAgentToolArgs,
2096
+ });
2097
+
2098
+ const res = await fetch(`${mainBase}/api/v1/db/write/`, {
2099
+ method: "POST",
2100
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
2101
+ body: JSON.stringify({
2102
+ userId: context.userId,
2103
+ customKey: agent.dbKey,
2104
+ data: agent,
2105
+ }),
2106
+ });
2107
+ if (!res.ok) {
2108
+ return JSON.stringify({ error: `createSkillAgent: HTTP ${res.status}`, detail: await res.text() });
2109
+ }
2110
+ if (agent.isPublic) {
2111
+ const publicRes = await fetch(`${mainBase}/api/v1/db/write/`, {
2112
+ method: "POST",
2113
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
2114
+ body: JSON.stringify({
2115
+ userId: context.userId,
2116
+ customKey: agent.publicDbKey,
2117
+ data: agent,
2118
+ }),
2119
+ });
2120
+ if (!publicRes.ok) {
2121
+ return JSON.stringify({
2122
+ error: `createSkillAgent(public): HTTP ${publicRes.status}`,
2123
+ detail: await publicRes.text(),
2124
+ });
2125
+ }
2126
+ }
2127
+ return res.text();
2128
+ }
2129
+ case "prepareAgentDraft": {
2130
+ const result = await prepareAgentDraftToolFunc(args as PrepareAgentDraftToolArgs);
2131
+ return JSON.stringify(result);
2132
+ }
2133
+ case "createAgent": {
2134
+ if (!context?.userId) {
2135
+ return JSON.stringify({ error: "createAgent: missing userId in execution context" });
2136
+ }
2137
+ let agent: ReturnType<typeof buildServerCreatedAgentRecord>;
2138
+ try {
2139
+ agent = buildServerCreatedAgentRecord(
2140
+ context.userId,
2141
+ args as CreateAgentToolArgs,
2142
+ context.currentSpaceId,
2143
+ );
2144
+ } catch (error) {
2145
+ return JSON.stringify({
2146
+ error: error instanceof Error ? error.message : String(error),
2147
+ });
2148
+ }
2149
+ const privateKey = createAgentKey.private(context.userId, agent.id);
2150
+ const publicKey = createAgentKey.public(agent.id);
2151
+ const writeAgent = async (customKey: string) =>
2152
+ fetch(`${mainBase}/api/v1/db/write/`, {
2153
+ method: "POST",
2154
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
2155
+ body: JSON.stringify({
2156
+ userId: context.userId,
2157
+ customKey,
2158
+ data: agent,
2159
+ }),
2160
+ });
2161
+
2162
+ const privateRes = await writeAgent(privateKey);
2163
+ if (!privateRes.ok) {
2164
+ return JSON.stringify({
2165
+ error: `createAgent(private): HTTP ${privateRes.status}`,
2166
+ detail: await privateRes.text(),
2167
+ });
2168
+ }
2169
+ if (agent.isPublic) {
2170
+ const publicRes = await writeAgent(publicKey);
2171
+ if (!publicRes.ok) {
2172
+ return JSON.stringify({
2173
+ error: `createAgent(public): HTTP ${publicRes.status}`,
2174
+ detail: await publicRes.text(),
2175
+ });
2176
+ }
2177
+ }
2178
+ return JSON.stringify({
2179
+ rawData: {
2180
+ ...agent,
2181
+ dbKey: privateKey,
2182
+ publicDbKey: agent.isPublic ? publicKey : undefined,
2183
+ },
2184
+ displayData: [
2185
+ `已创建 Agent: ${agent.name}`,
2186
+ `- ID: ${agent.id}`,
2187
+ `- 模型: ${agent.model}`,
2188
+ `- Provider: ${agent.provider}`,
2189
+ `- 是否公开: ${agent.isPublic ? "是" : "否"}`,
2190
+ agent.isPublic ? `- Public Key: ${publicKey}` : "",
2191
+ ].filter(Boolean).join("\n"),
2192
+ });
2193
+ }
2194
+ case "importSkill": {
2195
+ const sourceUrl = typeof args.url === "string" ? normalizeSkillImportUrl(args.url) : "";
2196
+ let rawMarkdown =
2197
+ typeof args.content === "string" ? args.content.trim() : "";
2198
+ if (!rawMarkdown && !sourceUrl) {
2199
+ return JSON.stringify({ error: "importSkill: url 或 content 至少需要一个" });
2200
+ }
2201
+ if (!rawMarkdown) {
2202
+ const sourceRes = await fetch(sourceUrl);
2203
+ if (!sourceRes.ok) {
2204
+ return JSON.stringify({
2205
+ error: `importSkill(fetch): HTTP ${sourceRes.status}`,
2206
+ detail: await sourceRes.text(),
2207
+ });
2208
+ }
2209
+ rawMarkdown = (await sourceRes.text()).trim();
2210
+ }
2211
+
2212
+ const parsed = parseExternalSkillMarkdown(rawMarkdown);
2213
+ const title = typeof args.title === "string" && args.title.trim()
2214
+ ? args.title.trim()
2215
+ : parsed.name || "Imported Skill";
2216
+ const skillConfig: SkillDocConfig = {
2217
+ version: "0.1",
2218
+ kind: "skill",
2219
+ id:
2220
+ (parsed.name || title)
2221
+ .trim()
2222
+ .toLowerCase()
2223
+ .replace(/[^a-z0-9]+/g, "-")
2224
+ .replace(/^-+|-+$/g, "") || "imported-skill",
2225
+ name: parsed.name || title,
2226
+ description: parsed.description || "Imported external skill.",
2227
+ triggerMode: "explicit",
2228
+ toolNames: parsed.allowedTools,
2229
+ budgetTier: "medium",
2230
+ dispatchPreferred: false,
2231
+ modalities: ["text"],
2232
+ };
2233
+ const content = buildSkillDocMarkdown({
2234
+ body: [
2235
+ parsed.body,
2236
+ parsed.compatibility ? `## Compatibility\n${parsed.compatibility}` : "",
2237
+ sourceUrl ? `Imported from: ${sourceUrl}` : "",
2238
+ ]
2239
+ .filter(Boolean)
2240
+ .join("\n\n"),
2241
+ skillConfig,
2242
+ });
2243
+
2244
+ const blockedKnowledgeResult = guardKnowledgeCapture({
2245
+ context,
2246
+ target: "doc",
2247
+ });
2248
+ if (blockedKnowledgeResult) return blockedKnowledgeResult;
2249
+
2250
+ const res = await fetch(`${mainBase}/api/page/create`, {
2251
+ method: "POST",
2252
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
2253
+ body: JSON.stringify({
2254
+ title,
2255
+ content,
2256
+ spaceId: args.spaceId,
2257
+ categoryId: args.categoryId,
2258
+ }),
2259
+ });
2260
+ if (!res.ok) {
2261
+ return JSON.stringify({ error: `importSkill: HTTP ${res.status}`, detail: await res.text() });
2262
+ }
2263
+ recordKnowledgeCapture(context);
2264
+ const created = await res.json();
2265
+ return JSON.stringify(
2266
+ buildSkillFollowupResult({
2267
+ dbKey: created?.dbKey ?? created?.id ?? "",
2268
+ title: created?.title ?? title,
2269
+ skillId: skillConfig.id,
2270
+ spaceId: created?.spaceId ?? args.spaceId ?? null,
2271
+ toolNames: skillConfig.toolNames ?? [],
2272
+ importedFrom: sourceUrl || null,
2273
+ hasEvalConfig: false,
2274
+ }).rawData
2275
+ );
2276
+ }
2277
+ case "shareTable": {
2278
+ const blockedShareResult = guardPublicTableShare(context);
2279
+ if (blockedShareResult) return blockedShareResult;
2280
+ if (!context?.userId) {
2281
+ return JSON.stringify({ error: "shareTable requires an authenticated user." });
2282
+ }
2283
+
2284
+ const tableDbKey =
2285
+ typeof args.dbKey === "string" && args.dbKey.trim()
2286
+ ? args.dbKey.trim()
2287
+ : typeof args.tenantId === "string" &&
2288
+ args.tenantId.trim() &&
2289
+ typeof args.tableId === "string" &&
2290
+ args.tableId.trim()
2291
+ ? `meta-${args.tenantId.trim()}-${args.tableId.trim()}`
2292
+ : "";
2293
+ if (!tableDbKey) {
2294
+ return JSON.stringify({
2295
+ error: "shareTable requires dbKey, or both tenantId and tableId.",
2296
+ });
2297
+ }
2298
+
2299
+ const tableReadRes = await fetch(
2300
+ `${mainBase}/api/v1/db/read/${encodeURIComponent(tableDbKey)}`,
2301
+ { headers: buildAuthHeaders() },
2302
+ );
2303
+ if (!tableReadRes.ok) {
2304
+ return JSON.stringify({
2305
+ error: `shareTable: failed to read table meta (${tableReadRes.status})`,
2306
+ detail: await tableReadRes.text(),
2307
+ });
2308
+ }
2309
+ const tableReadPayload = await tableReadRes.json();
2310
+ const tableMeta = tableReadPayload?.data ?? tableReadPayload;
2311
+ const tableOwnerId =
2312
+ (typeof args.tenantId === "string" && args.tenantId.trim()) ||
2313
+ (typeof tableMeta?.tenantId === "string" && tableMeta.tenantId.trim()) ||
2314
+ context.userId;
2315
+ const tableId =
2316
+ (typeof args.tableId === "string" && args.tableId.trim()) ||
2317
+ (typeof tableMeta?.tableId === "string" && tableMeta.tableId.trim()) ||
2318
+ tableDbKey;
2319
+
2320
+ let settings: any = null;
2321
+ try {
2322
+ const settingsRes = await fetch(
2323
+ `${mainBase}/api/v1/db/read/${encodeURIComponent(createUserKey.settings(context.userId))}`,
2324
+ { headers: buildAuthHeaders() },
2325
+ );
2326
+ if (settingsRes.ok) {
2327
+ const settingsPayload = await settingsRes.json();
2328
+ settings = settingsPayload?.data ?? settingsPayload;
2329
+ }
2330
+ } catch {
2331
+ settings = null;
2332
+ }
2333
+
2334
+ const originServer =
2335
+ normalizeServerOrigin(settings?.currentServer) ??
2336
+ normalizeServerOrigin(mainBase) ??
2337
+ normalizeBase(mainBase);
2338
+ const fanoutServers = buildFanoutServerList(originServer, settings?.syncServers);
2339
+ const token = generateShareToken();
2340
+ const dbKey = shareKey.create(token);
2341
+ const createdAt = Date.now();
2342
+ const title =
2343
+ (typeof args.title === "string" && args.title.trim()) ||
2344
+ (typeof tableMeta?.displayName === "string" && tableMeta.displayName.trim()) ||
2345
+ tableId;
2346
+ const description =
2347
+ typeof args.description === "string" && args.description.trim()
2348
+ ? args.description.trim()
2349
+ : undefined;
2350
+ const visibility = args.visibility === "private" ? "private" : "community";
2351
+
2352
+ const sharedObject = {
2353
+ type: DataType.TABLE,
2354
+ version: 1,
2355
+ data: {
2356
+ mode: "live",
2357
+ tableDbKey,
2358
+ tableOwnerId,
2359
+ originServer,
2360
+ },
2361
+ meta: {
2362
+ authorId: context.userId,
2363
+ createdAt,
2364
+ visibility,
2365
+ title,
2366
+ description,
2367
+ originalId: tableDbKey,
2368
+ mode: "live",
2369
+ tableDbKey,
2370
+ tableOwnerId,
2371
+ originServer,
2372
+ },
2373
+ };
2374
+ const indexKeys = shareKey.allIndexKeysFromShare(dbKey, sharedObject);
2375
+ const writeBody = {
2376
+ data: sharedObject,
2377
+ customKey: dbKey,
2378
+ userId: context.userId,
2379
+ indexKeys,
2380
+ };
2381
+ const originResult = {
2382
+ server: originServer,
2383
+ ...(await postJson(originServer, "/api/v1/db/write/", writeBody)),
2384
+ };
2385
+ if (!originResult.ok) {
2386
+ return JSON.stringify({
2387
+ error: "shareTable: failed to publish on origin server",
2388
+ originServer,
2389
+ detail: originResult.text ?? "",
2390
+ });
2391
+ }
2392
+ const replicaServers = fanoutServers.filter(
2393
+ (server) => normalizeServerOrigin(server) !== originServer,
2394
+ );
2395
+ const replicaResults = await Promise.all(
2396
+ replicaServers.map(async (server) => ({
2397
+ server,
2398
+ ...(await postJson(server, "/api/v1/db/write/", writeBody)),
2399
+ })),
2400
+ );
2401
+ const writeResults = [originResult, ...replicaResults];
2402
+
2403
+ const replicaFailures = writeResults
2404
+ .filter(
2405
+ (result) =>
2406
+ normalizeServerOrigin(result.server) !== originServer && !result.ok,
2407
+ )
2408
+ .map((result) => ({
2409
+ server: result.server,
2410
+ status: result.status,
2411
+ detail: result.text,
2412
+ }));
2413
+
2414
+ return JSON.stringify({
2415
+ token,
2416
+ key: dbKey,
2417
+ url: `/share/${token}`,
2418
+ originServer,
2419
+ replicatedServers: fanoutServers,
2420
+ ...(replicaFailures.length > 0 ? { replicaFailures } : {}),
2421
+ });
2422
+ }
2423
+ case "createTable":
2424
+ {
2425
+ const blockedKnowledgeResult = guardKnowledgeCapture({
2426
+ context,
2427
+ target: "table",
2428
+ });
2429
+ if (blockedKnowledgeResult) return blockedKnowledgeResult;
2430
+ }
2431
+ {
2432
+ const result = await postMain("/api/table/create", {
2433
+ spaceId: args.spaceId,
2434
+ title: args.title,
2435
+ description: args.description,
2436
+ tags: args.tags,
2437
+ categoryId: args.categoryId,
2438
+ columns: args.columns,
2439
+ withDefaultRows: args.withDefaultRows,
2440
+ });
2441
+ recordKnowledgeCapture(context);
2442
+ return result;
2443
+ }
2444
+ case "addTableRow":
2445
+ return postMain(
2446
+ "/api/table/add-row",
2447
+ withFeedbackSubmitterUserId({
2448
+ tenantId: args.tenantId,
2449
+ tableId: args.tableId,
2450
+ values: args.values,
2451
+ }),
2452
+ );
2453
+ case "queryTableRows":
2454
+ return postMain("/api/table/query-rows", {
2455
+ tenantId: args.tenantId,
2456
+ tableId: args.tableId,
2457
+ filters: args.filters,
2458
+ columns: args.columns,
2459
+ limit: args.limit,
2460
+ offset: args.offset,
2461
+ includeBaseFields: args.includeBaseFields,
2462
+ sortBy: args.sortBy,
2463
+ sortOrder: args.sortOrder,
2464
+ });
2465
+ case "updateTableRow":
2466
+ return postMain("/api/table/update-row", {
2467
+ tenantId: args.tenantId,
2468
+ tableId: args.tableId,
2469
+ rowId: args.rowId,
2470
+ dbKey: args.dbKey,
2471
+ changes: args.changes,
2472
+ });
2473
+ case "deleteTableRow":
2474
+ {
2475
+ const blockedDeleteResult = guardDestructiveAction({
2476
+ context,
2477
+ target: "table_row_delete",
2478
+ detail: "deleteTableRow",
2479
+ });
2480
+ if (blockedDeleteResult) return blockedDeleteResult;
2481
+ }
2482
+ return postMain("/api/table/delete-row", {
2483
+ tenantId: args.tenantId,
2484
+ tableId: args.tableId,
2485
+ rowId: args.rowId,
2486
+ dbKey: args.dbKey,
2487
+ });
2488
+ case "addTableRows":
2489
+ return postMain("/api/table/add-rows", {
2490
+ tenantId: args.tenantId,
2491
+ tableId: args.tableId,
2492
+ rows: args.rows,
2493
+ });
2494
+ case "updateTableRows":
2495
+ return postMain("/api/table/update-rows", {
2496
+ tenantId: args.tenantId,
2497
+ tableId: args.tableId,
2498
+ updates: args.updates,
2499
+ });
2500
+ case "deleteTableRows":
2501
+ {
2502
+ const blockedDeleteResult = guardDestructiveAction({
2503
+ context,
2504
+ target: "table_row_delete",
2505
+ detail: "deleteTableRows",
2506
+ });
2507
+ if (blockedDeleteResult) return blockedDeleteResult;
2508
+ }
2509
+ return postMain("/api/table/delete-rows", {
2510
+ tenantId: args.tenantId,
2511
+ tableId: args.tableId,
2512
+ rowIds: args.rowIds,
2513
+ dbKeys: args.dbKeys,
2514
+ });
2515
+ case "addTableColumn":
2516
+ return postMain("/api/table/add-column", {
2517
+ tenantId: args.tenantId,
2518
+ tableId: args.tableId,
2519
+ name: args.name,
2520
+ label: args.label,
2521
+ type: args.type,
2522
+ description: args.description,
2523
+ required: args.required,
2524
+ options: args.options,
2525
+ });
2526
+ case "deleteTableColumn":
2527
+ {
2528
+ const blockedDeleteResult = guardDestructiveAction({
2529
+ context,
2530
+ target: "table_column_delete",
2531
+ detail: "deleteTableColumn",
2532
+ });
2533
+ if (blockedDeleteResult) return blockedDeleteResult;
2534
+ }
2535
+ return postMain("/api/table/delete-column", {
2536
+ tenantId: args.tenantId,
2537
+ tableId: args.tableId,
2538
+ columnName: args.columnName,
2539
+ });
2540
+ case "renameTableColumn":
2541
+ return postMain("/api/table/rename-column", {
2542
+ tenantId: args.tenantId,
2543
+ tableId: args.tableId,
2544
+ oldName: args.oldName,
2545
+ newName: args.newName,
2546
+ });
2547
+ case "renameTableColumnLabel":
2548
+ return postMain("/api/table/rename-column-label", {
2549
+ tenantId: args.tenantId,
2550
+ tableId: args.tableId,
2551
+ columnName: args.columnName,
2552
+ newLabel: args.newLabel,
2553
+ });
2554
+ case "renameTable":
2555
+ return postMain("/api/table/rename", {
2556
+ tenantId: args.tenantId,
2557
+ tableId: args.tableId,
2558
+ newName: args.newName,
2559
+ });
2560
+
2561
+ case "updateDoc":
2562
+ case "update_page": {
2563
+ const { id, title, content, mode = "replace" } = args;
2564
+ if (!id) return JSON.stringify({ error: "updateDoc: id (dbKey) is required" });
2565
+ if (typeof content !== "string") {
2566
+ return JSON.stringify({ error: "updateDoc: content is required" });
2567
+ }
2568
+
2569
+ const existingRes = await fetch(`${mainBase}/api/v1/db/read/${encodeURIComponent(id)}`, {
2570
+ headers: { Authorization: `Bearer ${authToken}` },
2571
+ });
2572
+ if (!existingRes.ok) {
2573
+ return JSON.stringify({ error: `updateDoc(read): HTTP ${existingRes.status}`, detail: await existingRes.text() });
2574
+ }
2575
+
2576
+ const existing = await existingRes.json();
2577
+ const currentMarkdown =
2578
+ typeof existing?.content === "string" && existing.content.trim()
2579
+ ? existing.content
2580
+ : slateToRenderMarkdown(
2581
+ Array.isArray(existing?.slateData) ? existing.slateData : [],
2582
+ );
2583
+ const mergedMarkdown = mode === "append"
2584
+ ? [currentMarkdown, content].filter(Boolean).join("\n\n")
2585
+ : content;
2586
+ const parsedProtocol = parseSkillDocProtocol(
2587
+ mergedMarkdown,
2588
+ existing?.meta,
2589
+ existing?.tools,
2590
+ );
2591
+ const slateData = markdownToSlate(parsedProtocol.content) as any[];
2592
+ const tools = extractMentionsFromSlate(slateData as any);
2593
+
2594
+ const changes: Record<string, any> = {
2595
+ slateData,
2596
+ content: parsedProtocol.content,
2597
+ tools,
2598
+ ...(parsedProtocol.meta ? { meta: parsedProtocol.meta } : {}),
2599
+ updated_at: new Date().toISOString(),
2600
+ };
2601
+ if (typeof title === "string" && title.trim()) {
2602
+ changes.title = title.trim();
2603
+ }
2604
+
2605
+ const res = await fetch(`${mainBase}/api/v1/db/patch/${encodeURIComponent(id)}`, {
2606
+ method: "PATCH",
2607
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
2608
+ body: JSON.stringify(changes),
2609
+ });
2610
+ if (!res.ok) return JSON.stringify({ error: `updateDoc: HTTP ${res.status}`, detail: await res.text() });
2611
+ return JSON.stringify({ success: true, id, title: changes.title ?? existing?.title });
2612
+ }
2613
+
2614
+ // ── 数据库(服务端专属)──
2615
+ case "executeSql":
2616
+ return postMain("/api/v1/sqlite/execute_sql", { sql: args.sql, params: args.params });
2617
+
2618
+ // ── 文件系统 / shell(由目标 server 直接提供)──
2619
+ case "readFile":
2620
+ return postMain("/api/read-file", { filePath: args.filePath, startLine: args.startLine, endLine: args.endLine });
2621
+ case "writeFile":
2622
+ return postMain("/api/write-file", { filePath: args.filePath, content: args.content, overwrite: args.overwrite });
2623
+ case "applyEdit":
2624
+ return postMain("/api/apply-edit", { filePath: args.filePath, edits: args.edits });
2625
+ case "execShell":
2626
+ if (isDestructiveShellCommand({ command: args.command, input: args.input })) {
2627
+ const blockedDeleteResult = guardDestructiveAction({
2628
+ context,
2629
+ target: "shell_command",
2630
+ detail: "execShell destructive command",
2631
+ });
2632
+ if (blockedDeleteResult) return blockedDeleteResult;
2633
+ }
2634
+ return postMain("/api/exec-shell", {
2635
+ command: args.command,
2636
+ cwd: args.cwd,
2637
+ shell: args.shell,
2638
+ interactive: args.interactive,
2639
+ pty: args.pty,
2640
+ sessionId: args.sessionId,
2641
+ input: args.input,
2642
+ close: args.close,
2643
+ });
2644
+ case "codeSearch":
2645
+ return postMain("/api/code-search", {
2646
+ query: args.query,
2647
+ path: args.path ?? args.pathScope ?? args.dirPath,
2648
+ glob: args.glob,
2649
+ mode: args.mode ?? "content",
2650
+ maxResults: args.maxResults ?? args.maxFiles,
2651
+ caseSensitive: args.caseSensitive,
2652
+ });
2653
+ case "search_workspace":
2654
+ return postMain("/api/search-repo", {
2655
+ query: args.query,
2656
+ pathScope: args.pathScope,
2657
+ maxResults: args.maxResults,
2658
+ contextLines: args.contextLines,
2659
+ });
2660
+ case "applyLineEdits":
2661
+ return postMain("/api/apply-line-edits", { filePath: args.filePath, edits: args.edits });
2662
+ case "checkEnv":
2663
+ case "check_env":
2664
+ return postMain("/api/check-env", { check: args.check ?? "build" });
2665
+
2666
+ // ── 浏览器自动化(服务端 Puppeteer)──
2667
+ case "browser_openSession":
2668
+ case "browser_closeSession":
2669
+ case "browser_selectOption":
2670
+ case "browser_click":
2671
+ case "browser_typeText":
2672
+ case "browser_readContent":
2673
+ case "browser_probePage":
2674
+ return postMain("/api/browser-tool", {
2675
+ toolName: serverToolName,
2676
+ params: args,
2677
+ });
2678
+
2679
+ case "email_provision_identity": {
2680
+ const missingAgentKey = requireCurrentAgentKey();
2681
+ if (missingAgentKey) return missingAgentKey;
2682
+ const result = await postJson(mainBase, "/rpc/provisionAgentEmailIdentity", {
2683
+ ...args,
2684
+ agentId: currentAgentKey,
2685
+ });
2686
+ if (!result.ok) {
2687
+ return JSON.stringify(
2688
+ result.data ?? {
2689
+ error: `email_provision_identity: HTTP ${result.status}`,
2690
+ detail: result.text,
2691
+ },
2692
+ );
2693
+ }
2694
+ return JSON.stringify(result.data ?? {});
2695
+ }
2696
+ case "email_wait_for": {
2697
+ const missingAgentKey = requireCurrentAgentKey();
2698
+ if (missingAgentKey) return missingAgentKey;
2699
+
2700
+ const timeoutSecondsRaw =
2701
+ typeof args.timeoutSeconds === "number"
2702
+ ? args.timeoutSeconds
2703
+ : Number(args.timeoutSeconds ?? 60);
2704
+ const timeoutMs = Math.min(Math.max(timeoutSecondsRaw, 1), 180) * 1000;
2705
+ const pollIntervalRaw =
2706
+ typeof args.pollIntervalMs === "number"
2707
+ ? args.pollIntervalMs
2708
+ : Number(args.pollIntervalMs ?? 3000);
2709
+ const pollIntervalMs = Math.min(Math.max(pollIntervalRaw, 500), 10_000);
2710
+ const limitRaw =
2711
+ typeof args.limit === "number" ? args.limit : Number(args.limit ?? 20);
2712
+ const limit = Math.min(Math.max(limitRaw, 1), 200);
2713
+ const startedAt = Date.now();
2714
+ let attempts = 0;
2715
+
2716
+ while (Date.now() - startedAt <= timeoutMs) {
2717
+ attempts += 1;
2718
+ const result = await postJson(mainBase, "/rpc/listEmails", {
2719
+ ownerId: currentAgentKey,
2720
+ mailbox: typeof args.mailbox === "string" ? args.mailbox : "inbox",
2721
+ status: args.status,
2722
+ tag: args.tag,
2723
+ limit,
2724
+ });
2725
+ if (!result.ok) {
2726
+ return JSON.stringify(
2727
+ result.data ?? {
2728
+ error: `email_wait_for: HTTP ${result.status}`,
2729
+ detail: result.text,
2730
+ },
2731
+ );
2732
+ }
2733
+ const items = Array.isArray(result.data) ? result.data : [];
2734
+ const match = items.find(
2735
+ (email) => emailIsFreshForWait(email, startedAt) && emailMatchesWaitFilters(email, args),
2736
+ );
2737
+ if (match) {
2738
+ return JSON.stringify({
2739
+ email: match,
2740
+ attempts,
2741
+ waitedMs: Date.now() - startedAt,
2742
+ });
2743
+ }
2744
+ await sleep(pollIntervalMs);
2745
+ }
2746
+
2747
+ return JSON.stringify({
2748
+ error: `等待邮件超时:${Math.ceil(timeoutMs / 1000)} 秒内没有匹配邮件`,
2749
+ });
2750
+ }
2751
+ case "email_extract_verification": {
2752
+ let email: any = null;
2753
+ let text = typeof args.text === "string" ? args.text : undefined;
2754
+ let html = typeof args.html === "string" ? args.html : undefined;
2755
+ if (typeof args.dbKey === "string" && args.dbKey.trim()) {
2756
+ const result = await postJson(mainBase, "/rpc/getEmail", {
2757
+ dbKey: args.dbKey.trim(),
2758
+ });
2759
+ if (!result.ok) {
2760
+ return JSON.stringify(
2761
+ result.data ?? {
2762
+ error: `email_extract_verification: HTTP ${result.status}`,
2763
+ detail: result.text,
2764
+ },
2765
+ );
2766
+ }
2767
+ email = result.data;
2768
+ text = typeof email?.text === "string" ? email.text : text;
2769
+ html = typeof email?.html === "string" ? email.html : html;
2770
+ }
2771
+ if (!text && !html) {
2772
+ return JSON.stringify({
2773
+ error: "必须提供 dbKey、text 或 html 中至少一个",
2774
+ });
2775
+ }
2776
+ return JSON.stringify({
2777
+ email,
2778
+ ...extractEmailVerificationArtifacts({ text, html }),
2779
+ });
2780
+ }
2781
+
2782
+ // ── 应用部署管理 ──
2783
+ case "appPreflight":
2784
+ return postMain("/api/app/preflight", {
2785
+ name: args.name,
2786
+ code: args.code,
2787
+ files: normalizeAppFiles(),
2788
+ appId: args.appId,
2789
+ framework: args.framework,
2790
+ spaceId: args.spaceId,
2791
+ });
2792
+ case "appDeploy": {
2793
+ const nextFiles = normalizeAppFiles();
2794
+ const guardUserInput =
2795
+ typeof context?.userInput === "string" ? context.userInput.trim() : "";
2796
+ if (args.appId && guardUserInput && (typeof args.code === "string" || (Array.isArray(nextFiles) && nextFiles.length > 0))) {
2797
+ const previousRead = await postJson(mainBase, "/api/app/prepare-edit", {
2798
+ appId: args.appId,
2799
+ });
2800
+ if (previousRead.ok) {
2801
+ const guardResult = evaluateSmallVisualEditGuard({
2802
+ userInput: guardUserInput,
2803
+ previousSource: previousRead.data ?? {},
2804
+ nextSource: {
2805
+ code: typeof args.code === "string" ? args.code : undefined,
2806
+ files: nextFiles,
2807
+ },
2808
+ });
2809
+ if (!guardResult.ok) {
2810
+ return JSON.stringify(guardResult.rawData);
2811
+ }
2812
+ }
2813
+ }
2814
+
2815
+ const deployStart = await postJson(mainBase, "/api/app/deploy", {
2816
+ name: args.name,
2817
+ code: args.code,
2818
+ files: nextFiles,
2819
+ appId: args.appId,
2820
+ framework: args.framework,
2821
+ spaceId: args.spaceId,
2822
+ });
2823
+ if (!deployStart.ok) {
2824
+ return JSON.stringify(
2825
+ deployStart.data ?? {
2826
+ error: `appDeploy: HTTP ${deployStart.status}`,
2827
+ detail: deployStart.text,
2828
+ },
2829
+ );
2830
+ }
2831
+
2832
+ const jobId =
2833
+ typeof deployStart.data?.jobId === "string"
2834
+ ? deployStart.data.jobId
2835
+ : "";
2836
+ if (!jobId) {
2837
+ return deployStart.text;
2838
+ }
2839
+ return waitForAppDeployResult(jobId);
2840
+ }
2841
+ case "appList":
2842
+ return postMain("/api/app/list", args.spaceId ? { spaceId: args.spaceId } : {});
2843
+ case "appDelete": {
2844
+ if (!args.appId) {
2845
+ return JSON.stringify({ error: "appDelete: appId is required; call appList first" });
2846
+ }
2847
+ {
2848
+ const blockedDeleteResult = guardDestructiveAction({
2849
+ context,
2850
+ target: "app_delete",
2851
+ detail: "appDelete",
2852
+ });
2853
+ if (blockedDeleteResult) return blockedDeleteResult;
2854
+ }
2855
+ const lookupRes = await fetch(`${mainBase}/api/app/get`, {
2856
+ method: "POST",
2857
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
2858
+ body: JSON.stringify({ appId: args.appId }),
2859
+ });
2860
+ if (!lookupRes.ok) {
2861
+ return JSON.stringify({ error: `appDelete lookup: HTTP ${lookupRes.status}`, detail: await lookupRes.text() });
2862
+ }
2863
+ const lookupJson = await lookupRes.json().catch(() => null) as { appKey?: string } | null;
2864
+ if (!lookupJson?.appKey) {
2865
+ return JSON.stringify({ error: "appDelete: appKey not found" });
2866
+ }
2867
+ const deleteRes = await fetch(`${mainBase}/api/v1/db/delete/${encodeURIComponent(lookupJson.appKey)}`, {
2868
+ method: "DELETE",
2869
+ headers: { Authorization: `Bearer ${authToken}` },
2870
+ });
2871
+ if (!deleteRes.ok) {
2872
+ return JSON.stringify({ error: `appDelete: HTTP ${deleteRes.status}`, detail: await deleteRes.text() });
2873
+ }
2874
+ return deleteRes.text();
2875
+ }
2876
+ case "appRead":
2877
+ if (!args.appId) {
2878
+ return JSON.stringify({ error: "appRead: appId is required; call appList first" });
2879
+ }
2880
+ {
2881
+ const readResult = await postJson(mainBase, "/api/app/prepare-edit", {
2882
+ appId: args.appId,
2883
+ });
2884
+ if (!readResult.ok) {
2885
+ return JSON.stringify(
2886
+ readResult.data ?? {
2887
+ error: `appRead: HTTP ${readResult.status}`,
2888
+ detail: readResult.text,
2889
+ },
2890
+ );
2891
+ }
2892
+ const styleSystemAnalysis = analyzeAppStyleSystem(readResult.data ?? {});
2893
+ const styleSystemHint = buildAppStyleSystemHint(styleSystemAnalysis);
2894
+ return JSON.stringify({
2895
+ ...(readResult.data ?? {}),
2896
+ styleSystemStatus: styleSystemAnalysis.status,
2897
+ legacyMigrationRecommended:
2898
+ styleSystemAnalysis.legacyMigrationRecommended,
2899
+ styleSystemEvidence: styleSystemAnalysis.evidence,
2900
+ ...(styleSystemHint ? { styleSystemHint } : {}),
2901
+ });
2902
+ }
2903
+
2904
+ default:
2905
+ return JSON.stringify({
2906
+ error: `Tool "${toolCall.function.name}" is not available in server-side agent mode.`,
2907
+ });
2908
+ }
2909
+ }