nolo-cli 0.38.0-alpha.3 → 0.47.0-alpha.2

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 (134) hide show
  1. package/{_executeModel-SWONBJ7Z.js → _executeModel-5PG6CUWD.js} +41 -42
  2. package/{action-KMBZ3LCZ.js → action-FLLC2SIX.js} +7 -7
  3. package/{addContentAction-KQ44UT2U.js → addContentAction-SVSPUUK4.js} +6 -6
  4. package/{addDialogAgentAction-ILSDCMYL.js → addDialogAgentAction-W3JGU4F7.js} +5 -5
  5. package/{agentDeleteCommand-SMUJYI6N.js → agentDeleteCommand-SHSPQZHI.js} +25 -26
  6. package/{agentEmailCommands-YWCGZ4RO.js → agentEmailCommands-LQKO5GRW.js} +54 -55
  7. package/{agentListCommands-ULFV2XJQ.js → agentListCommands-5QTNEYMQ.js} +31 -29
  8. package/{agentMachineCommands-7YZ2TIYZ.js → agentMachineCommands-P5K454CN.js} +24 -25
  9. package/{agentPullCommand-TSWAJPS2.js → agentPullCommand-M552CYSI.js} +2 -2
  10. package/{agentRecordCommands-EVOSSHJR.js → agentRecordCommands-Z4QYCNP4.js} +50 -51
  11. package/{agentRunCommand-PO55WUIY.js → agentRunCommand-HV3Y34B5.js} +52 -53
  12. package/{agentRunControl-7MUPSYDQ.js → agentRunControl-LHXOP4IU.js} +43 -1
  13. package/{agentRuntimeLocal-Q6D3G6G7.js → agentRuntimeLocal-ZKXYFLXI.js} +20 -21
  14. package/{agentSlice-6TRUUOSX.js → agentSlice-NKFLP3RI.js} +6 -6
  15. package/{agentSuperviseCommands-MKWW3ICX.js → agentSuperviseCommands-IMRZ56RC.js} +2 -2
  16. package/{appDeleteCommands-JDBSRLTX.js → appDeleteCommands-XYGAZIJX.js} +24 -25
  17. package/{appDeployCommands-Q5H2NBKQ.js → appDeployCommands-7T5CABRB.js} +24 -25
  18. package/{appDeployStatusCommands-PSYBUIZT.js → appDeployStatusCommands-KTFQMRPZ.js} +24 -25
  19. package/{appGetCommands-IX64IUW6.js → appGetCommands-HOX2ULSV.js} +24 -25
  20. package/{appListCommands-BJZFX65H.js → appListCommands-3SLCEHND.js} +24 -25
  21. package/{authCommand-B2XRHNJH.js → authCommand-OY2E2VQK.js} +12 -12
  22. package/{authCommands-GWABTFMR.js → authCommands-SBQVTD6V.js} +5 -5
  23. package/{chatQueueReduxAdapter-N7Z5MUPU.js → chatQueueReduxAdapter-WMMBQK3Y.js} +20 -20
  24. package/chunk-25J3BB35.js +6041 -0
  25. package/{chunk-U6QQLXWI.js → chunk-2X5S4IBZ.js} +1 -1
  26. package/{chunk-MJWX4JQO.js → chunk-3EEK7T3D.js} +1 -1
  27. package/{chunk-UNHKVD2N.js → chunk-43CXXVJD.js} +1 -1
  28. package/{chunk-WRP5TTM6.js → chunk-4MXGXSYN.js} +83 -3
  29. package/{chunk-7N7XKGEQ.js → chunk-4ZNDBDWG.js} +6 -6
  30. package/{chunk-XVVNNJAA.js → chunk-5BPZLBFB.js} +20 -51
  31. package/{chunk-MWGCZ4CS.js → chunk-5PPFYHU2.js} +3 -3
  32. package/{chunk-W445DPVT.js → chunk-5QRCPERU.js} +1 -1
  33. package/{chunk-GKHV4UH5.js → chunk-5UOBIU5G.js} +31 -3
  34. package/{chunk-BMB563Y6.js → chunk-6BYAXNH5.js} +3 -3
  35. package/{chunk-SMPAUSX5.js → chunk-6FGXGFAH.js} +2 -2
  36. package/{chunk-46VPXYIV.js → chunk-6LYUN76O.js} +5 -5
  37. package/{chunk-FTM4KUOZ.js → chunk-7XTC3KRG.js} +1 -1
  38. package/{chunk-IMHO5LC6.js → chunk-7XZ5GXSN.js} +1 -1
  39. package/{chunk-E2OQ5N2F.js → chunk-AEXP2UZT.js} +341 -16
  40. package/{chunk-MZZZYUZS.js → chunk-AV2CELZZ.js} +37 -12
  41. package/{chunk-JI2TIPLP.js → chunk-AYXSUBVC.js} +1 -1
  42. package/{chunk-J6WH4PYZ.js → chunk-CIF4X6ZM.js} +1 -1
  43. package/{chunk-GZRMWK5R.js → chunk-DQLYEGP7.js} +2 -2
  44. package/{chunk-GUYMR3JL.js → chunk-E2QH2AYX.js} +69 -3
  45. package/{chunk-B6H5XCT2.js → chunk-EMEUU5IY.js} +3 -3
  46. package/{chunk-X6EN3KJX.js → chunk-ENYDQKOB.js} +319 -71
  47. package/{chunk-RCFIB45Q.js → chunk-EVBFYPDC.js} +2 -2
  48. package/{chunk-PV734VZX.js → chunk-EXLOROHG.js} +1 -1
  49. package/{chunk-WRN7L5CS.js → chunk-FA4SY4F5.js} +1 -1
  50. package/{chunk-4WVNHL3V.js → chunk-FAWK6DBF.js} +157 -51
  51. package/{chunk-IFS5CUEH.js → chunk-FJHLA6SX.js} +1 -1
  52. package/{chunk-T2BZICLK.js → chunk-G46DB6KG.js} +49 -6
  53. package/{chunk-FGLKRJDI.js → chunk-GK74OOFT.js} +2 -2
  54. package/{chunk-LM6IYQ3F.js → chunk-GLKOYSRU.js} +8 -1
  55. package/{chunk-JIADXJYU.js → chunk-H2G6JXTR.js} +1 -1
  56. package/{chunk-IKGHZMK2.js → chunk-H2JQB6B6.js} +12 -12
  57. package/{chunk-MGIHZ5CJ.js → chunk-HAPCUPEO.js} +2 -2
  58. package/{chunk-LD6Y6RJY.js → chunk-HGDOIDQ4.js} +2 -2
  59. package/{chunk-NZLQ7B5P.js → chunk-HOM6NILS.js} +3 -3
  60. package/{chunk-IZNJDUJ4.js → chunk-I4JISVWK.js} +1 -1
  61. package/{chunk-N4XRDM26.js → chunk-IA3A5373.js} +2 -2
  62. package/{chunk-Y5MMUI3L.js → chunk-IWUPQUWA.js} +2 -2
  63. package/{chunk-L7SMDIL6.js → chunk-JEGPB5H2.js} +3 -3
  64. package/{chunk-GEPHJJW4.js → chunk-L7NG2M6H.js} +1 -1
  65. package/{chunk-XQES6LXQ.js → chunk-LFLWZX76.js} +2 -2
  66. package/{chunk-IIOHYLIG.js → chunk-LGUQHYAL.js} +1 -1
  67. package/{chunk-4AWH4LQA.js → chunk-LYGNQHUW.js} +3 -1
  68. package/{db-3H3JECGY.js → chunk-M5PVFLD4.js} +11 -158
  69. package/{chunk-WN5AJG5I.js → chunk-MKZRKDQM.js} +1 -1
  70. package/{chunk-VOXNBPLB.js → chunk-MUIJYGYW.js} +649 -41
  71. package/{chunk-CYAC5WXX.js → chunk-MWT2BBCH.js} +213 -45
  72. package/{chunk-V5GA74HI.js → chunk-MZXZJVVD.js} +20 -39
  73. package/{chunk-ZBB3MZR3.js → chunk-OLNC7AWK.js} +7 -4
  74. package/{chunk-J5NMOM35.js → chunk-OYNDYVSE.js} +1 -1
  75. package/{chunk-C6ELZQ7H.js → chunk-OZVGA4SY.js} +1 -1
  76. package/{chunk-K4KIFRIN.js → chunk-Q24S4NDF.js} +1 -1
  77. package/{chunk-NRROOY22.js → chunk-Q6DMA2OM.js} +271 -130
  78. package/{chunk-2WKUUY2E.js → chunk-SVEUG45B.js} +5 -3
  79. package/{chunk-IZCHPD7T.js → chunk-TNPCQNGQ.js} +11 -6
  80. package/{chunk-4DMPISV6.js → chunk-URBGEE42.js} +2 -2
  81. package/{chunk-2KO5QQFV.js → chunk-V2IPBG5U.js} +1 -1
  82. package/{chunk-B6YYACBT.js → chunk-WPFNAEIW.js} +1 -1
  83. package/{chunk-23KKIMD5.js → chunk-WVGEBWA6.js} +4 -4
  84. package/{chunk-KU6CDTZ5.js → chunk-XMI3APSU.js} +61 -49
  85. package/{chunk-64KIQZA2.js → chunk-XO3G35OV.js} +1 -1
  86. package/{chunk-UWGWUOVN.js → chunk-YNOGNUBC.js} +108 -47
  87. package/{chunk-XT73C4VH.js → chunk-Z5NW3O7V.js} +1 -1
  88. package/{codingSkills-H6N5EKSX.js → codingSkills-BYQI6EPT.js} +2 -2
  89. package/{createAgentAutomationAction-U57ZMPMS.js → createAgentAutomationAction-ENDNA3Q4.js} +21 -21
  90. package/{createDialogAction-MAJLBNK4.js → createDialogAction-2KNX6S2D.js} +23 -23
  91. package/{createPageAction-4EX7HU6G.js → createPageAction-SNBCYPK6.js} +21 -21
  92. package/db-VQSAOWAO.js +162 -0
  93. package/{dbSlice-PIQGICNM.js → dbSlice-XWUM4QOF.js} +5 -5
  94. package/deleteFile-NPZ64DFN.js +1 -1
  95. package/{dialogCommands-4MHZXEIS.js → dialogCommands-6E5P35DG.js} +28 -26
  96. package/{dialogSlice-AL3UJLOJ.js → dialogSlice-RTPOD6EW.js} +20 -20
  97. package/{docCreateCommands-GDYFEK67.js → docCreateCommands-JWY25UFB.js} +23 -24
  98. package/{docDeleteCommands-WIE5CXED.js → docDeleteCommands-BPJOCSX4.js} +24 -25
  99. package/{docReadCommands-LTOOPJVC.js → docReadCommands-BSEZCYTQ.js} +23 -24
  100. package/{docStore-35B5VAFF.js → docStore-TYHVLU7G.js} +22 -22
  101. package/{docUpdateCommands-TZGAGXSG.js → docUpdateCommands-S2IE2VV4.js} +23 -24
  102. package/{fetchMessages-CUEFN4GQ.js → fetchMessages-KZQVBXKY.js} +3 -3
  103. package/{getPricing-P3E2WRIH.js → getPricing-X3HXP6VQ.js} +3 -3
  104. package/{handleSendMessageAction-PXX2R5JS.js → handleSendMessageAction-QYXDQXGH.js} +21 -21
  105. package/index.js +69 -69
  106. package/levelLazyShim-GZBKODGI.js +7 -0
  107. package/{localDialogRead-P7CHFMIC.js → localDialogRead-NQ33HBSI.js} +2 -2
  108. package/{localRuntimeAuthority-S77B5QVB.js → localRuntimeAuthority-KQDAE64E.js} +4 -4
  109. package/{localRuntimeDb-N3H3HQ7G.js → localRuntimeDb-PF7CFKDL.js} +2 -2
  110. package/{machineCommands-VCPPY23X.js → machineCommands-QCE4KLGR.js} +48 -49
  111. package/{machineWsRunDispatch-A4C727GL.js → machineWsRunDispatch-FBRMGU5D.js} +48 -49
  112. package/{models-L7S2EKPM.js → models-7LWATQFH.js} +2 -2
  113. package/package.json +1 -1
  114. package/{read-6C2XD3YZ.js → read-DQQ75VI3.js} +2 -2
  115. package/{readDocTool-Y7AB365O.js → readDocTool-HCQQFAZD.js} +1 -1
  116. package/{readlineWorkspace-BIBIM6DG.js → readlineWorkspace-2TACWKMN.js} +164 -78
  117. package/{removeDialogAgentAction-KG5WMJRZ.js → removeDialogAgentAction-DNONRKST.js} +7 -7
  118. package/{runAgentClientLoop-RKDXMIZW.js → runAgentClientLoop-GBLDVBT5.js} +39 -39
  119. package/{runtimeDoctorCommands-HT4O2PXL.js → runtimeDoctorCommands-JKTTN723.js} +4 -4
  120. package/serverStoreFactory-YMXDF4NI.js +20 -0
  121. package/{setDialogExtraReferencesAction-O2NLXMSM.js → setDialogExtraReferencesAction-ERHUPT3F.js} +6 -6
  122. package/{setPrimaryDialogAgentAction-FYYUY7PB.js → setPrimaryDialogAgentAction-6C2HYNEC.js} +7 -7
  123. package/{settingSlice-GPLI6E3M.js → settingSlice-YVRJFKQX.js} +6 -6
  124. package/{spaceCommands-4FMO3SNP.js → spaceCommands-XOLPJMRK.js} +23 -24
  125. package/{spaceSlice-2W4GJ2OE.js → spaceSlice-OQPAGQDP.js} +21 -21
  126. package/{streamAgentChatTurn-FS52LDQP.js → streamAgentChatTurn-SN5XJJ7U.js} +91 -49
  127. package/{switchDialogAgentAction-GH5P6Q3Z.js → switchDialogAgentAction-HP57XYFP.js} +5 -5
  128. package/{tools-3J5CKEE7.js → tools-Y65Y3CI4.js} +32 -32
  129. package/{tuiSummaryLlmCaller-SHRB4RWM.js → tuiSummaryLlmCaller-NBTWT57U.js} +25 -14
  130. package/{updateDialogTitleAction-5MGPA3OO.js → updateDialogTitleAction-OAOP7CCE.js} +24 -23
  131. package/chunk-4APLX2RT.js +0 -1514
  132. package/chunk-P66M7LSQ.js +0 -58
  133. package/{chunk-6WD3OOJS.js → chunk-UV6VISQJ.js} +0 -0
  134. package/{tableCommands-PQUJ55AS.js → tableCommands-P2TXJ3CF.js} +1 -1
