nolo-cli 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/_executeModel-UD44KGZ4.js +203 -0
  2. package/action-ZJWE3Y5S.js +28 -0
  3. package/addContentAction-TVDBNJM5.js +26 -0
  4. package/addDialogAgentAction-EKH774VT.js +68 -0
  5. package/agentDeleteCommand-TCPEFJTF.js +327 -0
  6. package/agentEmailCommands-CZ3UILZ4.js +626 -0
  7. package/agentListCommands-SJKO2FFB.js +223 -0
  8. package/agentMachineCommands-PSNABISZ.js +425 -0
  9. package/agentPullCommand-O2MTUAFR.js +122 -0
  10. package/agentRecordCommands-MH2JKFHS.js +94 -0
  11. package/agentRunCommand-4KH6MIZR.js +110 -0
  12. package/agentRunControl-K4VKNEHF.js +57 -0
  13. package/agentRuntimeLocal-SKHJUWSS.js +104 -0
  14. package/agentSlice-3WXXN4VK.js +42 -0
  15. package/authCommand-PXFX6JDT.js +581 -0
  16. package/authCommands-356AYWEK.js +35 -0
  17. package/chunk-2EISRLRC.js +238 -0
  18. package/chunk-2FTTDCD4.js +675 -0
  19. package/chunk-2K2ECKSG.js +222 -0
  20. package/chunk-2PUGVR6E.js +19 -0
  21. package/chunk-3ASDTTEI.js +1774 -0
  22. package/chunk-3EUW3WEO.js +8 -0
  23. package/chunk-3LY4F7SV.js +9293 -0
  24. package/chunk-3TZDXYSF.js +71 -0
  25. package/chunk-3WYQEUBI.js +34 -0
  26. package/chunk-4CQLVGRV.js +50 -0
  27. package/chunk-4IJYA27C.js +342 -0
  28. package/chunk-4K2KKCSD.js +577 -0
  29. package/chunk-4SN6J65J.js +38 -0
  30. package/chunk-4VNS5WPM.js +42 -0
  31. package/chunk-4ZDM73SD.js +34 -0
  32. package/chunk-5CS33IBL.js +301 -0
  33. package/chunk-5KLGBAAR.js +386 -0
  34. package/chunk-5MIDPSSK.js +206 -0
  35. package/chunk-5MMAK75Q.js +15 -0
  36. package/chunk-5PJ3VWCS.js +360 -0
  37. package/chunk-63SLEOLK.js +175 -0
  38. package/chunk-63W5N6P3.js +150 -0
  39. package/chunk-6GANEXVO.js +231 -0
  40. package/chunk-6HYVJV7B.js +102 -0
  41. package/chunk-6WD3OOJS.js +20 -0
  42. package/chunk-7OOXPE3N.js +628 -0
  43. package/chunk-7QRKCBOP.js +1078 -0
  44. package/chunk-ATNTHIZI.js +13 -0
  45. package/chunk-AUQ747NZ.js +902 -0
  46. package/chunk-AVMKZHBC.js +85 -0
  47. package/chunk-AZPCASRE.js +36 -0
  48. package/chunk-BBYVOSU2.js +792 -0
  49. package/chunk-C3RUNRHT.js +51 -0
  50. package/chunk-CF2WZF4N.js +134 -0
  51. package/chunk-CF7PE763.js +10 -0
  52. package/chunk-CKOJQDKR.js +198 -0
  53. package/chunk-COMXDWNM.js +807 -0
  54. package/chunk-CPB2YM4D.js +171 -0
  55. package/chunk-CWMSB67P.js +34 -0
  56. package/chunk-DCOA4QSN.js +105 -0
  57. package/chunk-DFFIZ25G.js +30 -0
  58. package/chunk-DWLEOOGR.js +8 -0
  59. package/chunk-DZ3XJVET.js +231 -0
  60. package/chunk-EHLHSX7R.js +1433 -0
  61. package/chunk-ELRRLDWI.js +478 -0
  62. package/chunk-EXTIQUCI.js +482 -0
  63. package/chunk-EYEEHCU4.js +3066 -0
  64. package/chunk-G3SUCT4W.js +8 -0
  65. package/chunk-G43KEVSC.js +1447 -0
  66. package/chunk-GAKEBQD6.js +30 -0
  67. package/chunk-GBRG75BQ.js +86 -0
  68. package/chunk-GG4AJPSR.js +191 -0
  69. package/chunk-H33743XH.js +25 -0
  70. package/chunk-HNMXYYJR.js +12 -0
  71. package/chunk-I42VC5KR.js +15 -0
  72. package/chunk-IDZTNRP2.js +85 -0
  73. package/chunk-ISNCLGUZ.js +146 -0
  74. package/chunk-IWX4UW2E.js +548 -0
  75. package/chunk-JBTJAPUF.js +35 -0
  76. package/chunk-JEXVIMYZ.js +55 -0
  77. package/chunk-JRKKFRAV.js +537 -0
  78. package/chunk-JZPBVBIY.js +94 -0
  79. package/chunk-KKY4B2Q2.js +21 -0
  80. package/chunk-KOCA5FCS.js +4750 -0
  81. package/chunk-KQHGZWSV.js +63 -0
  82. package/chunk-KTVVPRJS.js +138 -0
  83. package/chunk-KUG52IAP.js +8 -0
  84. package/chunk-KX6YBIHG.js +8 -0
  85. package/chunk-LARL2V6G.js +9017 -0
  86. package/chunk-LCBAMY2M.js +60 -0
  87. package/chunk-LM6IYQ3F.js +16 -0
  88. package/chunk-M76ECQRD.js +13658 -0
  89. package/chunk-MGOJ5R6J.js +113 -0
  90. package/chunk-MKMWT7SA.js +27196 -0
  91. package/chunk-MRC4Q34M.js +188 -0
  92. package/chunk-OLZBQWZU.js +6 -0
  93. package/chunk-OPZYGHUC.js +89 -0
  94. package/chunk-OWOHNGCN.js +50 -0
  95. package/chunk-PAKN26FP.js +239 -0
  96. package/chunk-PCWC3JTN.js +91 -0
  97. package/chunk-PG5PNA7Y.js +939 -0
  98. package/chunk-Q2YZULBH.js +104 -0
  99. package/chunk-QSJ3HFEF.js +8 -0
  100. package/chunk-QYXLLLGL.js +4519 -0
  101. package/chunk-ROWQEJRP.js +139 -0
  102. package/chunk-S7Z2HMCN.js +25 -0
  103. package/chunk-SBR32ZZS.js +1901 -0
  104. package/chunk-SH2CFQOH.js +3391 -0
  105. package/chunk-SL35K7AH.js +226 -0
  106. package/chunk-TILFE6LV.js +381 -0
  107. package/chunk-TSS3XJY4.js +2052 -0
  108. package/chunk-U4TRT5V4.js +246 -0
  109. package/chunk-U6VC4MU4.js +8 -0
  110. package/chunk-UAD2WT54.js +64 -0
  111. package/chunk-UUJDGGAK.js +421 -0
  112. package/chunk-VF4K2QE6.js +21 -0
  113. package/chunk-VHBWHNVT.js +59 -0
  114. package/chunk-VIDPVFP3.js +20 -0
  115. package/chunk-VP4WJWKW.js +8882 -0
  116. package/chunk-W4NVOSFF.js +37 -0
  117. package/chunk-WKM6FH35.js +190 -0
  118. package/chunk-WWC7I6TA.js +8 -0
  119. package/chunk-X7W4TNB4.js +1550 -0
  120. package/chunk-XE635NI4.js +1948 -0
  121. package/chunk-XKIMRZO2.js +221 -0
  122. package/chunk-XS466O7S.js +933 -0
  123. package/chunk-Y5GCAMGP.js +9 -0
  124. package/chunk-YBWOP46I.js +3272 -0
  125. package/chunk-YPRZSPF3.js +148 -0
  126. package/chunk-YYUCRDOK.js +69 -0
  127. package/chunk-Z4NR32XR.js +50 -0
  128. package/chunk-ZIG5LJ7X.js +24765 -0
  129. package/chunk-ZNFJWEN4.js +56 -0
  130. package/chunk-ZQ2UM4KG.js +2878 -0
  131. package/cliExecutor-DNE7TCC4.js +36 -0
  132. package/clipboardy-BVE3LVEH.js +12001 -0
  133. package/createAgentAutomationAction-63OIP6X5.js +866 -0
  134. package/createDialogAction-ZLYZDYBB.js +54 -0
  135. package/createPageAction-AL5FSDCK.js +171 -0
  136. package/db-HCJ5PRB5.js +271 -0
  137. package/dbSlice-PR44QPXY.js +60 -0
  138. package/deleteFile-4SKGPHOZ.js +41 -0
  139. package/dialogCommands-F6YI5742.js +63 -0
  140. package/dialogSlice-JSBNZRLR.js +148 -0
  141. package/docCreateCommands-4CTO7ERT.js +219 -0
  142. package/docDeleteCommands-VBWERDRG.js +180 -0
  143. package/docReadCommands-KNP4MFYB.js +133 -0
  144. package/docStore-ADP5VYY4.js +98 -0
  145. package/docUpdateCommands-4BCBJQHA.js +317 -0
  146. package/fetchMessages-U6ZHN56A.js +17 -0
  147. package/getPricing-3E6UNPKL.js +30 -0
  148. package/handleSendMessageAction-IJDQ6ARA.js +185 -0
  149. package/index.js +188 -112943
  150. package/lib-FYYBQIXS.js +19839 -0
  151. package/localDialogRead-Z5UTAJPU.js +26 -0
  152. package/localFirstLog-DHNOY2NA.js +19 -0
  153. package/localRuntimeAuthority-TEGCOWX4.js +471 -0
  154. package/localRuntimeDb-LGDF6FQP.js +12 -0
  155. package/machineCommands-EA3M4XTN.js +779 -0
  156. package/machineInfo-M6KB6HZN.js +10 -0
  157. package/machineWsRunDispatch-NAPKE5ZA.js +110 -0
  158. package/memoryCommands-O4MIPIWQ.js +476 -0
  159. package/models-4OPOOLFS.js +9 -0
  160. package/offlineMarxistsAgentCommand-BCPJITJL.js +242 -0
  161. package/package.json +3 -25
  162. package/read-RIJCIVKX.js +17 -0
  163. package/readDocTool-GZD2N3LO.js +16 -0
  164. package/readlineWorkspace-KMWT4T4S.js +5509 -0
  165. package/removeDialogAgentAction-GJQJNDW6.js +73 -0
  166. package/runAgentClientLoop-U5Q6NDTJ.js +291 -0
  167. package/runtimeDoctorCommands-LRHLPDRC.js +289 -0
  168. package/setDialogExtraReferencesAction-M7OQG54N.js +60 -0
  169. package/setPrimaryDialogAgentAction-46UNFJDL.js +80 -0
  170. package/settingSlice-FVUUH4JA.js +199 -0
  171. package/skillSummaryMarker-42HKSXYY.js +9 -0
  172. package/slateToRenderMarkdown-Y5IYN73U.js +7 -0
  173. package/slateUtils-2M7MUTWX.js +19 -0
  174. package/spaceCommands-E2CFRPZJ.js +454 -0
  175. package/spaceSlice-L3R6IMXE.js +147 -0
  176. package/streamAgentChatTurn-UBDAOQWE.js +4528 -0
  177. package/tableCommands-GOFP7QKA.js +1286 -0
  178. package/toolApiClient-QI3YBNWB.js +26 -0
  179. package/tools-TMJXZTCA.js +85 -0
  180. package/tuiSummaryLlmCaller-RV3THLZF.js +78 -0
  181. package/understanding-GQKNDDWM.js +271 -0
  182. package/updateCommands-VOSPKXFF.js +31 -0
  183. package/updateDialogTitleAction-ZTWRDXI2.js +188 -0
