nolo-cli 0.1.37 → 0.1.39

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 (52) hide show
  1. package/agent-runtime/agentRecordConfig.ts +0 -14
  2. package/agent-runtime/hostAdapter.ts +0 -1
  3. package/agent-runtime/index.ts +24 -18
  4. package/agent-runtime/localDialogRead.ts +23 -0
  5. package/agent-runtime/localToolPolicy.ts +2 -7
  6. package/agent-runtime/localWorkspaceTools.ts +9 -0
  7. package/agent-runtime/noloWorkspaceTools.ts +371 -0
  8. package/agent-runtime/runtimeToolPolicy.ts +1 -3
  9. package/agent-runtime/types.ts +1 -1
  10. package/agentAliases.ts +6 -0
  11. package/agentRunCommand.ts +57 -65
  12. package/agentRuntimeLocal.ts +0 -7
  13. package/chat/messages/fetchMessages.ts +84 -0
  14. package/chat/messages/types.ts +185 -0
  15. package/cli/agentAliases.ts +6 -0
  16. package/cli/agentRunCommand.ts +57 -65
  17. package/cli/agentRuntimeLocal.ts +0 -7
  18. package/cli/cliEnvHelpers.ts +11 -7
  19. package/cli/client/agentRun.ts +123 -24
  20. package/cli/client/localRuntimeAdapter.ts +87 -59
  21. package/cli/connectorRunArtifact.ts +0 -1
  22. package/cli/dialogCommands.ts +572 -0
  23. package/cli/dialogInternalCommandEntries.ts +4 -0
  24. package/cli/machineWsRunDispatch.ts +29 -37
  25. package/cli/scriptCommandEntries.ts +0 -2
  26. package/cli/tui/readlineWorkspace.ts +69 -0
  27. package/cli/tui/session.ts +176 -1
  28. package/cliEnvHelpers.ts +11 -7
  29. package/client/agentConfigResolver.test.ts +2 -3
  30. package/client/agentRun.test.ts +185 -1
  31. package/client/agentRun.ts +123 -24
  32. package/client/localRuntimeAdapter.test.ts +90 -25
  33. package/client/localRuntimeAdapter.ts +87 -59
  34. package/connectorRunArtifact.ts +0 -1
  35. package/database/server/db.ts +99 -0
  36. package/database/server/ensureDbOpen.ts +12 -0
  37. package/database/server/memoryAuthorityStore.ts +133 -0
  38. package/database/server/serverStoreFactory.ts +118 -0
  39. package/dialogCommands.ts +572 -0
  40. package/dialogInternalCommandEntries.ts +4 -0
  41. package/machineWsRunDispatch.ts +29 -37
  42. package/package.json +10 -9
  43. package/scriptCommandEntries.ts +0 -2
  44. package/tui/readlineWorkspace.ts +69 -0
  45. package/tui/session.ts +176 -1
  46. package/agent-runtime/taskWorkspace.ts +0 -193
  47. package/agent-runtime/workspaceSession.ts +0 -76
  48. package/cli/client/taskWorktree.ts +0 -8
  49. package/cli/client/workspaceSession.ts +0 -11
  50. package/client/taskWorktree.ts +0 -8
  51. package/client/workspaceSession.test.ts +0 -57
  52. package/client/workspaceSession.ts +0 -11
package/dialogCommands.ts CHANGED
@@ -14,6 +14,15 @@ import {
14
14
  readLiveDbRecordAfterTombstoneMerge,
15
15
  } from "./globalRecordOperations";
16
16
 
