@phnx-labs/agents-cli 1.22.127 → 1.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +15 -16
  3. package/dist/bootstrap.js +4 -3
  4. package/dist/commands/browser.js +4 -19
  5. package/dist/commands/cloud-transcripts.js +1 -2
  6. package/dist/commands/computer.d.ts +2 -6
  7. package/dist/commands/computer.js +12 -18
  8. package/dist/commands/daemon.js +70 -11
  9. package/dist/commands/exec.js +1 -1
  10. package/dist/commands/feed.js +1 -2
  11. package/dist/commands/focus.js +4 -1
  12. package/dist/commands/go.js +3 -2
  13. package/dist/commands/logs.js +3 -7
  14. package/dist/commands/menubar.js +55 -3
  15. package/dist/commands/projects.js +103 -40
  16. package/dist/commands/ps-roster.d.ts +0 -11
  17. package/dist/commands/ps-roster.js +3 -116
  18. package/dist/commands/ps.d.ts +10 -0
  19. package/dist/commands/ps.js +182 -1
  20. package/dist/commands/resume.js +1 -1
  21. package/dist/commands/sessions-browser.d.ts +0 -1
  22. package/dist/commands/sessions-browser.js +6 -23
  23. package/dist/commands/sessions-export.js +1 -1
  24. package/dist/commands/sessions-migrate.js +1 -1
  25. package/dist/commands/sessions-picker.d.ts +6 -32
  26. package/dist/commands/sessions-picker.js +81 -8
  27. package/dist/commands/sessions-render.js +1 -1
  28. package/dist/commands/sessions-resume.js +2 -2
  29. package/dist/commands/sessions-share.js +1 -1
  30. package/dist/commands/sessions-trace.js +1 -1
  31. package/dist/commands/sessions.d.ts +2 -176
  32. package/dist/commands/sessions.js +44 -1577
  33. package/dist/index.js +10 -11
  34. package/dist/lib/browser-client.d.ts +0 -21
  35. package/dist/lib/browser-client.js +1 -44
  36. package/dist/lib/computer/record.d.ts +1 -0
  37. package/dist/lib/computer/record.js +2 -16
  38. package/dist/lib/config-keys.d.ts +2 -2
  39. package/dist/lib/config-keys.js +8 -2
  40. package/dist/lib/daemon/account-state-daemon-service.d.ts +2 -2
  41. package/dist/lib/daemon/account-state-daemon-service.js +2 -2
  42. package/dist/lib/daemon/attention-notify-service.js +8 -4
  43. package/dist/lib/daemon/daemon.d.ts +5 -1
  44. package/dist/lib/daemon/daemon.js +54 -14
  45. package/dist/lib/daemon/diagnostics.d.ts +70 -0
  46. package/dist/lib/daemon/diagnostics.js +185 -0
  47. package/dist/lib/daemon/runner.js +3 -2
  48. package/dist/lib/daemon/service.d.ts +1 -1
  49. package/dist/lib/daemon/session-state-service.d.ts +1 -1
  50. package/dist/lib/daemon/session-state-service.js +2 -2
  51. package/dist/lib/daemon/supervisor.d.ts +8 -0
  52. package/dist/lib/daemon/supervisor.js +47 -6
  53. package/dist/lib/daemon-services.d.ts +4 -1
  54. package/dist/lib/daemon-services.js +36 -5
  55. package/dist/lib/daemon-ticks.d.ts +3 -1
  56. package/dist/lib/daemon-ticks.js +18 -12
  57. package/dist/lib/device-config.d.ts +1 -1
  58. package/dist/lib/device-config.js +48 -7
  59. package/dist/lib/feed/tool-activity.d.ts +22 -10
  60. package/dist/lib/feed/tool-activity.js +168 -32
  61. package/dist/lib/feed/tools.d.ts +55 -2
  62. package/dist/lib/feed/tools.js +22 -28
  63. package/dist/lib/feed/watch.js +12 -8
  64. package/dist/lib/github/open-prs.d.ts +41 -0
  65. package/dist/lib/github/open-prs.js +157 -0
  66. package/dist/lib/github/project-prs.d.ts +20 -1
  67. package/dist/lib/github/project-prs.js +8 -7
  68. package/dist/lib/helper-versions.js +1 -1
  69. package/dist/lib/menubar/install-menubar.d.ts +23 -7
  70. package/dist/lib/menubar/install-menubar.js +179 -30
  71. package/dist/lib/menubar/resolve-version.d.ts +1 -0
  72. package/dist/lib/menubar/resolve-version.js +4 -2
  73. package/dist/lib/menubar/snapshot.d.ts +2 -0
  74. package/dist/lib/menubar/snapshot.js +2 -0
  75. package/dist/lib/menubar/update-state.d.ts +15 -0
  76. package/dist/lib/menubar/update-state.js +36 -0
  77. package/dist/lib/owner-notify.d.ts +0 -12
  78. package/dist/lib/owner-notify.js +1 -10
  79. package/dist/lib/self-heal/checks/menubar-helper.js +1 -0
  80. package/dist/lib/session/active.js +18 -14
  81. package/dist/lib/session/cloud.d.ts +0 -1
  82. package/dist/lib/session/cloud.js +0 -5
  83. package/dist/lib/session/db.d.ts +0 -64
  84. package/dist/lib/session/db.js +0 -116
  85. package/dist/lib/session/pid-registry.js +9 -6
  86. package/dist/lib/session/presentation.d.ts +107 -1
  87. package/dist/lib/session/presentation.js +543 -4
  88. package/dist/lib/session/remote/remote-list.d.ts +5 -36
  89. package/dist/lib/session/remote/remote-list.js +16 -320
  90. package/dist/lib/session/resume-command.d.ts +9 -0
  91. package/dist/lib/session/resume-command.js +107 -0
  92. package/dist/lib/session/selection.d.ts +102 -0
  93. package/dist/lib/session/selection.js +443 -0
  94. package/dist/lib/session/tool-index.d.ts +0 -62
  95. package/dist/lib/session/tool-index.js +1 -537
  96. package/dist/lib/sessions-client.d.ts +1 -0
  97. package/dist/lib/sessions-client.js +17 -1
  98. package/dist/lib/standalone-tools.js +2 -2
  99. package/dist/lib/testdata/owner-notify-api.d.ts +0 -13
  100. package/dist/lib/testdata/owner-notify-api.js +3 -23
  101. package/package.json +1 -1
  102. package/dist/commands/browser-sessions-picker.d.ts +0 -9
  103. package/dist/commands/browser-sessions-picker.js +0 -136
  104. package/dist/commands/computer-sessions-picker.d.ts +0 -11
  105. package/dist/commands/computer-sessions-picker.js +0 -90
  106. package/dist/commands/sessions-tail.d.ts +0 -13
  107. package/dist/commands/sessions-tail.js +0 -222
  108. package/dist/lib/browser/native-history.test-fixture.d.ts +0 -12
  109. package/dist/lib/browser/native-history.test-fixture.js +0 -43
  110. package/dist/lib/browser/paths.d.ts +0 -9
  111. package/dist/lib/browser/paths.js +0 -31
  112. package/dist/lib/browser/record.d.ts +0 -4
  113. package/dist/lib/browser/record.js +0 -19
  114. package/dist/lib/browser/sessions-list.d.ts +0 -79
  115. package/dist/lib/browser/sessions-list.js +0 -415
  116. package/dist/lib/computer/sessions-list.d.ts +0 -78
  117. package/dist/lib/computer/sessions-list.js +0 -372
  118. package/dist/lib/daemon/owner-device-delivery-service.d.ts +0 -10
  119. package/dist/lib/daemon/owner-device-delivery-service.js +0 -28
