@phnx-labs/agents-cli 1.23.0 → 1.23.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 (59) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +2 -0
  3. package/dist/commands/cloud-transcripts.js +1 -2
  4. package/dist/commands/daemon.js +70 -11
  5. package/dist/commands/exec.js +1 -1
  6. package/dist/commands/feed.js +1 -2
  7. package/dist/commands/focus.js +4 -1
  8. package/dist/commands/go.js +3 -2
  9. package/dist/commands/logs.js +1 -1
  10. package/dist/commands/menubar.js +28 -3
  11. package/dist/commands/ps-roster.d.ts +0 -11
  12. package/dist/commands/ps-roster.js +3 -116
  13. package/dist/commands/ps.d.ts +10 -0
  14. package/dist/commands/ps.js +182 -1
  15. package/dist/commands/resume.js +1 -1
  16. package/dist/commands/sessions-browser.d.ts +0 -1
  17. package/dist/commands/sessions-browser.js +6 -23
  18. package/dist/commands/sessions-export.js +1 -1
  19. package/dist/commands/sessions-migrate.js +1 -1
  20. package/dist/commands/sessions-picker.d.ts +6 -32
  21. package/dist/commands/sessions-picker.js +81 -8
  22. package/dist/commands/sessions-render.js +1 -1
  23. package/dist/commands/sessions-resume.js +2 -2
  24. package/dist/commands/sessions-share.js +1 -1
  25. package/dist/commands/sessions-trace.js +1 -1
  26. package/dist/commands/sessions.d.ts +2 -165
  27. package/dist/commands/sessions.js +16 -1216
  28. package/dist/lib/daemon/account-state-daemon-service.d.ts +2 -2
  29. package/dist/lib/daemon/account-state-daemon-service.js +2 -2
  30. package/dist/lib/daemon/attention-notify-service.js +8 -4
  31. package/dist/lib/daemon/daemon.d.ts +5 -1
  32. package/dist/lib/daemon/daemon.js +53 -6
  33. package/dist/lib/daemon/diagnostics.d.ts +70 -0
  34. package/dist/lib/daemon/diagnostics.js +185 -0
  35. package/dist/lib/daemon/service.d.ts +1 -1
  36. package/dist/lib/daemon/session-state-service.d.ts +1 -1
  37. package/dist/lib/daemon/session-state-service.js +2 -2
  38. package/dist/lib/daemon/supervisor.d.ts +8 -0
  39. package/dist/lib/daemon/supervisor.js +47 -6
  40. package/dist/lib/daemon-services.d.ts +3 -0
  41. package/dist/lib/daemon-services.js +36 -0
  42. package/dist/lib/daemon-ticks.d.ts +3 -1
  43. package/dist/lib/daemon-ticks.js +18 -12
  44. package/dist/lib/feed/tool-activity.js +10 -3
  45. package/dist/lib/feed/watch.js +8 -5
  46. package/dist/lib/helper-versions.js +1 -1
  47. package/dist/lib/menubar/install-menubar.d.ts +19 -1
  48. package/dist/lib/menubar/install-menubar.js +81 -12
  49. package/dist/lib/session/active.js +18 -14
  50. package/dist/lib/session/pid-registry.js +9 -6
  51. package/dist/lib/session/presentation.d.ts +107 -1
  52. package/dist/lib/session/presentation.js +543 -4
  53. package/dist/lib/session/remote/remote-list.d.ts +3 -0
  54. package/dist/lib/session/remote/remote-list.js +13 -0
  55. package/dist/lib/session/resume-command.d.ts +9 -0
  56. package/dist/lib/session/resume-command.js +107 -0
  57. package/dist/lib/session/selection.d.ts +102 -0
  58. package/dist/lib/session/selection.js +443 -0
  59. package/package.json +1 -1
@@ -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
+ }
@@ -49,4 +49,7 @@ export declare function runOnPeer(args: string[], machine: string, opts?: {
49
49
  env?: Record<string, string>;
50
50
  sessionId?: string;
51
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;
52
55
  export {};
@@ -216,3 +216,16 @@ export async function runOnPeer(args, machine, opts = {}) {
216
216
  });
217
217
  });
218
218
  }
219
+ export function hostToken(h) {
220
+ return normalizeHost(h.split('@').pop() || h);
221
+ }
222
+ export function shouldIncludeLocal(hosts, self) {
223
+ if (!hosts || hosts.length === 0)
224
+ return true;
225
+ return hosts.some(h => hostToken(h) === self);
226
+ }
227
+ export function remoteHostsToDial(hosts, self) {
228
+ if (!hosts || hosts.length === 0)
229
+ return undefined;
230
+ return hosts.filter(h => hostToken(h) !== self);
231
+ }
@@ -1 +1,10 @@
1
+ import type { SessionMeta } from '@phnx-labs/sessions-cli/reader';
1
2
  export declare function buildCanonicalResumeCommand(sessionId: string): string[];
3
+ export declare function resumeSessionInPlace(session: SessionMeta): Promise<void>;
4
+ export declare function buildSessionRecoveryCommand(session: Pick<SessionMeta, 'id'>, portable?: boolean): string[];
5
+ export declare function resumeSpawnInvocation(cmd: string[], platform?: NodeJS.Platform): {
6
+ command: string;
7
+ args: string[];
8
+ shell: boolean;
9
+ };
10
+ export declare function buildResumeCommand(session: SessionMeta): string[] | null;