nolo-cli 0.1.32 → 0.1.34

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 (234) hide show
  1. package/README.md +4 -10
  2. package/agent-runtime/agentRecordConfig.ts +10 -0
  3. package/agent-runtime/hostAdapter.ts +10 -1
  4. package/agent-runtime/index.ts +9 -20
  5. package/agent-runtime/localLoop.ts +49 -2
  6. package/agent-runtime/localToolPolicy.ts +76 -34
  7. package/agent-runtime/localWorkspaceTools.ts +30 -333
  8. package/agent-runtime/openAiCompatibleProvider.ts +7 -3
  9. package/agent-runtime/openAiCompatibleProviderConfig.ts +15 -26
  10. package/agent-runtime/platformChatProvider.ts +47 -73
  11. package/agent-runtime/providerResolution.ts +244 -0
  12. package/agent-runtime/runtimeToolPolicy.ts +77 -29
  13. package/agent-runtime/shellCommandPolicy.ts +120 -0
  14. package/agentAliases.ts +14 -83
  15. package/agentCommandSupport.ts +3 -6
  16. package/agentInternalCommandEntries.ts +4 -13
  17. package/agentListCommands.ts +18 -27
  18. package/agentMachineCommands.ts +40 -336
  19. package/agentPullCommand.ts +30 -55
  20. package/agentRecordCommands.ts +84 -1
  21. package/agentRecordHelpers.ts +102 -186
  22. package/agentRunCommand.ts +438 -107
  23. package/agentRuntimeLocal.ts +2 -9
  24. package/ai/agent/cliExecutor.ts +19 -323
  25. package/ai/tools/toolNameAliases.ts +70 -0
  26. package/authCommands.ts +2 -36
  27. package/cli/agentAliases.ts +14 -83
  28. package/cli/agentCommandSupport.ts +3 -6
  29. package/cli/agentInternalCommandEntries.ts +4 -13
  30. package/cli/agentListCommands.ts +18 -27
  31. package/cli/agentMachineCommands.ts +40 -336
  32. package/cli/agentPullCommand.ts +30 -55
  33. package/cli/agentRecordCommands.ts +84 -1
  34. package/cli/agentRecordHelpers.ts +102 -186
  35. package/cli/agentRunCommand.ts +438 -107
  36. package/cli/agentRuntimeLocal.ts +2 -9
  37. package/cli/authCommands.ts +2 -36
  38. package/cli/cliCommandDispatch.ts +2 -2
  39. package/cli/cliEnvHelpers.ts +34 -107
  40. package/cli/client/agentRun.ts +854 -57
  41. package/cli/client/localRuntimeAdapter.ts +59 -159
  42. package/cli/client/streamingOutput.ts +3 -1
  43. package/cli/client/taskRunPrompt.ts +24 -7
  44. package/cli/commandRegistry.ts +4 -5
  45. package/cli/connectorRunArtifact.ts +10 -34
  46. package/cli/connectorWebSocketTarget.ts +6 -10
  47. package/cli/internalCommandEntries.ts +0 -8
  48. package/cli/localRuntimeDb.ts +2 -39
  49. package/cli/machineCommands.ts +189 -190
  50. package/cli/machineDaemonCommands.ts +165 -9
  51. package/cli/machineHeartbeatCommands.ts +2 -1
  52. package/cli/machineStatusCommands.ts +13 -5
  53. package/cli/machineWatchCommands.ts +1 -1
  54. package/cli/machineWsRunDispatch.ts +30 -44
  55. package/cli/machineWsSession.ts +0 -2
  56. package/cli/offlineMarxistsAgentCommand.ts +314 -0
  57. package/cli/runtimeDoctorCommands.ts +72 -15
  58. package/cli/scriptCommandEntries.ts +45 -5
  59. package/cli/tableCommands.ts +133 -33
  60. package/cli/taskRunCommand.ts +211 -16
  61. package/cli/tui/session.ts +372 -43
  62. package/cli/workflowInternalCommandEntries.ts +0 -20
  63. package/cliCommandDispatch.ts +2 -2
  64. package/cliEnvHelpers.ts +34 -107
  65. package/client/agentConfigResolver.test.ts +2 -0
  66. package/client/agentRun.test.ts +12 -208
  67. package/client/agentRun.ts +854 -57
  68. package/client/localProviderResolver.test.ts +26 -2
  69. package/client/localRuntimeAdapter.test.ts +296 -171
  70. package/client/localRuntimeAdapter.ts +59 -159
  71. package/client/localToolPolicy.test.ts +4 -28
  72. package/client/streamingOutput.ts +3 -1
  73. package/client/taskRunPrompt.ts +24 -7
  74. package/commandRegistry.ts +4 -5
  75. package/connectorRunArtifact.ts +10 -34
  76. package/connectorWebSocketTarget.ts +6 -10
  77. package/database/server/serverStoreFactory.ts +2 -8
  78. package/internalCommandEntries.ts +0 -8
  79. package/localRuntimeDb.ts +2 -39
  80. package/machineCommands.ts +189 -190
  81. package/machineDaemonCommands.ts +165 -9
  82. package/machineHeartbeatCommands.ts +2 -1
  83. package/machineStatusCommands.ts +13 -5
  84. package/machineWatchCommands.ts +1 -1
  85. package/machineWsRunDispatch.ts +30 -44
  86. package/machineWsSession.ts +0 -2
  87. package/offlineMarxistsAgentCommand.ts +314 -0
  88. package/package.json +52 -188
  89. package/runtimeDoctorCommands.ts +72 -15
  90. package/scriptCommandEntries.ts +45 -5
  91. package/tableCommands.ts +133 -33
  92. package/taskRunCommand.ts +211 -16
  93. package/tui/session.ts +372 -43
  94. package/workflowInternalCommandEntries.ts +0 -20
  95. package/agent-runtime/dialogStatus.ts +0 -139
  96. package/agent-runtime/hostRuntimeConfig.ts +0 -86
  97. package/agentCreateCustomCommands.ts +0 -278
  98. package/agentDialogsCommands.ts +0 -227
  99. package/agentDoctorCommands.ts +0 -203
  100. package/agentRunLocalWorkspace.ts +0 -182
  101. package/agentRunParsing.ts +0 -298
  102. package/agentSuperviseCommands.ts +0 -8
  103. package/agentUnpublishCommands.ts +0 -113
  104. package/ai/agent/agentRunDialogLineage.ts +0 -56
  105. package/ai/policy/types.ts +0 -64
  106. package/ai/skills/skillSummaryMarker.ts +0 -26
  107. package/app/types.ts +0 -358
  108. package/build.ts +0 -16
  109. package/buildPublish.ts +0 -138
  110. package/buildPublishArtifactAssembly.ts +0 -724
  111. package/buildPublishImportAnalysis.ts +0 -242
  112. package/chat/messages/fetchMessages.ts +0 -84
  113. package/chat/messages/types.ts +0 -185
  114. package/cli/agentCreateCustomCommands.ts +0 -278
  115. package/cli/agentDialogsCommands.ts +0 -227
  116. package/cli/agentDoctorCommands.ts +0 -203
  117. package/cli/agentRunLocalWorkspace.ts +0 -182
  118. package/cli/agentRunParsing.ts +0 -298
  119. package/cli/agentSuperviseCommands.ts +0 -8
  120. package/cli/agentUnpublishCommands.ts +0 -113
  121. package/cli/buildPublish.ts +0 -138
  122. package/cli/buildPublishArtifactAssembly.ts +0 -724
  123. package/cli/buildPublishImportAnalysis.ts +0 -242
  124. package/cli/cliIoTypes.ts +0 -3
  125. package/cli/cliRuntimeDoctorReport.ts +0 -193
  126. package/cli/client/agentRunInput.ts +0 -10
  127. package/cli/client/agentRunLocalExecution.ts +0 -124
  128. package/cli/client/agentRunLocalExecutor.ts +0 -179
  129. package/cli/client/agentRunRuntimeSelection.ts +0 -145
  130. package/cli/client/agentRunServerTransport.ts +0 -397
  131. package/cli/client/agentRunTaskRunRecorder.ts +0 -176
  132. package/cli/customCodingAgentFlow.ts +0 -208
  133. package/cli/customCodingAgentRecord.ts +0 -179
  134. package/cli/dialogDataAccess.ts +0 -186
  135. package/cli/dialogInternalCommandEntries.ts +0 -11
  136. package/cli/dialogReadCommands.ts +0 -180
  137. package/cli/dialogReadHelpers.ts +0 -226
  138. package/cli/dialogStatusCommands.ts +0 -123
  139. package/cli/docInternalCommandEntries.ts +0 -20
  140. package/cli/hybridReadHelpers.ts +0 -109
  141. package/cli/machineCommandPrompts.ts +0 -79
  142. package/cli/machineCommandResolution.ts +0 -43
  143. package/cli/noloReadBridgePrompt.ts +0 -16
  144. package/cli/pageCreateCommands.ts +0 -219
  145. package/cli/pageDeleteCommands.ts +0 -167
  146. package/cli/pageReadCommands.ts +0 -151
  147. package/cli/pageUpdateCommands.ts +0 -249
  148. package/cli/pageWriteHelpers.ts +0 -209
  149. package/cli/publishPackage.ts +0 -36
  150. package/cli/runtimeInternalCommandEntries.ts +0 -15
  151. package/cli/runtimePassthroughCommands.ts +0 -22
  152. package/cli/scriptPassthroughHelpers.ts +0 -28
  153. package/cli/secretScanHelpers.ts +0 -31
  154. package/cli/spaceAttachCommands.ts +0 -134
  155. package/cli/spaceCategoryCommands.ts +0 -263
  156. package/cli/spaceCommands.ts +0 -295
  157. package/cli/spaceDeleteCommands.ts +0 -312
  158. package/cli/spaceInternalCommandEntries.ts +0 -21
  159. package/cli/spaceMutationHelpers.ts +0 -135
  160. package/cli/spaceReadCommands.ts +0 -323
  161. package/cli/tableDataOutput.ts +0 -41
  162. package/cli/tableDataSafety.ts +0 -26
  163. package/cli/tableMetaCommands.ts +0 -307
  164. package/cli/tableMutationCommands.ts +0 -266
  165. package/cli/tableQueryParsing.ts +0 -90
  166. package/cli/tableQueryRequest.ts +0 -53
  167. package/cli/taskRunActions.ts +0 -122
  168. package/cli/taskRunParsing.ts +0 -86
  169. package/cli/taskRunPromptShared.ts +0 -55
  170. package/cli/tui/tuiCatalog.ts +0 -22
  171. package/cli/tui/tuiCommandInterpreter.ts +0 -253
  172. package/cli/tui/tuiPresentation.ts +0 -146
  173. package/cliIoTypes.ts +0 -3
  174. package/cliRuntimeDoctorReport.ts +0 -193
  175. package/client/agentRunInput.ts +0 -10
  176. package/client/agentRunLocalExecution.test.ts +0 -123
  177. package/client/agentRunLocalExecution.ts +0 -124
  178. package/client/agentRunLocalExecutor.ts +0 -179
  179. package/client/agentRunRuntimeSelection.test.ts +0 -159
  180. package/client/agentRunRuntimeSelection.ts +0 -145
  181. package/client/agentRunServerTransport.ts +0 -397
  182. package/client/agentRunTaskRunRecorder.ts +0 -176
  183. package/connector-experimental/daemonLauncher.ts +0 -223
  184. package/create/space/spaceKeys.ts +0 -65
  185. package/create/types.ts +0 -21
  186. package/customCodingAgentFlow.ts +0 -208
  187. package/customCodingAgentRecord.ts +0 -179
  188. package/database/keys.ts +0 -765
  189. package/database/tombstones.ts +0 -52
  190. package/database/utils/ulid.ts +0 -1
  191. package/dialogDataAccess.ts +0 -186
  192. package/dialogInternalCommandEntries.ts +0 -11
  193. package/dialogReadCommands.ts +0 -180
  194. package/dialogReadHelpers.ts +0 -226
  195. package/dialogStatusCommands.ts +0 -123
  196. package/docInternalCommandEntries.ts +0 -20
  197. package/hybridReadHelpers.ts +0 -109
  198. package/machineCommandPrompts.ts +0 -79
  199. package/machineCommandResolution.ts +0 -43
  200. package/noloReadBridgePrompt.ts +0 -16
  201. package/pageCreateCommands.ts +0 -219
  202. package/pageDeleteCommands.ts +0 -167
  203. package/pageReadCommands.ts +0 -151
  204. package/pageUpdateCommands.ts +0 -249
  205. package/pageWriteHelpers.ts +0 -209
  206. package/publishPackage.ts +0 -36
  207. package/runtimeInternalCommandEntries.ts +0 -15
  208. package/runtimePassthroughCommands.ts +0 -22
  209. package/scriptPassthroughHelpers.ts +0 -28
  210. package/secretScanHelpers.ts +0 -31
  211. package/share/helpers.ts +0 -302
  212. package/share/keys.ts +0 -243
  213. package/share/types.ts +0 -100
  214. package/spaceAttachCommands.ts +0 -134
  215. package/spaceCategoryCommands.ts +0 -263
  216. package/spaceCommands.ts +0 -295
  217. package/spaceDeleteCommands.ts +0 -312
  218. package/spaceInternalCommandEntries.ts +0 -21
  219. package/spaceMutationHelpers.ts +0 -135
  220. package/spaceReadCommands.ts +0 -323
  221. package/tableDataOutput.ts +0 -41
  222. package/tableDataSafety.ts +0 -26
  223. package/tableMetaCommands.ts +0 -307
  224. package/tableMutationCommands.ts +0 -266
  225. package/tableQueryParsing.ts +0 -90
  226. package/tableQueryRequest.ts +0 -53
  227. package/taskRunActions.ts +0 -122
  228. package/taskRunParsing.ts +0 -86
  229. package/taskRunPromptShared.ts +0 -55
  230. package/tui/tuiCatalog.ts +0 -22
  231. package/tui/tuiCommandInterpreter.test.ts +0 -169
  232. package/tui/tuiCommandInterpreter.ts +0 -253
  233. package/tui/tuiPresentation.test.ts +0 -154
  234. package/tui/tuiPresentation.ts +0 -146