@@ -1,13 +1,18 @@
1
1
  import * as fs from 'fs';
2
2
  import chalk from 'chalk';
3
3
  import ora from 'ora';
4
- import { computeSummaryStats, filterEvents, inferSessionState, linearIssueUrl, linkUrl, parseRoleList, parseSession, renderConversationMarkdown, renderJson, renderSummary, renderSummaryHeader, sessionDisplayAgent, } from '@phnx-labs/sessions-cli/reader';
4
+ import { computeSummaryStats, filterEvents, inferSessionState, linearIssueUrl, linkPath, linkUrl, parseRoleList, parseSession, renderConversationMarkdown, renderJson, renderSummary, renderSummaryHeader, safeTeamText, foldTimeline, emptyTimelineState, projectTimeline, projectSessionFiles, readSessionTail, sessionDisplayAgent, shortenModel, } from '@phnx-labs/sessions-cli/reader';
5
5
  import { colorAgent } from '../agents.js';
6
+ import { padRight, truncate } from '../format.js';
6
7
  import { renderMarkdown } from '../markdown.js';
7
- import { redactSecrets } from '../redact.js';
8
- import { readArchivedSessionPreview, readSessionContent } from './db.js';
9
- import { formatRelativeTime } from './relative-time.js';
8
+ import { homeDir, toComparablePath } from '../platform/index.js';
9
+ import { redactSecrets, sanitizeForTerminal } from '../redact.js';
10
+ import { listBookmarks } from './bookmarks.js';
11
+ import { readArchivedSessionPreview, readSessionContent, readSessionTimelineAny } from './db.js';
12
+ import { formatRelativeTime, sessionAgeParts } from './relative-time.js';
13
+ import { ticketLabel } from './selection.js';
10
14
  import { sessionHeadline } from './title.js';