package/chunk-4APLX2RT.js DELETED
@@ -1,1514 +0,0 @@
1
- import {
2
- buildSpaceLookup,
3
- getSpaceContentKeys
4
- } from "./chunk-ID4G2MAR.js";
5
- import {
6
- deleteDbRecordOnServers,
7
- listUserRecordsFromServers,
8
- readDbRecordFromServers,
9
- readLiveDbRecordAfterTombstoneMerge
10
- } from "./chunk-K4KIFRIN.js";
11
- import {
12
- buildDialogAttachmentPlan,
13
- extractFileContentIds
14
- } from "./chunk-JIADXJYU.js";
15
- import {
16
- isLevelLockError
17
- } from "./chunk-URMS4XY2.js";
18
- import {
19
- toErrorMessage
20
- } from "./chunk-HNMXYYJR.js";
21
- import {
22
- parseUserIdFromAuthToken,
23
- readOption,
24
- resolveAuthToken,
25
- resolveDeleteServerCandidates,
26
- resolveServerCandidates,
27
- resolveServerUrl
28
- } from "./chunk-A7GB5UGH.js";
29
- import {
30
- parsePositiveFiniteNumberOrFallback
31
- } from "./chunk-Y5GCAMGP.js";
32
- import {
33
- asRecordOrEmpty
34
- } from "./chunk-KX6YBIHG.js";
35
- import {
36
- asNonEmptyStringArray,
37
- asTrimmedNonEmptyStringArray
38
- } from "./chunk-I42VC5KR.js";
39
- import {
40
- isRecord
41
- } from "./chunk-KUG52IAP.js";
42
- import {
43
- isLevelNotFoundError
44
- } from "./chunk-OW765XBU.js";
45
- import {
46
- asTrimmedString
47
- } from "./chunk-3EUW3WEO.js";
48
- import {
49
- DEFAULT_LOCAL_API_ORIGIN
50
- } from "./chunk-4SN6J65J.js";
51
- import {
52
- asOptionalTrimmedString
53
- } from "./chunk-G3SUCT4W.js";
54
-
55
- // packages/cli/dialogAttachmentCleanup.ts
56
- function asText(value) {
57
- return asOptionalTrimmedString(value) ?? null;
58
- }
59
- async function readDialogMessages(args) {
60
- const response = await args.fetchImpl(`${args.serverUrl}/rpc/getConvMsgs`, {
61
- method: "POST",
62
- headers: {
63
- Authorization: `Bearer ${args.authToken}`,
64
- "Content-Type": "application/json"
65
- },
66
- body: JSON.stringify({ dialogId: args.dialogId, limit: 1e4 })
67
- });
68
- if (!response.ok) {
69
- throw new Error(`read dialog messages failed on ${args.serverUrl}: HTTP ${response.status}`);
70
- }
71
- const payload = await response.json();
72
- return Array.isArray(payload) ? payload : [];
73
- }
74
- async function planDialogAttachmentCleanup(args) {
75
- const messages = await readDialogMessages({
76
- authToken: args.authToken,
77
- dialogId: args.dialogId,
78
- fetchImpl: args.fetchImpl,
79
- serverUrl: args.serverUrl
80
- });
81
- const fileIds = [...new Set(messages.flatMap((message) => extractFileContentIds(message)))];
82
- const metadataByFileId = {};
83
- const metadataReadFailures = [];
84
- for (const fileId of fileIds) {
85
- try {
86
- const result = await readDbRecordFromServers({
87
- authToken: args.authToken,
88
- dbKey: `file-id-${fileId}`,
89
- fallbackFetchImpl: args.fallbackFetchImpl,
90
- fetchImpl: args.fetchImpl,
91
- serverUrls: args.serverUrls,
92
- label: `file metadata index ${fileId}`
93
- });
94
- const mainKey = asText(result.record?.mainKey);
95
- if (!mainKey) throw new Error(`file-id index missing mainKey`);
96
- const metadata = await readDbRecordFromServers({
97
- authToken: args.authToken,
98
- dbKey: mainKey,
99
- fallbackFetchImpl: args.fallbackFetchImpl,
100
- fetchImpl: args.fetchImpl,
101
- serverUrls: args.serverUrls,
102
- label: `file metadata ${fileId}`
103
- });
104
- metadataByFileId[fileId] = {
105
- ...metadata.record,
106
- dbKey: asText(metadata.record?.dbKey) ?? mainKey
107
- };
108
- } catch (error) {
109
- const fallbackKey = args.ownerId && !fileId.startsWith("file-") ? `file-${args.ownerId}-${fileId}` : null;
110
- if (fallbackKey) {
111
- try {
112
- const metadata = await readDbRecordFromServers({
113
- authToken: args.authToken,
114
- dbKey: fallbackKey,
115
- fallbackFetchImpl: args.fallbackFetchImpl,
116
- fetchImpl: args.fetchImpl,
117
- serverUrls: args.serverUrls,
118
- label: `file metadata ${fileId}`
119
- });
120
- metadataByFileId[fileId] = {
121
- ...metadata.record,
122
- dbKey: asText(metadata.record?.dbKey) ?? fallbackKey
123
- };
124
- continue;
125
- } catch {
126
- }
127
- }
128
- metadataReadFailures.push({
129
- fileId,
130
- error: toErrorMessage(error)
131
- });
132
- }
133
- }
134
- return buildDialogAttachmentPlan({
135
- dialogId: args.dialogId,
136
- ownerId: args.ownerId,
137
- includeUserOwnedReferenced: args.includeUserOwnedReferenced,
138
- messages,
139
- metadataByFileId,
140
- metadataReadFailures
141
- });
142
- }
143
- async function deleteDialogAttachmentCandidates(args) {
144
- const results = [];
145
- for (const candidate of args.candidates) {
146
- if (candidate.status !== "delete" || !candidate.fileDbKey) continue;
147
- const deleteResults = await deleteDbRecordOnServers({
148
- authToken: args.authToken,
149
- dbKey: candidate.fileDbKey,
150
- fallbackFetchImpl: args.fallbackFetchImpl,
151
- fetchImpl: args.fetchImpl,
152
- serverUrls: args.serverUrls
153
- });
154
- results.push({
155
- fileId: candidate.fileId,
156
- fileDbKey: candidate.fileDbKey,
157
- deleteResults
158
- });
159
- }
160
- return results;
161
- }
162
-
163
- // packages/core/positiveIntegerOrFallback.ts
164
- function parsePositiveIntegerOrFallback(value, fallback) {
165
- const parsed = Number(value);
166
- return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
167
- }
168
-
169
- // packages/cli/dialogCommands.ts
170
- var DIALOG_ID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
171
- var DIALOG_PATH_RE = /^\/(?:space\/([^/]+)\/)?dialog-(.+)-([0-9A-HJKMNP-TV-Z]{26})\/?$/i;
172
- var DEFAULT_DIALOG_LIST_LIMIT = 50;
173
- var DEFAULT_DIALOG_QUERY_LIMIT = 50;
174
- var UNBOUNDED_DIALOG_CAP = 1e5;
175
- var VALUE_FLAGS = /* @__PURE__ */ new Set([
176
- "--limit",
177
- "--offset",
178
- "--exclude-dialog",
179
- "--row-dbkey",
180
- "--server",
181
- "--server-url",
182
- "--space",
183
- "--space-id",
184
- "--subject-id",
185
- "--subject-kind",
186
- "--subject-role",
187
- "--token",
188
- "--machine-key",
189
- "--user"
190
- ]);
191
- function hasFlag(args, flag) {
192
- return args.includes(flag);
193
- }
194
- function readFirstPositional(args) {
195
- for (let index = 0; index < args.length; index += 1) {
196
- const value = args[index];
197
- if (VALUE_FLAGS.has(value)) {
198
- index += 1;
199
- continue;
200
- }
201
- if (!value.startsWith("-")) return value;
202
- }
203
- return void 0;
204
- }
205
- function readAllPositional(args) {
206
- const positionals = [];
207
- for (let index = 0; index < args.length; index += 1) {
208
- const value = args[index];
209
- if (VALUE_FLAGS.has(value)) {
210
- index += 1;
211
- continue;
212
- }
213
- if (!value.startsWith("-")) {
214
- positionals.push(value);
215
- }
216
- }
217
- return positionals;
218
- }
219
- function resolveResultLimit(args, fallback) {
220
- if (hasFlag(args, "--all")) {
221
- return { limit: null, unlimited: true, fromDefault: false };
222
- }
223
- const raw = readOption(args, "--limit");
224
- if (!raw) {
225
- return { limit: fallback, unlimited: false, fromDefault: true };
226
- }
227
- const parsed = Number(raw);
228
- if (!Number.isFinite(parsed) || parsed < 0) {
229
- return { limit: fallback, unlimited: false, fromDefault: true };
230
- }
231
- if (parsed === 0) {
232
- return { limit: null, unlimited: true, fromDefault: false };
233
- }
234
- return { limit: Math.floor(parsed), unlimited: false, fromDefault: false };
235
- }
236
- function readOffset(args) {
237
- const raw = readOption(args, "--offset");
238
- if (!raw) return 0;
239
- return Math.floor(parsePositiveFiniteNumberOrFallback(raw, 0));
240
- }
241
- function writeJsonStream(output, value) {
242
- if (Array.isArray(value)) {
243
- output.write("[\n");
244
- for (let i = 0; i < value.length; i++) {
245
- const pretty = JSON.stringify(value[i], null, 2);
246
- const indented = pretty.split("\n").map((line) => ` ${line}`).join("\n");
247
- output.write(i === 0 ? indented : `,
248
- ${indented}`);
249
- }
250
- output.write("\n]\n");
251
- return;
252
- }
253
- if (isRecord(value)) {
254
- const record = value;
255
- const largeArrayKey = ["dialogs", "items", "messages"].find((key) => Array.isArray(record[key]));
256
- if (largeArrayKey && Array.isArray(record[largeArrayKey]) && record[largeArrayKey].length > 32) {
257
- const items = record[largeArrayKey];
258
- output.write("{\n");
259
- let wrote = false;
260
- for (const [key, fieldValue] of Object.entries(record)) {
261
- if (key === largeArrayKey) continue;
262
- const pretty = JSON.stringify(fieldValue, null, 2).split("\n").map((line, idx) => idx === 0 ? line : ` ${line}`).join("\n");
263
- output.write(`${wrote ? ",\n" : ""} ${JSON.stringify(key)}: ${pretty}`);
264
- wrote = true;
265
- }
266
- output.write(`${wrote ? ",\n" : ""} ${JSON.stringify(largeArrayKey)}: [
267
- `);
268
- for (let i = 0; i < items.length; i++) {
269
- const pretty = JSON.stringify(items[i], null, 2);
270
- const indented = pretty.split("\n").map((line) => ` ${line}`).join("\n");
271
- output.write(i === 0 ? indented : `,
272
- ${indented}`);
273
- }
274
- output.write("\n ]\n}\n");
275
- return;
276
- }
277
- }
278
- output.write(`${JSON.stringify(value, null, 2)}
279
- `);
280
- }
281
- function writeJsonlStream(output, items) {
282
- for (const item of items) {
283
- output.write(`${JSON.stringify(item)}
284
- `);
285
- }
286
- }
287
- function getDialogIdFromKey(dbKey) {
288
- const index = dbKey.lastIndexOf("-");
289
- return index >= 0 ? dbKey.slice(index + 1) : dbKey;
290
- }
291
- function resolveDialogInput(rawInput, userId) {
292
- const raw = rawInput.trim();
293
- if (raw.startsWith("http://") || raw.startsWith("https://")) {
294
- const url = new URL(raw);
295
- const match = url.pathname.match(DIALOG_PATH_RE);
296
- if (!match) {
297
- throw new Error(`Unsupported dialog URL path: ${url.pathname}`);
298
- }
299
- const [, spaceId, ownerId, dialogId] = match;
300
- return {
301
- dbKey: `dialog-${ownerId}-${dialogId}`,
302
- dialogId,
303
- ownerId,
304
- spaceId: spaceId ? decodeURIComponent(spaceId) : null
305
- };
306
- }
307
- if (raw.startsWith("dialog-")) {
308
- const dialogId = getDialogIdFromKey(raw);
309
- return {
310
- dbKey: raw,
311
- dialogId,
312
- ownerId: raw.slice("dialog-".length, Math.max("dialog-".length, raw.length - dialogId.length - 1)),
313
- spaceId: null
314
- };
315
- }
316
- if (!DIALOG_ID_RE.test(raw)) {
317
- throw new Error(`Unsupported dialog id: ${raw}`);
318
- }
319
- return {
320
- dbKey: `dialog-${userId}-${raw}`,
321
- dialogId: raw,
322
- ownerId: userId,
323
- spaceId: null
324
- };
325
- }
326
- function normalizeDialogRecord(record, fallbackDbKey) {
327
- const dbKey = asOptionalTrimmedString(record?.dbKey) ?? fallbackDbKey ?? "";
328
- const id = asOptionalTrimmedString(record?.id) ?? (dbKey ? getDialogIdFromKey(dbKey) : "");
329
- if (!dbKey || !id) return null;
330
- return {
331
- id,
332
- dbKey,
333
- title: asOptionalTrimmedString(record?.title) ?? asOptionalTrimmedString(record?.taskLabel) ?? "(untitled)",
334
- status: typeof record?.status === "string" ? record.status : null,
335
- 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,
336
- createdAt: typeof record?.createdAt === "string" || typeof record?.createdAt === "number" ? record.createdAt : typeof record?.created === "string" || typeof record?.created === "number" ? record.created : null,
337
- spaceId: typeof record?.spaceId === "string" && record.spaceId.trim() ? record.spaceId : null,
338
- triggerType: typeof record?.triggerType === "string" ? record.triggerType : null,
339
- primaryAgentKey: typeof record?.primaryAgentKey === "string" && record.primaryAgentKey.trim() ? record.primaryAgentKey : null,
340
- cybots: Array.isArray(record?.cybots) ? record.cybots.filter((agent) => typeof agent === "string") : []
341
- };
342
- }
343
- function sortDialogs(dialogs) {
344
- return dialogs.sort((a, b) => {
345
- const ta = a.updatedAt ?? a.createdAt ?? 0;
346
- const tb = b.updatedAt ?? b.createdAt ?? 0;
347
- const left = typeof ta === "number" ? ta : Date.parse(String(ta)) || 0;
348
- const right = typeof tb === "number" ? tb : Date.parse(String(tb)) || 0;
349
- return right - left;
350
- });
351
- }
352
- function isScheduledDialog(record) {
353
- return record.triggerType === "automation_run" || record.triggerType === "scheduled_run" || Boolean(record.parentAutomationKey) || Boolean(record.parentTaskKey);
354
- }
355
- function printListUsage(output) {
356
- output.write(`Usage:
357
- nolo dialog list [--space <spaceId|spaceUrl>] [--limit ${DEFAULT_DIALOG_LIST_LIMIT}] [--offset <n>] [--all] [--json] [--jsonl] [--ids-only]
358
-
359
- Options:
360
- --space <space> List current user's dialogs attached to one space.
361
- --limit <n> Maximum dialogs to return. Default: ${DEFAULT_DIALOG_LIST_LIMIT}. Use 0 or --all for full dump.
362
- --offset <n> Skip first n dialogs after sort/filter (paging).
363
- --all Full dump (same as --limit 0). Prefer --jsonl for large results.
364
- --include-scheduled Include scheduled automation run dialogs.
365
- --json Print machine-readable JSON object.
366
- --jsonl Stream one dialog JSON object per line (lowest memory).
367
- --ids-only Print only dialog ids.
368
- --server <url> Override NOLO_SERVER/BASE_URL.
369
- --token <jwt> Override AUTH_TOKEN.
370
-
371
- Lists merge global server candidates and ignore newer tombstones.
372
- Human default is a short summary; use --json/--jsonl for automation.
373
- `);
374
- }
375
- function printDeleteUsage(output) {
376
- output.write(`Usage:
377
- nolo dialog delete <dialogId|dialogKey|dialogUrl...> [--yes] [--include-attachments] [--include-referenced-attachments] [--json]
378
-
379
- Options:
380
- --yes Actually delete. Without this, the command is a dry-run.
381
- --include-attachments Also delete files explicitly owned by this dialog/messages.
382
- --include-referenced-attachments
383
- Also delete same-account user-owned files referenced by this dialog.
384
- --json Print machine-readable JSON.
385
- --server <url> Prefer this server and include it in global deletion.
386
- --token <jwt> Override AUTH_TOKEN.
387
-
388
- Deletes are global across the selected/profile server plus known Nolo cluster peers.
389
- Attachment cleanup is conservative by default. Use --include-referenced-attachments only
390
- when you intentionally want to remove user-owned files referenced by the dialog too.
391
- `);
392
- }
393
- function printReadUsage(output) {
394
- output.write(`Usage:
395
- nolo dialog read <dialogId|dialogKey|dialogUrl> [limit]
396
-
397
- Options:
398
- --server <url> Prefer this server when reading by raw dialog id.
399
- --token <jwt> Override AUTH_TOKEN.
400
- --user <userId> Override dialog owner for raw dialog ids.
401
-
402
- Reads dialog metadata and messages as JSON.
403
- `);
404
- }
405
- function printStatusUsage(output) {
406
- output.write(`Usage:
407
- nolo dialog status <dialogId|dialogKey|dialogUrl>
408
-
409
- Options:
410
- --server <url> Prefer this server when reading by raw dialog id.
411
- --token <jwt> Override AUTH_TOKEN.
412
- --user <userId> Override dialog owner for raw dialog ids.
413
-
414
- Prints compact dialog run status and next-step hints.
415
- `);
416
- }
417
- function printQueryUsage(output) {
418
- output.write(`Usage:
419
- nolo dialog query --subject-kind <kind> --subject-id <id> [--subject-role <role>]
420
- nolo dialog query --row-dbkey <rowDbKey>
421
-
422
- Options:
423
- --row-dbkey <dbKey> Convenience target for table-row task subject refs.
424
- --subject-kind <kind> Generic subject ref kind. Defaults to table-row with --row-dbkey.
425
- --subject-id <id> Generic subject ref id. Defaults to --row-dbkey.
426
- --subject-role <role> Optional role included in the query payload.
427
- --limit <n> Query limit. Default: ${DEFAULT_DIALOG_QUERY_LIMIT}. Use 0 or --all for full dump.
428
- --all Full dump (same as --limit 0). Prefer --jsonl for large results.
429
- --exclude-dialog <id> Exclude one dialog id or dbKey from evidence results.
430
- --allow-empty Exit 0 when no dialogs match.
431
- --json Print machine-readable JSON object.
432
- --jsonl Stream one dialog JSON object per line.
433
- --server <url> Target server. Defaults to NOLO_SERVER/BASE_URL/profile.
434
- --token <jwt> Override AUTH_TOKEN.
435
-
436
- Reads dialog evidence by dialog.subjectRefs through the server query endpoint.
437
- It is read-only and does not write task rows, row-side evidence caches, or retired orchestration metadata.
438
- `);
439
- }
440
- function isHelpArg(value) {
441
- return value === "-h" || value === "--help";
442
- }
443
- function readDialogLimitArg(args, fallback) {
444
- const explicit = readOption(args, "--limit");
445
- const positional = args.find(
446
- (value, index) => index > 0 && /^\d+$/.test(value) && args[index - 1] !== "--limit"
447
- );
448
- const raw = explicit ?? positional;
449
- if (!raw) return fallback;
450
- return parsePositiveIntegerOrFallback(raw, fallback);
451
- }
452
- function readDialogOwnerId(args, env, authToken) {
453
- return readOption(args, "--user") ?? env.USER_ID ?? parseUserIdFromAuthToken(authToken) ?? "";
454
- }
455
- function resolveDialogReadTarget(args, env, authToken) {
456
- const rawInput = readFirstPositional(args);
457
- if (!rawInput) return null;
458
- const preferredServer = readOption(args, "--server") ?? readOption(args, "--server-url");
459
- const ownerFallback = readDialogOwnerId(args, env, authToken);
460
- const raw = rawInput.trim();
461
- if (raw.startsWith("http://") || raw.startsWith("https://")) {
462
- const url = new URL(raw);
463
- const match = url.pathname.match(DIALOG_PATH_RE);
464
- if (!match) throw new Error(`Unsupported dialog URL path: ${url.pathname}`);
465
- const [, spaceId, ownerId, dialogId] = match;
466
- const base = preferredServer ?? env.READ_DIALOG_BASE ?? url.origin;
467
- return {
468
- base,
469
- dialogId,
470
- dialogKey: `dialog-${ownerId}-${dialogId}`,
471
- userId: ownerId,
472
- spaceId: spaceId ? decodeURIComponent(spaceId) : void 0
473
- };
474
- }
475
- if (raw.startsWith("dialog-")) {
476
- const dialogId = getDialogIdFromKey(raw);
477
- const ownerId = raw.slice("dialog-".length, Math.max("dialog-".length, raw.length - dialogId.length - 1));
478
- return {
479
- base: preferredServer ?? env.READ_DIALOG_BASE ?? resolveServerUrl(args, env),
480
- dialogId,
481
- dialogKey: raw,
482
- userId: ownerId || ownerFallback
483
- };
484
- }
485
- if (!DIALOG_ID_RE.test(raw)) {
486
- throw new Error(`Unsupported dialog id: ${raw}`);
487
- }
488
- if (!ownerFallback) {
489
- throw new Error("raw dialog ids require an auth token userId or --user");
490
- }
491
- return {
492
- base: preferredServer ?? env.READ_DIALOG_BASE ?? resolveServerUrl(args, env),
493
- dialogId: raw,
494
- dialogKey: `dialog-${ownerFallback}-${raw}`,
495
- userId: ownerFallback
496
- };
497
- }
498
- function toToolName(value) {
499
- return asTrimmedString(value);
500
- }
501
- function countByName(values) {
502
- return values.reduce((acc, value) => {
503
- acc[value] = (acc[value] ?? 0) + 1;
504
- return acc;
505
- }, {});
506
- }
507
- function uniq(values) {
508
- return [...new Set(values.filter(Boolean))];
509
- }
510
- function parseJsonObject(raw) {
511
- if (typeof raw !== "string" || !raw.trim()) return null;
512
- try {
513
- const parsed = JSON.parse(raw);
514
- return parsed && typeof parsed === "object" ? parsed : null;
515
- } catch {
516
- return null;
517
- }
518
- }
519
- function deriveWrittenFiles(toolMessages) {
520
- const writeToolNames = /* @__PURE__ */ new Set(["applyEdit", "applyLineEdits", "writeFile", "createDoc", "updateDoc"]);
521
- const files = [];
522
- for (const message of toolMessages) {
523
- const toolName = toToolName(message?.toolName ?? message?.name);
524
- if (!writeToolNames.has(toolName)) continue;
525
- const payload = message?.toolPayload ?? {};
526
- const content = parseJsonObject(message?.content);
527
- for (const candidate of [payload?.input?.filePath, payload?.response?.filePath, content?.filePath]) {
528
- const normalized = asTrimmedString(candidate);
529
- if (normalized) files.push(normalized);
530
- }
531
- }
532
- return uniq(files);
533
- }
534
- function deriveToolErrors(toolMessages) {
535
- const errors = [];
536
- for (const message of toolMessages) {
537
- const toolName = toToolName(message?.toolName ?? message?.name);
538
- const payload = message?.toolPayload ?? {};
539
- const content = parseJsonObject(message?.content);
540
- if (payload?.status === "failed" || content?.ok === false || content?.applied === false || content?.success === false) {
541
- errors.push(toolName || "unknown-tool");
542
- }
543
- }
544
- return uniq(errors);
545
- }
546
- async function readDialogOverHttp(args) {
547
- const authHeaders = {
548
- Authorization: `Bearer ${args.authToken}`,
549
- "Content-Type": "application/json"
550
- };
551
- const buildGetConvMsgsBody = () => JSON.stringify({ dialogId: args.dialogId, dialogKey: args.dialogKey, limit: args.limit });
552
- const readViaBridge = async () => {
553
- const bridgeRes = await args.fetchImpl(`${args.base}/api/dialog-read`, {
554
- method: "POST",
555
- headers: authHeaders,
556
- body: JSON.stringify({
557
- dialogKey: args.dialogKey,
558
- dialogId: args.dialogId,
559
- limit: args.limit
560
- })
561
- });
562
- if (!bridgeRes.ok) {
563
- throw Object.assign(new Error(`dialog read bridge failed: HTTP ${bridgeRes.status}`), {
564
- status: bridgeRes.status,
565
- base: args.base
566
- });
567
- }
568
- const payload = await bridgeRes.json();
569
- if (!payload?.ok) {
570
- throw Object.assign(new Error(`dialog read bridge failed: ${payload?.error ?? "unknown error"}`), {
571
- status: 500,
572
- base: args.base
573
- });
574
- }
575
- return {
576
- meta: payload.meta,
577
- msgs: payload.msgs,
578
- source: "http"
579
- };
580
- };
581
- if (args.messagesOnly) {
582
- const msgsOnlyRes = await args.fetchImpl(`${args.base}/rpc/getConvMsgs`, {
583
- method: "POST",
584
- headers: authHeaders,
585
- body: buildGetConvMsgsBody()
586
- });
587
- if (!msgsOnlyRes.ok) {
588
- if (msgsOnlyRes.status === 401 || msgsOnlyRes.status === 403) return readViaBridge();
589
- throw Object.assign(new Error(`read dialog messages failed: HTTP ${msgsOnlyRes.status}`), {
590
- status: msgsOnlyRes.status,
591
- base: args.base
592
- });
593
- }
594
- return { meta: null, msgs: await msgsOnlyRes.json(), source: "http" };
595
- }
596
- const metaRes = await args.fetchImpl(
597
- `${args.base}/api/v1/db/read/${encodeURIComponent(args.dialogKey)}`,
598
- { headers: { Authorization: `Bearer ${args.authToken}` } }
599
- );
600
- if (!metaRes.ok) {
601
- if (metaRes.status === 401 || metaRes.status === 403) return readViaBridge();
602
- throw Object.assign(new Error(`read dialog meta failed: HTTP ${metaRes.status}`), {
603
- status: metaRes.status,
604
- base: args.base
605
- });
606
- }
607
- const meta = await metaRes.json();
608
- const msgsRes = await args.fetchImpl(`${args.base}/rpc/getConvMsgs`, {
609
- method: "POST",
610
- headers: authHeaders,
611
- body: buildGetConvMsgsBody()
612
- });
613
- if (!msgsRes.ok) {
614
- if (msgsRes.status === 401 || msgsRes.status === 403) return readViaBridge();
615
- throw Object.assign(new Error(`read dialog messages failed: HTTP ${msgsRes.status}`), {
616
- status: msgsRes.status,
617
- base: args.base
618
- });
619
- }
620
- return {
621
- meta,
622
- msgs: await msgsRes.json(),
623
- source: "http"
624
- };
625
- }
626
- async function tryHttpDialogCandidates(args) {
627
- const attempts = [];
628
- for (const base of args.bases) {
629
- try {
630
- const result = await readDialogOverHttp({ ...args, base });
631
- attempts.push({ base, ok: true });
632
- return { ...result, resolvedBase: base, attempts };
633
- } catch (error) {
634
- attempts.push({
635
- base,
636
- ok: false,
637
- status: typeof error === "object" && error !== null && "status" in error ? Number(error.status) : void 0,
638
- message: toErrorMessage(error)
639
- });
640
- }
641
- }
642
- throw Object.assign(new Error("All HTTP dialog reads failed"), { attempts });
643
- }
644
- async function readDialogFromLocalDb(dialogKey, dialogId, limit, readLocalDialog) {
645
- const reader = readLocalDialog ?? (await import("./localDialogRead-P7CHFMIC.js")).readDialogFromLocalDb;
646
- const result = await reader({ dialogKey, dialogId, limit });
647
- return {
648
- ...result,
649
- source: "local-db-fallback"
650
- };
651
- }
652
- async function readDialogSnapshot(args) {
653
- const candidateBases = [
654
- ...resolveServerCandidates({ NOLO_SERVER: args.base }, args.base),
655
- DEFAULT_LOCAL_API_ORIGIN
656
- ].filter((value, index, all) => all.indexOf(value) === index);
657
- try {
658
- const local = await readDialogFromLocalDb(
659
- args.dialogKey,
660
- args.dialogId,
661
- args.limit,
662
- args.readLocalDialog
663
- );
664
- const localMeta = local.meta;
665
- const localKey = localMeta && typeof localMeta === "object" ? String(localMeta.dbKey ?? localMeta.contentKey ?? "") : "";
666
- if (!localMeta || localKey && localKey !== args.dialogKey) {
667
- const miss = new Error("local dialog not found");
668
- miss.code = "LEVEL_NOT_FOUND";
669
- throw miss;
670
- }
671
- return {
672
- ...local,
673
- resolvedBase: args.base,
674
- attempts: [],
675
- candidateBases
676
- };
677
- } catch (error) {
678
- const localDbUnavailable = isLevelLockError(error) || typeof error === "object" && error.code === "LEVEL_DATABASE_NOT_OPEN";
679
- if (!isLevelNotFoundError(error) && !localDbUnavailable) throw error;
680
- }
681
- const result = await tryHttpDialogCandidates({
682
- bases: candidateBases,
683
- dialogKey: args.dialogKey,
684
- dialogId: args.dialogId,
685
- limit: args.limit,
686
- authToken: args.authToken,
687
- fetchImpl: args.fetchImpl,
688
- messagesOnly: args.messagesOnly
689
- });
690
- return { ...result, candidateBases };
691
- }
692
- function compact(value, max = 180) {
693
- const text = asTrimmedString(value);
694
- if (!text) return "";
695
- return text.length > max ? `${text.slice(0, max - 3)}...` : text;
696
- }
697
- function normalizeNonEmptyString(value) {
698
- return asOptionalTrimmedString(value) ?? null;
699
- }
700
- function normalizeSubjectKind(kind) {
701
- return kind === "tableRow" ? "table-row" : kind;
702
- }
703
- function normalizeDialogSubjectRef(value) {
704
- if (!isRecord(value)) return null;
705
- const kindRaw = asOptionalTrimmedString(value.kind);
706
- const kind = kindRaw ? normalizeSubjectKind(kindRaw) : "";
707
- const id = asOptionalTrimmedString(value.id) ?? "";
708
- if (!kind || !id) return null;
709
- const role = asOptionalTrimmedString(value.role) ?? "";
710
- return {
711
- kind,
712
- id,
713
- ...role ? { role } : {}
714
- };
715
- }
716
- function extractDialogSubjectRefs(dialog) {
717
- if (!isRecord(dialog) || !Array.isArray(dialog.subjectRefs)) return [];
718
- return dialog.subjectRefs.map(normalizeDialogSubjectRef).filter((ref) => Boolean(ref));
719
- }
720
- function dialogMatchesSubjectRef(dialog, target) {
721
- const normalizedTarget = normalizeDialogSubjectRef(target);
722
- if (!normalizedTarget) return false;
723
- return extractDialogSubjectRefs(dialog).some(
724
- (ref) => ref.kind === normalizedTarget.kind && ref.id === normalizedTarget.id
725
- );
726
- }
727
- function hasArtifactEvidence(value) {
728
- if (Array.isArray(value)) return value.length > 0;
729
- if (isRecord(value)) return Object.keys(value).length > 0;
730
- return Boolean(value);
731
- }
732
- function artifactEvidenceCount(value) {
733
- if (Array.isArray(value)) return value.length;
734
- if (isRecord(value)) return Object.keys(value).length > 0 ? 1 : 0;
735
- return value ? 1 : 0;
736
- }
737
- function summarizeDialogEvidence(dialog, target) {
738
- const dialogKey = asOptionalTrimmedString(dialog?.dbKey) ?? "";
739
- const checkpoint = asRecordOrEmpty(dialog?.runtimeCheckpoint);
740
- const matchedSubjectRefs = extractDialogSubjectRefs(dialog).filter(
741
- (ref) => ref.kind === normalizeSubjectKind(target.kind) && ref.id === target.id
742
- );
743
- const lastToolNames = asNonEmptyStringArray(checkpoint.lastToolNames);
744
- return {
745
- dialogId: asOptionalTrimmedString(dialog?.dialogId) ?? asOptionalTrimmedString(dialog?.id) ?? (dialogKey ? getDialogIdFromKey(dialogKey) : null),
746
- dialogKey: dialogKey || null,
747
- title: asOptionalTrimmedString(dialog?.title) ?? null,
748
- status: asOptionalTrimmedString(dialog?.status) ?? null,
749
- checkpointStatus: asOptionalTrimmedString(checkpoint.status) ?? null,
750
- updatedAt: typeof dialog?.updatedAt === "string" || typeof dialog?.updatedAt === "number" ? dialog.updatedAt : null,
751
- hasArtifacts: hasArtifactEvidence(dialog?.artifacts),
752
- artifactCount: artifactEvidenceCount(dialog?.artifacts),
753
- subjectRefs: matchedSubjectRefs,
754
- lastToolNames
755
- };
756
- }
757
- function verifyDialogSubjectQuery(dialogs, target, allowEmpty) {
758
- const unmatchedDialogs = dialogs.filter((dialog) => !dialogMatchesSubjectRef(dialog, target)).map((dialog) => ({
759
- dialogId: asOptionalTrimmedString(dialog?.dialogId) ?? asOptionalTrimmedString(dialog?.id) ?? (typeof dialog?.dbKey === "string" ? getDialogIdFromKey(dialog.dbKey) : null),
760
- dialogKey: asOptionalTrimmedString(dialog?.dbKey) ?? null,
761
- subjectRefs: extractDialogSubjectRefs(dialog)
762
- }));
763
- const reason = unmatchedDialogs.length > 0 ? "unmatched_results" : dialogs.length === 0 && !allowEmpty ? "empty_results" : "ok";
764
- return {
765
- ok: reason === "ok",
766
- reason,
767
- target,
768
- returnedCount: dialogs.length,
769
- matchedCount: dialogs.length - unmatchedDialogs.length,
770
- unmatchedCount: unmatchedDialogs.length,
771
- unmatchedDialogs
772
- };
773
- }
774
- function normalizeExcludedDialogIds(value) {
775
- const rawValues = Array.isArray(value) ? value : [value];
776
- const ids = /* @__PURE__ */ new Set();
777
- for (const rawValue of rawValues) {
778
- if (typeof rawValue !== "string") continue;
779
- const trimmed = rawValue.trim();
780
- if (!trimmed) continue;
781
- ids.add(trimmed);
782
- if (trimmed.startsWith("dialog-")) {
783
- ids.add(getDialogIdFromKey(trimmed));
784
- }
785
- }
786
- return [...ids];
787
- }
788
- function getDialogIdentityValues(dialog) {
789
- if (!isRecord(dialog)) return [];
790
- const values = /* @__PURE__ */ new Set();
791
- for (const rawValue of [dialog.dialogId, dialog.id, dialog.dbKey]) {
792
- if (typeof rawValue !== "string") continue;
793
- const trimmed = rawValue.trim();
794
- if (!trimmed) continue;
795
- values.add(trimmed);
796
- if (trimmed.startsWith("dialog-")) {
797
- values.add(getDialogIdFromKey(trimmed));
798
- }
799
- }
800
- return [...values];
801
- }
802
- function excludeDialogsById(dialogs, excludeDialogIds) {
803
- if (excludeDialogIds.length === 0) return dialogs;
804
- const excluded = new Set(excludeDialogIds);
805
- return dialogs.filter(
806
- (dialog) => getDialogIdentityValues(dialog).every((value) => !excluded.has(value))
807
- );
808
- }
809
- async function queryDialogEvidenceBySubjectRef(args) {
810
- const res = await args.fetchImpl(
811
- `${args.serverUrl}/api/v1/db/query/${encodeURIComponent(args.userId)}`,
812
- {
813
- method: "POST",
814
- headers: {
815
- Authorization: `Bearer ${args.authToken}`,
816
- "Content-Type": "application/json"
817
- },
818
- body: JSON.stringify({
819
- type: "dialog",
820
- limit: args.limit,
821
- subjectRef: args.subjectRef
822
- })
823
- }
824
- );
825
- const data = await res.json().catch(() => ({}));
826
- if (!res.ok) {
827
- throw new Error(`dialog subject query failed: HTTP ${res.status} ${JSON.stringify(data)}`);
828
- }
829
- return Array.isArray(data?.data?.data) ? data.data.data : Array.isArray(data?.data) ? data.data : [];
830
- }
831
- function renderCompactDialogStatus(snapshot) {
832
- const checkpoint = snapshot.runtimeCheckpoint ?? {};
833
- const checkpointStatus = typeof checkpoint.status === "string" ? checkpoint.status : null;
834
- const status = snapshot.status ?? checkpointStatus ?? "unknown";
835
- 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";
836
- const tools = (Array.isArray(snapshot.toolsUsed) ? asNonEmptyStringArray(snapshot.toolsUsed) : asNonEmptyStringArray(checkpoint.lastToolNames)).slice(0, 8);
837
- const artifactFiles = snapshot.artifacts && typeof snapshot.artifacts === "object" ? snapshot.artifacts.changedFiles ?? snapshot.artifacts.writtenFiles ?? snapshot.artifacts.files : void 0;
838
- const files = (Array.isArray(snapshot.writtenFiles) && snapshot.writtenFiles.length ? asNonEmptyStringArray(snapshot.writtenFiles) : asNonEmptyStringArray(artifactFiles)).slice(0, 8);
839
- const subjectRefs = Array.isArray(snapshot.subjectRefs) ? snapshot.subjectRefs.map((ref) => {
840
- const kind = asTrimmedString(ref?.kind);
841
- const id = asTrimmedString(ref?.id);
842
- if (!kind || !id) return "";
843
- const rolePart = asOptionalTrimmedString(ref?.role);
844
- const role = rolePart ? `#${rolePart}` : "";
845
- return `${kind}:${id}${role}`;
846
- }).filter(Boolean).slice(0, 8) : [];
847
- const runtimeContext = asRecordOrEmpty(snapshot.runtimeContext);
848
- const runtimeFieldLines = [
849
- ["triggerType", snapshot.triggerType],
850
- ["executionMode", snapshot.executionMode],
851
- ["threadKind", snapshot.threadKind],
852
- ["presentationIntent", snapshot.presentationIntent],
853
- ["parentThreadId", snapshot.parentThreadId],
854
- ["rootThreadId", snapshot.rootThreadId],
855
- ["runtimeEntrypoint", runtimeContext.entrypoint ?? checkpoint.runtimeContext?.entrypoint],
856
- ["parentWakeStatus", snapshot.parentWake?.terminalStatus],
857
- ["parentWakeAt", snapshot.parentWake?.terminalNotifiedAt]
858
- ].map(([label, value]) => {
859
- const normalized = typeof value === "number" ? String(value) : normalizeNonEmptyString(value);
860
- return normalized ? `${label}: ${normalized}` : "";
861
- }).filter(Boolean);
862
- const toolErrors = asNonEmptyStringArray(snapshot.toolErrors).slice(0, 8);
863
- const checkpointUpdatedAt = typeof checkpoint.updatedAt === "number" || typeof checkpoint.updatedAt === "string" ? Date.parse(String(checkpoint.updatedAt)) : NaN;
864
- const activeHealth = state !== "active" ? "" : !snapshot.runtimeCheckpoint ? "no-checkpoint" : !Number.isFinite(checkpointUpdatedAt) ? "checkpoint-without-updatedAt" : Date.now() - checkpointUpdatedAt > 5 * 6e4 ? "stale-running" : "running";
865
- const errorMessage = compact(checkpoint.errorMessage ?? snapshot.errorMessage);
866
- const lines = [
867
- `dialog: ${snapshot.dialogId}`,
868
- ...snapshot.base ? [`base: ${snapshot.base}`] : [],
869
- ...snapshot.title ? [`title: ${snapshot.title}`] : [],
870
- ...snapshot.parentDialogId ? [`parentDialogId: ${snapshot.parentDialogId}`] : [],
871
- ...snapshot.rootDialogId ? [`rootDialogId: ${snapshot.rootDialogId}`] : [],
872
- ...runtimeFieldLines,
873
- `status: ${status}`,
874
- ...checkpointStatus ? [`checkpoint: ${checkpointStatus}`] : [],
875
- `state: ${state}`,
876
- ...activeHealth ? [`activeHealth: ${activeHealth}`] : [],
877
- ...typeof snapshot.durationMs === "number" ? [`durationMs: ${snapshot.durationMs}`] : [],
878
- ...snapshot.updatedAt ? [`updatedAt: ${snapshot.updatedAt}`] : [],
879
- ...snapshot.finishedAt ? [`finishedAt: ${snapshot.finishedAt}`] : [],
880
- ...compact(checkpoint.lastUserInput) ? [`lastUserInput: ${compact(checkpoint.lastUserInput)}`] : [],
881
- ...compact(checkpoint.lastAssistantText) ? [`lastAssistantText: ${compact(checkpoint.lastAssistantText)}`] : [],
882
- ...errorMessage ? [`error: ${errorMessage}`] : [],
883
- ...tools.length ? [`tools: ${tools.join(", ")}`] : [],
884
- ...files.length ? [`files: ${files.join(", ")}`] : [],
885
- ...subjectRefs.length ? [`subjects: ${subjectRefs.join(", ")}`] : [],
886
- ...toolErrors.length ? [`toolErrors: ${toolErrors.join(", ")}`] : [],
887
- "",
888
- "next:",
889
- `- read full dialog: nolo dialog read ${snapshot.dialogId} 120`
890
- ];
891
- if (state === "active") lines.push(`- poll again: nolo dialog status ${snapshot.dialogId}`);
892
- else if (state === "failed") lines.push(`- inspect failure and rerun/continue with: nolo agent run <agent> --continue ${snapshot.dialogId} --msg "..."`);
893
- else if (state === "done") lines.push("- use artifacts/files above for review, handoff, or alpha integration.");
894
- else lines.push("- inspect meta/messages before deciding whether to continue or rerun.");
895
- return `${lines.join("\n")}
896
- `;
897
- }
898
- async function readSpaceDialogRecords(args) {
899
- const { spaceId, spaceKey } = buildSpaceLookup(args.spaceInput);
900
- const spaceRead = await readLiveDbRecordAfterTombstoneMerge({
901
- authToken: args.authToken,
902
- dbKey: spaceKey,
903
- fallbackFetchImpl: args.fallbackFetchImpl,
904
- fetchImpl: args.fetchImpl,
905
- label: "space record",
906
- serverUrls: args.serverUrls
907
- });
908
- const contentKeys = [...getSpaceContentKeys(spaceRead.record)].filter((key) => key.startsWith(`dialog-${args.userId}-`));
909
- const contentKeySet = new Set(contentKeys);
910
- const dialogResult = await listUserRecordsFromServers({
911
- authToken: args.authToken,
912
- fallbackFetchImpl: args.fallbackFetchImpl,
913
- fetchImpl: args.fetchImpl,
914
- label: "dialog query",
915
- serverUrls: args.serverUrls,
916
- type: "dialog",
917
- userId: args.userId
918
- });
919
- const records = dialogResult.records.filter(
920
- (record) => typeof record?.dbKey === "string" && contentKeySet.has(record.dbKey)
921
- );
922
- const failures = [...spaceRead.failures, ...dialogResult.failures];
923
- return { spaceId, records, failures };
924
- }
925
- var MAX_ATTEMPT_LINES = 5;
926
- function formatDialogReadFailure(error) {
927
- const message = toErrorMessage(error);
928
- const attempts = typeof error === "object" && error !== null && Array.isArray(error.attempts) ? error.attempts : [];
929
- const lines = [`[nolo] dialog read failed: ${message}`];
930
- if (attempts.length > 0) {
931
- const seen = /* @__PURE__ */ new Set();
932
- const deduped = [];
933
- for (const attempt of attempts) {
934
- const key = `${attempt.base}|${attempt.status ?? ""}|${attempt.message ?? ""}`;
935
- if (seen.has(key)) continue;
936
- seen.add(key);
937
- deduped.push(attempt);
938
- if (deduped.length >= MAX_ATTEMPT_LINES) break;
939
- }
940
- lines.push(" attempts:");
941
- for (const attempt of deduped) {
942
- const status = attempt.status != null ? ` HTTP ${attempt.status}` : "";
943
- const detail = attempt.message ? ` \u2014 ${attempt.message}` : "";
944
- lines.push(` - ${attempt.base}${status}${detail}`);
945
- }
946
- if (attempts.length > deduped.length) {
947
- lines.push(` \u2026 and ${attempts.length - deduped.length} more`);
948
- }
949
- }
950
- const allNotFound = attempts.length > 0 && attempts.every((attempt) => attempt.status === 404);
951
- const hasConnRefusedOrTimeout = attempts.some((attempt) => {
952
- const text = `${attempt.status ?? ""} ${attempt.message ?? ""}`.toLowerCase();
953
- return text.includes("connection refused") || text.includes("econnrefused") || text.includes("enotfound") || text.includes("getaddrinfo") || text.includes("timeout") || text.includes("timed out") || text.includes("fetch failed") || // bun fetch 对连接失败的真实文案(无 refused/timeout 关键词)。
954
- text.includes("unable to connect");
955
- });
956
- if (allNotFound) {
957
- lines.push(
958
- " next-step: \u76EE\u6807 dialog \u53EF\u80FD\u4E0D\u5728\u8FD9\u4E9B server \u4E0A\uFF1B\u672C\u5730 run \u7684\u5BF9\u8BDD\u5728\u672C\u5730\u5E93\uFF08<cwd>/data/leveldb\uFF09\uFF0C\u8BF7\u7528\u5B58\u50A8\u65B9\u5BF9\u5E94\u73AF\u5883/\u670D\u52A1\u8BFB\u53D6\uFF0C\u8FD0\u884C\u4E2D run \u53EF\u7528 `nolo agent status <runId|pid>` \u6216 dialog \u7684 status \u6A21\u5F0F\u67E5\u6458\u8981\u3002"
959
- );
960
- } else if (hasConnRefusedOrTimeout) {
961
- lines.push(
962
- " next-step: \u5B58\u5728\u8FDE\u63A5\u62D2\u7EDD/\u8D85\u65F6\uFF0C\u8BF7\u68C0\u67E5 NOLO_SERVER/--server \u6307\u5411\u7684 server \u662F\u5426\u53EF\u8FBE\u3001\u662F\u5426\u5728\u8FD0\u884C\u3002"
963
- );
964
- }
965
- return lines.join("\n");
966
- }
967
- async function runDialogReadCommand(args, deps = {}) {
968
- const env = deps.env ?? process.env;
969
- const output = deps.output ?? process.stdout;
970
- if (isHelpArg(args[0])) {
971
- printReadUsage(output);
972
- return 0;
973
- }
974
- const authToken = resolveAuthToken(args, env);
975
- if (!authToken) {
976
- output.write("[nolo] dialog read requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
977
- return 1;
978
- }
979
- let target;
980
- try {
981
- target = resolveDialogReadTarget(args, env, authToken);
982
- } catch (error) {
983
- output.write(`${formatDialogReadFailure(error)}
984
- `);
985
- return 1;
986
- }
987
- if (!target) {
988
- printReadUsage(output);
989
- return 1;
990
- }
991
- try {
992
- const limit = readDialogLimitArg(args, 0);
993
- const read = await readDialogSnapshot({
994
- authToken,
995
- base: target.base,
996
- dialogId: target.dialogId,
997
- dialogKey: target.dialogKey,
998
- fetchImpl: deps.fetchImpl ?? fetch,
999
- limit
1000
- });
1001
- const orderedMsgs = Array.isArray(read.msgs) ? [...read.msgs].reverse() : read.msgs;
1002
- const lastAssistantMessage = Array.isArray(orderedMsgs) ? [...orderedMsgs].reverse().find((message) => message?.role === "assistant" || message?.authorRole === "assistant") : null;
1003
- const toolMessages = Array.isArray(orderedMsgs) ? orderedMsgs.filter((message) => message?.role === "tool" || message?.authorRole === "tool") : [];
1004
- const toolNamesFromMessages = toolMessages.map((message) => toToolName(message?.toolName ?? message?.name)).filter(Boolean);
1005
- const toolsUsed = Array.isArray(read.meta?.toolsUsed) && read.meta.toolsUsed.length > 0 ? read.meta.toolsUsed.map((tool) => toToolName(tool)).filter(Boolean) : uniq(toolNamesFromMessages);
1006
- const writtenFiles = Array.isArray(read.meta?.writtenFiles) && read.meta.writtenFiles.length > 0 ? uniq(asTrimmedNonEmptyStringArray(read.meta.writtenFiles)) : deriveWrittenFiles(toolMessages);
1007
- const toolErrors = Array.isArray(read.meta?.toolErrors) && read.meta.toolErrors.length > 0 ? uniq(asTrimmedNonEmptyStringArray(read.meta.toolErrors)) : deriveToolErrors(toolMessages);
1008
- output.write(JSON.stringify({
1009
- source: read.source,
1010
- base: read.resolvedBase,
1011
- triedBases: read.candidateBases,
1012
- httpAttempts: read.attempts,
1013
- spaceId: target.spaceId,
1014
- dialogId: target.dialogId,
1015
- dialogKey: target.dialogKey,
1016
- userId: target.userId,
1017
- title: read.meta?.title ?? null,
1018
- cybots: Array.isArray(read.meta?.cybots) ? read.meta.cybots : [],
1019
- category: read.meta?.category ?? null,
1020
- inheritedFromDialogKey: read.meta?.inheritedFromDialogKey ?? null,
1021
- inheritedFromDialogTitle: read.meta?.inheritedFromDialogTitle ?? null,
1022
- parentDialogId: read.meta?.parentDialogId ?? null,
1023
- rootDialogId: read.meta?.rootDialogId ?? null,
1024
- triggerType: read.meta?.triggerType ?? null,
1025
- executionMode: read.meta?.executionMode ?? null,
1026
- threadKind: read.meta?.threadKind ?? null,
1027
- presentationIntent: read.meta?.presentationIntent ?? null,
1028
- parentThreadId: read.meta?.parentThreadId ?? null,
1029
- rootThreadId: read.meta?.rootThreadId ?? null,
1030
- runtimeBinding: read.meta?.runtimeBinding ?? null,
1031
- runtimeContext: read.meta?.runtimeContext ?? null,
1032
- parentWake: read.meta?.parentWake ?? null,
1033
- subjectRefs: Array.isArray(read.meta?.subjectRefs) ? read.meta.subjectRefs : [],
1034
- status: read.meta?.status,
1035
- errorMessage: read.meta?.errorMessage ?? null,
1036
- runtimeCheckpoint: read.meta?.runtimeCheckpoint ?? null,
1037
- durationMs: read.meta?.durationMs,
1038
- finishedAt: read.meta?.finishedAt,
1039
- createdAt: read.meta?.createdAt,
1040
- updatedAt: read.meta?.updatedAt,
1041
- artifacts: read.meta?.artifacts ?? null,
1042
- writtenFiles,
1043
- toolsUsed,
1044
- toolErrors,
1045
- toolSummary: {
1046
- metaToolsCount: toolsUsed.length,
1047
- metaToolsUnique: [...new Set(toolsUsed)],
1048
- toolMessageCount: toolMessages.length,
1049
- toolNamesFromMessages: [...new Set(toolNamesFromMessages)],
1050
- toolMessageCountsByName: countByName(toolNamesFromMessages)
1051
- },
1052
- agentReply: read.meta?.agentReply ?? null,
1053
- messagesCount: Array.isArray(orderedMsgs) ? orderedMsgs.length : 0,
1054
- lastAssistantMessage,
1055
- messages: orderedMsgs
1056
- }, null, 2));
1057
- output.write("\n");
1058
- return 0;
1059
- } catch (error) {
1060
- output.write(`${formatDialogReadFailure(error)}
1061
- `);
1062
- return 1;
1063
- }
1064
- }
1065
- async function runDialogStatusCommand(args, deps = {}) {
1066
- const env = deps.env ?? process.env;
1067
- const output = deps.output ?? process.stdout;
1068
- if (isHelpArg(args[0])) {
1069
- printStatusUsage(output);
1070
- return 0;
1071
- }
1072
- const authToken = resolveAuthToken(args, env);
1073
- if (!authToken) {
1074
- output.write("[nolo] dialog status requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
1075
- return 1;
1076
- }
1077
- let target;
1078
- try {
1079
- target = resolveDialogReadTarget(args, env, authToken);
1080
- } catch (error) {
1081
- output.write(`[nolo] dialog status failed: ${toErrorMessage(error)}
1082
- `);
1083
- return 1;
1084
- }
1085
- if (!target) {
1086
- printStatusUsage(output);
1087
- return 1;
1088
- }
1089
- try {
1090
- const read = await readDialogSnapshot({
1091
- authToken,
1092
- base: target.base,
1093
- dialogId: target.dialogId,
1094
- dialogKey: target.dialogKey,
1095
- fetchImpl: deps.fetchImpl ?? fetch,
1096
- limit: 1
1097
- });
1098
- output.write(renderCompactDialogStatus({
1099
- ...read.meta ?? {},
1100
- dialogId: target.dialogId,
1101
- dialogKey: target.dialogKey,
1102
- base: read.resolvedBase
1103
- }));
1104
- return 0;
1105
- } catch (error) {
1106
- output.write(`[nolo] dialog status failed: ${toErrorMessage(error)}
1107
- `);
1108
- return 1;
1109
- }
1110
- }
1111
- async function runDialogQueryCommand(args, deps = {}) {
1112
- const env = deps.env ?? process.env;
1113
- const output = deps.output ?? process.stdout;
1114
- if (hasFlag(args, "--help") || hasFlag(args, "-h")) {
1115
- printQueryUsage(output);
1116
- return 0;
1117
- }
1118
- const authToken = resolveAuthToken(args, env);
1119
- if (!authToken) {
1120
- output.write("[nolo] dialog query requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
1121
- return 1;
1122
- }
1123
- const userId = parseUserIdFromAuthToken(authToken);
1124
- if (!userId) {
1125
- output.write("[nolo] dialog query could not read userId from AUTH_TOKEN.\n");
1126
- return 1;
1127
- }
1128
- const rowDbKey = readOption(args, "--row-dbkey") ?? env.TASK_ROW_DBKEY;
1129
- const subjectKind = readOption(args, "--subject-kind") ?? (rowDbKey ? "table-row" : "");
1130
- const subjectId = readOption(args, "--subject-id") ?? rowDbKey ?? "";
1131
- const subjectRole = readOption(args, "--subject-role") ?? (rowDbKey ? "task" : "");
1132
- if (!subjectKind || !subjectId) {
1133
- printQueryUsage(output);
1134
- return 1;
1135
- }
1136
- const subjectRef = {
1137
- kind: normalizeSubjectKind(subjectKind),
1138
- id: subjectId,
1139
- ...subjectRole ? { role: subjectRole } : {}
1140
- };
1141
- const serverUrl = resolveServerUrl(args, env);
1142
- const resultLimit = resolveResultLimit(args, DEFAULT_DIALOG_QUERY_LIMIT);
1143
- const limit = resultLimit.unlimited ? UNBOUNDED_DIALOG_CAP : Math.max(1, resultLimit.limit ?? DEFAULT_DIALOG_QUERY_LIMIT);
1144
- const fetchImpl = deps.fetchImpl ?? fetch;
1145
- const excludeDialogIds = normalizeExcludedDialogIds(readOption(args, "--exclude-dialog"));
1146
- try {
1147
- const rawRecords = await queryDialogEvidenceBySubjectRef({
1148
- authToken,
1149
- fetchImpl,
1150
- limit,
1151
- serverUrl,
1152
- subjectRef,
1153
- userId
1154
- });
1155
- const records = excludeDialogsById(rawRecords, excludeDialogIds);
1156
- const strict = verifyDialogSubjectQuery(records, subjectRef, hasFlag(args, "--allow-empty"));
1157
- const allDialogs = records.filter((record) => dialogMatchesSubjectRef(record, subjectRef)).map((record) => summarizeDialogEvidence(record, subjectRef));
1158
- const hitLimit = !resultLimit.unlimited && allDialogs.length > limit;
1159
- const dialogs = hitLimit ? allDialogs.slice(0, limit) : allDialogs;
1160
- if (hasFlag(args, "--jsonl")) {
1161
- writeJsonlStream(output, dialogs);
1162
- } else if (hasFlag(args, "--json")) {
1163
- writeJsonStream(output, {
1164
- source: "db.query.subjectRef",
1165
- readOnly: true,
1166
- server: serverUrl,
1167
- userId,
1168
- ...rowDbKey ? { rowDbKey } : {},
1169
- target: subjectRef,
1170
- ...excludeDialogIds.length ? { excludedDialogIds: excludeDialogIds } : {},
1171
- strict,
1172
- total: dialogs.length,
1173
- ...hitLimit ? { limit, truncated: true, nextOffset: dialogs.length } : {},
1174
- dialogs
1175
- });
1176
- } else {
1177
- output.write(`source: db.query.subjectRef
1178
- `);
1179
- output.write(`server: ${serverUrl}
1180
- `);
1181
- output.write(`subject: ${subjectRef.kind}:${subjectRef.id}${subjectRef.role ? `#${subjectRef.role}` : ""}
1182
- `);
1183
- if (excludeDialogIds.length) output.write(`excluded dialogs: ${excludeDialogIds.join(", ")}
1184
- `);
1185
- output.write(`strict: ${strict.ok ? "ok" : strict.reason}
1186
- `);
1187
- output.write(`total dialogs: ${dialogs.length}
1188
- `);
1189
- if (hitLimit) {
1190
- output.write(
1191
- `truncated: showing ${dialogs.length}; use --all or --limit 0 for full dump
1192
- `
1193
- );
1194
- }
1195
- for (const dialog of dialogs) {
1196
- output.write(
1197
- `
1198
- ${dialog.title ?? "(untitled)"}
1199
- id=${dialog.dialogId ?? "-"}
1200
- status=${dialog.status ?? "-"}
1201
- checkpoint=${dialog.checkpointStatus ?? "-"}
1202
- artifacts=${dialog.artifactCount}
1203
- updatedAt=${dialog.updatedAt ?? "-"}
1204
- dbKey=${dialog.dialogKey ?? "-"}
1205
- `
1206
- );
1207
- }
1208
- }
1209
- return strict.ok ? 0 : 1;
1210
- } catch (error) {
1211
- output.write(`[nolo] dialog query failed: ${toErrorMessage(error)}
1212
- `);
1213
- return 1;
1214
- }
1215
- }
1216
- async function runDialogListCommand(args, deps = {}) {
1217
- const env = deps.env ?? process.env;
1218
- const output = deps.output ?? process.stdout;
1219
- if (hasFlag(args, "--help") || hasFlag(args, "-h")) {
1220
- printListUsage(output);
1221
- return 0;
1222
- }
1223
- const authToken = resolveAuthToken(args, env);
1224
- if (!authToken) {
1225
- output.write("[nolo] dialog list requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
1226
- return 1;
1227
- }
1228
- const userId = parseUserIdFromAuthToken(authToken);
1229
- if (!userId) {
1230
- output.write("[nolo] dialog list could not read userId from AUTH_TOKEN.\n");
1231
- return 1;
1232
- }
1233
- const fetchImpl = deps.fetchImpl ?? fetch;
1234
- const fallbackFetchImpl = deps.fallbackFetchImpl;
1235
- const serverUrl = resolveServerUrl(args, env);
1236
- const serverUrls = resolveServerCandidates(args, env, serverUrl);
1237
- const resultLimit = resolveResultLimit(args, DEFAULT_DIALOG_LIST_LIMIT);
1238
- const limit = resultLimit.unlimited ? UNBOUNDED_DIALOG_CAP : Math.max(1, resultLimit.limit ?? DEFAULT_DIALOG_LIST_LIMIT);
1239
- const offset = readOffset(args);
1240
- const spaceInput = readOption(args, "--space") ?? readOption(args, "--space-id");
1241
- const includeScheduled = hasFlag(args, "--include-scheduled");
1242
- try {
1243
- let source = "user-data";
1244
- let resolvedSpaceId = null;
1245
- let queryFailures = [];
1246
- let records;
1247
- if (spaceInput) {
1248
- source = "space";
1249
- const result = await readSpaceDialogRecords({
1250
- authToken,
1251
- fallbackFetchImpl,
1252
- fetchImpl,
1253
- serverUrls,
1254
- spaceInput,
1255
- userId
1256
- });
1257
- resolvedSpaceId = result.spaceId;
1258
- records = result.records;
1259
- queryFailures = result.failures;
1260
- } else {
1261
- const result = await listUserRecordsFromServers({
1262
- authToken,
1263
- fallbackFetchImpl,
1264
- fetchImpl,
1265
- label: "dialog query",
1266
- serverUrls,
1267
- type: "dialog",
1268
- userId
1269
- });
1270
- records = result.records;
1271
- queryFailures = result.failures;
1272
- }
1273
- const sorted = sortDialogs(
1274
- records.map((record) => normalizeDialogRecord(record)).filter((dialog) => dialog != null).filter((dialog) => includeScheduled || !isScheduledDialog(dialog))
1275
- );
1276
- const window = resultLimit.unlimited ? sorted.slice(offset, offset + UNBOUNDED_DIALOG_CAP) : sorted.slice(offset, offset + limit);
1277
- const hitLimit = !resultLimit.unlimited && sorted.length > offset + window.length;
1278
- const dialogs = window;
1279
- if (hasFlag(args, "--ids-only")) {
1280
- output.write(`${dialogs.map((dialog) => dialog.id).join("\n")}
1281
- `);
1282
- return 0;
1283
- }
1284
- if (hasFlag(args, "--jsonl")) {
1285
- writeJsonlStream(output, dialogs);
1286
- return 0;
1287
- }
1288
- if (hasFlag(args, "--json")) {
1289
- writeJsonStream(output, {
1290
- userId,
1291
- ...resolvedSpaceId ? { spaceId: resolvedSpaceId } : {},
1292
- source,
1293
- targetServers: serverUrls,
1294
- ...queryFailures.length ? { serverFailures: queryFailures } : {},
1295
- total: dialogs.length,
1296
- ...hitLimit ? {
1297
- limit,
1298
- offset,
1299
- truncated: true,
1300
- nextOffset: offset + dialogs.length
1301
- } : {},
1302
- dialogs
1303
- });
1304
- return 0;
1305
- }
1306
- output.write(`userId: ${userId}
1307
- `);
1308
- if (resolvedSpaceId) output.write(`spaceId: ${resolvedSpaceId}
1309
- `);
1310
- output.write(`source: ${source}
1311
- `);
1312
- output.write(`targetServers: ${serverUrls.join(", ")}
1313
- `);
1314
- if (queryFailures.length) {
1315
- output.write(`serverFailures: ${queryFailures.length}
1316
- `);
1317
- }
1318
- output.write(`total dialogs: ${dialogs.length}
1319
- `);
1320
- if (hitLimit) {
1321
- output.write(
1322
- `truncated: showing ${dialogs.length} (offset ${offset}); use --offset ${offset + dialogs.length} --limit ${limit}, or --all / --limit 0 for full dump
1323
- `
1324
- );
1325
- }
1326
- for (const dialog of dialogs) {
1327
- output.write(
1328
- `
1329
- ${dialog.title}
1330
- id=${dialog.id}
1331
- status=${dialog.status ?? "-"}
1332
- updatedAt=${dialog.updatedAt ?? "-"}
1333
- dbKey=${dialog.dbKey}
1334
- `
1335
- );
1336
- }
1337
- return 0;
1338
- } catch (error) {
1339
- output.write(
1340
- `[nolo] dialog list failed: ${toErrorMessage(error)}
1341
- `
1342
- );
1343
- return 1;
1344
- }
1345
- }
1346
- async function runDialogDeleteCommand(args, deps = {}) {
1347
- const env = deps.env ?? process.env;
1348
- const output = deps.output ?? process.stdout;
1349
- if (hasFlag(args, "--help") || hasFlag(args, "-h")) {
1350
- printDeleteUsage(output);
1351
- return 0;
1352
- }
1353
- const rawDialogs = readAllPositional(args);
1354
- if (rawDialogs.length === 0) {
1355
- printDeleteUsage(output);
1356
- return 1;
1357
- }
1358
- const authToken = resolveAuthToken(args, env);
1359
- if (!authToken) {
1360
- output.write("[nolo] dialog delete requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
1361
- return 1;
1362
- }
1363
- const userId = parseUserIdFromAuthToken(authToken);
1364
- if (!userId) {
1365
- output.write("[nolo] dialog delete could not read userId from AUTH_TOKEN.\n");
1366
- return 1;
1367
- }
1368
- const fetchImpl = deps.fetchImpl ?? fetch;
1369
- const fallbackFetchImpl = deps.fallbackFetchImpl;
1370
- const serverUrl = resolveServerUrl(args, env);
1371
- const serverUrls = resolveDeleteServerCandidates(args, env, serverUrl);
1372
- const shouldDelete = hasFlag(args, "--yes");
1373
- const includeReferencedAttachments = hasFlag(args, "--include-referenced-attachments");
1374
- const includeAttachments = hasFlag(args, "--include-attachments") || includeReferencedAttachments;
1375
- let hasErrors = false;
1376
- const payloads = [];
1377
- for (const rawDialog of rawDialogs) {
1378
- try {
1379
- const resolved = resolveDialogInput(rawDialog, userId);
1380
- const readResult = await readDbRecordFromServers({
1381
- authToken,
1382
- dbKey: resolved.dbKey,
1383
- fallbackFetchImpl,
1384
- fetchImpl,
1385
- label: "dialog record",
1386
- serverUrls
1387
- });
1388
- const dialog = normalizeDialogRecord(readResult.record, resolved.dbKey);
1389
- if (!dialog) {
1390
- throw new Error(`dialog record is unreadable: ${resolved.dbKey}`);
1391
- }
1392
- const attachmentPlan = includeAttachments ? await planDialogAttachmentCleanup({
1393
- authToken,
1394
- dialogId: resolved.dialogId,
1395
- ownerId: resolved.ownerId,
1396
- includeUserOwnedReferenced: includeReferencedAttachments,
1397
- fallbackFetchImpl,
1398
- fetchImpl,
1399
- serverUrl: readResult.serverUrl,
1400
- serverUrls
1401
- }) : null;
1402
- const attachmentDeleteResults = includeAttachments && shouldDelete && attachmentPlan ? await deleteDialogAttachmentCandidates({
1403
- authToken,
1404
- candidates: attachmentPlan.deleteCandidates,
1405
- fallbackFetchImpl,
1406
- fetchImpl,
1407
- serverUrls
1408
- }) : [];
1409
- let deleteResults = [];
1410
- if (shouldDelete) {
1411
- deleteResults = await deleteDbRecordOnServers({
1412
- authToken,
1413
- dbKey: resolved.dbKey,
1414
- fallbackFetchImpl,
1415
- fetchImpl,
1416
- serverUrls
1417
- });
1418
- }
1419
- const failedDeletes = deleteResults.filter((result) => !result.ok);
1420
- const failedAttachmentDeletes = attachmentDeleteResults.flatMap(
1421
- (result) => result.deleteResults.filter((deleteResult) => !deleteResult.ok).map((deleteResult) => ({
1422
- fileId: result.fileId,
1423
- fileDbKey: result.fileDbKey,
1424
- ...deleteResult
1425
- }))
1426
- );
1427
- if (failedDeletes.length > 0 || failedAttachmentDeletes.length > 0) {
1428
- hasErrors = true;
1429
- }
1430
- const payload = {
1431
- dbKey: resolved.dbKey,
1432
- dialogId: resolved.dialogId,
1433
- title: dialog.title,
1434
- readServerUrl: readResult.serverUrl,
1435
- targetServers: serverUrls,
1436
- dryRun: !shouldDelete,
1437
- deleted: shouldDelete,
1438
- includeAttachments,
1439
- includeReferencedAttachments,
1440
- ...attachmentPlan ? { attachmentPlan } : {},
1441
- ...readResult.failures.length ? { readFailures: readResult.failures } : {},
1442
- ...shouldDelete ? { deleteResults } : {},
1443
- ...attachmentDeleteResults.length ? { attachmentDeleteResults } : {}
1444
- };
1445
- payloads.push(payload);
1446
- if (!hasFlag(args, "--json")) {
1447
- output.write(`dialog: ${dialog.title}
1448
- `);
1449
- output.write(`dbKey: ${resolved.dbKey}
1450
- `);
1451
- output.write(`readServer: ${readResult.serverUrl}
1452
- `);
1453
- output.write(`targetServers: ${serverUrls.join(", ")}
1454
- `);
1455
- if (attachmentPlan) {
1456
- output.write(
1457
- `attachments: ${attachmentPlan.deleteCandidates.length} delete candidates, ${attachmentPlan.retainedCandidates.length} retained, ${attachmentPlan.bytesToDelete} bytes planned
1458
- `
1459
- );
1460
- for (const candidate of attachmentPlan.retainedCandidates) {
1461
- output.write(`retained attachment: ${candidate.fileId} (${candidate.reason})
1462
- `);
1463
- }
1464
- }
1465
- output.write(
1466
- shouldDelete ? failedDeletes.length > 0 ? `Deleted dialog on ${deleteResults.length - failedDeletes.length}/${deleteResults.length} servers. Failed: ${failedDeletes.map((result) => `${result.serverUrl} (${result.error})`).join(", ")}
1467
- ` : "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"
1468
- );
1469
- if (failedAttachmentDeletes.length > 0) {
1470
- output.write(
1471
- `Attachment delete failures: ${failedAttachmentDeletes.map((result) => `${result.fileDbKey}@${result.serverUrl} (${result.error})`).join(", ")}
1472
- `
1473
- );
1474
- }
1475
- if (rawDialogs.length > 1) {
1476
- output.write("\n");
1477
- }
1478
- }
1479
- } catch (error) {
1480
- hasErrors = true;
1481
- const errorMsg = toErrorMessage(error);
1482
- if (hasFlag(args, "--json")) {
1483
- payloads.push({
1484
- rawDialog,
1485
- error: errorMsg
1486
- });
1487
- } else {
1488
- output.write(`[nolo] dialog delete failed for ${rawDialog}: ${errorMsg}
1489
- `);
1490
- if (rawDialogs.length > 1) {
1491
- output.write("\n");
1492
- }
1493
- }
1494
- }
1495
- }
1496
- if (hasFlag(args, "--json")) {
1497
- const finalPayload = rawDialogs.length === 1 ? payloads[0] : payloads;
1498
- output.write(JSON.stringify(finalPayload, null, 2));
1499
- output.write("\n");
1500
- }
1501
- return hasErrors ? 1 : 0;
1502
- }
1503
-
1504
- export {
1505
- normalizeDialogRecord,
1506
- sortDialogs,
1507
- isScheduledDialog,
1508
- readDialogSnapshot,
1509
- runDialogReadCommand,
1510
- runDialogStatusCommand,
1511
- runDialogQueryCommand,
1512
- runDialogListCommand,
1513
- runDialogDeleteCommand
1514
- };