nolo-cli 0.1.32 → 0.1.33

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 (230) hide show
  1. package/README.md +0 -6
  2. package/agent-runtime/agentRecordConfig.ts +2 -0
  3. package/agent-runtime/hostAdapter.ts +1 -0
  4. package/agent-runtime/index.ts +0 -21
  5. package/agent-runtime/localToolPolicy.ts +6 -13
  6. package/agent-runtime/localWorkspaceTools.ts +30 -333
  7. package/agent-runtime/platformChatProvider.ts +1 -4
  8. package/agent-runtime/runtimeToolPolicy.ts +47 -32
  9. package/agentAliases.ts +14 -83
  10. package/agentCommandSupport.ts +3 -6
  11. package/agentInternalCommandEntries.ts +2 -13
  12. package/agentListCommands.ts +19 -28
  13. package/agentMachineCommands.ts +40 -336
  14. package/agentPullCommand.ts +36 -56
  15. package/agentRecordCommands.ts +3 -5
  16. package/agentRecordHelpers.ts +22 -189
  17. package/agentRunCommand.ts +438 -107
  18. package/agentRuntimeLocal.ts +0 -10
  19. package/ai/agent/cliExecutor.ts +19 -323
  20. package/authCommands.ts +2 -36
  21. package/cli/agentAliases.ts +14 -83
  22. package/cli/agentCommandSupport.ts +3 -6
  23. package/cli/agentInternalCommandEntries.ts +2 -13
  24. package/cli/agentListCommands.ts +19 -28
  25. package/cli/agentMachineCommands.ts +40 -336
  26. package/cli/agentPullCommand.ts +36 -56
  27. package/cli/agentRecordCommands.ts +3 -5
  28. package/cli/agentRecordHelpers.ts +22 -189
  29. package/cli/agentRunCommand.ts +438 -107
  30. package/cli/agentRuntimeLocal.ts +0 -10
  31. package/cli/authCommands.ts +2 -36
  32. package/cli/cliEnvHelpers.ts +21 -162
  33. package/cli/client/agentRun.ts +853 -57
  34. package/cli/client/localRuntimeAdapter.ts +22 -159
  35. package/cli/client/streamingOutput.ts +3 -1
  36. package/cli/client/taskRunPrompt.ts +24 -7
  37. package/cli/commandRegistry.ts +2 -3
  38. package/cli/connectorRunArtifact.ts +10 -34
  39. package/cli/connectorWebSocketTarget.ts +6 -10
  40. package/cli/internalCommandEntries.ts +0 -8
  41. package/cli/localRuntimeDb.ts +2 -39
  42. package/cli/machineCommands.ts +189 -190
  43. package/cli/machineDaemonCommands.ts +165 -9
  44. package/cli/machineHeartbeatCommands.ts +2 -1
  45. package/cli/machineStatusCommands.ts +13 -5
  46. package/cli/machineWatchCommands.ts +1 -1
  47. package/cli/machineWsRunDispatch.ts +14 -48
  48. package/cli/machineWsSession.ts +0 -2
  49. package/cli/offlineMarxistsAgentCommand.ts +314 -0
  50. package/cli/runtimeDoctorCommands.ts +69 -18
  51. package/cli/scriptCommandEntries.ts +45 -5
  52. package/cli/tableCommands.ts +133 -33
  53. package/cli/taskRunCommand.ts +211 -16
  54. package/cli/tui/session.ts +372 -43
  55. package/cli/workflowInternalCommandEntries.ts +0 -20
  56. package/cliEnvHelpers.ts +21 -162
  57. package/client/agentConfigResolver.test.ts +2 -0
  58. package/client/agentRun.test.ts +12 -208
  59. package/client/agentRun.ts +853 -57
  60. package/client/localRuntimeAdapter.test.ts +9 -168
  61. package/client/localRuntimeAdapter.ts +22 -159
  62. package/client/localToolPolicy.test.ts +4 -28
  63. package/client/streamingOutput.ts +3 -1
  64. package/client/taskRunPrompt.ts +24 -7
  65. package/commandRegistry.ts +2 -3
  66. package/connectorRunArtifact.ts +10 -34
  67. package/connectorWebSocketTarget.ts +6 -10
  68. package/database/server/db.ts +34 -15
  69. package/internalCommandEntries.ts +0 -8
  70. package/localRuntimeDb.ts +2 -39
  71. package/machineCommands.ts +189 -190
  72. package/machineDaemonCommands.ts +165 -9
  73. package/machineHeartbeatCommands.ts +2 -1
  74. package/machineStatusCommands.ts +13 -5
  75. package/machineWatchCommands.ts +1 -1
  76. package/machineWsRunDispatch.ts +14 -48
  77. package/machineWsSession.ts +0 -2
  78. package/offlineMarxistsAgentCommand.ts +314 -0
  79. package/package.json +49 -193
  80. package/runtimeDoctorCommands.ts +69 -18
  81. package/scriptCommandEntries.ts +45 -5
  82. package/tableCommands.ts +133 -33
  83. package/taskRunCommand.ts +211 -16
  84. package/tui/session.ts +372 -43
  85. package/workflowInternalCommandEntries.ts +0 -20
  86. package/agent-runtime/dialogStatus.ts +0 -139
  87. package/agent-runtime/hostRuntimeConfig.ts +0 -86
  88. package/agentCreateCustomCommands.ts +0 -278
  89. package/agentDialogsCommands.ts +0 -227
  90. package/agentDoctorCommands.ts +0 -203
  91. package/agentRunLocalWorkspace.ts +0 -182
  92. package/agentRunParsing.ts +0 -298
  93. package/agentSuperviseCommands.ts +0 -8
  94. package/agentUnpublishCommands.ts +0 -113
  95. package/ai/agent/agentRunDialogLineage.ts +0 -56
  96. package/ai/policy/types.ts +0 -64
  97. package/ai/skills/skillSummaryMarker.ts +0 -26
  98. package/app/types.ts +0 -358
  99. package/build.ts +0 -16
  100. package/buildPublish.ts +0 -138
  101. package/buildPublishArtifactAssembly.ts +0 -724
  102. package/buildPublishImportAnalysis.ts +0 -242
  103. package/chat/messages/fetchMessages.ts +0 -84
  104. package/chat/messages/types.ts +0 -185
  105. package/cli/agentCreateCustomCommands.ts +0 -278
  106. package/cli/agentDialogsCommands.ts +0 -227
  107. package/cli/agentDoctorCommands.ts +0 -203
  108. package/cli/agentRunLocalWorkspace.ts +0 -182
  109. package/cli/agentRunParsing.ts +0 -298
  110. package/cli/agentSuperviseCommands.ts +0 -8
  111. package/cli/agentUnpublishCommands.ts +0 -113
  112. package/cli/buildPublish.ts +0 -138
  113. package/cli/buildPublishArtifactAssembly.ts +0 -724
  114. package/cli/buildPublishImportAnalysis.ts +0 -242
  115. package/cli/cliIoTypes.ts +0 -3
  116. package/cli/cliRuntimeDoctorReport.ts +0 -193
  117. package/cli/client/agentRunInput.ts +0 -10
  118. package/cli/client/agentRunLocalExecution.ts +0 -124
  119. package/cli/client/agentRunLocalExecutor.ts +0 -179
  120. package/cli/client/agentRunRuntimeSelection.ts +0 -145
  121. package/cli/client/agentRunServerTransport.ts +0 -397
  122. package/cli/client/agentRunTaskRunRecorder.ts +0 -176
  123. package/cli/customCodingAgentFlow.ts +0 -208
  124. package/cli/customCodingAgentRecord.ts +0 -179
  125. package/cli/dialogDataAccess.ts +0 -186
  126. package/cli/dialogInternalCommandEntries.ts +0 -11
  127. package/cli/dialogReadCommands.ts +0 -180
  128. package/cli/dialogReadHelpers.ts +0 -226
  129. package/cli/dialogStatusCommands.ts +0 -123
  130. package/cli/docInternalCommandEntries.ts +0 -20
  131. package/cli/hybridReadHelpers.ts +0 -109
  132. package/cli/machineCommandPrompts.ts +0 -79
  133. package/cli/machineCommandResolution.ts +0 -43
  134. package/cli/noloReadBridgePrompt.ts +0 -16
  135. package/cli/pageCreateCommands.ts +0 -219
  136. package/cli/pageDeleteCommands.ts +0 -167
  137. package/cli/pageReadCommands.ts +0 -151
  138. package/cli/pageUpdateCommands.ts +0 -249
  139. package/cli/pageWriteHelpers.ts +0 -209
  140. package/cli/publishPackage.ts +0 -36
  141. package/cli/runtimeInternalCommandEntries.ts +0 -15
  142. package/cli/runtimePassthroughCommands.ts +0 -22
  143. package/cli/scriptPassthroughHelpers.ts +0 -28
  144. package/cli/secretScanHelpers.ts +0 -31
  145. package/cli/spaceAttachCommands.ts +0 -134
  146. package/cli/spaceCategoryCommands.ts +0 -263
  147. package/cli/spaceCommands.ts +0 -295
  148. package/cli/spaceDeleteCommands.ts +0 -312
  149. package/cli/spaceInternalCommandEntries.ts +0 -21
  150. package/cli/spaceMutationHelpers.ts +0 -135
  151. package/cli/spaceReadCommands.ts +0 -323
  152. package/cli/tableDataOutput.ts +0 -41
  153. package/cli/tableDataSafety.ts +0 -26
  154. package/cli/tableMetaCommands.ts +0 -307
  155. package/cli/tableMutationCommands.ts +0 -266
  156. package/cli/tableQueryParsing.ts +0 -90
  157. package/cli/tableQueryRequest.ts +0 -53
  158. package/cli/taskRunActions.ts +0 -122
  159. package/cli/taskRunParsing.ts +0 -86
  160. package/cli/taskRunPromptShared.ts +0 -55
  161. package/cli/tui/tuiCatalog.ts +0 -22
  162. package/cli/tui/tuiCommandInterpreter.ts +0 -253
  163. package/cli/tui/tuiPresentation.ts +0 -146
  164. package/cliIoTypes.ts +0 -3
  165. package/cliRuntimeDoctorReport.ts +0 -193
  166. package/client/agentRunInput.ts +0 -10
  167. package/client/agentRunLocalExecution.test.ts +0 -123
  168. package/client/agentRunLocalExecution.ts +0 -124
  169. package/client/agentRunLocalExecutor.ts +0 -179
  170. package/client/agentRunRuntimeSelection.test.ts +0 -159
  171. package/client/agentRunRuntimeSelection.ts +0 -145
  172. package/client/agentRunServerTransport.ts +0 -397
  173. package/client/agentRunTaskRunRecorder.ts +0 -176
  174. package/connector-experimental/daemonLauncher.ts +0 -223
  175. package/create/space/spaceKeys.ts +0 -65
  176. package/create/types.ts +0 -21
  177. package/customCodingAgentFlow.ts +0 -208
  178. package/customCodingAgentRecord.ts +0 -179
  179. package/database/keys.ts +0 -765
  180. package/database/server/authorityStoreTypes.ts +0 -31
  181. package/database/server/legacyServerDb.ts +0 -58
  182. package/database/server/levelAuthorityStore.ts +0 -75
  183. package/database/server/memoryAuthorityStore.ts +0 -133
  184. package/database/server/serverStoreFactory.ts +0 -124
  185. package/database/tombstones.ts +0 -52
  186. package/database/utils/ulid.ts +0 -1
  187. package/dialogDataAccess.ts +0 -186
  188. package/dialogInternalCommandEntries.ts +0 -11
  189. package/dialogReadCommands.ts +0 -180
  190. package/dialogReadHelpers.ts +0 -226
  191. package/dialogStatusCommands.ts +0 -123
  192. package/docInternalCommandEntries.ts +0 -20
  193. package/hybridReadHelpers.ts +0 -109
  194. package/machineCommandPrompts.ts +0 -79
  195. package/machineCommandResolution.ts +0 -43
  196. package/noloReadBridgePrompt.ts +0 -16
  197. package/pageCreateCommands.ts +0 -219
  198. package/pageDeleteCommands.ts +0 -167
  199. package/pageReadCommands.ts +0 -151
  200. package/pageUpdateCommands.ts +0 -249
  201. package/pageWriteHelpers.ts +0 -209
  202. package/publishPackage.ts +0 -36
  203. package/runtimeInternalCommandEntries.ts +0 -15
  204. package/runtimePassthroughCommands.ts +0 -22
  205. package/scriptPassthroughHelpers.ts +0 -28
  206. package/secretScanHelpers.ts +0 -31
  207. package/share/helpers.ts +0 -302
  208. package/share/keys.ts +0 -243
  209. package/share/types.ts +0 -100
  210. package/spaceAttachCommands.ts +0 -134
  211. package/spaceCategoryCommands.ts +0 -263
  212. package/spaceCommands.ts +0 -295
  213. package/spaceDeleteCommands.ts +0 -312
  214. package/spaceInternalCommandEntries.ts +0 -21
  215. package/spaceMutationHelpers.ts +0 -135
  216. package/spaceReadCommands.ts +0 -323
  217. package/tableDataOutput.ts +0 -41
  218. package/tableDataSafety.ts +0 -26
  219. package/tableMetaCommands.ts +0 -307
  220. package/tableMutationCommands.ts +0 -266
  221. package/tableQueryParsing.ts +0 -90
  222. package/tableQueryRequest.ts +0 -53
  223. package/taskRunActions.ts +0 -122
  224. package/taskRunParsing.ts +0 -86
  225. package/taskRunPromptShared.ts +0 -55
  226. package/tui/tuiCatalog.ts +0 -22
  227. package/tui/tuiCommandInterpreter.test.ts +0 -169
  228. package/tui/tuiCommandInterpreter.ts +0 -253
  229. package/tui/tuiPresentation.test.ts +0 -154
  230. package/tui/tuiPresentation.ts +0 -146