15
+ import { padToWidth, stringWidth, terminalWidth, truncateToWidth } from './width.js';
11
16
  export function signalBadges(s) {
12
17
  const parts = [];
13
18
  if (s.awaitingReason === 'plan_review')
@@ -196,3 +201,537 @@ function formatAbsoluteTime(isoTimestamp) {
196
201
  const mm = String(d.getMinutes()).padStart(2, '0');
197
202
  return `${months[d.getMonth()]} ${d.getDate()} ${hh}:${mm}`;
198
203
  }
204
+ export function formatTodoCompact(todos) {
205
+ if (!todos || !Number.isFinite(todos.total) || todos.total < 1)
206
+ return '';
207
+ const done = Number.isFinite(todos.done) ? Math.max(0, todos.done) : 0;
208
+ const tally = `✓${done}/${todos.total}`;
209
+ const step = todos.activeForm?.replace(/\s+/g, ' ').trim();
210
+ return step ? `${tally} · ${step}` : tally;
211
+ }
212
+ export function statusColor(status) {
213
+ switch (status) {
214
+ case 'running': return chalk.green;
215
+ case 'idle': return chalk.gray;
216
+ case 'queued': return chalk.blue;
217
+ case 'input_required': return chalk.yellow;
218
+ case 'closed': return chalk.dim;
219
+ case 'abandoned': return chalk.red;
220
+ case 'crashed': return chalk.redBright;
221
+ case 'orphaned': return chalk.yellow;
222
+ case 'unknown': return chalk.magenta;
223
+ }
224
+ }
225
+ export function cleanPreview(text) {
226
+ // eslint-disable-next-line no-control-regex
227
+ return text
228
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
229
+ .replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '')
230
+ .replace(/<\/?(?:local-command-stdout|command-name|command-message|command-args|task-notification|system-reminder)>/g, '')
231
+ .replace(/\s+/g, ' ')
232
+ .trim();
233
+ }
234
+ export function buildSessionDescription(s) {
235
+ const todo = formatTodoCompact(s.todos);
236
+ if (s.context === 'cloud') {
237
+ const base = s.preview || `${s.cloudProvider ?? ''}${s.cloudTaskId ? ` · ${s.cloudTaskId.slice(0, 12)}` : ''}`;
238
+ return cleanPreview([todo, base].filter(Boolean).join(' · '));
239
+ }
240
+ if (s.context === 'teams') {
241
+ const parts = [s.teamName];
242
+ if (s.label && s.label !== s.teamName)
243
+ parts.push(s.label);
244
+ const orch = s.orchestratorLabel || (s.orchestratorSessionId ? s.orchestratorSessionId.slice(0, 8) : '');
245
+ if (orch)
246
+ parts.push(`by ${orch}`);
247
+ if (todo)
248
+ parts.push(todo);
249
+ const target = s.preview || s.assignedTask || s.topic;
250
+ if (target)
251
+ parts.push(target);
252
+ return cleanPreview(parts.filter(Boolean).join(' · '));
253
+ }
254
+ // ladder-exempt: compact live preview base, not the row's headline.
255
+ const base = s.preview || s.label || s.topic || '';
256
+ return cleanPreview([todo, base].filter(Boolean).join(' · '));
257
+ }
258
+ export function liveGlyphAndPreview(a) {
259
+ if (!a)
260
+ return { glyph: '', preview: '' };
261
+ if (a.status === 'abandoned')
262
+ return { glyph: statusColor(a.status)('⊘'), preview: buildSessionDescription(a) };
263
+ if (a.status === 'closed')
264
+ return { glyph: statusColor(a.status)('×'), preview: buildSessionDescription(a) };
265
+ if (a.status === 'crashed')
266
+ return { glyph: statusColor(a.status)('✗'), preview: buildSessionDescription(a) };
267
+ if (a.status === 'orphaned')
268
+ return { glyph: statusColor(a.status)('◍'), preview: buildSessionDescription(a) };
269
+ const waiting = a.status === 'input_required' || a.activity === 'waiting_input';
270
+ const running = a.status === 'running' || a.activity === 'working';
271
+ const unknown = a.status === 'unknown';
272
+ const shape = waiting ? '◐'
273
+ : running ? '●'
274
+ : unknown ? '◌'
275
+ : '○';
276
+ return { glyph: statusColor(a.status)(shape), preview: buildSessionDescription(a) };
277
+ }
278
+ export function liveStatusWord(a) {
279
+ if (!a)
280
+ return '';
281
+ if (a.status === 'closed' || a.status === 'abandoned')
282
+ return a.status;
283
+ if (a.status === 'crashed')
284
+ return 'crashed';
285
+ if (a.status === 'orphaned')
286
+ return 'orphan';
287
+ if (a.status === 'input_required' || a.activity === 'waiting_input')
288
+ return 'waiting';
289
+ if (a.status === 'running' || a.activity === 'working')
290
+ return 'working';
291
+ if (a.status === 'idle' || a.activity === 'idle')
292
+ return 'idle';
293
+ if (a.status === 'queued')
294
+ return 'queued';
295
+ return '';
296
+ }
297
+ export function isAwaitingUser(s) {
298
+ if (s.status === 'crashed' || s.status === 'closed')
299
+ return false;
300
+ if (s.status === 'abandoned' && s.pidAlive !== true)
301
+ return false;
302
+ return s.status === 'input_required' || s.activity === 'waiting_input';
303
+ }
304
+ export function shortCwd(cwd) {
305
+ if (!cwd)
306
+ return '-';
307
+ const home = homeDir();
308
+ return toComparablePath(cwd).startsWith(toComparablePath(home))
309
+ ? '~' + cwd.slice(home.length)
310
+ : cwd;
311
+ }
312
+ export const LIVE_STATUS_W = 8;
313
+ export function liveStatusCell(live) {
314
+ const word = liveStatusWord(live);
315
+ if (!word || !live)
316
+ return { cell: '', width: 0 };
317
+ return { cell: statusColor(live.status)(padToWidth(word, LIVE_STATUS_W)), width: LIVE_STATUS_W };
318
+ }
319
+ function ticketUrl(s) {
320
+ if (s.ticketId)
321
+ return linearIssueUrl(s.ticketId);
322
+ return s.prNumber ? s.prUrl : undefined;
323
+ }
324
+ export function linkTicketCell(s, label) {
325
+ const url = ticketUrl(s);
326
+ return url && label.trim() !== '-' ? linkUrl(url, label) : label;
327
+ }
328
+ export function linkCwdCell(s, label) {
329
+ return s.cwd && !s._remote ? linkPath(s.cwd, label) : label;
330
+ }
331
+ function modelLabel(model) {
332
+ return model ? shortenModel(model) : '-';
333
+ }
334
+ export function formatLiveStatusHeadline(live, bookmarked = false) {
335
+ const star = bookmarked ? chalk.yellow('★ ') : '';
336
+ if (!live)
337
+ return bookmarked ? chalk.yellow('★ bookmarked') : '';
338
+ const { glyph } = liveGlyphAndPreview(live);
339
+ const word = liveStatusWord(live) || live.status;
340
+ const needsYou = isAwaitingUser(live);
341
+ const reason = live.awaitingReason ? ` (${live.awaitingReason.replace('_', ' ')})` : '';
342
+ let suffix = needsYou ? chalk.yellow(` ← needs you${reason}`) : '';
343
+ if (live.status === 'crashed') {
344
+ suffix = chalk.redBright(' ← the host app or connection went away and took the agent with it');
345
+ }
346
+ else if (live.status === 'orphaned') {
347
+ suffix = needsYou
348
+ ? chalk.yellow(` ← waiting on you${reason}, and no client is attached to answer it`)
349
+ : chalk.yellow(' ← still running, but no client is attached — nothing is showing it');
350
+ }
351
+ return `${star}${glyph} ${statusColor(live.status)(word)}${suffix}`;
352
+ }
353
+ export function teamTag(session) {
354
+ const origin = session.teamOrigin;
355
+ if (!origin)
356
+ return '';
357
+ const handle = safeTeamText(origin.handle);
358
+ const team = safeTeamText(origin.team);
359
+ if (team)
360
+ return `[${team}${handle ? `/${handle}` : ''}] `;
361
+ return handle ? `[${handle}] ` : '[team] ';
362
+ }
363
+ const TEAM_BADGE_MAX = 10;
364
+ export function teamBadge(session) {
365
+ const team = safeTeamText(session.spawnedTeam);
366
+ if (!team)
367
+ return { plain: '', width: 0 };
368
+ const plain = `team:${truncate(team, TEAM_BADGE_MAX)} `;
369
+ return { plain, width: stringWidth(plain) };
370
+ }
371
+ export function originTag(session) {
372
+ if (session.origin !== 'routine')
373
+ return '';
374
+ return `[routine${session.routineName ? ` · ${session.routineName}` : ''}] `;
375
+ }
376
+ const MIN_TOPIC_W = 16;
377
+ export function timeCell(age, topicSlack) {
378
+ const lastOnly = { plain: age.last, text: chalk.gray(age.last), extraW: 0 };
379
+ if (!age.created)
380
+ return lastOnly;
381
+ const prefix = `${age.created} → `;
382
+ const extraW = stringWidth(prefix);
383
+ if (topicSlack - extraW < MIN_TOPIC_W)
384
+ return lastOnly;
385
+ return { plain: prefix + age.last, text: chalk.dim(prefix) + chalk.gray(age.last), extraW };
386
+ }
387
+ export function flatSessionRow(session, live, showTicket = false, cols = {}, bookmarked = false) {
388
+ const shown = sessionDisplayAgent(session);
389
+ const agentColor = colorAgent(shown);
390
+ const age = sessionAgeParts(session.timestamp, session.lastActivity);
391
+ const project = session.project || '-';
392
+ const tag = originTag(session) || teamTag(session);
393
+ const label = session.label;
394
+ const { glyph, preview } = liveGlyphAndPreview(live);
395
+ const restingTodo = !live ? formatTodoCompact(session.todos) : '';
396
+ const topicBase = tag ? `${tag}${session.topic ?? ''}` : session.topic;
397
+ const doing = [restingTodo, preview || topicBase].filter(Boolean).join(' · ') || undefined;
398
+ const wt = session.worktreeSlug ? chalk.magenta(`wt:${session.worktreeSlug}`) : '';
399
+ const team = teamBadge(session);
400
+ const teamSeg = team.plain ? chalk.green(team.plain) : '';
401
+ const machineColW = cols.machineWidth ?? PICKER_MACHINE_W;
402
+ const machineCell = cols.showMachine
403
+ ? chalk.gray(padToWidth(truncateToWidth((cols.machineLabel?.(session.machine ?? '') ?? session.machine ?? '') || '-', machineColW - 1), machineColW))
404
+ : '';
405
+ const TICKET_W = 10;
406
+ const ticketCell = showTicket
407
+ ? chalk.blue(linkTicketCell(session, padToWidth(truncateToWidth(ticketLabel(session) || '-', TICKET_W), TICKET_W + 1)))
408
+ : '';
409
+ const { cell: statusCell, width: statusW } = liveStatusCell(live);
410
+ const glyphW = glyph ? 2 : 0;
411
+ const machineW = cols.showMachine ? machineColW : 0;
412
+ const ticketW = showTicket ? TICKET_W + 1 : 0;
413
+ const wtW = wt ? stringWidth(wt) + 1 : 0;
414
+ const width = terminalWidth();
415
+ const requestedModelW = cols.showModel ? (cols.modelWidth ?? PICKER_MODEL_MAX) : 0;
416
+ const bookmarkW = cols.showBookmark ? 2 : 0;
417
+ const bookmarkCell = cols.showBookmark ? (bookmarked ? chalk.yellow('★ ') : ' ') : '';
418
+ const fixedW = bookmarkW + (10 + 9 + 8 + 16) + glyphW + statusW + machineW + ticketW + wtW + team.width + stringWidth(age.last) + 1;
419
+ const modelSlack = width - fixedW - MIN_TOPIC_W;
420
+ const modelW = requestedModelW <= modelSlack
421
+ ? requestedModelW
422
+ : modelSlack >= PICKER_MODEL_MIN ? modelSlack : 0;
423
+ const when = timeCell(age, width - fixedW - modelW);
424
+ const topicW = Math.max(MIN_TOPIC_W, width - fixedW - modelW - when.extraW);
425
+ return (bookmarkCell +
426
+ chalk.white(padToWidth(truncateToWidth(session.shortId, 9), 10)) +
427
+ agentColor(padToWidth(truncateToWidth(shown, 8), 9)) +
428
+ chalk.yellow(padToWidth(truncateToWidth(session.version || '-', 7), 8)) +
429
+ (modelW ? chalk.yellow(padToWidth(truncateToWidth(modelLabel(session.model), modelW - 1), modelW)) : '') +
430
+ machineCell +
431
+ chalk.cyan(linkCwdCell(session, padToWidth(truncateToWidth(project, 14), 16))) +
432
+ (glyph ? glyph + ' ' : '') +
433
+ statusCell +
434
+ teamSeg +
435
+ renderTopicCell(label, doing, '', topicW, topicW) +
436
+ ticketCell +
437
+ (wt ? wt + ' ' : '') +
438
+ when.text);
439
+ }
440
+ export function treeSessionRow(session, live) {
441
+ const shown = sessionDisplayAgent(session);
442
+ const agentColor = colorAgent(shown);
443
+ const age = sessionAgeParts(session.timestamp, session.lastActivity);
444
+ const tag = originTag(session) || teamTag(session);
445
+ const label = session.label;
446
+ const { glyph, preview } = liveGlyphAndPreview(live);
447
+ const restingTodo = !live ? formatTodoCompact(session.todos) : '';
448
+ const topicBase = preview || (tag ? `${tag}${session.topic ?? ''}` : session.topic);
449
+ const topic = [restingTodo, topicBase].filter(Boolean).join(' · ') || '-';
450
+ const badges = signalBadges(metaSignals(session));
451
+ const badgeW = badges ? stringWidth(badges) + 1 : 0;
452
+ const team = teamBadge(session);
453
+ const teamSeg = team.plain ? chalk.green(team.plain) : '';
454
+ const head = label ? `${label} · ${topic}` : topic;
455
+ const { cell: statusCell, width: statusW } = liveStatusCell(live);
456
+ const glyphW = glyph ? 2 : 0;
457
+ const baseTopicW = terminalWidth() - (2 + 9 + 8) - glyphW - statusW - badgeW - team.width - stringWidth(age.last) - 1;
458
+ const when = timeCell(age, baseTopicW);
459
+ const topicW = Math.max(12, baseTopicW - when.extraW);
460
+ return (' ' +
461
+ chalk.dim(padToWidth(session.shortId, 9)) +
462
+ agentColor(padToWidth(truncateToWidth(shown, 7), 8)) +
463
+ (badges ? badges + ' ' : '') +
464
+ (glyph ? glyph + ' ' : '') +
465
+ statusCell +
466
+ teamSeg +
467
+ padToWidth(chalk.white(truncateToWidth(head, topicW)), topicW) +
468
+ ' ' + when.text);
469
+ }
470
+ export function printSessionTable(sessions, hiddenCount = 0, tree = false, liveIndex) {
471
+ if (tree) {
472
+ const byDir = new Map();
473
+ for (const s of sessions) {
474
+ const key = s.cwd || s.project || 'unknown';
475
+ (byDir.get(key) ?? byDir.set(key, []).get(key)).push(s);
476
+ }
477
+ const keys = [...byDir.keys()].sort((a, b) => {
478
+ const d = byDir.get(b).length - byDir.get(a).length;
479
+ return d !== 0 ? d : a.localeCompare(b);
480
+ });
481
+ let first = true;
482
+ for (const key of keys) {
483
+ if (!first)
484
+ console.log();
485
+ first = false;
486
+ const group = byDir.get(key);
487
+ const cwd = group.find((s) => s.cwd && !s._remote)?.cwd;
488
+ const header = cwd ? linkPath(cwd, shortCwd(key)) : shortCwd(key);
489
+ console.log(`${chalk.cyan.bold(header)} ${chalk.gray(`(${group.length})`)}`);
490
+ for (const s of group)
491
+ console.log(treeSessionRow(s, liveIndex?.get(s.id)));
492
+ }
493
+ const dirWord = keys.length === 1 ? 'directory' : 'directories';
494
+ console.log(chalk.gray(`\n${sessions.length} session${sessions.length === 1 ? '' : 's'} across ${keys.length} ${dirWord}.`));
495
+ if (hiddenCount > 0)
496
+ console.log(chalk.gray(formatTeamHiddenFooter(hiddenCount)));
497
+ return;
498
+ }
499
+ const showTicket = sessions.some((s) => ticketLabel(s) !== '');
500
+ const cols = pickerColumnsFor(sessions);
501
+ const bookmarks = listBookmarks();
502
+ for (const session of sessions) {
503
+ console.log(flatSessionRow(session, liveIndex?.get(session.id), showTicket, cols, bookmarks.has(session.id)));
504
+ }
505
+ const countLine = `${sessions.length} session${sessions.length === 1 ? '' : 's'}.`;
506
+ console.log(chalk.gray(`\n${countLine}`));
507
+ if (hiddenCount > 0) {
508
+ console.log(chalk.gray(formatTeamHiddenFooter(hiddenCount)));
509
+ }
510
+ }
511
+ export function renderTopicCell(label, topic, query, visibleWidth, paddedWidth) {
512
+ const lbl = (label ?? '').trim();
513
+ const tpc = (topic ?? '').trim();
514
+ const sep = ' · ';
515
+ const raw = lbl && tpc ? `${lbl}${sep}${tpc}` : (lbl || tpc);
516
+ const visible = truncateToWidth(raw, visibleWidth);
517
+ const padding = ' '.repeat(Math.max(0, paddedWidth - stringWidth(visible)));
518
+ const labelEnd = lbl ? Math.min(lbl.length, visible.length) : 0;
519
+ let matchStart = -1, matchEnd = -1;
520
+ const q = query.trim().toLowerCase();
521
+ if (q) {
522
+ const lower = visible.toLowerCase();
523
+ for (const term of q.split(/\s+/).filter(Boolean)) {
524
+ const idx = lower.indexOf(term);
525
+ if (idx !== -1) {
526
+ matchStart = idx;
527
+ matchEnd = idx + term.length;
528
+ break;
529
+ }
530
+ }
531
+ }
532
+ const cuts = new Set([0, labelEnd, visible.length]);
533
+ if (matchStart >= 0) {
534
+ cuts.add(matchStart);
535
+ cuts.add(matchEnd);
536
+ }
537
+ const boundaries = [...cuts].sort((a, b) => a - b);
538
+ let out = '';
539
+ for (let i = 0; i < boundaries.length - 1; i++) {
540
+ const s = boundaries[i], e = boundaries[i + 1];
541
+ if (s >= e)
542
+ continue;
543
+ const text = visible.slice(s, e);
544
+ const isLabel = s < labelEnd;
545
+ const isMatch = matchStart >= 0 && s >= matchStart && e <= matchEnd;
546
+ out += (isMatch || isLabel) ? chalk.bold.white(text) : chalk.white(text);
547
+ }
548
+ return out + padding;
549
+ }
550
+ const PICKER_MACHINE_W = 11;
551
+ const PICKER_MACHINE_MIN = 8;
552
+ const PICKER_MACHINE_MAX = 18;
553
+ const PICKER_MODEL_MIN = 6;
554
+ const PICKER_MODEL_MAX = 13;
555
+ function machineColumnWidth(machines, label) {
556
+ const widest = machines.reduce((w, m) => Math.max(w, stringWidth(label(m))), 0);
557
+ return Math.min(PICKER_MACHINE_MAX, Math.max(PICKER_MACHINE_MIN, widest + 1));
558
+ }
559
+ function modelColumnWidth(sessions) {
560
+ const widest = sessions.reduce((width, session) => (Math.max(width, session.model ? stringWidth(modelLabel(session.model)) : 0)), 0);
561
+ return Math.min(PICKER_MODEL_MAX, Math.max(PICKER_MODEL_MIN, widest + 1));
562
+ }
563
+ export function machineLabeler(machines) {
564
+ const uniq = [...new Set(machines.filter(Boolean))];
565
+ if (uniq.length < 2)
566
+ return (m) => m;
567
+ const parts = uniq.map((m) => m.split('-'));
568
+ const min = Math.min(...parts.map((p) => p.length));
569
+ let shared = 0;
570
+ while (shared < min - 1 && parts.every((p) => p[shared] === parts[0][shared]))
571
+ shared++;
572
+ if (shared === 0)
573
+ return (m) => m;
574
+ return (m) => {
575
+ const p = m.split('-');
576
+ return p.length > shared ? p.slice(shared).join('-') : m;
577
+ };
578
+ }
579
+ export function pickerColumnsFor(sessions) {
580
+ const machines = sessions.map((s) => s.machine).filter((m) => !!m);
581
+ const distinct = [...new Set(machines)];
582
+ const machineLabel = machineLabeler(machines);
583
+ return {
584
+ showMachine: distinct.length > 1,
585
+ machineLabel,
586
+ machineWidth: machineColumnWidth(distinct, machineLabel),
587
+ showModel: sessions.some((s) => !!s.model),
588
+ modelWidth: modelColumnWidth(sessions),
589
+ showTicket: sessions.some((s) => ticketLabel(s) !== ''),
590
+ showBookmark: (() => {
591
+ const bookmarks = listBookmarks();
592
+ return bookmarks.size > 0 && sessions.some((s) => bookmarks.has(s.id));
593
+ })(),
594
+ };
595
+ }
596
+ const PICKER_HOST_W = 14;
597
+ export function liveHostLabel(a) {
598
+ if (!a?.host)
599
+ return '';
600
+ const viewer = a.viewingIn?.app;
601
+ return viewer && viewer !== a.host ? `${a.host}→${viewer}` : a.host;
602
+ }
603
+ export function formatPickerLabel(s, query, cols = {}, ssh, host = '', bookmarked = false, live) {
604
+ const shown = sessionDisplayAgent(s);
605
+ const agentColor = colorAgent(shown);
606
+ const age = sessionAgeParts(s.timestamp, s.lastActivity);
607
+ const project = s.project || '-';
608
+ const sshPlain = ssh ? (ssh.device ? `ssh←${ssh.device} ` : 'ssh ') : '';
609
+ const sshSeg = sshPlain ? chalk.red(sshPlain) : '';
610
+ const sshW = sshPlain ? stringWidth(sshPlain) : 0;
611
+ const team = teamBadge(s);
612
+ const teamSeg = team.plain ? chalk.green(team.plain) : '';
613
+ const tag = originTag(s) || teamTag(s);
614
+ const label = s.label;
615
+ const topic = tag ? `${tag}${s.topic ?? ''}` : s.topic;
616
+ const versionStr = s.version || '-';
617
+ const wt = s.worktreeSlug ? chalk.magenta(`wt:${s.worktreeSlug}`) : '';
618
+ const machineW = cols.machineWidth ?? PICKER_MACHINE_W;
619
+ const machineCell = cols.showMachine
620
+ ? chalk.gray(padRight(truncate((cols.machineLabel?.(s.machine ?? '') ?? s.machine ?? '') || '-', machineW - 1), machineW))
621
+ : '';
622
+ const TICKET_W = 10;
623
+ const ticketCell = cols.showTicket
624
+ ? chalk.blue(padRight(truncate(ticketLabel(s) || '-', TICKET_W), TICKET_W + 1))
625
+ : '';
626
+ const hostCell = cols.showHost
627
+ ? chalk.gray(padRight(truncate(host || '-', PICKER_HOST_W - 1), PICKER_HOST_W))
628
+ : '';
629
+ const gutter = cols.gutter ?? 2;
630
+ const machineColW = cols.showMachine ? machineW : 0;
631
+ const ticketW = cols.showTicket ? TICKET_W + 1 : 0;
632
+ const hostW = cols.showHost ? PICKER_HOST_W : 0;
633
+ const wtW = wt ? stringWidth(wt) + 1 : 0;
634
+ const bookmarkW = cols.showBookmark ? 2 : 0;
635
+ const bookmarkCell = cols.showBookmark ? (bookmarked ? chalk.yellow('★ ') : ' ') : '';
636
+ const status = cols.showStatus ? liveStatusCell(live) : { cell: '', width: 0 };
637
+ const statusW = cols.showStatus ? LIVE_STATUS_W : 0;
638
+ const statusCell = cols.showStatus ? (status.cell || ' '.repeat(LIVE_STATUS_W)) : '';
639
+ const baseTopicW = terminalWidth() - gutter - bookmarkW - statusW - (10 + 9 + 8 + 16) - machineColW - hostW - ticketW - wtW - sshW - team.width - stringWidth(age.last) - 1;
640
+ const when = timeCell(age, baseTopicW);
641
+ const topicW = Math.max(MIN_TOPIC_W, baseTopicW - when.extraW);
642
+ return (bookmarkCell +
643
+ chalk.white(padRight(truncate(s.shortId, 9), 10)) +
644
+ agentColor(padRight(truncate(shown, 8), 9)) +
645
+ chalk.yellow(padRight(truncate(versionStr, 7), 8)) +
646
+ machineCell +
647
+ hostCell +
648
+ chalk.cyan(padRight(truncate(project, 14), 16)) +
649
+ statusCell +
650
+ sshSeg +
651
+ teamSeg +
652
+ renderTopicCell(label, topic, query, topicW, topicW) +
653
+ ticketCell +
654
+ (wt ? wt + ' ' : '') +
655
+ when.text);
656
+ }
657
+ const PICKER_TIPS = [
658
+ 'Tip: narrow with -a/--agent (e.g. -a codex), or --project <name> for another folder.',
659
+ "Tip: --all searches every directory; -D/--device <machine> folds in another box's sessions.",
660
+ 'Tip: just type to fuzzy-search prompts and responses; press space to preview a session.',
661
+ 'Tip: --since 2d / --until <date> bound the time window; pass a session id to open it directly.',
662
+ ];
663
+ export function formatPickerTip(sessions) {
664
+ return chalk.gray(PICKER_TIPS[sessions.length % PICKER_TIPS.length]);
665
+ }
666
+ export function formatTeamHiddenFooter(hiddenCount) {
667
+ const noun = hiddenCount === 1 ? 'team session' : 'team sessions';
668
+ return `(${hiddenCount} ${noun} hidden — use --teams to show, or \`agents teams status\`)`;
669
+ }
670
+ export function notFoundByIdMessage(query) {
671
+ return [chalk.red(`No session with id ${query.trim()} on this machine.`)];
672
+ }
673
+ const SESSION_DETAIL_MAX_MESSAGES = 8;
674
+ const SESSION_DETAIL_MESSAGE_MAX_CHARS = 4_000;
675
+ export function sessionTranscriptStamp(session) {
676
+ try {
677
+ if (!session.filePath)
678
+ return undefined;
679
+ const stat = fs.statSync(session.filePath);
680
+ return { fileMtimeMs: stat.mtimeMs, fileSize: stat.size };
681
+ }
682
+ catch {
683
+ return undefined;
684
+ }
685
+ }
686
+ export function buildSessionDetailBlock(session, digest, events, sourceStamp) {
687
+ const bound = (text) => redactSecrets(sanitizeForTerminal(text)).slice(0, SESSION_DETAIL_MESSAGE_MAX_CHARS);
688
+ const stamp = sourceStamp ?? sessionTranscriptStamp(session);
689
+ const canDateEvents = sourceStamp !== undefined || events.length === 0;
690
+ const daemonProjection = stamp ? readSessionTimelineAny(session.id, stamp) : undefined;
691
+ let foldEvents = events;
692
+ if (foldEvents.length === 0 && session.filePath) {
693
+ foldEvents = readSessionTail(session.filePath, session.agent);
694
+ }
695
+ let projection = daemonProjection;
696
+ let onDemand = false;
697
+ if (!projection && foldEvents.length > 0) {
698
+ const state = foldTimeline(foldEvents, emptyTimelineState());
699
+ projection = {
700
+ request: state.request,
701
+ timeline: projectTimeline(state, undefined),
702
+ files: projectSessionFiles(state),
703
+ };
704
+ onDemand = true;
705
+ }
706
+ let messages;
707
+ if (foldEvents.length > 0) {
708
+ messages = foldEvents
709
+ .filter((e) => e.type === 'message' && !e._synthetic && Boolean(e.content) && (e.role === 'user' || e.role === 'assistant'))
710
+ .slice(-SESSION_DETAIL_MAX_MESSAGES)
711
+ .map(e => ({ role: e.role, text: bound(e.content), at: e.timestamp ?? null }));
712
+ }
713
+ else {
714
+ messages = [];
715
+ if (digest?.firstUser)
716
+ messages.push({ role: 'user', text: bound(digest.firstUser), at: session.timestamp ?? null });
717
+ if (digest?.lastAssistant)
718
+ messages.push({ role: 'assistant', text: bound(digest.lastAssistant), at: session.lastActivity ?? null });
719
+ }
720
+ const endStamp = sessionTranscriptStamp(session);
721
+ const unchanged = canDateEvents && stamp !== undefined && endStamp !== undefined
722
+ && stamp.fileMtimeMs === endStamp.fileMtimeMs && stamp.fileSize === endStamp.fileSize;
723
+ const partial = Boolean(digest?.partial) || !daemonProjection || !unchanged;
724
+ const reason = digest?.partialReason
725
+ ?? (onDemand
726
+ ? 'background timeline pass has not reached this session yet; request/timeline/files below are an on-demand bounded fold, not the full-history daemon projection'
727
+ : (!projection ? 'no transcript available to fold request/timeline/files for this session' : null));
728
+ return {
729
+ request: projection?.request ?? null,
730
+ timeline: projection?.timeline ?? null,
731
+ files: projection?.files ?? null,
732
+ messages,
733
+ sourceRevision: unchanged ? new Date(stamp.fileMtimeMs).toISOString() : null,
734
+ partial,
735
+ reason,
736
+ };
737
+ }
@@ -1,29 +1,18 @@
1
1
  import { type DeviceProfile } from '../../devices/registry.js';