@@ -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
- }
@@ -1,176 +0,0 @@
1
- import { join } from "node:path";
2
-
3
- import type { EnvLike } from "../cliEnvHelpers";
4
- import type { OutputLike } from "../cliIoTypes";
5
- import {
6
- classifyTaskRunReviewStatus,
7
- type TaskRunToolEvidence,
8
- } from "./agentRunLocalExecution";
9
- import type { TaskRunPromptContext } from "./taskRunPrompt";
10
-
11
- type TaskRunAgentRole = "pm" | "frontend" | "fullstack" | "reviewer" | "codex";
12
- type TaskRunStatus = "running" | "completed" | "failed";
13
-
14
- type TaskRunRecorderOptionShape = {
15
- agentName: string;
16
- agentKey: string;
17
- serverUrl: string;
18
- scriptDir: string;
19
- env: EnvLike;
20
- output: OutputLike;
21
- taskRunContext?: TaskRunPromptContext;
22
- taskRunRecorder?: unknown;
23
- };
24
-
25
- export type TaskRunRecorderArgs<
26
- TOptions extends TaskRunRecorderOptionShape = TaskRunRecorderOptionShape,
27
- > = {
28
- options: TOptions;
29
- status: TaskRunStatus;
30
- dialogId?: string;
31
- resultSummary?: string;
32
- errorCode?: string;
33
- toolEvidence?: TaskRunToolEvidence;
34
- };
35
-
36
- export type TaskRunRecorder<
37
- TOptions extends TaskRunRecorderOptionShape = TaskRunRecorderOptionShape,
38
- > = (args: TaskRunRecorderArgs<TOptions>) => Promise<void>;
39
-
40
- export function inferTaskRunAgentRole(agentRef: string): TaskRunAgentRole {
41
- const normalized = agentRef.toLowerCase();
42
- if (normalized.includes("project-manager") || normalized.includes("manager")) return "pm";
43
- if (normalized.includes("frontend")) return "frontend";
44
- if (normalized.includes("fullstack")) return "fullstack";
45
- if (normalized.includes("review")) return "reviewer";
46
- return "codex";
47
- }
48
-
49
- export async function runTaskRunCli<TOptions extends TaskRunRecorderOptionShape>(args: {
50
- options: TOptions;
51
- cliArgs: string[];
52
- }) {
53
- const scriptPath = join(args.options.scriptDir, "taskRun.ts");
54
- const proc = Bun.spawn({
55
- cmd: [process.execPath, scriptPath, ...args.cliArgs],
56
- stdout: "pipe",
57
- stderr: "pipe",
58
- env: {
59
- ...process.env,
60
- ...args.options.env,
61
- BASE_URL: args.options.serverUrl,
62
- },
63
- });
64
- const [stdout, stderr, exitCode] = await Promise.all([
65
- new Response(proc.stdout).text(),
66
- new Response(proc.stderr).text(),
67
- proc.exited,
68
- ]);
69
- if (exitCode !== 0) {
70
- throw new Error((stderr || stdout || `taskRun.ts exited ${exitCode}`).trim());
71
- }
72
- }
73
-
74
- export async function defaultTaskRunRecorder<TOptions extends TaskRunRecorderOptionShape>(
75
- args: TaskRunRecorderArgs<TOptions>
76
- ) {
77
- const context = args.options.taskRunContext;
78
- if (!context?.rowDbKey) return;
79
- const role = inferTaskRunAgentRole(args.options.agentName || args.options.agentKey);
80
- if (role === "reviewer" && args.status !== "running") {
81
- await runTaskRunCli({
82
- options: args.options,
83
- cliArgs: [
84
- "request-review",
85
- "--row-dbkey",
86
- context.rowDbKey,
87
- "--base-url",
88
- args.options.serverUrl,
89
- "--reviewer-agent-key",
90
- args.options.agentKey,
91
- ...(context.artifactIds?.length ? ["--artifact-ids", context.artifactIds.join(",")] : []),
92
- ...(args.dialogId ? ["--dialog-id", args.dialogId] : []),
93
- ],
94
- });
95
- }
96
- await runTaskRunCli({
97
- options: args.options,
98
- cliArgs: [
99
- "record-agent-run",
100
- "--row-dbkey",
101
- context.rowDbKey,
102
- "--base-url",
103
- args.options.serverUrl,
104
- "--agent-key",
105
- args.options.agentKey,
106
- "--role",
107
- role,
108
- "--run-status",
109
- args.status,
110
- ...(context.workItemId ? ["--work-item-id", context.workItemId] : []),
111
- ...(args.dialogId ? ["--dialog-id", args.dialogId] : []),
112
- ...(args.resultSummary ? ["--result-summary", args.resultSummary.slice(0, 240)] : []),
113
- ...(args.errorCode ? ["--error-code", args.errorCode] : []),
114
- ...(args.toolEvidence?.toolsUsed?.length
115
- ? ["--tools-used", args.toolEvidence.toolsUsed.join(",")]
116
- : []),
117
- ...(args.toolEvidence?.summary
118
- ? ["--tool-trace-summary", JSON.stringify(args.toolEvidence.summary)]
119
- : []),
120
- ],
121
- });
122
- if (context.workItemId && args.dialogId) {
123
- await runTaskRunCli({
124
- options: args.options,
125
- cliArgs: [
126
- "update-work-item",
127
- "--row-dbkey",
128
- context.rowDbKey,
129
- "--base-url",
130
- args.options.serverUrl,
131
- "--id",
132
- context.workItemId,
133
- "--dialog-ids",
134
- args.dialogId,
135
- ],
136
- });
137
- }
138
- if (role === "reviewer" && args.status !== "running") {
139
- const reviewStatus =
140
- args.status === "failed" ? "blocked" : classifyTaskRunReviewStatus(args.resultSummary);
141
- if (reviewStatus) {
142
- await runTaskRunCli({
143
- options: args.options,
144
- cliArgs: [
145
- "review-result",
146
- "--row-dbkey",
147
- context.rowDbKey,
148
- "--base-url",
149
- args.options.serverUrl,
150
- "--review-status",
151
- reviewStatus,
152
- "--reviewer-agent-key",
153
- args.options.agentKey,
154
- ...(context.artifactIds?.length ? ["--artifact-ids", context.artifactIds.join(",")] : []),
155
- ...(args.dialogId ? ["--dialog-id", args.dialogId] : []),
156
- ],
157
- });
158
- }
159
- }
160
- }
161
-
162
- export async function recordTaskRunOutcome<TOptions extends TaskRunRecorderOptionShape>(
163
- args: TaskRunRecorderArgs<TOptions>
164
- ) {
165
- if (!args.options.taskRunContext?.rowDbKey) return;
166
- try {
167
- const recorder =
168
- (args.options.taskRunRecorder as TaskRunRecorder<TOptions> | undefined) ??
169
- ((nextArgs: TaskRunRecorderArgs<TOptions>) => defaultTaskRunRecorder(nextArgs));
170
- await recorder(args);
171
- } catch (error) {
172
- args.options.output.write(
173
- `[nolo] task-run writeback failed: ${error instanceof Error ? error.message : String(error)}\n`
174
- );
175
- }
176
- }