@@ -1,145 +0,0 @@
1
- import type { AgentRuntimeRequestedMode } from "../agentRuntimeLocal";
2
- import {
3
- isKnownPlatformAgentKey,
4
- } from "../agentAliases";
5
- import type { EnvLike } from "../cliEnvHelpers";
6
- import type { OutputLike } from "../cliIoTypes";
7
- export type { OutputLike } from "../cliIoTypes";
8
-
9
- export type ScriptBridgeDecision = {
10
- hasAuthToken: boolean;
11
- scriptPathExists: boolean;
12
- };
13
-
14
- export type RuntimeSelectionAgentConfig = {
15
- toolNames?: string[];
16
- runtimeToolPolicy?: {
17
- agentTools?: string[];
18
- };
19
- };
20
-
21
- export type RuntimeSelectionAdapter = {
22
- loadAgentConfig(agentKey: string): Promise<RuntimeSelectionAgentConfig | undefined>;
23
- };
24
-
25
- export type RuntimeSelectionOptions = {
26
- agentKey: string;
27
- env: EnvLike;
28
- output: OutputLike;
29
- runtimeMode?: AgentRuntimeRequestedMode;
30
- localRuntimeAdapter?: RuntimeSelectionAdapter;
31
- localRuntimeAdapterFactory?: unknown;
32
- resolveLocalRuntimeAdapter?: () => RuntimeSelectionAdapter | undefined;
33
- };
34
-
35
- const SERVER_PLATFORM_TOOL_NAMES = new Set([
36
- "addTableRow",
37
- "addTableRows",
38
- "deleteTableRow",
39
- "deleteTableRows",
40
- "queryTableRows",
41
- "streamParallelAgents",
42
- "taskRun",
43
- "updateTableRow",
44
- "updateTableRows",
45
- ]);
46
-
47
- const KNOWN_SERVER_PLATFORM_AGENT_ALIASES = new Set([
48
- "code-review",
49
- "frontend",
50
- "frontend-agent",
51
- "frontend-implementer",
52
- "full-stack",
53
- "fullstack",
54
- "nolo code review",
55
- "nolo frontend",
56
- "nolo fullstack",
57
- "nolo reviewer",
58
- "nolo-code-review",
59
- "nolo-frontend",
60
- "nolo-fullstack",
61
- "nolo-reviewer",
62
- "review",
63
- "reviewer",
64
- ]);
65
-
66
- export function shouldUseScriptBridge(decision: ScriptBridgeDecision) {
67
- return !decision.hasAuthToken && decision.scriptPathExists;
68
- }
69
-
70
- export function findServerPlatformTools(toolNames?: string[]) {
71
- if (!Array.isArray(toolNames)) return [];
72
- return toolNames.filter((toolName) => SERVER_PLATFORM_TOOL_NAMES.has(toolName));
73
- }
74
-
75
- export function resolveServerPlatformToolNames(agentConfig: RuntimeSelectionAgentConfig | undefined) {
76
- return findServerPlatformTools([
77
- ...(Array.isArray(agentConfig?.toolNames) ? agentConfig.toolNames : []),
78
- ...(Array.isArray(agentConfig?.runtimeToolPolicy?.agentTools)
79
- ? agentConfig.runtimeToolPolicy.agentTools
80
- : []),
81
- ]);
82
- }
83
-
84
- export function normalizeAgentRef(ref?: string) {
85
- return ref?.trim().toLowerCase().replace(/\s+/g, " ");
86
- }
87
-
88
- export function isKnownServerPlatformAgent(options: Pick<RuntimeSelectionOptions, "agentKey">) {
89
- if (isKnownPlatformAgentKey(options.agentKey)) return true;
90
- const normalizedKey = normalizeAgentRef(options.agentKey);
91
- return Boolean(normalizedKey && KNOWN_SERVER_PLATFORM_AGENT_ALIASES.has(normalizedKey));
92
- }
93
-
94
- export function shouldShowUsage(env: EnvLike) {
95
- return env.NOLO_DEBUG === "1" || env.NOLO_SHOW_USAGE === "1";
96
- }
97
-
98
- export function resolveRequestedRuntimeMode(
99
- options: Pick<RuntimeSelectionOptions, "env" | "runtimeMode">
100
- ) {
101
- const envMode = options.env.NOLO_RUNTIME_MODE;
102
- if (options.runtimeMode) return options.runtimeMode;
103
- if (envMode === "local" || envMode === "server" || envMode === "auto") return envMode;
104
- return "auto";
105
- }
106
-
107
- export function shouldAttemptAutoLocal(
108
- options: Pick<RuntimeSelectionOptions, "env" | "localRuntimeAdapter" | "localRuntimeAdapterFactory">
109
- ) {
110
- if (options.localRuntimeAdapter || options.localRuntimeAdapterFactory) return true;
111
- return Boolean(
112
- options.env.NOLO_LOCAL_OPENAI_API_KEY ||
113
- options.env.OPENAI_API_KEY ||
114
- options.env.NOLO_LOCAL_OPENAI_BASE_URL ||
115
- options.env.OPENAI_BASE_URL ||
116
- options.env.NOLO_LOCAL_AGENT_KEY
117
- );
118
- }
119
-
120
- export async function shouldSkipAutoLocalForServerPlatformTools(
121
- options: RuntimeSelectionOptions
122
- ) {
123
- if (isKnownServerPlatformAgent(options)) {
124
- options.output.write(
125
- `[nolo] auto runtime: skipping local runtime because ${options.agentKey} is a known platform agent. ` +
126
- "Use --local explicitly to force local workspace tools.\n"
127
- );
128
- return true;
129
- }
130
- const adapter = options.localRuntimeAdapter || options.resolveLocalRuntimeAdapter?.();
131
- if (!adapter) return false;
132
- let agentConfig;
133
- try {
134
- agentConfig = await adapter.loadAgentConfig(options.agentKey);
135
- } catch {
136
- return false;
137
- }
138
- const serverTools = resolveServerPlatformToolNames(agentConfig);
139
- if (serverTools.length === 0) return false;
140
- options.output.write(
141
- `[nolo] auto runtime: skipping local runtime because ${options.agentKey} declares server platform tools ` +
142
- `(${serverTools.join(", ")}). Use --local explicitly to force local workspace tools.\n`
143
- );
144
- return true;
145
- }
@@ -1,397 +0,0 @@
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
- const errorText = typeof data?.error === "string" ? data.error.trim() : "";
363
- const messageText = typeof data?.message === "string" ? data.message.trim() : "";
364
- const reasonText = typeof data?.reason === "string" ? data.reason.trim() : "";
365
- if (errorText) options.output.write(`${errorText}\n`);
366
- if (messageText && messageText !== errorText) options.output.write(`${messageText}\n`);
367
- if (reasonText) options.output.write(`reason=${reasonText}\n`);
368
- await recordTaskRunOutcome({
369
- options,
370
- status: "failed",
371
- errorCode: `HTTP_${res.status}`,
372
- resultSummary: messageText || errorText || undefined,
373
- });
374
- return { exitCode: 1 };
375
- }
376
-
377
- const content = String(data?.content ?? data?.message ?? "").trim();
378
- if (content) {
379
- options.output.write(`\n${options.agentName} > ${content}\n`);
380
- } else {
381
- options.output.write(`\n${options.agentName} > (no text response)\n`);
382
- }
383
-
384
- const usage = formatUsage(data?.usage, data?.dialogId);
385
- if (usage && shouldShowUsage(options.env)) options.output.write(`${usage}\n`);
386
- const result = {
387
- exitCode: 0,
388
- ...(typeof data?.dialogId === "string" && data.dialogId ? { dialogId: data.dialogId } : {}),
389
- };
390
- await recordTaskRunOutcome({
391
- options,
392
- status: options.background ? "running" : "completed",
393
- dialogId: result.dialogId,
394
- ...(!options.background && content ? { resultSummary: content } : {}),
395
- });
396
- return result;
397
- }