2
- import { type RemoteAgentsJsonParseResult } from '../../remote-agents-json.js';
3
2
  import type { SessionMeta } from '@phnx-labs/sessions-cli/reader';
4
- import { type ToolProgramCountEnvelope, type ToolSearchEnvelope } from '../tool-index.js';
5
- export { REMOTE_STDOUT_MAX_BYTES, RemoteUtf8Accumulator } from '../../ssh-exec.js';
6
- export declare const REMOTE_TOOL_AGGREGATE_MAX_BYTES: number;
7
- interface RemoteToolByteBudget {
8
- remainingBytes: number;
9
- exhausted: boolean;
10
- }
11
- export declare function consumeRemoteToolByteBudget(budget: RemoteToolByteBudget, bytes: number): boolean;
12
- export declare function consumeParsedRemoteToolSearchBudget(budget: RemoteToolByteBudget, envelope: ToolSearchEnvelope): boolean;
13
3
  export declare function remoteListCommand(forwardedArgs: string[], os?: string): string;
14
4
  export declare function parseRemoteList(stdout: string, machine: string): SessionMeta[];
15
5
  export declare function parseRemoteListPayload(stdout: string, machine: string, safeResolver?: boolean): {
16
6
  items: SessionMeta[];
17
7
  valid: boolean;
18
8
  };
