nolo-cli 0.1.29 → 0.1.31

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 (329) hide show
  1. package/agent-runtime/agentRecordConfig.ts +0 -2
  2. package/agent-runtime/hostAdapter.ts +0 -1
  3. package/agent-runtime/hostRuntimeCapabilities.ts +7 -0
  4. package/agent-runtime/hostRuntimeConfig.ts +86 -0
  5. package/agent-runtime/index.ts +13 -0
  6. package/agent-runtime/localToolPolicy.ts +13 -6
  7. package/agent-runtime/localWorkspaceTools.ts +333 -30
  8. package/agent-runtime/platformChatProvider.ts +4 -1
  9. package/agent-runtime/runtimeToolPolicy.ts +32 -47
  10. package/agent-runtime/shellCommandPolicy.ts +117 -0
  11. package/agent-runtime/toolGate.ts +38 -0
  12. package/agentCreateCustomCommands.ts +9 -4
  13. package/agentDialogsCommands.ts +4 -3
  14. package/agentDoctorCommands.ts +3 -3
  15. package/agentListCommands.ts +3 -3
  16. package/agentMachineCommands.ts +6 -6
  17. package/agentPullCommand.ts +4 -12
  18. package/agentRecordCommands.ts +5 -3
  19. package/agentRecordHelpers.ts +42 -23
  20. package/agentRunCommand.ts +2 -6
  21. package/agentRunParsing.ts +18 -5
  22. package/agentRuntimeLocal.ts +10 -0
  23. package/agentUnpublishCommands.ts +3 -2
  24. package/ai/agent/agentRunDialogLineage.ts +56 -0
  25. package/ai/agent/agentSlice.ts +45 -10
  26. package/ai/agent/avatarUtils.ts +1 -1
  27. package/ai/agent/buildSystemPrompt.ts +1 -2
  28. package/ai/agent/cliExecutor.ts +330 -19
  29. package/ai/agent/createAgentSchema.ts +22 -0
  30. package/ai/agent/hooks/fetchPublicAgents.ts +14 -39
  31. package/ai/agent/hooks/usePublicAgents.ts +90 -192
  32. package/ai/agent/publicAgentCatalog.ts +359 -0
  33. package/ai/agent/publicAgentIdentity.ts +76 -0
  34. package/ai/agent/server/fetchPublicAgents.ts +21 -46
  35. package/ai/agent/serverOrigin.ts +7 -0
  36. package/ai/agent/streamAgentChatTurn.ts +23 -21
  37. package/ai/agent/streamAgentChatTurnUtils.ts +292 -6
  38. package/ai/agent/types.ts +2 -0
  39. package/ai/agent/web/agentDisplayUtils.ts +171 -0
  40. package/ai/agent/web/useAgentModelAvatarComponent.ts +32 -0
  41. package/ai/ai.locale.ts +8 -0
  42. package/ai/chat/sendOpenAICompletionsRequest.native.ts +15 -0
  43. package/ai/chat/sendOpenAICompletionsRequest.ts +93 -1
  44. package/ai/chat/sendOpenAIResponseRequest.ts +86 -9
  45. package/ai/chat/updateTotalUsage.ts +7 -0
  46. package/ai/llm/deepinfra.ts +30 -15
  47. package/ai/llm/mistral.ts +3 -4
  48. package/ai/llm/providers.ts +2 -0
  49. package/ai/llm/types.ts +15 -0
  50. package/ai/memory/capture.ts +3 -3
  51. package/ai/memory/consolidate.ts +2 -2
  52. package/ai/memory/delete.ts +4 -3
  53. package/ai/memory/query.ts +3 -3
  54. package/ai/memory/remember.ts +2 -2
  55. package/ai/memory/store.ts +3 -3
  56. package/ai/memory/storeShared.ts +3 -2
  57. package/ai/policy/commercialMultiplier.ts +16 -0
  58. package/ai/token/billingAdminAuditEvent.ts +68 -0
  59. package/ai/token/billingAdminAuditEventWriter.ts +41 -0
  60. package/ai/token/billingAnomaly.ts +90 -0
  61. package/ai/token/billingAnomalyLifecycle.ts +54 -0
  62. package/ai/token/billingAnomalyLifecycleWriter.ts +44 -0
  63. package/ai/token/billingAnomalyWriter.ts +41 -0
  64. package/ai/token/calculatePrice.ts +3 -2
  65. package/ai/token/deepinfraReconciliation.ts +153 -0
  66. package/ai/token/deepinfraRequestIdQuery.ts +92 -0
  67. package/ai/token/externalToolCost.ts +54 -41
  68. package/ai/token/missingUsageEstimate.ts +12 -3
  69. package/ai/token/normalizeUsage.ts +45 -5
  70. package/ai/token/openaiReconciliation.ts +188 -0
  71. package/ai/token/providerBillableEvent.ts +84 -0
  72. package/ai/token/providerBillableEventWriter.ts +36 -0
  73. package/ai/token/providerBillingAnomalyDrilldown.ts +308 -0
  74. package/ai/token/providerBillingDrilldown.ts +361 -0
  75. package/ai/token/providerBillingHealthReport.ts +366 -0
  76. package/ai/token/providerCall.ts +144 -0
  77. package/ai/token/providerCallSweeper.ts +168 -0
  78. package/ai/token/providerCallWriter.ts +33 -0
  79. package/ai/token/providerCredential.ts +89 -0
  80. package/ai/token/providerCredentialAnomaly.ts +154 -0
  81. package/ai/token/providerCredentialLifecycle.ts +59 -0
  82. package/ai/token/providerCredentialLifecycleWriter.ts +44 -0
  83. package/ai/token/providerCredentialRegistry.ts +83 -0
  84. package/ai/token/providerCredentialRegistryCommand.ts +97 -0
  85. package/ai/token/providerCredentialRegistryList.ts +124 -0
  86. package/ai/token/providerCredentialRegistryResolver.ts +150 -0
  87. package/ai/token/providerCredentialRegistryWriter.ts +41 -0
  88. package/ai/token/providerCredentialRotationCommand.ts +102 -0
  89. package/ai/token/providerCredentialRuntime.ts +56 -0
  90. package/ai/token/providerDispatchIntent.ts +67 -0
  91. package/ai/token/providerDispatchIntentWriter.ts +36 -0
  92. package/ai/token/providerGateway.ts +260 -0
  93. package/ai/token/providerReconciliation.ts +148 -0
  94. package/ai/token/providerReconciliationLocal.ts +97 -0
  95. package/ai/token/providerReconciliationRunner.ts +165 -0
  96. package/ai/token/providerReconciliationWriter.ts +41 -0
  97. package/ai/token/ratingResult.ts +202 -0
  98. package/ai/token/ratingResultWriter.ts +33 -0
  99. package/ai/token/serverDialogProjection.ts +5 -3
  100. package/ai/token/serverTokenWriter.ts +11 -3
  101. package/ai/token/types.ts +10 -0
  102. package/ai/tools/agent/callAgentTool.ts +3 -4
  103. package/ai/tools/agent/presets/appBuilderPreset.ts +5 -7
  104. package/ai/tools/agent/runStreamingAgentTool.ts +1 -2
  105. package/ai/tools/agent/streamParallelAgentsTool.ts +2 -3
  106. package/ai/tools/readXPostTool.ts +1 -5
  107. package/app/admin/adminPages.ts +9 -0
  108. package/app/i18n/i18n.config.ts +5 -0
  109. package/app/i18n/translations/pricing.locale.ts +397 -0
  110. package/app/utils/desktopAgentRuntimeStatusClient.ts +5 -4
  111. package/app/utils/desktopAgentRuntimeTurnClient.ts +4 -1
  112. package/app/utils/imageUtils.ts +64 -34
  113. package/auth/adminPermissions.ts +18 -0
  114. package/auth/authSlice.ts +26 -12
  115. package/auth/hooks/useFetchUsers.ts +3 -0
  116. package/auth/routes.ts +46 -0
  117. package/auth/server/accessActivity.ts +4 -3
  118. package/auth/server/adminPermissions.ts +43 -0
  119. package/auth/server/adminUsageReport.ts +375 -0
  120. package/auth/server/billingAnomalies.ts +235 -0
  121. package/auth/server/billingUsageReport.ts +41 -2
  122. package/auth/server/creatorEarningCreditConversion.ts +10 -2
  123. package/auth/server/deduct.ts +14 -7
  124. package/auth/server/delete.ts +10 -2
  125. package/auth/server/disable.ts +4 -3
  126. package/auth/server/emailAutomation.ts +7 -5
  127. package/auth/server/emailDbConfig.ts +4 -2
  128. package/auth/server/emailDelivery.ts +24 -20
  129. package/auth/server/emailDeliveryGuards.ts +10 -7
  130. package/auth/server/emailPreferences.ts +6 -4
  131. package/auth/server/emailReport.ts +6 -4
  132. package/auth/server/emailRuntimeConfig.ts +3 -3
  133. package/auth/server/emailScenarioNotifications.ts +9 -8
  134. package/auth/server/enable.ts +4 -3
  135. package/auth/server/getRechargeHistory.ts +3 -2
  136. package/auth/server/getUser.ts +3 -2
  137. package/auth/server/gptProAccess.ts +44 -0
  138. package/auth/server/inviteReward.ts +10 -7
  139. package/auth/server/listusers.ts +6 -4
  140. package/auth/server/login.ts +2 -2
  141. package/auth/server/productEntitlements.ts +7 -4
  142. package/auth/server/productPurchase.ts +10 -2
  143. package/auth/server/providerBillingDrilldown.ts +47 -0
  144. package/auth/server/providerBillingHealth.ts +71 -0
  145. package/auth/server/providerCredentials.ts +136 -0
  146. package/auth/server/recharge.ts +14 -8
  147. package/auth/server/revokeSessions.ts +4 -3
  148. package/auth/server/route.ts +77 -0
  149. package/auth/server/sendEmail.ts +5 -4
  150. package/auth/server/signup.ts +10 -3
  151. package/auth/server/token.ts +53 -55
  152. package/auth/server/tokenUsageBilling.ts +18 -7
  153. package/auth/server/usageManagementAccess.ts +43 -0
  154. package/auth/server/usageReport.ts +59 -0
  155. package/auth/types.ts +12 -0
  156. package/auth/utils.ts +24 -22
  157. package/authCommands.ts +36 -2
  158. package/buildPublish.ts +3 -1
  159. package/buildPublishArtifactAssembly.ts +62 -1
  160. package/buildPublishImportAnalysis.ts +21 -16
  161. package/chat/dialog/dialogLaunchScope.ts +32 -0
  162. package/chat/dialog/objectAssistantRegistry.ts +2 -2
  163. package/chat/dialog/useCreateDialog.ts +1 -1
  164. package/chat/hooks/useChatInput.ts +41 -10
  165. package/chat/messages/messageSlice.ts +5 -1
  166. package/chat/messages/pendingAttachmentParts.ts +28 -2
  167. package/chat/messages/sendFirstMessage.ts +76 -79
  168. package/chat/messages/types.ts +9 -0
  169. package/chat/messages/web/streamingMarkdownModel.ts +41 -0
  170. package/chat/messages/web/useStreamingReveal.ts +91 -0
  171. package/chat/web/messageInputAgentUi.ts +94 -6
  172. package/cliEnvHelpers.ts +68 -13
  173. package/cliRuntimeDoctorReport.ts +193 -0
  174. package/client/agentConfigResolver.test.ts +0 -2
  175. package/client/agentRun.test.ts +171 -10
  176. package/client/agentRun.ts +44 -637
  177. package/client/agentRunInput.ts +10 -0
  178. package/client/agentRunLocalExecutor.ts +179 -0
  179. package/client/agentRunServerTransport.ts +394 -0
  180. package/client/agentRunTaskRunRecorder.ts +176 -0
  181. package/client/localRuntimeAdapter.test.ts +236 -9
  182. package/client/localRuntimeAdapter.ts +221 -23
  183. package/client/localToolPolicy.test.ts +28 -4
  184. package/connector-experimental/daemonLauncher.ts +38 -4
  185. package/connectorRunArtifact.ts +34 -10
  186. package/connectorWebSocketTarget.ts +40 -15
  187. package/core/builtinAgents.ts +155 -11
  188. package/create/space/contentLabels.ts +1 -1
  189. package/create/space/contentTypeMeta.ts +3 -2
  190. package/create/space/sidebarVisibleTypes.ts +27 -0
  191. package/create/space/space.locale.ts +76 -4
  192. package/database/actions/agentReadResolution.ts +2 -8
  193. package/database/actions/read.ts +11 -9
  194. package/database/actions/readAndWait.ts +10 -5
  195. package/database/server/agentDelegation.ts +3 -2
  196. package/database/server/authorityStoreConformance.ts +209 -0
  197. package/database/server/authorityStoreTypes.ts +31 -0
  198. package/database/server/coreDataProxy.ts +1 -1
  199. package/database/server/dataHandlers.ts +13 -5
  200. package/database/server/db.ts +15 -34
  201. package/database/server/delete.ts +88 -71
  202. package/database/server/emailRepository.ts +11 -9
  203. package/database/server/fileService.ts +2 -1
  204. package/database/server/legacyServerDb.ts +58 -0
  205. package/database/server/levelAuthorityStore.ts +75 -0
  206. package/database/server/memoryAuthorityStore.ts +133 -0
  207. package/database/server/patch.ts +13 -12
  208. package/database/server/query.ts +3 -2
  209. package/database/server/read.ts +33 -30
  210. package/database/server/resourceAccess.ts +7 -5
  211. package/database/server/serverStoreFactory.ts +124 -0
  212. package/database/server/spaceMemberAuthority.ts +3 -2
  213. package/database/server/storeBatchCompat.ts +37 -0
  214. package/database/server/testAuthorityStore.ts +76 -0
  215. package/database/server/write.ts +29 -27
  216. package/dialogReadCommands.ts +2 -1
  217. package/dialogStatusCommands.ts +2 -1
  218. package/integrations/anthropic/anthropicModels.ts +12 -12
  219. package/integrations/deepseek/models.ts +67 -67
  220. package/integrations/google/models.ts +111 -53
  221. package/integrations/openai/models.ts +22 -22
  222. package/integrations/xai/models.ts +1 -1
  223. package/localRuntimeDb.ts +39 -2
  224. package/machineCommandPrompts.ts +2 -0
  225. package/machineCommands.ts +193 -62
  226. package/machineStatusCommands.ts +4 -12
  227. package/machineWsRunDispatch.ts +80 -15
  228. package/machineWsSession.ts +46 -2
  229. package/noloReadBridgePrompt.ts +16 -0
  230. package/package.json +114 -21
  231. package/pageCreateCommands.ts +2 -2
  232. package/pageDeleteCommands.ts +3 -3
  233. package/pageReadCommands.ts +3 -3
  234. package/pageUpdateCommands.ts +3 -3
  235. package/render/layout/mainLayoutViewMode.ts +25 -0
  236. package/render/page/server/createPage.ts +3 -1
  237. package/render/page/server/handleCreatePage.ts +2 -11
  238. package/runtimeDoctorCommands.ts +18 -69
  239. package/server/api/methods.ts +34 -12
  240. package/server/api/tableHandlers.ts +6 -3
  241. package/server/authenticateToken.ts +47 -2
  242. package/server/billingLedgerRoutes.ts +15 -0
  243. package/server/buildManifest.ts +54 -0
  244. package/server/coreReadiness.ts +34 -25
  245. package/server/coreRuntime.ts +15 -10
  246. package/server/handlers/activityStatsHandler.ts +5 -2
  247. package/server/handlers/agentEmailRegistrationE2EHandler.ts +25 -23
  248. package/server/handlers/agentRun/agentLookup.ts +1 -7
  249. package/server/handlers/agentRun/autonomousRuntime.ts +11 -10
  250. package/server/handlers/agentRun/builtinAgents.ts +12 -88
  251. package/server/handlers/agentRun/continueDialogContext.ts +15 -3
  252. package/server/handlers/agentRun/{inheritedDialogPrompt.ts → conversationReference.ts} +3 -3
  253. package/server/handlers/agentRun/dialogLookup.ts +4 -3
  254. package/server/handlers/agentRun/index.ts +864 -404
  255. package/server/handlers/agentRun/localRuntimeBootstrap.ts +17 -1
  256. package/server/handlers/agentRun/loop.ts +920 -508
  257. package/server/handlers/agentRun/machineConnector.ts +56 -8
  258. package/server/handlers/agentRun/machineRunAudit.ts +3 -2
  259. package/server/handlers/agentRun/modelUsageToolHandlers.ts +13 -10
  260. package/server/handlers/agentRun/requestContext.ts +12 -8
  261. package/server/handlers/agentRun/runtimeExecutionContext.ts +15 -3
  262. package/server/handlers/agentRun/runtimePreparation.ts +26 -24
  263. package/server/handlers/agentRun/runtimeRouting.ts +25 -40
  264. package/server/handlers/agentRun/runtimeSystemMessages.ts +65 -0
  265. package/server/handlers/agentRun/saveDialog.ts +97 -87
  266. package/server/handlers/agentRun/taskRunToolHandler.ts +9 -7
  267. package/server/handlers/agentRun/toolExecutor.ts +42 -78
  268. package/server/handlers/agentRun/types.ts +2 -1
  269. package/server/handlers/appDeployStatusStore.ts +17 -10
  270. package/server/handlers/appDomainHandler.ts +21 -15
  271. package/server/handlers/appLegacyInfraCleanup.ts +5 -2
  272. package/server/handlers/appSandboxHandler.ts +29 -8
  273. package/server/handlers/appSpaceAccess.ts +15 -8
  274. package/server/handlers/chatHandler.ts +22 -2
  275. package/server/handlers/chatUpstreamRetry.ts +225 -2
  276. package/server/handlers/connector/connectorConnectionRegistry.ts +55 -7
  277. package/server/handlers/connector/connectorWebSocket.ts +14 -10
  278. package/server/handlers/desktopAgentRuntimeAdapter.ts +4 -4
  279. package/server/handlers/desktopAgentRuntimeHostCapabilities.ts +25 -0
  280. package/server/handlers/desktopAgentRuntimeReadiness.ts +62 -0
  281. package/server/handlers/desktopAgentRuntimeStatusHandler.ts +38 -30
  282. package/server/handlers/desktopAgentRuntimeTurnHandler.ts +7 -3
  283. package/server/handlers/desktopAgentRuntimeTurnService.ts +39 -45
  284. package/server/handlers/desktopLlamaRuntimeHandler.ts +85 -51
  285. package/server/handlers/desktopUpdaterHandler.ts +132 -24
  286. package/server/handlers/favoriteHandlers.ts +8 -2
  287. package/server/handlers/getDialogBillingHandler.ts +4 -3
  288. package/server/handlers/getTransactionsHandler.ts +5 -2
  289. package/server/handlers/machines/machineBinding.ts +1 -0
  290. package/server/handlers/machines/machineHandlers.ts +0 -14
  291. package/server/handlers/machines/machineInstallAssets.ts +4 -2
  292. package/server/handlers/notificationEmitter.ts +5 -3
  293. package/server/handlers/notificationsHandler.ts +5 -2
  294. package/server/handlers/providerCallsRecentHandler.ts +234 -0
  295. package/server/handlers/providerReconciliationRunHandler.ts +180 -0
  296. package/server/handlers/providerRequestIdsHandler.ts +105 -0
  297. package/server/handlers/tableAccess.ts +6 -2
  298. package/server/handlers/tableToolHandlers.ts +28 -14
  299. package/server/handlers/userSecretsHandler.ts +17 -6
  300. package/server/handlers/versionHandler.ts +9 -4
  301. package/server/handlers/versionStore.ts +18 -10
  302. package/server/html/ssrPreload.ts +5 -3
  303. package/server/payments/crypto/cryptoUsdcBasePaymentProvider.ts +11 -8
  304. package/server/payments/crypto/cryptoUsdcBaseScanner.ts +12 -7
  305. package/server/payments/crypto/cryptoUsdtTronPaymentProvider.ts +11 -8
  306. package/server/payments/crypto/cryptoUsdtTronScanner.ts +9 -7
  307. package/server/payments/waffo/waffoPaymentProvider.ts +12 -9
  308. package/server/runtimeRole.ts +15 -0
  309. package/server/scheduler/scheduledTaskRuntime.ts +4 -2
  310. package/server/scheduler/schedulerService.ts +2 -2
  311. package/server/taskRunBridgeRoutes.ts +8 -5
  312. package/share/server/fetchCommunityShares.ts +1 -1
  313. package/share/server/helpers.ts +19 -17
  314. package/share/server/importShare.ts +9 -13
  315. package/share/server/listCommunityShares.ts +4 -4
  316. package/share/server/purchaseDoc.ts +8 -16
  317. package/share/server/readCommunityShareCover.ts +3 -2
  318. package/share/server/readSharedTable.ts +14 -13
  319. package/share/server/tableReplication.ts +42 -39
  320. package/spaceAttachCommands.ts +135 -0
  321. package/spaceCategoryCommands.ts +6 -6
  322. package/spaceCommands.ts +3 -3
  323. package/spaceDeleteCommands.ts +2 -2
  324. package/spaceInternalCommandEntries.ts +2 -0
  325. package/spaceReadCommands.ts +3 -3
  326. package/tableMetaCommands.ts +2 -2
  327. package/taskRunCommand.ts +11 -0
  328. package/ai/agent/runtimeServerBase.ts +0 -37
  329. package/server/handlers/desktopAgentRuntimeHostFacts.ts +0 -40