@@ -0,0 +1,1447 @@
1
+ import {
2
+ buildSpaceLookup,
3
+ getSpaceContentKeys
4
+ } from "./chunk-4CQLVGRV.js";
5
+ import {
6
+ deleteDbRecordOnServers,
7
+ listUserRecordsFromServers,
8
+ readDbRecordFromServers,
9
+ readLiveDbRecordAfterTombstoneMerge
10
+ } from "./chunk-WKM6FH35.js";
11
+ import {
12
+ buildDialogAttachmentPlan,
13
+ extractFileContentIds
14
+ } from "./chunk-PCWC3JTN.js";
15
+ import {
16
+ parseUserIdFromAuthToken,
17
+ readOption,
18
+ resolveAuthToken,
19
+ resolveDeleteServerCandidates,
20
+ resolveServerCandidates,
21
+ resolveServerUrl
22
+ } from "./chunk-ISNCLGUZ.js";
23
+ import {
24
+ toErrorMessage
25
+ } from "./chunk-HNMXYYJR.js";
26
+ import {
27
+ parsePositiveFiniteNumberOrFallback
28
+ } from "./chunk-Y5GCAMGP.js";
29
+ import {
30
+ asRecordOrEmpty
31
+ } from "./chunk-KX6YBIHG.js";
32
+ import {
33
+ asNonEmptyStringArray,
34
+ asTrimmedNonEmptyStringArray
35
+ } from "./chunk-I42VC5KR.js";
36
+ import {
37
+ asTrimmedString
38
+ } from "./chunk-3EUW3WEO.js";
39
+ import {
40
+ asOptionalTrimmedString
41
+ } from "./chunk-G3SUCT4W.js";
42
+ import {
43
+ isRecord
44
+ } from "./chunk-KUG52IAP.js";
45
+
46
+ // packages/cli/dialogAttachmentCleanup.ts
47
+ function asText(value) {
48
+ return asOptionalTrimmedString(value) ?? null;
49
+ }
50
+ async function readDialogMessages(args) {
51
+ const response = await args.fetchImpl(`${args.serverUrl}/rpc/getConvMsgs`, {
52
+ method: "POST",
53
+ headers: {
54
+ Authorization: `Bearer ${args.authToken}`,
55
+ "Content-Type": "application/json"
56
+ },
57
+ body: JSON.stringify({ dialogId: args.dialogId, limit: 1e4 })
58
+ });
59
+ if (!response.ok) {
60
+ throw new Error(`read dialog messages failed on ${args.serverUrl}: HTTP ${response.status}`);
61
+ }
62
+ const payload = await response.json();
63
+ return Array.isArray(payload) ? payload : [];
64
+ }
65
+ async function planDialogAttachmentCleanup(args) {
66
+ const messages = await readDialogMessages({
67
+ authToken: args.authToken,
68
+ dialogId: args.dialogId,
69
+ fetchImpl: args.fetchImpl,
70
+ serverUrl: args.serverUrl
71
+ });
72
+ const fileIds = [...new Set(messages.flatMap((message) => extractFileContentIds(message)))];
73
+ const metadataByFileId = {};
74
+ const metadataReadFailures = [];
75
+ for (const fileId of fileIds) {
76
+ try {
77
+ const result = await readDbRecordFromServers({
78
+ authToken: args.authToken,
79
+ dbKey: `file-id-${fileId}`,
80
+ fallbackFetchImpl: args.fallbackFetchImpl,
81
+ fetchImpl: args.fetchImpl,
82
+ serverUrls: args.serverUrls,
83
+ label: `file metadata index ${fileId}`
84
+ });
85
+ const mainKey = asText(result.record?.mainKey);
86
+ if (!mainKey) throw new Error(`file-id index missing mainKey`);
87
+ const metadata = await readDbRecordFromServers({
88
+ authToken: args.authToken,
89
+ dbKey: mainKey,
90
+ fallbackFetchImpl: args.fallbackFetchImpl,
91
+ fetchImpl: args.fetchImpl,
92
+ serverUrls: args.serverUrls,
93
+ label: `file metadata ${fileId}`
94
+ });
95
+ metadataByFileId[fileId] = {
96
+ ...metadata.record,
97
+ dbKey: asText(metadata.record?.dbKey) ?? mainKey
98
+ };
99
+ } catch (error) {
100
+ const fallbackKey = args.ownerId && !fileId.startsWith("file-") ? `file-${args.ownerId}-${fileId}` : null;
101
+ if (fallbackKey) {
102
+ try {
103
+ const metadata = await readDbRecordFromServers({
104
+ authToken: args.authToken,
105
+ dbKey: fallbackKey,
106
+ fallbackFetchImpl: args.fallbackFetchImpl,
107
+ fetchImpl: args.fetchImpl,
108
+ serverUrls: args.serverUrls,
109
+ label: `file metadata ${fileId}`
110
+ });
111
+ metadataByFileId[fileId] = {
112
+ ...metadata.record,
113
+ dbKey: asText(metadata.record?.dbKey) ?? fallbackKey
114
+ };
115
+ continue;
116
+ } catch {
117
+ }
118
+ }
119
+ metadataReadFailures.push({
120
+ fileId,
121
+ error: toErrorMessage(error)
122
+ });
123
+ }
124
+ }
125
+ return buildDialogAttachmentPlan({
126
+ dialogId: args.dialogId,
127
+ ownerId: args.ownerId,
128
+ includeUserOwnedReferenced: args.includeUserOwnedReferenced,
129
+ messages,
130
+ metadataByFileId,
131
+ metadataReadFailures
132
+ });
133
+ }
134
+ async function deleteDialogAttachmentCandidates(args) {
135
+ const results = [];
136
+ for (const candidate of args.candidates) {
137
+ if (candidate.status !== "delete" || !candidate.fileDbKey) continue;
138
+ const deleteResults = await deleteDbRecordOnServers({
139
+ authToken: args.authToken,
140
+ dbKey: candidate.fileDbKey,
141
+ fallbackFetchImpl: args.fallbackFetchImpl,
142
+ fetchImpl: args.fetchImpl,
143
+ serverUrls: args.serverUrls
144
+ });
145
+ results.push({
146
+ fileId: candidate.fileId,
147
+ fileDbKey: candidate.fileDbKey,
148
+ deleteResults
149
+ });
150
+ }
151
+ return results;
152
+ }
153
+
154
+ // packages/core/positiveIntegerOrFallback.ts
155
+ function parsePositiveIntegerOrFallback(value, fallback) {
156
+ const parsed = Number(value);
157
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
158
+ }
159
+
160
+ // packages/cli/dialogCommands.ts
161
+ var DIALOG_ID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
162
+ var DIALOG_PATH_RE = /^\/(?:space\/([^/]+)\/)?dialog-(.+)-([0-9A-HJKMNP-TV-Z]{26})\/?$/i;
163
+ var DEFAULT_DIALOG_LIST_LIMIT = 50;
164
+ var DEFAULT_DIALOG_QUERY_LIMIT = 50;
165
+ var UNBOUNDED_DIALOG_CAP = 1e5;
166
+ var VALUE_FLAGS = /* @__PURE__ */ new Set([
167
+ "--limit",
168
+ "--offset",
169
+ "--exclude-dialog",
170
+ "--row-dbkey",
171
+ "--server",
172
+ "--server-url",
173
+ "--space",
174
+ "--space-id",
175
+ "--subject-id",
176
+ "--subject-kind",
177
+ "--subject-role",
178
+ "--token",
179
+ "--machine-key",
180
+ "--user"
181
+ ]);
182
+ function hasFlag(args, flag) {
183
+ return args.includes(flag);
184
+ }
185
+ function readFirstPositional(args) {
186
+ for (let index = 0; index < args.length; index += 1) {
187
+ const value = args[index];
188
+ if (VALUE_FLAGS.has(value)) {
189
+ index += 1;
190
+ continue;
191
+ }
192
+ if (!value.startsWith("-")) return value;
193
+ }
194
+ return void 0;
195
+ }
196
+ function readAllPositional(args) {
197
+ const positionals = [];
198
+ for (let index = 0; index < args.length; index += 1) {
199
+ const value = args[index];
200
+ if (VALUE_FLAGS.has(value)) {
201
+ index += 1;
202
+ continue;
203
+ }
204
+ if (!value.startsWith("-")) {
205
+ positionals.push(value);
206
+ }
207
+ }
208
+ return positionals;
209
+ }
210
+ function resolveResultLimit(args, fallback) {
211
+ if (hasFlag(args, "--all")) {
212
+ return { limit: null, unlimited: true, fromDefault: false };
213
+ }
214
+ const raw = readOption(args, "--limit");
215
+ if (!raw) {
216
+ return { limit: fallback, unlimited: false, fromDefault: true };
217
+ }
218
+ const parsed = Number(raw);
219
+ if (!Number.isFinite(parsed) || parsed < 0) {
220
+ return { limit: fallback, unlimited: false, fromDefault: true };
221
+ }
222
+ if (parsed === 0) {
223
+ return { limit: null, unlimited: true, fromDefault: false };
224
+ }
225
+ return { limit: Math.floor(parsed), unlimited: false, fromDefault: false };
226
+ }
227
+ function readOffset(args) {
228
+ const raw = readOption(args, "--offset");
229
+ if (!raw) return 0;
230
+ return Math.floor(parsePositiveFiniteNumberOrFallback(raw, 0));
231
+ }
232
+ function writeJsonStream(output, value) {
233
+ if (Array.isArray(value)) {
234
+ output.write("[\n");
235
+ for (let i = 0; i < value.length; i++) {
236
+ const pretty = JSON.stringify(value[i], null, 2);
237
+ const indented = pretty.split("\n").map((line) => ` ${line}`).join("\n");
238
+ output.write(i === 0 ? indented : `,
239
+ ${indented}`);
240
+ }
241
+ output.write("\n]\n");
242
+ return;
243
+ }
244
+ if (isRecord(value)) {
245
+ const record = value;
246
+ const largeArrayKey = ["dialogs", "items", "messages"].find((key) => Array.isArray(record[key]));
247
+ if (largeArrayKey && Array.isArray(record[largeArrayKey]) && record[largeArrayKey].length > 32) {
248
+ const items = record[largeArrayKey];
249
+ output.write("{\n");
250
+ let wrote = false;
251
+ for (const [key, fieldValue] of Object.entries(record)) {
252
+ if (key === largeArrayKey) continue;
253
+ const pretty = JSON.stringify(fieldValue, null, 2).split("\n").map((line, idx) => idx === 0 ? line : ` ${line}`).join("\n");
254
+ output.write(`${wrote ? ",\n" : ""} ${JSON.stringify(key)}: ${pretty}`);
255
+ wrote = true;
256
+ }
257
+ output.write(`${wrote ? ",\n" : ""} ${JSON.stringify(largeArrayKey)}: [
258
+ `);
259
+ for (let i = 0; i < items.length; i++) {
260
+ const pretty = JSON.stringify(items[i], null, 2);
261
+ const indented = pretty.split("\n").map((line) => ` ${line}`).join("\n");
262
+ output.write(i === 0 ? indented : `,
263
+ ${indented}`);
264
+ }
265
+ output.write("\n ]\n}\n");
266
+ return;
267
+ }
268
+ }
269
+ output.write(`${JSON.stringify(value, null, 2)}
270
+ `);
271
+ }
272
+ function writeJsonlStream(output, items) {
273
+ for (const item of items) {
274
+ output.write(`${JSON.stringify(item)}
275
+ `);
276
+ }
277
+ }
278
+ function getDialogIdFromKey(dbKey) {
279
+ const index = dbKey.lastIndexOf("-");
280
+ return index >= 0 ? dbKey.slice(index + 1) : dbKey;
281
+ }
282
+ function resolveDialogInput(rawInput, userId) {
283
+ const raw = rawInput.trim();
284
+ if (raw.startsWith("http://") || raw.startsWith("https://")) {
285
+ const url = new URL(raw);
286
+ const match = url.pathname.match(DIALOG_PATH_RE);
287
+ if (!match) {
288
+ throw new Error(`Unsupported dialog URL path: ${url.pathname}`);
289
+ }
290
+ const [, spaceId, ownerId, dialogId] = match;
291
+ return {
292
+ dbKey: `dialog-${ownerId}-${dialogId}`,
293
+ dialogId,
294
+ ownerId,
295
+ spaceId: spaceId ? decodeURIComponent(spaceId) : null
296
+ };
297
+ }
298
+ if (raw.startsWith("dialog-")) {
299
+ const dialogId = getDialogIdFromKey(raw);
300
+ return {
301
+ dbKey: raw,
302
+ dialogId,
303
+ ownerId: raw.slice("dialog-".length, Math.max("dialog-".length, raw.length - dialogId.length - 1)),
304
+ spaceId: null
305
+ };
306
+ }
307
+ if (!DIALOG_ID_RE.test(raw)) {
308
+ throw new Error(`Unsupported dialog id: ${raw}`);
309
+ }
310
+ return {
311
+ dbKey: `dialog-${userId}-${raw}`,
312
+ dialogId: raw,
313
+ ownerId: userId,
314
+ spaceId: null
315
+ };
316
+ }
317
+ function normalizeDialogRecord(record, fallbackDbKey) {
318
+ const dbKey = asOptionalTrimmedString(record?.dbKey) ?? fallbackDbKey ?? "";
319
+ const id = asOptionalTrimmedString(record?.id) ?? (dbKey ? getDialogIdFromKey(dbKey) : "");
320
+ if (!dbKey || !id) return null;
321
+ return {
322
+ id,
323
+ dbKey,
324
+ title: asOptionalTrimmedString(record?.title) ?? asOptionalTrimmedString(record?.taskLabel) ?? "(untitled)",
325
+ status: typeof record?.status === "string" ? record.status : null,
326
+ updatedAt: typeof record?.updatedAt === "string" || typeof record?.updatedAt === "number" ? record.updatedAt : typeof record?.updated_at === "string" || typeof record?.updated_at === "number" ? record.updated_at : null,
327
+ createdAt: typeof record?.createdAt === "string" || typeof record?.createdAt === "number" ? record.createdAt : typeof record?.created === "string" || typeof record?.created === "number" ? record.created : null,
328
+ spaceId: typeof record?.spaceId === "string" && record.spaceId.trim() ? record.spaceId : null,
329
+ triggerType: typeof record?.triggerType === "string" ? record.triggerType : null,
330
+ primaryAgentKey: typeof record?.primaryAgentKey === "string" && record.primaryAgentKey.trim() ? record.primaryAgentKey : null,
331
+ cybots: Array.isArray(record?.cybots) ? record.cybots.filter((agent) => typeof agent === "string") : []
332
+ };
333
+ }
334
+ function sortDialogs(dialogs) {
335
+ return dialogs.sort((a, b) => {
336
+ const ta = a.updatedAt ?? a.createdAt ?? 0;
337
+ const tb = b.updatedAt ?? b.createdAt ?? 0;
338
+ const left = typeof ta === "number" ? ta : Date.parse(String(ta)) || 0;
339
+ const right = typeof tb === "number" ? tb : Date.parse(String(tb)) || 0;
340
+ return right - left;
341
+ });
342
+ }
343
+ function isScheduledDialog(record) {
344
+ return record.triggerType === "automation_run" || record.triggerType === "scheduled_run" || Boolean(record.parentAutomationKey) || Boolean(record.parentTaskKey);
345
+ }
346
+ function printListUsage(output) {
347
+ output.write(`Usage:
348
+ nolo dialog list [--space <spaceId|spaceUrl>] [--limit ${DEFAULT_DIALOG_LIST_LIMIT}] [--offset <n>] [--all] [--json] [--jsonl] [--ids-only]
349
+
350
+ Options:
351
+ --space <space> List current user's dialogs attached to one space.
352
+ --limit <n> Maximum dialogs to return. Default: ${DEFAULT_DIALOG_LIST_LIMIT}. Use 0 or --all for full dump.
353
+ --offset <n> Skip first n dialogs after sort/filter (paging).
354
+ --all Full dump (same as --limit 0). Prefer --jsonl for large results.
355
+ --include-scheduled Include scheduled automation run dialogs.
356
+ --json Print machine-readable JSON object.
357
+ --jsonl Stream one dialog JSON object per line (lowest memory).
358
+ --ids-only Print only dialog ids.
359
+ --server <url> Override NOLO_SERVER/BASE_URL.
360
+ --token <jwt> Override AUTH_TOKEN.
361
+
362
+ Lists merge global server candidates and ignore newer tombstones.
363
+ Human default is a short summary; use --json/--jsonl for automation.
364
+ `);
365
+ }
366
+ function printDeleteUsage(output) {
367
+ output.write(`Usage:
368
+ nolo dialog delete <dialogId|dialogKey|dialogUrl...> [--yes] [--include-attachments] [--include-referenced-attachments] [--json]
369
+
370
+ Options:
371
+ --yes Actually delete. Without this, the command is a dry-run.
372
+ --include-attachments Also delete files explicitly owned by this dialog/messages.
373
+ --include-referenced-attachments
374
+ Also delete same-account user-owned files referenced by this dialog.
375
+ --json Print machine-readable JSON.
376
+ --server <url> Prefer this server and include it in global deletion.
377
+ --token <jwt> Override AUTH_TOKEN.
378
+
379
+ Deletes are global across the selected/profile server plus known Nolo cluster peers.
380
+ Attachment cleanup is conservative by default. Use --include-referenced-attachments only
381
+ when you intentionally want to remove user-owned files referenced by the dialog too.
382
+ `);
383
+ }
384
+ function printReadUsage(output) {
385
+ output.write(`Usage:
386
+ nolo dialog read <dialogId|dialogKey|dialogUrl> [limit]
387
+
388
+ Options:
389
+ --server <url> Prefer this server when reading by raw dialog id.
390
+ --token <jwt> Override AUTH_TOKEN.
391
+ --user <userId> Override dialog owner for raw dialog ids.
392
+
393
+ Reads dialog metadata and messages as JSON.
394
+ `);
395
+ }
396
+ function printStatusUsage(output) {
397
+ output.write(`Usage:
398
+ nolo dialog status <dialogId|dialogKey|dialogUrl>
399
+
400
+ Options:
401
+ --server <url> Prefer this server when reading by raw dialog id.
402
+ --token <jwt> Override AUTH_TOKEN.
403
+ --user <userId> Override dialog owner for raw dialog ids.
404
+
405
+ Prints compact dialog run status and next-step hints.
406
+ `);
407
+ }
408
+ function printQueryUsage(output) {
409
+ output.write(`Usage:
410
+ nolo dialog query --subject-kind <kind> --subject-id <id> [--subject-role <role>]
411
+ nolo dialog query --row-dbkey <rowDbKey>
412
+
413
+ Options:
414
+ --row-dbkey <dbKey> Convenience target for table-row task subject refs.
415
+ --subject-kind <kind> Generic subject ref kind. Defaults to table-row with --row-dbkey.
416
+ --subject-id <id> Generic subject ref id. Defaults to --row-dbkey.
417
+ --subject-role <role> Optional role included in the query payload.
418
+ --limit <n> Query limit. Default: ${DEFAULT_DIALOG_QUERY_LIMIT}. Use 0 or --all for full dump.
419
+ --all Full dump (same as --limit 0). Prefer --jsonl for large results.
420
+ --exclude-dialog <id> Exclude one dialog id or dbKey from evidence results.
421
+ --allow-empty Exit 0 when no dialogs match.
422
+ --json Print machine-readable JSON object.
423
+ --jsonl Stream one dialog JSON object per line.
424
+ --server <url> Target server. Defaults to NOLO_SERVER/BASE_URL/profile.
425
+ --token <jwt> Override AUTH_TOKEN.
426
+
427
+ Reads dialog evidence by dialog.subjectRefs through the server query endpoint.
428
+ It is read-only and does not write task rows, row-side evidence caches, or retired orchestration metadata.
429
+ `);
430
+ }
431
+ function isHelpArg(value) {
432
+ return value === "-h" || value === "--help";
433
+ }
434
+ function readDialogLimitArg(args, fallback) {
435
+ const explicit = readOption(args, "--limit");
436
+ const positional = args.find(
437
+ (value, index) => index > 0 && /^\d+$/.test(value) && args[index - 1] !== "--limit"
438
+ );
439
+ const raw = explicit ?? positional;
440
+ if (!raw) return fallback;
441
+ return parsePositiveIntegerOrFallback(raw, fallback);
442
+ }
443
+ function readDialogOwnerId(args, env, authToken) {
444
+ return readOption(args, "--user") ?? env.USER_ID ?? parseUserIdFromAuthToken(authToken) ?? "";
445
+ }
446
+ function resolveDialogReadTarget(args, env, authToken) {
447
+ const rawInput = readFirstPositional(args);
448
+ if (!rawInput) return null;
449
+ const preferredServer = readOption(args, "--server") ?? readOption(args, "--server-url");
450
+ const ownerFallback = readDialogOwnerId(args, env, authToken);
451
+ const raw = rawInput.trim();
452
+ if (raw.startsWith("http://") || raw.startsWith("https://")) {
453
+ const url = new URL(raw);
454
+ const match = url.pathname.match(DIALOG_PATH_RE);
455
+ if (!match) throw new Error(`Unsupported dialog URL path: ${url.pathname}`);
456
+ const [, spaceId, ownerId, dialogId] = match;
457
+ const base = preferredServer ?? env.READ_DIALOG_BASE ?? url.origin;
458
+ return {
459
+ base,
460
+ dialogId,
461
+ dialogKey: `dialog-${ownerId}-${dialogId}`,
462
+ userId: ownerId,
463
+ spaceId: spaceId ? decodeURIComponent(spaceId) : void 0
464
+ };
465
+ }
466
+ if (raw.startsWith("dialog-")) {
467
+ const dialogId = getDialogIdFromKey(raw);
468
+ const ownerId = raw.slice("dialog-".length, Math.max("dialog-".length, raw.length - dialogId.length - 1));
469
+ return {
470
+ base: preferredServer ?? env.READ_DIALOG_BASE ?? resolveServerUrl(args, env),
471
+ dialogId,
472
+ dialogKey: raw,
473
+ userId: ownerId || ownerFallback
474
+ };
475
+ }
476
+ if (!DIALOG_ID_RE.test(raw)) {
477
+ throw new Error(`Unsupported dialog id: ${raw}`);
478
+ }
479
+ if (!ownerFallback) {
480
+ throw new Error("raw dialog ids require an auth token userId or --user");
481
+ }
482
+ return {
483
+ base: preferredServer ?? env.READ_DIALOG_BASE ?? resolveServerUrl(args, env),
484
+ dialogId: raw,
485
+ dialogKey: `dialog-${ownerFallback}-${raw}`,
486
+ userId: ownerFallback
487
+ };
488
+ }
489
+ function toToolName(value) {
490
+ return asTrimmedString(value);
491
+ }
492
+ function countByName(values) {
493
+ return values.reduce((acc, value) => {
494
+ acc[value] = (acc[value] ?? 0) + 1;
495
+ return acc;
496
+ }, {});
497
+ }
498
+ function uniq(values) {
499
+ return [...new Set(values.filter(Boolean))];
500
+ }
501
+ function parseJsonObject(raw) {
502
+ if (typeof raw !== "string" || !raw.trim()) return null;
503
+ try {
504
+ const parsed = JSON.parse(raw);
505
+ return parsed && typeof parsed === "object" ? parsed : null;
506
+ } catch {
507
+ return null;
508
+ }
509
+ }
510
+ function deriveWrittenFiles(toolMessages) {
511
+ const writeToolNames = /* @__PURE__ */ new Set(["applyEdit", "applyLineEdits", "writeFile", "createDoc", "updateDoc"]);
512
+ const files = [];
513
+ for (const message of toolMessages) {
514
+ const toolName = toToolName(message?.toolName ?? message?.name);
515
+ if (!writeToolNames.has(toolName)) continue;
516
+ const payload = message?.toolPayload ?? {};
517
+ const content = parseJsonObject(message?.content);
518
+ for (const candidate of [payload?.input?.filePath, payload?.response?.filePath, content?.filePath]) {
519
+ const normalized = asTrimmedString(candidate);
520
+ if (normalized) files.push(normalized);
521
+ }
522
+ }
523
+ return uniq(files);
524
+ }
525
+ function deriveToolErrors(toolMessages) {
526
+ const errors = [];
527
+ for (const message of toolMessages) {
528
+ const toolName = toToolName(message?.toolName ?? message?.name);
529
+ const payload = message?.toolPayload ?? {};
530
+ const content = parseJsonObject(message?.content);
531
+ if (payload?.status === "failed" || content?.ok === false || content?.applied === false || content?.success === false) {
532
+ errors.push(toolName || "unknown-tool");
533
+ }
534
+ }
535
+ return uniq(errors);
536
+ }
537
+ function isLocalBaseUrl(base) {
538
+ try {
539
+ const url = new URL(base);
540
+ return url.hostname === "127.0.0.1" || url.hostname === "localhost";
541
+ } catch {
542
+ return false;
543
+ }
544
+ }
545
+ async function readDialogOverHttp(args) {
546
+ const authHeaders = {
547
+ Authorization: `Bearer ${args.authToken}`,
548
+ "Content-Type": "application/json"
549
+ };
550
+ const readViaBridge = async () => {
551
+ const bridgeRes = await args.fetchImpl(`${args.base}/api/dialog-read`, {
552
+ method: "POST",
553
+ headers: authHeaders,
554
+ body: JSON.stringify({
555
+ dialogKey: args.dialogKey,
556
+ dialogId: args.dialogId,
557
+ limit: args.limit
558
+ })
559
+ });
560
+ if (!bridgeRes.ok) {
561
+ throw Object.assign(new Error(`dialog read bridge failed: HTTP ${bridgeRes.status}`), {
562
+ status: bridgeRes.status,
563
+ base: args.base
564
+ });
565
+ }
566
+ const payload = await bridgeRes.json();
567
+ if (!payload?.ok) {
568
+ throw Object.assign(new Error(`dialog read bridge failed: ${payload?.error ?? "unknown error"}`), {
569
+ status: 500,
570
+ base: args.base
571
+ });
572
+ }
573
+ return {
574
+ meta: payload.meta,
575
+ msgs: payload.msgs,
576
+ source: "http"
577
+ };
578
+ };
579
+ const metaRes = await args.fetchImpl(
580
+ `${args.base}/api/v1/db/read/${encodeURIComponent(args.dialogKey)}`,
581
+ { headers: { Authorization: `Bearer ${args.authToken}` } }
582
+ );
583
+ if (!metaRes.ok) {
584
+ if (metaRes.status === 401 || metaRes.status === 403) return readViaBridge();
585
+ throw Object.assign(new Error(`read dialog meta failed: HTTP ${metaRes.status}`), {
586
+ status: metaRes.status,
587
+ base: args.base
588
+ });
589
+ }
590
+ const meta = await metaRes.json();
591
+ const msgsRes = await args.fetchImpl(`${args.base}/rpc/getConvMsgs`, {
592
+ method: "POST",
593
+ headers: authHeaders,
594
+ body: JSON.stringify({ dialogId: args.dialogId, limit: args.limit })
595
+ });
596
+ if (!msgsRes.ok) {
597
+ if (msgsRes.status === 401 || msgsRes.status === 403) return readViaBridge();
598
+ throw Object.assign(new Error(`read dialog messages failed: HTTP ${msgsRes.status}`), {
599
+ status: msgsRes.status,
600
+ base: args.base
601
+ });
602
+ }
603
+ return {
604
+ meta,
605
+ msgs: await msgsRes.json(),
606
+ source: "http"
607
+ };
608
+ }
609
+ async function tryHttpDialogCandidates(args) {
610
+ const attempts = [];
611
+ for (const base of args.bases) {
612
+ try {
613
+ const result = await readDialogOverHttp({ ...args, base });
614
+ attempts.push({ base, ok: true });
615
+ return { ...result, resolvedBase: base, attempts };
616
+ } catch (error) {
617
+ attempts.push({
618
+ base,
619
+ ok: false,
620
+ status: typeof error === "object" && error !== null && "status" in error ? Number(error.status) : void 0,
621
+ message: toErrorMessage(error)
622
+ });
623
+ }
624
+ }
625
+ throw Object.assign(new Error("All HTTP dialog reads failed"), { attempts });
626
+ }
627
+ async function readDialogFromLocalDb(dialogKey, dialogId, limit) {
628
+ const { readDialogFromLocalDb: readLocalDialog } = await import("./localDialogRead-Z5UTAJPU.js");
629
+ const result = await readLocalDialog({ dialogKey, dialogId, limit });
630
+ return {
631
+ ...result,
632
+ source: "local-db-fallback"
633
+ };
634
+ }
635
+ async function readDialogSnapshot(args) {
636
+ const candidateBases = resolveServerCandidates({ NOLO_SERVER: args.base }, args.base);
637
+ let attempts = [];
638
+ try {
639
+ const result = await tryHttpDialogCandidates({
640
+ bases: candidateBases,
641
+ dialogKey: args.dialogKey,
642
+ dialogId: args.dialogId,
643
+ limit: args.limit,
644
+ authToken: args.authToken,
645
+ fetchImpl: args.fetchImpl
646
+ });
647
+ return { ...result, candidateBases };
648
+ } catch (error) {
649
+ attempts = typeof error === "object" && error !== null && "attempts" in error ? error.attempts : attempts;
650
+ const statuses = attempts.map((attempt) => attempt.status).filter((status) => typeof status === "number");
651
+ const all404 = attempts.length > 0 && statuses.length === attempts.length && statuses.every((status) => status === 404);
652
+ const localhostCandidate = candidateBases.find(isLocalBaseUrl);
653
+ if (!localhostCandidate || all404) {
654
+ throw Object.assign(new Error(
655
+ all404 ? `dialog not found on tried servers: ${candidateBases.join(", ")}` : `read dialog failed across candidates: ${attempts.map((attempt) => `${attempt.base} -> ${attempt.status ?? attempt.message}`).join("; ")}`
656
+ ), { attempts });
657
+ }
658
+ const fallback = await readDialogFromLocalDb(args.dialogKey, args.dialogId, args.limit);
659
+ return {
660
+ ...fallback,
661
+ resolvedBase: localhostCandidate,
662
+ attempts,
663
+ candidateBases
664
+ };
665
+ }
666
+ }
667
+ function compact(value, max = 180) {
668
+ const text = asTrimmedString(value);
669
+ if (!text) return "";
670
+ return text.length > max ? `${text.slice(0, max - 3)}...` : text;
671
+ }
672
+ function normalizeNonEmptyString(value) {
673
+ return asOptionalTrimmedString(value) ?? null;
674
+ }
675
+ function normalizeSubjectKind(kind) {
676
+ return kind === "tableRow" ? "table-row" : kind;
677
+ }
678
+ function normalizeDialogSubjectRef(value) {
679
+ if (!isRecord(value)) return null;
680
+ const kindRaw = asOptionalTrimmedString(value.kind);
681
+ const kind = kindRaw ? normalizeSubjectKind(kindRaw) : "";
682
+ const id = asOptionalTrimmedString(value.id) ?? "";
683
+ if (!kind || !id) return null;
684
+ const role = asOptionalTrimmedString(value.role) ?? "";
685
+ return {
686
+ kind,
687
+ id,
688
+ ...role ? { role } : {}
689
+ };
690
+ }
691
+ function extractDialogSubjectRefs(dialog) {
692
+ if (!isRecord(dialog) || !Array.isArray(dialog.subjectRefs)) return [];
693
+ return dialog.subjectRefs.map(normalizeDialogSubjectRef).filter((ref) => Boolean(ref));
694
+ }
695
+ function dialogMatchesSubjectRef(dialog, target) {
696
+ const normalizedTarget = normalizeDialogSubjectRef(target);
697
+ if (!normalizedTarget) return false;
698
+ return extractDialogSubjectRefs(dialog).some(
699
+ (ref) => ref.kind === normalizedTarget.kind && ref.id === normalizedTarget.id
700
+ );
701
+ }
702
+ function hasArtifactEvidence(value) {
703
+ if (Array.isArray(value)) return value.length > 0;
704
+ if (isRecord(value)) return Object.keys(value).length > 0;
705
+ return Boolean(value);
706
+ }
707
+ function artifactEvidenceCount(value) {
708
+ if (Array.isArray(value)) return value.length;
709
+ if (isRecord(value)) return Object.keys(value).length > 0 ? 1 : 0;
710
+ return value ? 1 : 0;
711
+ }
712
+ function summarizeDialogEvidence(dialog, target) {
713
+ const dialogKey = asOptionalTrimmedString(dialog?.dbKey) ?? "";
714
+ const checkpoint = asRecordOrEmpty(dialog?.runtimeCheckpoint);
715
+ const matchedSubjectRefs = extractDialogSubjectRefs(dialog).filter(
716
+ (ref) => ref.kind === normalizeSubjectKind(target.kind) && ref.id === target.id
717
+ );
718
+ const lastToolNames = asNonEmptyStringArray(checkpoint.lastToolNames);
719
+ return {
720
+ dialogId: asOptionalTrimmedString(dialog?.dialogId) ?? asOptionalTrimmedString(dialog?.id) ?? (dialogKey ? getDialogIdFromKey(dialogKey) : null),
721
+ dialogKey: dialogKey || null,
722
+ title: asOptionalTrimmedString(dialog?.title) ?? null,
723
+ status: asOptionalTrimmedString(dialog?.status) ?? null,
724
+ checkpointStatus: asOptionalTrimmedString(checkpoint.status) ?? null,
725
+ updatedAt: typeof dialog?.updatedAt === "string" || typeof dialog?.updatedAt === "number" ? dialog.updatedAt : null,
726
+ hasArtifacts: hasArtifactEvidence(dialog?.artifacts),
727
+ artifactCount: artifactEvidenceCount(dialog?.artifacts),
728
+ subjectRefs: matchedSubjectRefs,
729
+ lastToolNames
730
+ };
731
+ }
732
+ function verifyDialogSubjectQuery(dialogs, target, allowEmpty) {
733
+ const unmatchedDialogs = dialogs.filter((dialog) => !dialogMatchesSubjectRef(dialog, target)).map((dialog) => ({
734
+ dialogId: asOptionalTrimmedString(dialog?.dialogId) ?? asOptionalTrimmedString(dialog?.id) ?? (typeof dialog?.dbKey === "string" ? getDialogIdFromKey(dialog.dbKey) : null),
735
+ dialogKey: asOptionalTrimmedString(dialog?.dbKey) ?? null,
736
+ subjectRefs: extractDialogSubjectRefs(dialog)
737
+ }));
738
+ const reason = unmatchedDialogs.length > 0 ? "unmatched_results" : dialogs.length === 0 && !allowEmpty ? "empty_results" : "ok";
739
+ return {
740
+ ok: reason === "ok",
741
+ reason,
742
+ target,
743
+ returnedCount: dialogs.length,
744
+ matchedCount: dialogs.length - unmatchedDialogs.length,
745
+ unmatchedCount: unmatchedDialogs.length,
746
+ unmatchedDialogs
747
+ };
748
+ }
749
+ function normalizeExcludedDialogIds(value) {
750
+ const rawValues = Array.isArray(value) ? value : [value];
751
+ const ids = /* @__PURE__ */ new Set();
752
+ for (const rawValue of rawValues) {
753
+ if (typeof rawValue !== "string") continue;
754
+ const trimmed = rawValue.trim();
755
+ if (!trimmed) continue;
756
+ ids.add(trimmed);
757
+ if (trimmed.startsWith("dialog-")) {
758
+ ids.add(getDialogIdFromKey(trimmed));
759
+ }
760
+ }
761
+ return [...ids];
762
+ }
763
+ function getDialogIdentityValues(dialog) {
764
+ if (!isRecord(dialog)) return [];
765
+ const values = /* @__PURE__ */ new Set();
766
+ for (const rawValue of [dialog.dialogId, dialog.id, dialog.dbKey]) {
767
+ if (typeof rawValue !== "string") continue;
768
+ const trimmed = rawValue.trim();
769
+ if (!trimmed) continue;
770
+ values.add(trimmed);
771
+ if (trimmed.startsWith("dialog-")) {
772
+ values.add(getDialogIdFromKey(trimmed));
773
+ }
774
+ }
775
+ return [...values];
776
+ }
777
+ function excludeDialogsById(dialogs, excludeDialogIds) {
778
+ if (excludeDialogIds.length === 0) return dialogs;
779
+ const excluded = new Set(excludeDialogIds);
780
+ return dialogs.filter(
781
+ (dialog) => getDialogIdentityValues(dialog).every((value) => !excluded.has(value))
782
+ );
783
+ }
784
+ async function queryDialogEvidenceBySubjectRef(args) {
785
+ const res = await args.fetchImpl(
786
+ `${args.serverUrl}/api/v1/db/query/${encodeURIComponent(args.userId)}`,
787
+ {
788
+ method: "POST",
789
+ headers: {
790
+ Authorization: `Bearer ${args.authToken}`,
791
+ "Content-Type": "application/json"
792
+ },
793
+ body: JSON.stringify({
794
+ type: "dialog",
795
+ limit: args.limit,
796
+ subjectRef: args.subjectRef
797
+ })
798
+ }
799
+ );
800
+ const data = await res.json().catch(() => ({}));
801
+ if (!res.ok) {
802
+ throw new Error(`dialog subject query failed: HTTP ${res.status} ${JSON.stringify(data)}`);
803
+ }
804
+ return Array.isArray(data?.data?.data) ? data.data.data : Array.isArray(data?.data) ? data.data : [];
805
+ }
806
+ function renderCompactDialogStatus(snapshot) {
807
+ const checkpoint = snapshot.runtimeCheckpoint ?? {};
808
+ const checkpointStatus = typeof checkpoint.status === "string" ? checkpoint.status : null;
809
+ const status = snapshot.status ?? checkpointStatus ?? "unknown";
810
+ const state = checkpointStatus === "done" || checkpointStatus === "completed" || status === "done" || status === "completed" ? "done" : checkpointStatus === "failed" || checkpointStatus === "error" || status === "failed" || status === "error" ? "failed" : status === "running" || status === "pending" || status === "queued" ? "active" : "unknown";
811
+ const tools = (Array.isArray(snapshot.toolsUsed) ? asNonEmptyStringArray(snapshot.toolsUsed) : asNonEmptyStringArray(checkpoint.lastToolNames)).slice(0, 8);
812
+ const artifactFiles = snapshot.artifacts && typeof snapshot.artifacts === "object" ? snapshot.artifacts.changedFiles ?? snapshot.artifacts.writtenFiles ?? snapshot.artifacts.files : void 0;
813
+ const files = (Array.isArray(snapshot.writtenFiles) && snapshot.writtenFiles.length ? asNonEmptyStringArray(snapshot.writtenFiles) : asNonEmptyStringArray(artifactFiles)).slice(0, 8);
814
+ const subjectRefs = Array.isArray(snapshot.subjectRefs) ? snapshot.subjectRefs.map((ref) => {
815
+ const kind = asTrimmedString(ref?.kind);
816
+ const id = asTrimmedString(ref?.id);
817
+ if (!kind || !id) return "";
818
+ const rolePart = asOptionalTrimmedString(ref?.role);
819
+ const role = rolePart ? `#${rolePart}` : "";
820
+ return `${kind}:${id}${role}`;
821
+ }).filter(Boolean).slice(0, 8) : [];
822
+ const runtimeContext = asRecordOrEmpty(snapshot.runtimeContext);
823
+ const runtimeFieldLines = [
824
+ ["triggerType", snapshot.triggerType],
825
+ ["executionMode", snapshot.executionMode],
826
+ ["threadKind", snapshot.threadKind],
827
+ ["presentationIntent", snapshot.presentationIntent],
828
+ ["parentThreadId", snapshot.parentThreadId],
829
+ ["rootThreadId", snapshot.rootThreadId],
830
+ ["runtimeEntrypoint", runtimeContext.entrypoint ?? checkpoint.runtimeContext?.entrypoint],
831
+ ["parentWakeStatus", snapshot.parentWake?.terminalStatus],
832
+ ["parentWakeAt", snapshot.parentWake?.terminalNotifiedAt]
833
+ ].map(([label, value]) => {
834
+ const normalized = typeof value === "number" ? String(value) : normalizeNonEmptyString(value);
835
+ return normalized ? `${label}: ${normalized}` : "";
836
+ }).filter(Boolean);
837
+ const toolErrors = asNonEmptyStringArray(snapshot.toolErrors).slice(0, 8);
838
+ const checkpointUpdatedAt = typeof checkpoint.updatedAt === "number" || typeof checkpoint.updatedAt === "string" ? Date.parse(String(checkpoint.updatedAt)) : NaN;
839
+ const activeHealth = state !== "active" ? "" : !snapshot.runtimeCheckpoint ? "no-checkpoint" : !Number.isFinite(checkpointUpdatedAt) ? "checkpoint-without-updatedAt" : Date.now() - checkpointUpdatedAt > 5 * 6e4 ? "stale-running" : "running";
840
+ const errorMessage = compact(checkpoint.errorMessage ?? snapshot.errorMessage);
841
+ const lines = [
842
+ `dialog: ${snapshot.dialogId}`,
843
+ ...snapshot.base ? [`base: ${snapshot.base}`] : [],
844
+ ...snapshot.title ? [`title: ${snapshot.title}`] : [],
845
+ ...snapshot.parentDialogId ? [`parentDialogId: ${snapshot.parentDialogId}`] : [],
846
+ ...snapshot.rootDialogId ? [`rootDialogId: ${snapshot.rootDialogId}`] : [],
847
+ ...runtimeFieldLines,
848
+ `status: ${status}`,
849
+ ...checkpointStatus ? [`checkpoint: ${checkpointStatus}`] : [],
850
+ `state: ${state}`,
851
+ ...activeHealth ? [`activeHealth: ${activeHealth}`] : [],
852
+ ...typeof snapshot.durationMs === "number" ? [`durationMs: ${snapshot.durationMs}`] : [],
853
+ ...snapshot.updatedAt ? [`updatedAt: ${snapshot.updatedAt}`] : [],
854
+ ...snapshot.finishedAt ? [`finishedAt: ${snapshot.finishedAt}`] : [],
855
+ ...compact(checkpoint.lastUserInput) ? [`lastUserInput: ${compact(checkpoint.lastUserInput)}`] : [],
856
+ ...compact(checkpoint.lastAssistantText) ? [`lastAssistantText: ${compact(checkpoint.lastAssistantText)}`] : [],
857
+ ...errorMessage ? [`error: ${errorMessage}`] : [],
858
+ ...tools.length ? [`tools: ${tools.join(", ")}`] : [],
859
+ ...files.length ? [`files: ${files.join(", ")}`] : [],
860
+ ...subjectRefs.length ? [`subjects: ${subjectRefs.join(", ")}`] : [],
861
+ ...toolErrors.length ? [`toolErrors: ${toolErrors.join(", ")}`] : [],
862
+ "",
863
+ "next:",
864
+ `- read full dialog: nolo dialog read ${snapshot.dialogId} 120`
865
+ ];
866
+ if (state === "active") lines.push(`- poll again: nolo dialog status ${snapshot.dialogId}`);
867
+ else if (state === "failed") lines.push(`- inspect failure and rerun/continue with: nolo agent run <agent> --continue ${snapshot.dialogId} --msg "..."`);
868
+ else if (state === "done") lines.push("- use artifacts/files above for review, handoff, or alpha integration.");
869
+ else lines.push("- inspect meta/messages before deciding whether to continue or rerun.");
870
+ return `${lines.join("\n")}
871
+ `;
872
+ }
873
+ async function readSpaceDialogRecords(args) {
874
+ const { spaceId, spaceKey } = buildSpaceLookup(args.spaceInput);
875
+ const spaceRead = await readLiveDbRecordAfterTombstoneMerge({
876
+ authToken: args.authToken,
877
+ dbKey: spaceKey,
878
+ fallbackFetchImpl: args.fallbackFetchImpl,
879
+ fetchImpl: args.fetchImpl,
880
+ label: "space record",
881
+ serverUrls: args.serverUrls
882
+ });
883
+ const contentKeys = [...getSpaceContentKeys(spaceRead.record)].filter((key) => key.startsWith(`dialog-${args.userId}-`));
884
+ const contentKeySet = new Set(contentKeys);
885
+ const dialogResult = await listUserRecordsFromServers({
886
+ authToken: args.authToken,
887
+ fallbackFetchImpl: args.fallbackFetchImpl,
888
+ fetchImpl: args.fetchImpl,
889
+ label: "dialog query",
890
+ serverUrls: args.serverUrls,
891
+ type: "dialog",
892
+ userId: args.userId
893
+ });
894
+ const records = dialogResult.records.filter(
895
+ (record) => typeof record?.dbKey === "string" && contentKeySet.has(record.dbKey)
896
+ );
897
+ const failures = [...spaceRead.failures, ...dialogResult.failures];
898
+ return { spaceId, records, failures };
899
+ }
900
+ async function runDialogReadCommand(args, deps = {}) {
901
+ const env = deps.env ?? process.env;
902
+ const output = deps.output ?? process.stdout;
903
+ if (isHelpArg(args[0])) {
904
+ printReadUsage(output);
905
+ return 0;
906
+ }
907
+ const authToken = resolveAuthToken(args, env);
908
+ if (!authToken) {
909
+ output.write("[nolo] dialog read requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
910
+ return 1;
911
+ }
912
+ let target;
913
+ try {
914
+ target = resolveDialogReadTarget(args, env, authToken);
915
+ } catch (error) {
916
+ output.write(`[nolo] dialog read failed: ${toErrorMessage(error)}
917
+ `);
918
+ return 1;
919
+ }
920
+ if (!target) {
921
+ printReadUsage(output);
922
+ return 1;
923
+ }
924
+ try {
925
+ const limit = readDialogLimitArg(args, 0);
926
+ const read = await readDialogSnapshot({
927
+ authToken,
928
+ base: target.base,
929
+ dialogId: target.dialogId,
930
+ dialogKey: target.dialogKey,
931
+ fetchImpl: deps.fetchImpl ?? fetch,
932
+ limit
933
+ });
934
+ const orderedMsgs = Array.isArray(read.msgs) ? [...read.msgs].reverse() : read.msgs;
935
+ const lastAssistantMessage = Array.isArray(orderedMsgs) ? [...orderedMsgs].reverse().find((message) => message?.role === "assistant" || message?.authorRole === "assistant") : null;
936
+ const toolMessages = Array.isArray(orderedMsgs) ? orderedMsgs.filter((message) => message?.role === "tool" || message?.authorRole === "tool") : [];
937
+ const toolNamesFromMessages = toolMessages.map((message) => toToolName(message?.toolName ?? message?.name)).filter(Boolean);
938
+ const toolsUsed = Array.isArray(read.meta?.toolsUsed) && read.meta.toolsUsed.length > 0 ? read.meta.toolsUsed.map((tool) => toToolName(tool)).filter(Boolean) : uniq(toolNamesFromMessages);
939
+ const writtenFiles = Array.isArray(read.meta?.writtenFiles) && read.meta.writtenFiles.length > 0 ? uniq(asTrimmedNonEmptyStringArray(read.meta.writtenFiles)) : deriveWrittenFiles(toolMessages);
940
+ const toolErrors = Array.isArray(read.meta?.toolErrors) && read.meta.toolErrors.length > 0 ? uniq(asTrimmedNonEmptyStringArray(read.meta.toolErrors)) : deriveToolErrors(toolMessages);
941
+ output.write(JSON.stringify({
942
+ source: read.source,
943
+ base: read.resolvedBase,
944
+ triedBases: read.candidateBases,
945
+ httpAttempts: read.attempts,
946
+ spaceId: target.spaceId,
947
+ dialogId: target.dialogId,
948
+ dialogKey: target.dialogKey,
949
+ userId: target.userId,
950
+ title: read.meta?.title ?? null,
951
+ cybots: Array.isArray(read.meta?.cybots) ? read.meta.cybots : [],
952
+ category: read.meta?.category ?? null,
953
+ inheritedFromDialogKey: read.meta?.inheritedFromDialogKey ?? null,
954
+ inheritedFromDialogTitle: read.meta?.inheritedFromDialogTitle ?? null,
955
+ parentDialogId: read.meta?.parentDialogId ?? null,
956
+ rootDialogId: read.meta?.rootDialogId ?? null,
957
+ triggerType: read.meta?.triggerType ?? null,
958
+ executionMode: read.meta?.executionMode ?? null,
959
+ threadKind: read.meta?.threadKind ?? null,
960
+ presentationIntent: read.meta?.presentationIntent ?? null,
961
+ parentThreadId: read.meta?.parentThreadId ?? null,
962
+ rootThreadId: read.meta?.rootThreadId ?? null,
963
+ runtimeBinding: read.meta?.runtimeBinding ?? null,
964
+ runtimeContext: read.meta?.runtimeContext ?? null,
965
+ parentWake: read.meta?.parentWake ?? null,
966
+ subjectRefs: Array.isArray(read.meta?.subjectRefs) ? read.meta.subjectRefs : [],
967
+ status: read.meta?.status,
968
+ errorMessage: read.meta?.errorMessage ?? null,
969
+ runtimeCheckpoint: read.meta?.runtimeCheckpoint ?? null,
970
+ durationMs: read.meta?.durationMs,
971
+ finishedAt: read.meta?.finishedAt,
972
+ createdAt: read.meta?.createdAt,
973
+ updatedAt: read.meta?.updatedAt,
974
+ artifacts: read.meta?.artifacts ?? null,
975
+ writtenFiles,
976
+ toolsUsed,
977
+ toolErrors,
978
+ toolSummary: {
979
+ metaToolsCount: toolsUsed.length,
980
+ metaToolsUnique: [...new Set(toolsUsed)],
981
+ toolMessageCount: toolMessages.length,
982
+ toolNamesFromMessages: [...new Set(toolNamesFromMessages)],
983
+ toolMessageCountsByName: countByName(toolNamesFromMessages)
984
+ },
985
+ agentReply: read.meta?.agentReply ?? null,
986
+ messagesCount: Array.isArray(orderedMsgs) ? orderedMsgs.length : 0,
987
+ lastAssistantMessage,
988
+ messages: orderedMsgs
989
+ }, null, 2));
990
+ output.write("\n");
991
+ return 0;
992
+ } catch (error) {
993
+ output.write(`[nolo] dialog read failed: ${toErrorMessage(error)}
994
+ `);
995
+ return 1;
996
+ }
997
+ }
998
+ async function runDialogStatusCommand(args, deps = {}) {
999
+ const env = deps.env ?? process.env;
1000
+ const output = deps.output ?? process.stdout;
1001
+ if (isHelpArg(args[0])) {
1002
+ printStatusUsage(output);
1003
+ return 0;
1004
+ }
1005
+ const authToken = resolveAuthToken(args, env);
1006
+ if (!authToken) {
1007
+ output.write("[nolo] dialog status requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
1008
+ return 1;
1009
+ }
1010
+ let target;
1011
+ try {
1012
+ target = resolveDialogReadTarget(args, env, authToken);
1013
+ } catch (error) {
1014
+ output.write(`[nolo] dialog status failed: ${toErrorMessage(error)}
1015
+ `);
1016
+ return 1;
1017
+ }
1018
+ if (!target) {
1019
+ printStatusUsage(output);
1020
+ return 1;
1021
+ }
1022
+ try {
1023
+ const read = await readDialogSnapshot({
1024
+ authToken,
1025
+ base: target.base,
1026
+ dialogId: target.dialogId,
1027
+ dialogKey: target.dialogKey,
1028
+ fetchImpl: deps.fetchImpl ?? fetch,
1029
+ limit: 1
1030
+ });
1031
+ output.write(renderCompactDialogStatus({
1032
+ ...read.meta ?? {},
1033
+ dialogId: target.dialogId,
1034
+ dialogKey: target.dialogKey,
1035
+ base: read.resolvedBase
1036
+ }));
1037
+ return 0;
1038
+ } catch (error) {
1039
+ output.write(`[nolo] dialog status failed: ${toErrorMessage(error)}
1040
+ `);
1041
+ return 1;
1042
+ }
1043
+ }
1044
+ async function runDialogQueryCommand(args, deps = {}) {
1045
+ const env = deps.env ?? process.env;
1046
+ const output = deps.output ?? process.stdout;
1047
+ if (hasFlag(args, "--help") || hasFlag(args, "-h")) {
1048
+ printQueryUsage(output);
1049
+ return 0;
1050
+ }
1051
+ const authToken = resolveAuthToken(args, env);
1052
+ if (!authToken) {
1053
+ output.write("[nolo] dialog query requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
1054
+ return 1;
1055
+ }
1056
+ const userId = parseUserIdFromAuthToken(authToken);
1057
+ if (!userId) {
1058
+ output.write("[nolo] dialog query could not read userId from AUTH_TOKEN.\n");
1059
+ return 1;
1060
+ }
1061
+ const rowDbKey = readOption(args, "--row-dbkey") ?? env.TASK_ROW_DBKEY;
1062
+ const subjectKind = readOption(args, "--subject-kind") ?? (rowDbKey ? "table-row" : "");
1063
+ const subjectId = readOption(args, "--subject-id") ?? rowDbKey ?? "";
1064
+ const subjectRole = readOption(args, "--subject-role") ?? (rowDbKey ? "task" : "");
1065
+ if (!subjectKind || !subjectId) {
1066
+ printQueryUsage(output);
1067
+ return 1;
1068
+ }
1069
+ const subjectRef = {
1070
+ kind: normalizeSubjectKind(subjectKind),
1071
+ id: subjectId,
1072
+ ...subjectRole ? { role: subjectRole } : {}
1073
+ };
1074
+ const serverUrl = resolveServerUrl(args, env);
1075
+ const resultLimit = resolveResultLimit(args, DEFAULT_DIALOG_QUERY_LIMIT);
1076
+ const limit = resultLimit.unlimited ? UNBOUNDED_DIALOG_CAP : Math.max(1, resultLimit.limit ?? DEFAULT_DIALOG_QUERY_LIMIT);
1077
+ const fetchImpl = deps.fetchImpl ?? fetch;
1078
+ const excludeDialogIds = normalizeExcludedDialogIds(readOption(args, "--exclude-dialog"));
1079
+ try {
1080
+ const rawRecords = await queryDialogEvidenceBySubjectRef({
1081
+ authToken,
1082
+ fetchImpl,
1083
+ limit,
1084
+ serverUrl,
1085
+ subjectRef,
1086
+ userId
1087
+ });
1088
+ const records = excludeDialogsById(rawRecords, excludeDialogIds);
1089
+ const strict = verifyDialogSubjectQuery(records, subjectRef, hasFlag(args, "--allow-empty"));
1090
+ const allDialogs = records.filter((record) => dialogMatchesSubjectRef(record, subjectRef)).map((record) => summarizeDialogEvidence(record, subjectRef));
1091
+ const hitLimit = !resultLimit.unlimited && allDialogs.length > limit;
1092
+ const dialogs = hitLimit ? allDialogs.slice(0, limit) : allDialogs;
1093
+ if (hasFlag(args, "--jsonl")) {
1094
+ writeJsonlStream(output, dialogs);
1095
+ } else if (hasFlag(args, "--json")) {
1096
+ writeJsonStream(output, {
1097
+ source: "db.query.subjectRef",
1098
+ readOnly: true,
1099
+ server: serverUrl,
1100
+ userId,
1101
+ ...rowDbKey ? { rowDbKey } : {},
1102
+ target: subjectRef,
1103
+ ...excludeDialogIds.length ? { excludedDialogIds: excludeDialogIds } : {},
1104
+ strict,
1105
+ total: dialogs.length,
1106
+ ...hitLimit ? { limit, truncated: true, nextOffset: dialogs.length } : {},
1107
+ dialogs
1108
+ });
1109
+ } else {
1110
+ output.write(`source: db.query.subjectRef
1111
+ `);
1112
+ output.write(`server: ${serverUrl}
1113
+ `);
1114
+ output.write(`subject: ${subjectRef.kind}:${subjectRef.id}${subjectRef.role ? `#${subjectRef.role}` : ""}
1115
+ `);
1116
+ if (excludeDialogIds.length) output.write(`excluded dialogs: ${excludeDialogIds.join(", ")}
1117
+ `);
1118
+ output.write(`strict: ${strict.ok ? "ok" : strict.reason}
1119
+ `);
1120
+ output.write(`total dialogs: ${dialogs.length}
1121
+ `);
1122
+ if (hitLimit) {
1123
+ output.write(
1124
+ `truncated: showing ${dialogs.length}; use --all or --limit 0 for full dump
1125
+ `
1126
+ );
1127
+ }
1128
+ for (const dialog of dialogs) {
1129
+ output.write(
1130
+ `
1131
+ ${dialog.title ?? "(untitled)"}
1132
+ id=${dialog.dialogId ?? "-"}
1133
+ status=${dialog.status ?? "-"}
1134
+ checkpoint=${dialog.checkpointStatus ?? "-"}
1135
+ artifacts=${dialog.artifactCount}
1136
+ updatedAt=${dialog.updatedAt ?? "-"}
1137
+ dbKey=${dialog.dialogKey ?? "-"}
1138
+ `
1139
+ );
1140
+ }
1141
+ }
1142
+ return strict.ok ? 0 : 1;
1143
+ } catch (error) {
1144
+ output.write(`[nolo] dialog query failed: ${toErrorMessage(error)}
1145
+ `);
1146
+ return 1;
1147
+ }
1148
+ }
1149
+ async function runDialogListCommand(args, deps = {}) {
1150
+ const env = deps.env ?? process.env;
1151
+ const output = deps.output ?? process.stdout;
1152
+ if (hasFlag(args, "--help") || hasFlag(args, "-h")) {
1153
+ printListUsage(output);
1154
+ return 0;
1155
+ }
1156
+ const authToken = resolveAuthToken(args, env);
1157
+ if (!authToken) {
1158
+ output.write("[nolo] dialog list requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
1159
+ return 1;
1160
+ }
1161
+ const userId = parseUserIdFromAuthToken(authToken);
1162
+ if (!userId) {
1163
+ output.write("[nolo] dialog list could not read userId from AUTH_TOKEN.\n");
1164
+ return 1;
1165
+ }
1166
+ const fetchImpl = deps.fetchImpl ?? fetch;
1167
+ const fallbackFetchImpl = deps.fallbackFetchImpl;
1168
+ const serverUrl = resolveServerUrl(args, env);
1169
+ const serverUrls = resolveServerCandidates(args, env, serverUrl);
1170
+ const resultLimit = resolveResultLimit(args, DEFAULT_DIALOG_LIST_LIMIT);
1171
+ const limit = resultLimit.unlimited ? UNBOUNDED_DIALOG_CAP : Math.max(1, resultLimit.limit ?? DEFAULT_DIALOG_LIST_LIMIT);
1172
+ const offset = readOffset(args);
1173
+ const spaceInput = readOption(args, "--space") ?? readOption(args, "--space-id");
1174
+ const includeScheduled = hasFlag(args, "--include-scheduled");
1175
+ try {
1176
+ let source = "user-data";
1177
+ let resolvedSpaceId = null;
1178
+ let queryFailures = [];
1179
+ let records;
1180
+ if (spaceInput) {
1181
+ source = "space";
1182
+ const result = await readSpaceDialogRecords({
1183
+ authToken,
1184
+ fallbackFetchImpl,
1185
+ fetchImpl,
1186
+ serverUrls,
1187
+ spaceInput,
1188
+ userId
1189
+ });
1190
+ resolvedSpaceId = result.spaceId;
1191
+ records = result.records;
1192
+ queryFailures = result.failures;
1193
+ } else {
1194
+ const result = await listUserRecordsFromServers({
1195
+ authToken,
1196
+ fallbackFetchImpl,
1197
+ fetchImpl,
1198
+ label: "dialog query",
1199
+ serverUrls,
1200
+ type: "dialog",
1201
+ userId
1202
+ });
1203
+ records = result.records;
1204
+ queryFailures = result.failures;
1205
+ }
1206
+ const sorted = sortDialogs(
1207
+ records.map((record) => normalizeDialogRecord(record)).filter((dialog) => dialog != null).filter((dialog) => includeScheduled || !isScheduledDialog(dialog))
1208
+ );
1209
+ const window = resultLimit.unlimited ? sorted.slice(offset, offset + UNBOUNDED_DIALOG_CAP) : sorted.slice(offset, offset + limit);
1210
+ const hitLimit = !resultLimit.unlimited && sorted.length > offset + window.length;
1211
+ const dialogs = window;
1212
+ if (hasFlag(args, "--ids-only")) {
1213
+ output.write(`${dialogs.map((dialog) => dialog.id).join("\n")}
1214
+ `);
1215
+ return 0;
1216
+ }
1217
+ if (hasFlag(args, "--jsonl")) {
1218
+ writeJsonlStream(output, dialogs);
1219
+ return 0;
1220
+ }
1221
+ if (hasFlag(args, "--json")) {
1222
+ writeJsonStream(output, {
1223
+ userId,
1224
+ ...resolvedSpaceId ? { spaceId: resolvedSpaceId } : {},
1225
+ source,
1226
+ targetServers: serverUrls,
1227
+ ...queryFailures.length ? { serverFailures: queryFailures } : {},
1228
+ total: dialogs.length,
1229
+ ...hitLimit ? {
1230
+ limit,
1231
+ offset,
1232
+ truncated: true,
1233
+ nextOffset: offset + dialogs.length
1234
+ } : {},
1235
+ dialogs
1236
+ });
1237
+ return 0;
1238
+ }
1239
+ output.write(`userId: ${userId}
1240
+ `);
1241
+ if (resolvedSpaceId) output.write(`spaceId: ${resolvedSpaceId}
1242
+ `);
1243
+ output.write(`source: ${source}
1244
+ `);
1245
+ output.write(`targetServers: ${serverUrls.join(", ")}
1246
+ `);
1247
+ if (queryFailures.length) {
1248
+ output.write(`serverFailures: ${queryFailures.length}
1249
+ `);
1250
+ }
1251
+ output.write(`total dialogs: ${dialogs.length}
1252
+ `);
1253
+ if (hitLimit) {
1254
+ output.write(
1255
+ `truncated: showing ${dialogs.length} (offset ${offset}); use --offset ${offset + dialogs.length} --limit ${limit}, or --all / --limit 0 for full dump
1256
+ `
1257
+ );
1258
+ }
1259
+ for (const dialog of dialogs) {
1260
+ output.write(
1261
+ `
1262
+ ${dialog.title}
1263
+ id=${dialog.id}
1264
+ status=${dialog.status ?? "-"}
1265
+ updatedAt=${dialog.updatedAt ?? "-"}
1266
+ dbKey=${dialog.dbKey}
1267
+ `
1268
+ );
1269
+ }
1270
+ return 0;
1271
+ } catch (error) {
1272
+ output.write(
1273
+ `[nolo] dialog list failed: ${toErrorMessage(error)}
1274
+ `
1275
+ );
1276
+ return 1;
1277
+ }
1278
+ }
1279
+ async function runDialogDeleteCommand(args, deps = {}) {
1280
+ const env = deps.env ?? process.env;
1281
+ const output = deps.output ?? process.stdout;
1282
+ if (hasFlag(args, "--help") || hasFlag(args, "-h")) {
1283
+ printDeleteUsage(output);
1284
+ return 0;
1285
+ }
1286
+ const rawDialogs = readAllPositional(args);
1287
+ if (rawDialogs.length === 0) {
1288
+ printDeleteUsage(output);
1289
+ return 1;
1290
+ }
1291
+ const authToken = resolveAuthToken(args, env);
1292
+ if (!authToken) {
1293
+ output.write("[nolo] dialog delete requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
1294
+ return 1;
1295
+ }
1296
+ const userId = parseUserIdFromAuthToken(authToken);
1297
+ if (!userId) {
1298
+ output.write("[nolo] dialog delete could not read userId from AUTH_TOKEN.\n");
1299
+ return 1;
1300
+ }
1301
+ const fetchImpl = deps.fetchImpl ?? fetch;
1302
+ const fallbackFetchImpl = deps.fallbackFetchImpl;
1303
+ const serverUrl = resolveServerUrl(args, env);
1304
+ const serverUrls = resolveDeleteServerCandidates(args, env, serverUrl);
1305
+ const shouldDelete = hasFlag(args, "--yes");
1306
+ const includeReferencedAttachments = hasFlag(args, "--include-referenced-attachments");
1307
+ const includeAttachments = hasFlag(args, "--include-attachments") || includeReferencedAttachments;
1308
+ let hasErrors = false;
1309
+ const payloads = [];
1310
+ for (const rawDialog of rawDialogs) {
1311
+ try {
1312
+ const resolved = resolveDialogInput(rawDialog, userId);
1313
+ const readResult = await readDbRecordFromServers({
1314
+ authToken,
1315
+ dbKey: resolved.dbKey,
1316
+ fallbackFetchImpl,
1317
+ fetchImpl,
1318
+ label: "dialog record",
1319
+ serverUrls
1320
+ });
1321
+ const dialog = normalizeDialogRecord(readResult.record, resolved.dbKey);
1322
+ if (!dialog) {
1323
+ throw new Error(`dialog record is unreadable: ${resolved.dbKey}`);
1324
+ }
1325
+ const attachmentPlan = includeAttachments ? await planDialogAttachmentCleanup({
1326
+ authToken,
1327
+ dialogId: resolved.dialogId,
1328
+ ownerId: resolved.ownerId,
1329
+ includeUserOwnedReferenced: includeReferencedAttachments,
1330
+ fallbackFetchImpl,
1331
+ fetchImpl,
1332
+ serverUrl: readResult.serverUrl,
1333
+ serverUrls
1334
+ }) : null;
1335
+ const attachmentDeleteResults = includeAttachments && shouldDelete && attachmentPlan ? await deleteDialogAttachmentCandidates({
1336
+ authToken,
1337
+ candidates: attachmentPlan.deleteCandidates,
1338
+ fallbackFetchImpl,
1339
+ fetchImpl,
1340
+ serverUrls
1341
+ }) : [];
1342
+ let deleteResults = [];
1343
+ if (shouldDelete) {
1344
+ deleteResults = await deleteDbRecordOnServers({
1345
+ authToken,
1346
+ dbKey: resolved.dbKey,
1347
+ fallbackFetchImpl,
1348
+ fetchImpl,
1349
+ serverUrls
1350
+ });
1351
+ }
1352
+ const failedDeletes = deleteResults.filter((result) => !result.ok);
1353
+ const failedAttachmentDeletes = attachmentDeleteResults.flatMap(
1354
+ (result) => result.deleteResults.filter((deleteResult) => !deleteResult.ok).map((deleteResult) => ({
1355
+ fileId: result.fileId,
1356
+ fileDbKey: result.fileDbKey,
1357
+ ...deleteResult
1358
+ }))
1359
+ );
1360
+ if (failedDeletes.length > 0 || failedAttachmentDeletes.length > 0) {
1361
+ hasErrors = true;
1362
+ }
1363
+ const payload = {
1364
+ dbKey: resolved.dbKey,
1365
+ dialogId: resolved.dialogId,
1366
+ title: dialog.title,
1367
+ readServerUrl: readResult.serverUrl,
1368
+ targetServers: serverUrls,
1369
+ dryRun: !shouldDelete,
1370
+ deleted: shouldDelete,
1371
+ includeAttachments,
1372
+ includeReferencedAttachments,
1373
+ ...attachmentPlan ? { attachmentPlan } : {},
1374
+ ...readResult.failures.length ? { readFailures: readResult.failures } : {},
1375
+ ...shouldDelete ? { deleteResults } : {},
1376
+ ...attachmentDeleteResults.length ? { attachmentDeleteResults } : {}
1377
+ };
1378
+ payloads.push(payload);
1379
+ if (!hasFlag(args, "--json")) {
1380
+ output.write(`dialog: ${dialog.title}
1381
+ `);
1382
+ output.write(`dbKey: ${resolved.dbKey}
1383
+ `);
1384
+ output.write(`readServer: ${readResult.serverUrl}
1385
+ `);
1386
+ output.write(`targetServers: ${serverUrls.join(", ")}
1387
+ `);
1388
+ if (attachmentPlan) {
1389
+ output.write(
1390
+ `attachments: ${attachmentPlan.deleteCandidates.length} delete candidates, ${attachmentPlan.retainedCandidates.length} retained, ${attachmentPlan.bytesToDelete} bytes planned
1391
+ `
1392
+ );
1393
+ for (const candidate of attachmentPlan.retainedCandidates) {
1394
+ output.write(`retained attachment: ${candidate.fileId} (${candidate.reason})
1395
+ `);
1396
+ }
1397
+ }
1398
+ output.write(
1399
+ shouldDelete ? failedDeletes.length > 0 ? `Deleted dialog on ${deleteResults.length - failedDeletes.length}/${deleteResults.length} servers. Failed: ${failedDeletes.map((result) => `${result.serverUrl} (${result.error})`).join(", ")}
1400
+ ` : "Deleted dialog on all target servers. Server-side delete cascades dialog messages.\n" : includeAttachments ? "Dry-run only. Add --yes to delete this dialog, its messages, and delete-candidate attachments.\n" : "Dry-run only. Add --yes to delete this dialog and its messages.\n"
1401
+ );
1402
+ if (failedAttachmentDeletes.length > 0) {
1403
+ output.write(
1404
+ `Attachment delete failures: ${failedAttachmentDeletes.map((result) => `${result.fileDbKey}@${result.serverUrl} (${result.error})`).join(", ")}
1405
+ `
1406
+ );
1407
+ }
1408
+ if (rawDialogs.length > 1) {
1409
+ output.write("\n");
1410
+ }
1411
+ }
1412
+ } catch (error) {
1413
+ hasErrors = true;
1414
+ const errorMsg = toErrorMessage(error);
1415
+ if (hasFlag(args, "--json")) {
1416
+ payloads.push({
1417
+ rawDialog,
1418
+ error: errorMsg
1419
+ });
1420
+ } else {
1421
+ output.write(`[nolo] dialog delete failed for ${rawDialog}: ${errorMsg}
1422
+ `);
1423
+ if (rawDialogs.length > 1) {
1424
+ output.write("\n");
1425
+ }
1426
+ }
1427
+ }
1428
+ }
1429
+ if (hasFlag(args, "--json")) {
1430
+ const finalPayload = rawDialogs.length === 1 ? payloads[0] : payloads;
1431
+ output.write(JSON.stringify(finalPayload, null, 2));
1432
+ output.write("\n");
1433
+ }
1434
+ return hasErrors ? 1 : 0;
1435
+ }
1436
+
1437
+ export {
1438
+ normalizeDialogRecord,
1439
+ sortDialogs,
1440
+ isScheduledDialog,
1441
+ readDialogSnapshot,
1442
+ runDialogReadCommand,
1443
+ runDialogStatusCommand,
1444
+ runDialogQueryCommand,
1445
+ runDialogListCommand,
1446
+ runDialogDeleteCommand
1447
+ };