19
- export declare function sshCapture(target: string, remoteCmd: string, timeoutMs: number, aggregateBudget?: RemoteToolByteBudget, options?: {
9
+ export declare function sshCapture(target: string, remoteCmd: string, timeoutMs: number, options?: {
20
10
  multiplex?: boolean;
21
11
  port?: number;
22
12
  hostKeyOpts?: string[];
23
13
  }): Promise<{
24
14
  code: number | null;
25
15
  stdout: string;
26
- aggregateBudgetExceeded?: boolean;
27
16
  }>;
28
17
  interface RemoteListResult {
29
18
  sessions: SessionMeta[];
@@ -36,30 +25,6 @@ interface GatherRemoteListOptions {
36
25
  timeoutMs?: number;
37
26
  }
38
27
  export declare function gatherRemoteList(forwardedArgs: string[], hosts?: string[], opts?: GatherRemoteListOptions): Promise<RemoteListResult>;
39
- interface RemoteToolSearchResult {
40
- envelopes: Array<{
41
- machine: string;
42
- envelope: ToolSearchEnvelope;
43
- }>;
44
- deviceCount: number;
45
- unreachable: string[];
46
- truncated: string[];
47
- }
48
- interface RemoteToolProgramCountResult {
49
- envelopes: Array<{
50
- machine: string;
51
- envelope: ToolProgramCountEnvelope;
52
- }>;
53
- deviceCount: number;
54
- unreachable: string[];
55
- }
56
- export declare function parseRemoteToolProgramCount(stdout: string, machine: string, expectedProgram: string): RemoteAgentsJsonParseResult<{
57
- machine: string;
58
- envelope: ToolProgramCountEnvelope;
59
- }>;
60
- export declare function gatherRemoteToolProgramCounts(forwardedArgs: string[], hosts: string[] | undefined, expectedProgram: string): Promise<RemoteToolProgramCountResult>;
61
- export declare function parseRemoteToolSearch(stdout: string, machine: string, expectedClauses?: string[]): ToolSearchEnvelope | undefined;
62
- export declare function gatherRemoteToolSearch(forwardedArgs: string[], hosts?: string[], maxAggregateBytes?: number, expectedClauses?: string[]): Promise<RemoteToolSearchResult>;
63
28
  export declare function resolvePeerTarget(machine: string): Promise<{
64
29
  target: string;
65
30
  os?: string;
@@ -84,3 +49,7 @@ export declare function runOnPeer(args: string[], machine: string, opts?: {
84
49
  env?: Record<string, string>;
85
50
  sessionId?: string;
86
51
  }): Promise<'ok' | 'no-target' | 'unreachable'>;
52
+ export declare function hostToken(h: string): string;
53
+ export declare function shouldIncludeLocal(hosts: string[] | undefined, self: string): boolean;
54
+ export declare function remoteHostsToDial(hosts: string[] | undefined, self: string): string[] | undefined;
55
+ export {};