@@ -0,0 +1,10 @@
1
+ export function buildUserInputContent(message: string, imageUrls: string[] = []) {
2
+ if (imageUrls.length === 0) return message;
3
+ return [
4
+ ...(message.trim() ? [{ type: "text" as const, text: message }] : []),
5
+ ...imageUrls.map((url) => ({
6
+ type: "image_url" as const,
7
+ image_url: { url },
8
+ })),
9
+ ];
10
+ }
@@ -0,0 +1,179 @@
1
+ import { runLocalAgentTurn, resolveHostRuntimeConfigFromEnv } from "../agentRuntimeLocal";
2
+ import { LOCAL_AGENT_CONFIG_MISSING_CODE } from "../agent-runtime/localLoop";
3
+ import type { LocalAgentToolEvent } from "../agent-runtime/localLoop";
4
+ import { buildUserInputContent } from "./agentRunInput";
5
+ import { createCliLocalRuntimeAdapter } from "./localRuntimeAdapter";
6
+ import { prependTaskRunPrompt } from "./taskRunPrompt";
7
+ import { recordTaskRunOutcome } from "./agentRunTaskRunRecorder";
8
+ import {
9
+ formatToolTraceEvent,
10
+ nextLocalToolRoundLimit,
11
+ parseLocalToolRoundLimitError,
12
+ resolveLocalToolRoundRetryLimit,
13
+ shouldCollectLocalToolEvidence,
14
+ shouldTraceLocalTools,
15
+ summarizeLocalToolEvidence,
16
+ } from "./agentRunLocalExecution";
17
+ import type { RunAgentTurnOptions } from "./agentRun";
18
+
19
+ export type LocalAgentTurnResult = {
20
+ exitCode: number;
21
+ dialogId?: string;
22
+ localError?: unknown;
23
+ toolEvidence?: ReturnType<typeof summarizeLocalToolEvidence>;
24
+ };
25
+
26
+ function buildDefaultLocalRuntimeAdapter(options: RunAgentTurnOptions) {
27
+ return createCliLocalRuntimeAdapter({
28
+ env: options.env,
29
+ hostRuntimeConfig: resolveHostRuntimeConfigFromEnv({
30
+ env: options.env,
31
+ surface: "cli-local",
32
+ workspaceBinding: "explicit-cwd",
33
+ }),
34
+ fetchImpl: options.fetchImpl,
35
+ cwd: options.localRuntimeCwd,
36
+ output: options.output,
37
+ });
38
+ }
39
+
40
+ export function resolveLocalRuntimeAdapter(options: RunAgentTurnOptions) {
41
+ return (
42
+ options.localRuntimeAdapter ||
43
+ options.localRuntimeAdapterFactory?.(options.env, { cwd: options.localRuntimeCwd }) ||
44
+ buildDefaultLocalRuntimeAdapter(options)
45
+ );
46
+ }
47
+
48
+ export function isMissingLocalAgentConfigError(error: unknown, agentRef: string) {
49
+ return Boolean(
50
+ error &&
51
+ typeof error === "object" &&
52
+ "code" in error &&
53
+ (error as { code?: string; agentRef?: string }).code === LOCAL_AGENT_CONFIG_MISSING_CODE &&
54
+ (error as { code?: string; agentRef?: string }).agentRef === agentRef
55
+ );
56
+ }
57
+
58
+ export async function runInjectedLocalAgentTurn(options: RunAgentTurnOptions) {
59
+ return runLocalAgentTurnWithAutoRoundExpansion(options, { reportFailure: true });
60
+ }
61
+
62
+ export async function refreshMissingLocalAgentConfig(options: RunAgentTurnOptions) {
63
+ const adapter = resolveLocalRuntimeAdapter(options);
64
+ if (!adapter) return false;
65
+ const agentConfig = await adapter.loadAgentConfig(options.agentKey);
66
+ return Boolean(agentConfig);
67
+ }
68
+
69
+ export async function runLocalAgentTurnWithAutoRoundExpansion(
70
+ options: RunAgentTurnOptions,
71
+ settings: { reportFailure: boolean }
72
+ ) {
73
+ const maxRetryLimit = resolveLocalToolRoundRetryLimit(options);
74
+ let currentMaxToolRounds = options.maxToolRounds;
75
+ let lastResult: Awaited<ReturnType<typeof runLocalAgentTurnForCli>> | null = null;
76
+
77
+ while (true) {
78
+ const attemptOptions = {
79
+ ...options,
80
+ ...(typeof currentMaxToolRounds === "number" ? { maxToolRounds: currentMaxToolRounds } : {}),
81
+ };
82
+ const result = await runLocalAgentTurnForCli(attemptOptions, { reportFailure: false });
83
+ lastResult = result;
84
+ if (result.exitCode === 0) return result;
85
+
86
+ const exhaustedRounds = parseLocalToolRoundLimitError(result.localError);
87
+ if (exhaustedRounds === null) break;
88
+
89
+ const nextMaxToolRounds = nextLocalToolRoundLimit(exhaustedRounds);
90
+ if (nextMaxToolRounds > maxRetryLimit) break;
91
+
92
+ options.output.write(
93
+ `[nolo] Local agent used all ${exhaustedRounds} tool rounds; retrying with ${nextMaxToolRounds}.\n`
94
+ );
95
+ currentMaxToolRounds = nextMaxToolRounds;
96
+ }
97
+
98
+ if (settings.reportFailure && lastResult?.localError) {
99
+ options.output.write(
100
+ `[nolo] Local agent run failed: ${
101
+ lastResult.localError instanceof Error ? lastResult.localError.message : String(lastResult.localError)
102
+ }\n`
103
+ );
104
+ await recordTaskRunOutcome({
105
+ options,
106
+ status: "failed",
107
+ errorCode: "LOCAL_AGENT_FAILED",
108
+ resultSummary:
109
+ lastResult.localError instanceof Error ? lastResult.localError.message : String(lastResult.localError),
110
+ toolEvidence: lastResult.toolEvidence,
111
+ });
112
+ }
113
+ return lastResult ?? { exitCode: 1 };
114
+ }
115
+
116
+ export async function runLocalAgentTurnForCli(
117
+ options: RunAgentTurnOptions,
118
+ settings: { reportFailure: boolean }
119
+ ): Promise<LocalAgentTurnResult> {
120
+ const adapter = resolveLocalRuntimeAdapter(options);
121
+ if (!adapter) {
122
+ options.output.write("[nolo] Local runtime was requested but no local runtime adapter is available.\n");
123
+ return { exitCode: 1 };
124
+ }
125
+
126
+ options.output.write(`\n${options.agentName} -> working locally...\n`);
127
+ const toolEvents: LocalAgentToolEvent[] = [];
128
+ try {
129
+ const traceLocalTools = shouldTraceLocalTools(options);
130
+ const collectToolEvidence = shouldCollectLocalToolEvidence(options);
131
+ const result = await runLocalAgentTurn({
132
+ adapter,
133
+ agentRef: options.agentKey,
134
+ input: buildUserInputContent(
135
+ prependTaskRunPrompt(options.message, options.taskRunContext),
136
+ options.imageUrls
137
+ ),
138
+ continueDialogId: options.continueDialogId,
139
+ spaceId: options.spaceId,
140
+ category: options.category,
141
+ inheritedFromDialogKey: options.inheritedFromDialogKey,
142
+ parentDialogId: options.parentDialogId,
143
+ background: options.background,
144
+ noStream: options.noStream,
145
+ maxToolRounds: options.maxToolRounds,
146
+ ...(traceLocalTools || collectToolEvidence
147
+ ? {
148
+ onToolEvent: (event) => {
149
+ if (collectToolEvidence) toolEvents.push(event);
150
+ if (traceLocalTools) options.output.write(formatToolTraceEvent(event));
151
+ },
152
+ }
153
+ : {}),
154
+ });
155
+ const content = result.content.trim();
156
+ if (content) {
157
+ options.output.write(`\n${options.agentName} > ${content}\n`);
158
+ } else {
159
+ options.output.write(`\n${options.agentName} > (no text response)\n`);
160
+ }
161
+ await recordTaskRunOutcome({
162
+ options,
163
+ status: options.background ? "running" : "completed",
164
+ dialogId: result.dialogId,
165
+ ...(!options.background && content ? { resultSummary: content } : {}),
166
+ toolEvidence: summarizeLocalToolEvidence(toolEvents),
167
+ });
168
+ return { exitCode: 0, dialogId: result.dialogId };
169
+ } catch (error) {
170
+ if (settings.reportFailure) {
171
+ options.output.write(
172
+ `[nolo] Local agent run failed: ${
173
+ error instanceof Error ? error.message : String(error)
174
+ }\n`
175
+ );
176
+ }
177
+ return { exitCode: 1, localError: error, toolEvidence: summarizeLocalToolEvidence(toolEvents) };
178
+ }
179
+ }
@@ -0,0 +1,394 @@
1
+ import type { EnvLike } from "../cliEnvHelpers";
2
+ import type { OutputLike } from "../cliIoTypes";
3
+ import { NOLO_CLUSTER_SERVERS, normalizeKnownServerOrigin } from "../database/config";
4
+ import { createStreamingTextWriter } from "./streamingOutput";
5
+ import { buildUserInputContent } from "./agentRunInput";
6
+ import { recordTaskRunOutcome, type TaskRunRecorder } from "./agentRunTaskRunRecorder";
7
+ import { shouldShowUsage } from "./agentRunRuntimeSelection";
8
+ import { prependTaskRunPrompt, type TaskRunPromptContext } from "./taskRunPrompt";
9
+
10
+ type ServerTransportOptionShape = {
11
+ agentName: string;
12
+ agentKey: string;
13
+ serverUrl: string;
14
+ message: string;
15
+ imageUrls?: string[];
16
+ continueDialogId?: string;
17
+ spaceId?: string;
18
+ category?: string;
19
+ inheritedFromDialogKey?: string;
20
+ parentDialogId?: string;
21
+ background?: boolean;
22
+ noStream?: boolean;
23
+ scriptDir: string;
24
+ env: EnvLike;
25
+ output: OutputLike;
26
+ maxToolRounds?: number;
27
+ timeoutMs?: number;
28
+ taskRunContext?: TaskRunPromptContext;
29
+ taskRunRecorder?: TaskRunRecorder<any>;
30
+ fetchImpl?: typeof fetch;
31
+ };
32
+
33
+ export type ServerTransportRunResult = {
34
+ exitCode: number;
35
+ dialogId?: string;
36
+ streamInterrupted?: boolean;
37
+ };
38
+
39
+ export function formatUsage(usage: any, dialogId: unknown) {
40
+ const parts: string[] = [];
41
+ if (typeof dialogId === "string" && dialogId) parts.push(`dialog=${dialogId}`);
42
+
43
+ const input = usage?.input_tokens ?? usage?.prompt_tokens ?? 0;
44
+ const output = usage?.output_tokens ?? usage?.completion_tokens ?? 0;
45
+ if (input || output) parts.push(`tokens=${input}+${output}`);
46
+
47
+ return parts.length ? ` (${parts.join(" ")})` : "";
48
+ }
49
+
50
+ export function isLikelyTransportConnectivityError(reason: string) {
51
+ return /Unable to connect|ConnectionRefused|ECONNREFUSED|Failed to connect|timed out|Timeout|network|socket|handshake|certificate/i
52
+ .test(reason);
53
+ }
54
+
55
+ export function buildTransportErrorHint(serverUrl: string, error: unknown) {
56
+ const endpoint = `${serverUrl}/api/agent/run`;
57
+ const reason = error instanceof Error ? error.message : String(error);
58
+
59
+ let detail =
60
+ `[nolo] Could not reach ${endpoint}.\n` +
61
+ `Reason: ${reason}\n`;
62
+
63
+ try {
64
+ const parsed = new URL(serverUrl);
65
+ if (parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost") {
66
+ detail +=
67
+ "If you meant local dev, start the local API first.\n" +
68
+ "Otherwise set NOLO_SERVER to a reachable server, or re-run `nolo login --server https://nolo.chat`.\n";
69
+ return detail;
70
+ }
71
+ } catch {
72
+ // Keep the generic hint below when serverUrl is not a valid absolute URL.
73
+ }
74
+
75
+ if (isLikelyTransportConnectivityError(reason)) {
76
+ detail +=
77
+ "If this command is running inside a sandboxed agent session, outbound network access may be blocked even when the host machine can reach the server.\n";
78
+ }
79
+ detail += "Check NOLO_SERVER / BASE_URL and make sure the configured server is reachable.\n";
80
+ return detail;
81
+ }
82
+
83
+ function normalizeServerOrigin(serverUrl: string) {
84
+ return normalizeKnownServerOrigin(serverUrl) ?? serverUrl.trim().replace(/\/+$/, "");
85
+ }
86
+
87
+ function resolveNormalizedClusterServers() {
88
+ return [...new Set(NOLO_CLUSTER_SERVERS.map(normalizeServerOrigin))];
89
+ }
90
+
91
+ function resolveClusterRetryServers(serverUrl: string) {
92
+ const current = normalizeServerOrigin(serverUrl);
93
+ const clusterServers = resolveNormalizedClusterServers();
94
+ if (!clusterServers.includes(current)) return [];
95
+ return clusterServers.filter((candidate) => candidate !== current);
96
+ }
97
+
98
+ function shouldRetryBoundMachineUnavailable(response: Response, data: any) {
99
+ return response.status === 409 && data?.reason === "bound_machine_unavailable";
100
+ }
101
+
102
+ function resolveBoundMachineHintedRetryServer(
103
+ serverUrl: string,
104
+ data: any,
105
+ ) {
106
+ const current = normalizeServerOrigin(serverUrl);
107
+ const clusterServers = resolveNormalizedClusterServers();
108
+ const rawCandidates = [
109
+ typeof data?.retryServerBase === "string" ? data.retryServerBase : "",
110
+ typeof data?.serverBase === "string" ? data.serverBase : "",
111
+ ];
112
+ for (const rawCandidate of rawCandidates) {
113
+ const trimmed = rawCandidate.trim();
114
+ if (!trimmed) continue;
115
+ const normalized = normalizeServerOrigin(trimmed);
116
+ if (normalized === current) continue;
117
+ if (clusterServers.includes(normalized)) return normalized;
118
+ }
119
+ return null;
120
+ }
121
+
122
+ function resolveBoundMachineRetryTargets(
123
+ serverUrl: string,
124
+ data: any,
125
+ ) {
126
+ const hinted = resolveBoundMachineHintedRetryServer(serverUrl, data);
127
+ const siblings = resolveClusterRetryServers(serverUrl);
128
+ return [...new Set([
129
+ ...(hinted ? [hinted] : []),
130
+ ...siblings,
131
+ ])];
132
+ }
133
+
134
+ async function readJsonSafely(response: Response) {
135
+ try {
136
+ return await response.json();
137
+ } catch {
138
+ return {};
139
+ }
140
+ }
141
+
142
+ export async function readStreamingAgentRun(
143
+ options: ServerTransportOptionShape,
144
+ res: Response,
145
+ ): Promise<ServerTransportRunResult> {
146
+ const reader = res.body?.getReader();
147
+ if (!reader) {
148
+ options.output.write("[nolo] Agent stream response did not include a readable body.\n");
149
+ return { exitCode: 1 };
150
+ }
151
+
152
+ const decoder = new TextDecoder();
153
+ const writer = createStreamingTextWriter({
154
+ write: (chunk) => options.output.write(chunk),
155
+ });
156
+ let buffer = "";
157
+ let content = "";
158
+ let dialogId: string | undefined;
159
+ let usage: any;
160
+ let hasPrintedLabel = false;
161
+
162
+ const printLabel = () => {
163
+ if (hasPrintedLabel) return;
164
+ options.output.write(`\n${options.agentName} > `);
165
+ hasPrintedLabel = true;
166
+ };
167
+
168
+ const handlePayload = (payload: any) => {
169
+ if (typeof payload?.dialogId === "string" && payload.dialogId.trim()) {
170
+ dialogId = payload.dialogId;
171
+ }
172
+ if (payload?.error || payload?.type === "error") {
173
+ throw new Error(String(payload.error || payload.message || "Agent stream failed"));
174
+ }
175
+ if (payload?.type === "done") {
176
+ usage = payload.usage;
177
+ return;
178
+ }
179
+ if (payload?.type === "dialog" || payload?.type === "status") {
180
+ return;
181
+ }
182
+
183
+ const chunk =
184
+ payload?.type === "text"
185
+ ? payload.content
186
+ : typeof payload?.chunk === "string"
187
+ ? payload.chunk
188
+ : "";
189
+ if (!chunk) return;
190
+
191
+ printLabel();
192
+ content += chunk;
193
+ writer.push(chunk);
194
+ };
195
+
196
+ try {
197
+ while (true) {
198
+ const { done, value } = await reader.read();
199
+ if (done) break;
200
+
201
+ buffer += decoder.decode(value, { stream: true });
202
+ const events = buffer.split("\n\n");
203
+ buffer = events.pop() ?? "";
204
+
205
+ for (const event of events) {
206
+ const dataLines = event
207
+ .split("\n")
208
+ .filter((line) => line.startsWith("data:"))
209
+ .map((line) => line.slice(5).trim())
210
+ .filter(Boolean);
211
+ for (const raw of dataLines) {
212
+ handlePayload(JSON.parse(raw));
213
+ }
214
+ }
215
+ }
216
+ if (buffer.trim()) {
217
+ const raw = buffer
218
+ .split("\n")
219
+ .find((line) => line.startsWith("data:"))
220
+ ?.slice(5)
221
+ .trim();
222
+ if (raw) handlePayload(JSON.parse(raw));
223
+ }
224
+ } catch (error) {
225
+ const message = error instanceof Error ? error.message : String(error);
226
+ if (dialogId) {
227
+ options.output.write(
228
+ `\n[nolo] Agent stream transport interrupted after dialog ${dialogId} was created: ${message}\n`
229
+ );
230
+ options.output.write("[nolo] The agent run may still finish on the server; read the dialog before retrying.\n");
231
+ return { exitCode: 0, dialogId, streamInterrupted: true };
232
+ }
233
+ options.output.write(`\n[nolo] Agent stream failed: ${message}\n`);
234
+ return { exitCode: 1 };
235
+ } finally {
236
+ writer.flushAll();
237
+ }
238
+
239
+ if (!content) {
240
+ options.output.write(`\n${options.agentName} > (no text response)\n`);
241
+ } else {
242
+ options.output.write("\n");
243
+ }
244
+
245
+ const usageText = formatUsage(usage, dialogId);
246
+ if (usageText && shouldShowUsage(options.env)) options.output.write(`${usageText}\n`);
247
+ return {
248
+ exitCode: 0,
249
+ ...(dialogId ? { dialogId } : {}),
250
+ };
251
+ }
252
+
253
+ export async function runHttpAgentTurn(
254
+ options: ServerTransportOptionShape,
255
+ args: {
256
+ authToken: string;
257
+ }
258
+ ): Promise<ServerTransportRunResult> {
259
+ options.output.write(`\n${options.agentName} -> working...\n`);
260
+
261
+ const fetchImpl = options.fetchImpl ?? fetch;
262
+ const requestBody = {
263
+ agentKey: options.agentKey,
264
+ userInput: buildUserInputContent(
265
+ prependTaskRunPrompt(options.message, options.taskRunContext),
266
+ options.imageUrls
267
+ ),
268
+ runtimeContext: {
269
+ surface: "cli",
270
+ host: "terminal",
271
+ runtime: "bun",
272
+ entrypoint: "nolo-cli",
273
+ capabilities: ["text-io", "streaming", "slash-commands"],
274
+ ...(options.taskRunContext
275
+ ? {
276
+ taskRun: {
277
+ rowDbKey: options.taskRunContext.rowDbKey,
278
+ ...(options.taskRunContext.taskRunId
279
+ ? { taskRunId: options.taskRunContext.taskRunId }
280
+ : {}),
281
+ ...(options.taskRunContext.workItemId
282
+ ? { workItemId: options.taskRunContext.workItemId }
283
+ : {}),
284
+ ...(options.taskRunContext.artifactIds?.length
285
+ ? { artifactIds: options.taskRunContext.artifactIds }
286
+ : {}),
287
+ },
288
+ }
289
+ : {}),
290
+ },
291
+ ...(options.continueDialogId ? { continueDialogId: options.continueDialogId } : {}),
292
+ ...(options.spaceId ? { spaceId: options.spaceId } : {}),
293
+ ...(options.category ? { category: options.category } : {}),
294
+ ...(options.inheritedFromDialogKey
295
+ ? { inheritedFromDialogKey: options.inheritedFromDialogKey }
296
+ : {}),
297
+ ...(options.parentDialogId ? { parentDialogId: options.parentDialogId } : {}),
298
+ ...(options.background ? { background: true } : {}),
299
+ ...(typeof options.maxToolRounds === "number" ? { maxRounds: options.maxToolRounds } : {}),
300
+ ...(typeof options.timeoutMs === "number" ? { timeoutMs: options.timeoutMs } : {}),
301
+ stream: !options.noStream && !options.background,
302
+ };
303
+ let res: Response;
304
+ try {
305
+ const serverTargets = [options.serverUrl];
306
+ res = new Response(null, { status: 500 });
307
+ for (let index = 0; index < serverTargets.length; index += 1) {
308
+ const serverUrl = serverTargets[index]!;
309
+ res = await fetchImpl(`${serverUrl}/api/agent/run`, {
310
+ method: "POST",
311
+ headers: {
312
+ Authorization: `Bearer ${args.authToken}`,
313
+ "Content-Type": "application/json",
314
+ },
315
+ body: JSON.stringify(requestBody),
316
+ });
317
+ const contentType = res.headers.get("content-type") || "";
318
+ if (res.ok || contentType.includes("text/event-stream")) break;
319
+ const data = await readJsonSafely(res.clone());
320
+ if (!shouldRetryBoundMachineUnavailable(res, data)) break;
321
+ const retryTargets = resolveBoundMachineRetryTargets(serverUrl, data);
322
+ for (const retryTarget of retryTargets) {
323
+ if (serverTargets.includes(retryTarget)) continue;
324
+ serverTargets.push(retryTarget);
325
+ }
326
+ const retryTarget = serverTargets[index + 1];
327
+ if (!retryTarget) break;
328
+ options.output.write(
329
+ `[nolo] Bound runtime unavailable on ${normalizeServerOrigin(serverUrl)}; retrying ${normalizeServerOrigin(retryTarget)}.\n`
330
+ );
331
+ }
332
+ } catch (error) {
333
+ options.output.write(buildTransportErrorHint(options.serverUrl, error));
334
+ return { exitCode: 1 };
335
+ }
336
+
337
+ const contentType = res.headers.get("content-type") || "";
338
+ if (contentType.includes("text/event-stream") && res.body) {
339
+ const result = await readStreamingAgentRun(options, res);
340
+ await recordTaskRunOutcome({
341
+ options,
342
+ status: result.streamInterrupted
343
+ ? "running"
344
+ : result.exitCode === 0
345
+ ? "completed"
346
+ : "failed",
347
+ dialogId: result.dialogId,
348
+ ...(result.exitCode !== 0 ? { errorCode: "STREAM_FAILED" } : {}),
349
+ });
350
+ return result;
351
+ }
352
+
353
+ let data: any = {};
354
+ try {
355
+ data = await res.json();
356
+ } catch {
357
+ data = {};
358
+ }
359
+
360
+ if (!res.ok) {
361
+ options.output.write(`[nolo] Agent request failed: HTTP ${res.status}\n`);
362
+ if (data?.error || data?.message) {
363
+ options.output.write(`${data.error || data.message}\n`);
364
+ }
365
+ await recordTaskRunOutcome({
366
+ options,
367
+ status: "failed",
368
+ errorCode: `HTTP_${res.status}`,
369
+ resultSummary: String(data?.error || data?.message || "").trim() || undefined,
370
+ });
371
+ return { exitCode: 1 };
372
+ }
373
+
374
+ const content = String(data?.content ?? data?.message ?? "").trim();
375
+ if (content) {
376
+ options.output.write(`\n${options.agentName} > ${content}\n`);
377
+ } else {
378
+ options.output.write(`\n${options.agentName} > (no text response)\n`);
379
+ }
380
+
381
+ const usage = formatUsage(data?.usage, data?.dialogId);
382
+ if (usage && shouldShowUsage(options.env)) options.output.write(`${usage}\n`);
383
+ const result = {
384
+ exitCode: 0,
385
+ ...(typeof data?.dialogId === "string" && data.dialogId ? { dialogId: data.dialogId } : {}),
386
+ };
387
+ await recordTaskRunOutcome({
388
+ options,
389
+ status: options.background ? "running" : "completed",
390
+ dialogId: result.dialogId,
391
+ ...(!options.background && content ? { resultSummary: content } : {}),
392
+ });
393
+ return result;
394
+ }