17
+ type ReadSource = "http" | "local-db-fallback";
18
+
19
+ type HttpAttempt = {
20
+ base: string;
21
+ ok: boolean;
22
+ status?: number;
23
+ message?: string;
24
+ };
25
+
17
26
  type ListedDialog = {
18
27
  id: string;
19
28
  dbKey: string;
@@ -36,6 +45,7 @@ const VALUE_FLAGS = new Set([
36
45
  "--space",
37
46
  "--space-id",
38
47
  "--token",
48
+ "--user",
39
49
  ]);
40
50
 
41
51
  function hasFlag(args: string[], flag: string) {
@@ -196,6 +206,411 @@ Deletes are global across the selected/profile server plus known Nolo cluster pe
196
206
  `);
197
207
  }
198
208
 
209
+ function printReadUsage(output: { write(chunk: string): unknown }) {
210
+ output.write(`Usage:
211
+ nolo dialog read <dialogId|dialogKey|dialogUrl> [limit]
212
+
213
+ Options:
214
+ --server <url> Prefer this server when reading by raw dialog id.
215
+ --token <jwt> Override AUTH_TOKEN.
216
+ --user <userId> Override dialog owner for raw dialog ids.
217
+
218
+ Reads dialog metadata and messages as JSON.
219
+ `);
220
+ }
221
+
222
+ function printStatusUsage(output: { write(chunk: string): unknown }) {
223
+ output.write(`Usage:
224
+ nolo dialog status <dialogId|dialogKey|dialogUrl>
225
+
226
+ Options:
227
+ --server <url> Prefer this server when reading by raw dialog id.
228
+ --token <jwt> Override AUTH_TOKEN.
229
+ --user <userId> Override dialog owner for raw dialog ids.
230
+
231
+ Prints compact dialog run status and next-step hints.
232
+ `);
233
+ }
234
+
235
+ function isHelpArg(value?: string) {
236
+ return value === "-h" || value === "--help";
237
+ }
238
+
239
+ function readDialogLimitArg(args: string[], fallback: number) {
240
+ const explicit = readOption(args, "--limit");
241
+ const positional = args.find((value, index) =>
242
+ index > 0 && /^\d+$/.test(value) && args[index - 1] !== "--limit"
243
+ );
244
+ const raw = explicit ?? positional;
245
+ if (!raw) return fallback;
246
+ const parsed = Number(raw);
247
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
248
+ }
249
+
250
+ function readDialogOwnerId(args: string[], env: Record<string, string | undefined>, authToken: string) {
251
+ return readOption(args, "--user") ??
252
+ env.USER_ID ??
253
+ parseUserIdFromAuthToken(authToken) ??
254
+ "";
255
+ }
256
+
257
+ function resolveDialogReadTarget(args: string[], env: Record<string, string | undefined>, authToken: string) {
258
+ const rawInput = readFirstPositional(args);
259
+ if (!rawInput) return null;
260
+ const preferredServer = readOption(args, "--server") ?? readOption(args, "--server-url");
261
+ const ownerFallback = readDialogOwnerId(args, env, authToken);
262
+
263
+ const raw = rawInput.trim();
264
+ if (raw.startsWith("http://") || raw.startsWith("https://")) {
265
+ const url = new URL(raw);
266
+ const match = url.pathname.match(DIALOG_PATH_RE);
267
+ if (!match) throw new Error(`Unsupported dialog URL path: ${url.pathname}`);
268
+ const [, spaceId, ownerId, dialogId] = match;
269
+ const base = preferredServer ?? env.READ_DIALOG_BASE ?? url.origin;
270
+ return {
271
+ base,
272
+ dialogId,
273
+ dialogKey: `dialog-${ownerId}-${dialogId}`,
274
+ userId: ownerId,
275
+ spaceId: spaceId ? decodeURIComponent(spaceId) : undefined,
276
+ };
277
+ }
278
+
279
+ if (raw.startsWith("dialog-")) {
280
+ const dialogId = getDialogIdFromKey(raw);
281
+ const ownerId = raw.slice("dialog-".length, Math.max("dialog-".length, raw.length - dialogId.length - 1));
282
+ return {
283
+ base: preferredServer ?? env.READ_DIALOG_BASE ?? resolveServerUrl(args, env),
284
+ dialogId,
285
+ dialogKey: raw,
286
+ userId: ownerId || ownerFallback,
287
+ };
288
+ }
289
+
290
+ if (!DIALOG_ID_RE.test(raw)) {
291
+ throw new Error(`Unsupported dialog id: ${raw}`);
292
+ }
293
+
294
+ if (!ownerFallback) {
295
+ throw new Error("raw dialog ids require an auth token userId or --user");
296
+ }
297
+ return {
298
+ base: preferredServer ?? env.READ_DIALOG_BASE ?? resolveServerUrl(args, env),
299
+ dialogId: raw,
300
+ dialogKey: `dialog-${ownerFallback}-${raw}`,
301
+ userId: ownerFallback,
302
+ };
303
+ }
304
+
305
+ function toToolName(value: unknown) {
306
+ return typeof value === "string" ? value.trim() : "";
307
+ }
308
+
309
+ function countByName(values: string[]) {
310
+ return values.reduce<Record<string, number>>((acc, value) => {
311
+ acc[value] = (acc[value] ?? 0) + 1;
312
+ return acc;
313
+ }, {});
314
+ }
315
+
316
+ function uniq(values: string[]) {
317
+ return [...new Set(values.filter(Boolean))];
318
+ }
319
+
320
+ function parseJsonObject(raw: unknown): Record<string, any> | null {
321
+ if (typeof raw !== "string" || !raw.trim()) return null;
322
+ try {
323
+ const parsed = JSON.parse(raw);
324
+ return parsed && typeof parsed === "object" ? parsed : null;
325
+ } catch {
326
+ return null;
327
+ }
328
+ }
329
+
330
+ function deriveWrittenFiles(toolMessages: any[]) {
331
+ const writeToolNames = new Set(["applyEdit", "applyLineEdits", "writeFile", "createDoc", "updateDoc"]);
332
+ const files: string[] = [];
333
+ for (const message of toolMessages) {
334
+ const toolName = toToolName(message?.toolName ?? message?.name);
335
+ if (!writeToolNames.has(toolName)) continue;
336
+ const payload = message?.toolPayload ?? {};
337
+ const content = parseJsonObject(message?.content);
338
+ for (const candidate of [payload?.input?.filePath, payload?.response?.filePath, content?.filePath]) {
339
+ const normalized = typeof candidate === "string" ? candidate.trim() : "";
340
+ if (normalized) files.push(normalized);
341
+ }
342
+ }
343
+ return uniq(files);
344
+ }
345
+
346
+ function deriveToolErrors(toolMessages: any[]) {
347
+ const errors: string[] = [];
348
+ for (const message of toolMessages) {
349
+ const toolName = toToolName(message?.toolName ?? message?.name);
350
+ const payload = message?.toolPayload ?? {};
351
+ const content = parseJsonObject(message?.content);
352
+ if (payload?.status === "failed" || content?.ok === false || content?.applied === false || content?.success === false) {
353
+ errors.push(toolName || "unknown-tool");
354
+ }
355
+ }
356
+ return uniq(errors);
357
+ }
358
+
359
+ function isLocalBaseUrl(base: string) {
360
+ try {
361
+ const url = new URL(base);
362
+ return url.hostname === "127.0.0.1" || url.hostname === "localhost";
363
+ } catch {
364
+ return false;
365
+ }
366
+ }
367
+
368
+ async function readDialogOverHttp(args: {
369
+ base: string;
370
+ dialogKey: string;
371
+ dialogId: string;
372
+ limit: number;
373
+ authToken: string;
374
+ fetchImpl: typeof fetch;
375
+ }) {
376
+ const authHeaders = {
377
+ Authorization: `Bearer ${args.authToken}`,
378
+ "Content-Type": "application/json",
379
+ };
380
+ const readViaBridge = async () => {
381
+ const bridgeRes = await args.fetchImpl(`${args.base}/api/dialog-read`, {
382
+ method: "POST",
383
+ headers: authHeaders,
384
+ body: JSON.stringify({
385
+ dialogKey: args.dialogKey,
386
+ dialogId: args.dialogId,
387
+ limit: args.limit,
388
+ }),
389
+ });
390
+ if (!bridgeRes.ok) {
391
+ throw Object.assign(new Error(`dialog read bridge failed: HTTP ${bridgeRes.status}`), {
392
+ status: bridgeRes.status,
393
+ base: args.base,
394
+ });
395
+ }
396
+ const payload = await bridgeRes.json();
397
+ if (!payload?.ok) {
398
+ throw Object.assign(new Error(`dialog read bridge failed: ${payload?.error ?? "unknown error"}`), {
399
+ status: 500,
400
+ base: args.base,
401
+ });
402
+ }
403
+ return {
404
+ meta: payload.meta,
405
+ msgs: payload.msgs,
406
+ source: "http" as ReadSource,
407
+ };
408
+ };
409
+
410
+ const metaRes = await args.fetchImpl(
411
+ `${args.base}/api/v1/db/read/${encodeURIComponent(args.dialogKey)}`,
412
+ { headers: { Authorization: `Bearer ${args.authToken}` } }
413
+ );
414
+ if (!metaRes.ok) {
415
+ if (metaRes.status === 401 || metaRes.status === 403) return readViaBridge();
416
+ throw Object.assign(new Error(`read dialog meta failed: HTTP ${metaRes.status}`), {
417
+ status: metaRes.status,
418
+ base: args.base,
419
+ });
420
+ }
421
+ const meta = await metaRes.json();
422
+
423
+ const msgsRes = await args.fetchImpl(`${args.base}/rpc/getConvMsgs`, {
424
+ method: "POST",
425
+ headers: authHeaders,
426
+ body: JSON.stringify({ dialogId: args.dialogId, limit: args.limit }),
427
+ });
428
+ if (!msgsRes.ok) {
429
+ if (msgsRes.status === 401 || msgsRes.status === 403) return readViaBridge();
430
+ throw Object.assign(new Error(`read dialog messages failed: HTTP ${msgsRes.status}`), {
431
+ status: msgsRes.status,
432
+ base: args.base,
433
+ });
434
+ }
435
+ return {
436
+ meta,
437
+ msgs: await msgsRes.json(),
438
+ source: "http" as ReadSource,
439
+ };
440
+ }
441
+
442
+ async function tryHttpDialogCandidates(args: {
443
+ bases: string[];
444
+ dialogKey: string;
445
+ dialogId: string;
446
+ limit: number;
447
+ authToken: string;
448
+ fetchImpl: typeof fetch;
449
+ }) {
450
+ const attempts: HttpAttempt[] = [];
451
+ for (const base of args.bases) {
452
+ try {
453
+ const result = await readDialogOverHttp({ ...args, base });
454
+ attempts.push({ base, ok: true });
455
+ return { ...result, resolvedBase: base, attempts };
456
+ } catch (error) {
457
+ attempts.push({
458
+ base,
459
+ ok: false,
460
+ status:
461
+ typeof error === "object" && error !== null && "status" in error
462
+ ? Number((error as any).status)
463
+ : undefined,
464
+ message: error instanceof Error ? error.message : String(error),
465
+ });
466
+ }
467
+ }
468
+ throw Object.assign(new Error("All HTTP dialog reads failed"), { attempts });
469
+ }
470
+
471
+ async function readDialogFromLocalDb(dialogKey: string, dialogId: string, limit: number) {
472
+ const { readDialogFromLocalDb: readLocalDialog } = await import("./agent-runtime/localDialogRead");
473
+ const result = await readLocalDialog({ dialogKey, dialogId, limit });
474
+ return {
475
+ ...result,
476
+ source: "local-db-fallback" as ReadSource,
477
+ };
478
+ }
479
+
480
+ async function readDialogSnapshot(args: {
481
+ authToken: string;
482
+ base: string;
483
+ dialogId: string;
484
+ dialogKey: string;
485
+ fetchImpl: typeof fetch;
486
+ limit: number;
487
+ }) {
488
+ const candidateBases = resolveServerCandidates({ NOLO_SERVER: args.base }, args.base);
489
+ let attempts: HttpAttempt[] = [];
490
+ try {
491
+ const result = await tryHttpDialogCandidates({
492
+ bases: candidateBases,
493
+ dialogKey: args.dialogKey,
494
+ dialogId: args.dialogId,
495
+ limit: args.limit,
496
+ authToken: args.authToken,
497
+ fetchImpl: args.fetchImpl,
498
+ });
499
+ return { ...result, candidateBases };
500
+ } catch (error) {
501
+ attempts =
502
+ typeof error === "object" && error !== null && "attempts" in error
503
+ ? ((error as any).attempts as HttpAttempt[])
504
+ : attempts;
505
+ const statuses = attempts.map((attempt) => attempt.status).filter((status): status is number => typeof status === "number");
506
+ const all404 = attempts.length > 0 && statuses.length === attempts.length && statuses.every((status) => status === 404);
507
+ const localhostCandidate = candidateBases.find(isLocalBaseUrl);
508
+ if (!localhostCandidate || all404) {
509
+ throw Object.assign(new Error(
510
+ all404
511
+ ? `dialog not found on tried servers: ${candidateBases.join(", ")}`
512
+ : `read dialog failed across candidates: ${attempts.map((attempt) => `${attempt.base} -> ${attempt.status ?? attempt.message}`).join("; ")}`
513
+ ), { attempts });
514
+ }
515
+ const fallback = await readDialogFromLocalDb(args.dialogKey, args.dialogId, args.limit);
516
+ return {
517
+ ...fallback,
518
+ resolvedBase: localhostCandidate,
519
+ attempts,
520
+ candidateBases,
521
+ };
522
+ }
523
+ }
524
+
525
+ function compact(value: unknown, max = 180) {
526
+ const text = typeof value === "string" ? value.trim() : "";
527
+ if (!text) return "";
528
+ return text.length > max ? `${text.slice(0, max - 3)}...` : text;
529
+ }
530
+
531
+ function renderCompactDialogStatus(snapshot: any) {
532
+ const checkpoint = snapshot.runtimeCheckpoint ?? {};
533
+ const checkpointStatus = typeof checkpoint.status === "string" ? checkpoint.status : null;
534
+ const status = snapshot.status ?? checkpointStatus ?? "unknown";
535
+ const state =
536
+ checkpointStatus === "done" || checkpointStatus === "completed" || status === "done" || status === "completed"
537
+ ? "done"
538
+ : checkpointStatus === "failed" || checkpointStatus === "error" || status === "failed" || status === "error"
539
+ ? "failed"
540
+ : status === "running" || status === "pending" || status === "queued"
541
+ ? "active"
542
+ : "unknown";
543
+ const tools = Array.isArray(snapshot.toolsUsed)
544
+ ? snapshot.toolsUsed.filter((tool: unknown): tool is string => typeof tool === "string" && tool.trim()).slice(0, 8)
545
+ : Array.isArray(checkpoint.lastToolNames)
546
+ ? checkpoint.lastToolNames.filter((tool: unknown): tool is string => typeof tool === "string" && tool.trim()).slice(0, 8)
547
+ : [];
548
+ const files = Array.isArray(snapshot.writtenFiles) && snapshot.writtenFiles.length
549
+ ? snapshot.writtenFiles.filter((file: unknown): file is string => typeof file === "string" && file.trim()).slice(0, 8)
550
+ : snapshot.artifacts && typeof snapshot.artifacts === "object" && Array.isArray(snapshot.artifacts.changedFiles ?? snapshot.artifacts.writtenFiles ?? snapshot.artifacts.files)
551
+ ? (snapshot.artifacts.changedFiles ?? snapshot.artifacts.writtenFiles ?? snapshot.artifacts.files)
552
+ .filter((file: unknown): file is string => typeof file === "string" && file.trim())
553
+ .slice(0, 8)
554
+ : [];
555
+ const subjectRefs = Array.isArray(snapshot.subjectRefs)
556
+ ? snapshot.subjectRefs
557
+ .map((ref: any) => {
558
+ const kind = typeof ref?.kind === "string" ? ref.kind.trim() : "";
559
+ const id = typeof ref?.id === "string" ? ref.id.trim() : "";
560
+ if (!kind || !id) return "";
561
+ const role = typeof ref?.role === "string" && ref.role.trim() ? `#${ref.role.trim()}` : "";
562
+ return `${kind}:${id}${role}`;
563
+ })
564
+ .filter(Boolean)
565
+ .slice(0, 8)
566
+ : [];
567
+ const toolErrors = Array.isArray(snapshot.toolErrors)
568
+ ? snapshot.toolErrors.filter((tool: unknown): tool is string => typeof tool === "string" && tool.trim()).slice(0, 8)
569
+ : [];
570
+ const checkpointUpdatedAt = typeof checkpoint.updatedAt === "number" || typeof checkpoint.updatedAt === "string"
571
+ ? Date.parse(String(checkpoint.updatedAt))
572
+ : NaN;
573
+ const activeHealth = state !== "active"
574
+ ? ""
575
+ : !snapshot.runtimeCheckpoint
576
+ ? "no-checkpoint"
577
+ : !Number.isFinite(checkpointUpdatedAt)
578
+ ? "checkpoint-without-updatedAt"
579
+ : Date.now() - checkpointUpdatedAt > 5 * 60_000
580
+ ? "stale-running"
581
+ : "running";
582
+ const errorMessage = compact(checkpoint.errorMessage ?? snapshot.errorMessage);
583
+ const lines = [
584
+ `dialog: ${snapshot.dialogId}`,
585
+ ...(snapshot.base ? [`base: ${snapshot.base}`] : []),
586
+ ...(snapshot.title ? [`title: ${snapshot.title}`] : []),
587
+ ...(snapshot.parentDialogId ? [`parentDialogId: ${snapshot.parentDialogId}`] : []),
588
+ ...(snapshot.rootDialogId ? [`rootDialogId: ${snapshot.rootDialogId}`] : []),
589
+ `status: ${status}`,
590
+ ...(checkpointStatus ? [`checkpoint: ${checkpointStatus}`] : []),
591
+ `state: ${state}`,
592
+ ...(activeHealth ? [`activeHealth: ${activeHealth}`] : []),
593
+ ...(typeof snapshot.durationMs === "number" ? [`durationMs: ${snapshot.durationMs}`] : []),
594
+ ...(snapshot.updatedAt ? [`updatedAt: ${snapshot.updatedAt}`] : []),
595
+ ...(snapshot.finishedAt ? [`finishedAt: ${snapshot.finishedAt}`] : []),
596
+ ...(compact(checkpoint.lastUserInput) ? [`lastUserInput: ${compact(checkpoint.lastUserInput)}`] : []),
597
+ ...(compact(checkpoint.lastAssistantText) ? [`lastAssistantText: ${compact(checkpoint.lastAssistantText)}`] : []),
598
+ ...(errorMessage ? [`error: ${errorMessage}`] : []),
599
+ ...(tools.length ? [`tools: ${tools.join(", ")}`] : []),
600
+ ...(files.length ? [`files: ${files.join(", ")}`] : []),
601
+ ...(subjectRefs.length ? [`subjects: ${subjectRefs.join(", ")}`] : []),
602
+ ...(toolErrors.length ? [`toolErrors: ${toolErrors.join(", ")}`] : []),
603
+ "",
604
+ "next:",
605
+ `- read full dialog: nolo dialog read ${snapshot.dialogId} 120`,
606
+ ];
607
+ if (state === "active") lines.push(`- poll again: nolo dialog status ${snapshot.dialogId}`);
608
+ else if (state === "failed") lines.push(`- inspect failure and rerun/continue with: nolo agent run <agent> --continue ${snapshot.dialogId} --msg "..."`);
609
+ else if (state === "done") lines.push("- use artifacts/files above for review, handoff, or alpha integration.");
610
+ else lines.push("- inspect meta/messages before deciding whether to continue or rerun.");
611
+ return `${lines.join("\n")}\n`;
612
+ }
613
+
199
614
  async function readSpaceDialogRecords(args: {
200
615
  authToken: string;
201
616
  fetchImpl: typeof fetch;
@@ -232,6 +647,163 @@ async function readSpaceDialogRecords(args: {
232
647
  return { spaceId, records, failures };
233
648
  }
234
649
 
650
+ export async function runDialogReadCommand(
651
+ args: string[],
652
+ deps: AgentCommandDeps = {}
653
+ ) {
654
+ const env = deps.env ?? process.env;
655
+ const output = deps.output ?? process.stdout;
656
+ if (isHelpArg(args[0])) {
657
+ printReadUsage(output);
658
+ return 0;
659
+ }
660
+
661
+ const authToken = resolveAuthToken(args, env);
662
+ if (!authToken) {
663
+ output.write("[nolo] dialog read requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
664
+ return 1;
665
+ }
666
+
667
+ let target: ReturnType<typeof resolveDialogReadTarget>;
668
+ try {
669
+ target = resolveDialogReadTarget(args, env, authToken);
670
+ } catch (error) {
671
+ output.write(`[nolo] dialog read failed: ${error instanceof Error ? error.message : String(error)}\n`);
672
+ return 1;
673
+ }
674
+ if (!target) {
675
+ printReadUsage(output);
676
+ return 1;
677
+ }
678
+
679
+ try {
680
+ const limit = readDialogLimitArg(args, 50);
681
+ const read = await readDialogSnapshot({
682
+ authToken,
683
+ base: target.base,
684
+ dialogId: target.dialogId,
685
+ dialogKey: target.dialogKey,
686
+ fetchImpl: deps.fetchImpl ?? fetch,
687
+ limit,
688
+ });
689
+ const orderedMsgs = Array.isArray(read.msgs) ? [...read.msgs].reverse() : read.msgs;
690
+ const lastAssistantMessage = Array.isArray(orderedMsgs)
691
+ ? [...orderedMsgs].reverse().find((message) => message?.role === "assistant" || message?.authorRole === "assistant")
692
+ : null;
693
+ const toolMessages = Array.isArray(orderedMsgs)
694
+ ? orderedMsgs.filter((message) => message?.role === "tool" || message?.authorRole === "tool")
695
+ : [];
696
+ const toolNamesFromMessages = toolMessages
697
+ .map((message) => toToolName(message?.toolName ?? message?.name))
698
+ .filter(Boolean);
699
+ const toolsUsed = Array.isArray(read.meta?.toolsUsed) && read.meta.toolsUsed.length > 0
700
+ ? read.meta.toolsUsed.map((tool: unknown) => toToolName(tool)).filter(Boolean)
701
+ : uniq(toolNamesFromMessages);
702
+ const writtenFiles = Array.isArray(read.meta?.writtenFiles) && read.meta.writtenFiles.length > 0
703
+ ? uniq(read.meta.writtenFiles.map((value: unknown) => (typeof value === "string" ? value.trim() : "")).filter(Boolean))
704
+ : deriveWrittenFiles(toolMessages);
705
+ const toolErrors = Array.isArray(read.meta?.toolErrors) && read.meta.toolErrors.length > 0
706
+ ? uniq(read.meta.toolErrors.map((value: unknown) => (typeof value === "string" ? value.trim() : "")).filter(Boolean))
707
+ : deriveToolErrors(toolMessages);
708
+
709
+ output.write(JSON.stringify({
710
+ source: read.source as ReadSource,
711
+ base: read.resolvedBase,
712
+ triedBases: read.candidateBases,
713
+ httpAttempts: read.attempts,
714
+ spaceId: target.spaceId,
715
+ dialogId: target.dialogId,
716
+ dialogKey: target.dialogKey,
717
+ userId: target.userId,
718
+ title: read.meta?.title ?? null,
719
+ cybots: Array.isArray(read.meta?.cybots) ? read.meta.cybots : [],
720
+ category: read.meta?.category ?? null,
721
+ inheritedFromDialogKey: read.meta?.inheritedFromDialogKey ?? null,
722
+ inheritedFromDialogTitle: read.meta?.inheritedFromDialogTitle ?? null,
723
+ parentDialogId: read.meta?.parentDialogId ?? null,
724
+ rootDialogId: read.meta?.rootDialogId ?? null,
725
+ status: read.meta?.status,
726
+ errorMessage: read.meta?.errorMessage ?? null,
727
+ runtimeCheckpoint: read.meta?.runtimeCheckpoint ?? null,
728
+ durationMs: read.meta?.durationMs,
729
+ finishedAt: read.meta?.finishedAt,
730
+ createdAt: read.meta?.createdAt,
731
+ updatedAt: read.meta?.updatedAt,
732
+ artifacts: read.meta?.artifacts ?? null,
733
+ writtenFiles,
734
+ toolsUsed,
735
+ toolErrors,
736
+ toolSummary: {
737
+ metaToolsCount: toolsUsed.length,
738
+ metaToolsUnique: [...new Set(toolsUsed)],
739
+ toolMessageCount: toolMessages.length,
740
+ toolNamesFromMessages: [...new Set(toolNamesFromMessages)],
741
+ toolMessageCountsByName: countByName(toolNamesFromMessages),
742
+ },
743
+ agentReply: read.meta?.agentReply ?? null,
744
+ messagesCount: Array.isArray(orderedMsgs) ? orderedMsgs.length : 0,
745
+ lastAssistantMessage,
746
+ messages: orderedMsgs,
747
+ }, null, 2));
748
+ output.write("\n");
749
+ return 0;
750
+ } catch (error) {
751
+ output.write(`[nolo] dialog read failed: ${error instanceof Error ? error.message : String(error)}\n`);
752
+ return 1;
753
+ }
754
+ }
755
+
756
+ export async function runDialogStatusCommand(
757
+ args: string[],
758
+ deps: AgentCommandDeps = {}
759
+ ) {
760
+ const env = deps.env ?? process.env;
761
+ const output = deps.output ?? process.stdout;
762
+ if (isHelpArg(args[0])) {
763
+ printStatusUsage(output);
764
+ return 0;
765
+ }
766
+
767
+ const authToken = resolveAuthToken(args, env);
768
+ if (!authToken) {
769
+ output.write("[nolo] dialog status requires an auth token. Run `nolo login` or set AUTH_TOKEN.\n");
770
+ return 1;
771
+ }
772
+
773
+ let target: ReturnType<typeof resolveDialogReadTarget>;
774
+ try {
775
+ target = resolveDialogReadTarget(args, env, authToken);
776
+ } catch (error) {
777
+ output.write(`[nolo] dialog status failed: ${error instanceof Error ? error.message : String(error)}\n`);
778
+ return 1;
779
+ }
780
+ if (!target) {
781
+ printStatusUsage(output);
782
+ return 1;
783
+ }
784
+
785
+ try {
786
+ const read = await readDialogSnapshot({
787
+ authToken,
788
+ base: target.base,
789
+ dialogId: target.dialogId,
790
+ dialogKey: target.dialogKey,
791
+ fetchImpl: deps.fetchImpl ?? fetch,
792
+ limit: 1,
793
+ });
794
+ output.write(renderCompactDialogStatus({
795
+ ...(read.meta ?? {}),
796
+ dialogId: target.dialogId,
797
+ dialogKey: target.dialogKey,
798
+ base: read.resolvedBase,
799
+ }));
800
+ return 0;
801
+ } catch (error) {
802
+ output.write(`[nolo] dialog status failed: ${error instanceof Error ? error.message : String(error)}\n`);
803
+ return 1;
804
+ }
805
+ }
806
+
235
807
  export async function runDialogListCommand(
236
808
  args: string[],
237
809
  deps: AgentCommandDeps = {}
@@ -3,11 +3,15 @@ import { createEnvCommand } from "./cliCommandFactories";
3
3
  import {
4
4
  runDialogDeleteCommand,
5
5
  runDialogListCommand,
6
+ runDialogReadCommand,
7
+ runDialogStatusCommand,
6
8
  } from "./dialogCommands";
7
9
 
8
10
  export function getDialogInternalCommandEntries(): CommandEntry[] {
9
11
  return [
10
12
  createEnvCommand(["dialog", "list"], "List dialogs", runDialogListCommand),
11
13
  createEnvCommand(["dialog", "delete"], "Delete a dialog", runDialogDeleteCommand),
14
+ createEnvCommand(["dialog", "read"], "Read a dialog", runDialogReadCommand),
15
+ createEnvCommand(["dialog", "status"], "Read compact dialog status", runDialogStatusCommand),
12
16
  ];
13
17
  }