@phnx-labs/agents-cli 1.23.18 → 1.23.20

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 (78) hide show
  1. package/CHANGELOG.md +187 -0
  2. package/README.md +1 -1
  3. package/dist/bootstrap.js +1 -1
  4. package/dist/commands/cloud.js +1 -1
  5. package/dist/commands/config.js +1 -1
  6. package/dist/commands/detach.js +5 -1
  7. package/dist/commands/doctor.js +11 -7
  8. package/dist/commands/exec.d.ts +0 -17
  9. package/dist/commands/exec.js +17 -51
  10. package/dist/commands/focus.d.ts +10 -2
  11. package/dist/commands/focus.js +80 -19
  12. package/dist/commands/projects-todo.js +10 -5
  13. package/dist/commands/ps.d.ts +8 -2
  14. package/dist/commands/ps.js +175 -92
  15. package/dist/commands/sessions-picker.d.ts +0 -7
  16. package/dist/commands/sessions-picker.js +5 -299
  17. package/dist/commands/sessions-stop.js +2 -2
  18. package/dist/lib/account-registry.d.ts +3 -0
  19. package/dist/lib/account-registry.js +40 -0
  20. package/dist/lib/accounting/account-pool-collect.d.ts +2 -2
  21. package/dist/lib/accounting/account-pool-collect.js +4 -4
  22. package/dist/lib/accounting/account-pool.d.ts +1 -1
  23. package/dist/lib/accounting/account-pool.js +3 -1
  24. package/dist/lib/accounting/usage-sync.d.ts +1 -0
  25. package/dist/lib/accounting/usage-sync.js +20 -3
  26. package/dist/lib/accounting/usage.d.ts +4 -1
  27. package/dist/lib/accounting/usage.js +38 -6
  28. package/dist/lib/agent-spec/agents.js +12 -11
  29. package/dist/lib/cloud/store.d.ts +5 -1
  30. package/dist/lib/cloud/store.js +10 -3
  31. package/dist/lib/config-keys.d.ts +1 -1
  32. package/dist/lib/config-keys.js +1 -0
  33. package/dist/lib/daemon/account-state-daemon-service.js +9 -2
  34. package/dist/lib/daemon/self-update-service.js +1 -1
  35. package/dist/lib/device-config.d.ts +2 -1
  36. package/dist/lib/device-config.js +21 -11
  37. package/dist/lib/devices/health.d.ts +6 -0
  38. package/dist/lib/devices/health.js +11 -4
  39. package/dist/lib/feed/watch.js +2 -1
  40. package/dist/lib/fleet/apply.d.ts +1 -1
  41. package/dist/lib/fleet/apply.js +5 -2
  42. package/dist/lib/fleet-shared-state.d.ts +2 -0
  43. package/dist/lib/fleet-shared-state.js +3 -1
  44. package/dist/lib/github/project-prs.js +14 -1
  45. package/dist/lib/helper-versions.js +1 -1
  46. package/dist/lib/installations/versions.js +4 -3
  47. package/dist/lib/project-root.d.ts +1 -0
  48. package/dist/lib/project-root.js +11 -3
  49. package/dist/lib/projects.js +2 -2
  50. package/dist/lib/quick-todo.d.ts +5 -1
  51. package/dist/lib/quick-todo.js +14 -1
  52. package/dist/lib/remote-agents-json.js +4 -2
  53. package/dist/lib/self-update.d.ts +1 -1
  54. package/dist/lib/self-update.js +59 -2
  55. package/dist/lib/session/db.js +1 -1
  56. package/dist/lib/session/glance-files.d.ts +21 -0
  57. package/dist/lib/session/glance-files.js +123 -0
  58. package/dist/lib/session/presentation.d.ts +3 -0
  59. package/dist/lib/session/preview-digest.d.ts +13 -0
  60. package/dist/lib/session/preview-digest.js +328 -0
  61. package/dist/lib/session/recovery.d.ts +1 -1
  62. package/dist/lib/session/recovery.js +1 -1
  63. package/dist/lib/session/remote/remote-list.d.ts +3 -2
  64. package/dist/lib/session/remote/remote-list.js +12 -6
  65. package/dist/lib/session/remote/watch.d.ts +2 -0
  66. package/dist/lib/session/remote/watch.js +86 -5
  67. package/dist/lib/smart-launch.js +6 -1
  68. package/dist/lib/teams/placement-probe.d.ts +2 -0
  69. package/dist/lib/teams/placement-probe.js +8 -3
  70. package/dist/lib/terminal/engine.d.ts +2 -0
  71. package/dist/lib/terminal/engine.js +5 -3
  72. package/dist/lib/terminal/index.d.ts +1 -1
  73. package/dist/lib/terminal/index.js +1 -1
  74. package/dist/lib/terminal/run-surface.d.ts +1 -0
  75. package/dist/lib/terminal/run-surface.js +9 -0
  76. package/package.json +1 -1
  77. package/dist/lib/onepassword.d.ts +0 -57
  78. package/dist/lib/onepassword.js +0 -140
@@ -1,24 +1,20 @@
1
1
  import fs from 'node:fs';
2
- import path from 'node:path';
3
2
  import chalk from 'chalk';
4
- import { truncate, humanDuration, formatBytes } from '../lib/format.js';
3
+ import { truncate, humanDuration } from '../lib/format.js';
5
4
  import { sessionDisplayAgent } from '@phnx-labs/sessions-cli/reader';
6
5
  import { fetchPeerPreviewDigest, resolvePeerTarget, runOnPeer } from '../lib/session/remote-list.js';
7
- import { parseSession, sanitizeForTerminal, SNAPSHOT_TODO_TOOLS } from '@phnx-labs/sessions-cli/reader';
8
- import { readSessionTail, readSessionHead } from '@phnx-labs/sessions-cli/reader';
6
+ import { sanitizeForTerminal } from '@phnx-labs/sessions-cli/reader';
9
7
  import { safeTeamText } from '@phnx-labs/sessions-cli/reader';
10
- import { cleanSessionPrompt, extractSessionTopic, isSyntheticUserMessage, firstUserMessageFromEvents } from '@phnx-labs/sessions-cli/reader';
8
+ import { cleanSessionPrompt, extractSessionTopic, isSyntheticUserMessage } from '@phnx-labs/sessions-cli/reader';
11
9
  import { linkPath, linkUrl, relativeToCwd, shortenModel } from '@phnx-labs/sessions-cli/reader';
12
10
  import { linearIssueUrl } from '@phnx-labs/sessions-cli/reader';
13
- import { extractTodoProgress, WORKTREE_RE } from '@phnx-labs/sessions-cli/reader';
14
11
  import { renderMarkdown } from '../lib/markdown.js';
15
12
  import { wrapToWidth } from '../lib/wrap.js';
16
13
  import { terminalWidth, stringWidth } from '../lib/session/width.js';
17
14
  import { itemPicker } from '../lib/picker.js';
18
15
  import { createMemoryCache } from '../lib/memory-cache.js';
19
- import { classifyFileChanges, changeCounts, toolHistogram, detectTestResult } from '@phnx-labs/sessions-cli/reader';
20
- import { extractArtifacts, extractHooks, extractLinks, extractRepos, extractSkills, harnessTracksBackgroundShells, isBackgroundShellStart, isSubAgentTool, } from '@phnx-labs/sessions-cli/reader';
21
- import { getSessionPlugins, readSessionPreviewCache, writeSessionPreviewCache, readSessionContent, readArchivedSessionPreview } from '../lib/session/db.js';
16
+ import { readSessionContent } from '../lib/session/db.js';
17
+ import { CHANGED_FILES_MAX, DIRS_TOUCHED_MAX, loadSessionPreviewDigest, sanitizeMeta } from '../lib/session/preview-digest.js';
22
18
  import { machineId } from '../lib/session/sync/config.js';
23
19
  import { isPromptCancelled } from '../lib/format.js';
24
20
  import { sessionOwnerDevice } from '../lib/session/resume-owner.js';
@@ -43,42 +39,6 @@ export function githubRepoUrlFromCwd(cwd) {
43
39
  const m = norm.match(/\/github\.com\/([^/]+\/[^/]+)/);
44
40
  return m ? `https://github.com/${m[1]}` : undefined;
45
41
  }
46
- // Peer metadata is untrusted: bound its shape and strip terminal escapes before rendering.
47
- function sanitizeMeta(s) {
48
- const clean = (v) => (v == null ? v : sanitizeForTerminal(v));
49
- const todos = s.todos
50
- ? {
51
- ...s.todos,
52
- activeForm: clean(s.todos.activeForm),
53
- items: s.todos.items.map((it) => ({
54
- ...it,
55
- content: sanitizeForTerminal(it.content),
56
- activeForm: clean(it.activeForm),
57
- })),
58
- }
59
- : s.todos;
60
- return {
61
- ...s,
62
- id: sanitizeForTerminal(s.id),
63
- shortId: sanitizeForTerminal(s.shortId),
64
- filePath: sanitizeForTerminal(s.filePath),
65
- cwd: clean(s.cwd),
66
- project: clean(s.project),
67
- gitBranch: clean(s.gitBranch),
68
- version: clean(s.version),
69
- account: clean(s.account),
70
- topic: clean(s.topic),
71
- firstUserMessage: clean(s.firstUserMessage),
72
- label: clean(s.label),
73
- generatedTitle: clean(s.generatedTitle),
74
- ticketId: clean(s.ticketId),
75
- prUrl: clean(s.prUrl),
76
- plan: clean(s.plan),
77
- spawnedTeam: clean(s.spawnedTeam),
78
- recentDirectoriesTouched: s.recentDirectoriesTouched?.map(sanitizeForTerminal),
79
- todos,
80
- };
81
- }
82
42
  const previewCache = createMemoryCache({
83
43
  max: 256,
84
44
  ttlMs: 5 * 60_000,
@@ -242,67 +202,6 @@ function previewCacheKey(session, remote) {
242
202
  export function clearPreviewMemoryCacheForTest() {
243
203
  previewCache.clear();
244
204
  }
245
- export function loadSessionPreviewDigest(session) {
246
- if (!session.filePath || !fs.existsSync(session.filePath)) {
247
- const archived = readArchivedSessionPreview(session.id);
248
- if (archived) {
249
- archived.plugins = getSessionPlugins(session.id);
250
- return { digest: archived, events: [] };
251
- }
252
- return { events: [], error: 'no local transcript for this session (metadata-only entry, no archived digest)' };
253
- }
254
- const safe = sanitizeMeta(session);
255
- let events = [];
256
- let sourceStamp;
257
- try {
258
- sourceStamp = fs.statSync(session.filePath);
259
- }
260
- catch (err) {
261
- return { events, error: sanitizeForTerminal(err?.message ?? String(err)) };
262
- }
263
- let digest = readSessionPreviewCache(session.id, {
264
- fileMtimeMs: sourceStamp.mtimeMs,
265
- fileSize: sourceStamp.size,
266
- });
267
- if (!digest) {
268
- // Large uncached transcripts use bounded tail plus bounded head, so a tail follow-up is never mislabeled as the first prompt.
269
- if (sourceStamp.size > PREVIEW_DIGEST_MAX_PARSE_BYTES) {
270
- events = readSessionTail(session.filePath, session.agent);
271
- digest = buildSessionPreviewDigest(events, safe);
272
- if (session.firstUserMessage) {
273
- digest.firstUser = session.firstUserMessage;
274
- }
275
- else {
276
- digest.firstUser = firstUserMessageFromEvents(readSessionHead(session.filePath, session.agent)) ?? '';
277
- }
278
- digest.partial = true;
279
- digest.partialReason = `transcript is ${formatBytes(sourceStamp.size)}, over the ${formatBytes(PREVIEW_DIGEST_MAX_PARSE_BYTES)} bounded-parse limit for an uncached preview; digest reflects only the last ~128 KiB (tail) of the transcript, not the whole session`;
280
- writeSessionPreviewCache({
281
- id: session.id,
282
- fileMtimeMs: sourceStamp.mtimeMs,
283
- fileSize: sourceStamp.size,
284
- preview: digest,
285
- });
286
- }
287
- else {
288
- try {
289
- events = parseSession(session.filePath, session.agent);
290
- digest = buildSessionPreviewDigest(events, safe);
291
- writeSessionPreviewCache({
292
- id: session.id,
293
- fileMtimeMs: sourceStamp.mtimeMs,
294
- fileSize: sourceStamp.size,
295
- preview: digest,
296
- });
297
- }
298
- catch (err) {
299
- return { events, error: sanitizeForTerminal(err?.message ?? String(err)) };
300
- }
301
- }
302
- }
303
- digest.plugins = getSessionPlugins(session.id);
304
- return { digest, events };
305
- }
306
205
  export function buildPreview(session) {
307
206
  const remote = transcriptOnPeerOf(session);
308
207
  const cacheKey = previewCacheKey(session, remote);
@@ -540,15 +439,6 @@ function formatTokens(n) {
540
439
  const v = n / 1_000_000;
541
440
  return (v >= 100 ? Math.round(v).toString() : v.toFixed(1).replace(/\.0$/, '')) + 'm';
542
441
  }
543
- const SYSTEM_MESSAGE_PATTERNS = [
544
- /^\s*<environment_context>/i,
545
- /^\s*<system-reminder>/i,
546
- /^\s*<permissions\s/i,
547
- /^\s*<collaboration_mode>/i,
548
- /^\s*<local-command-caveat>/i,
549
- /^\s*# AGENTS\.md instructions for\b/i,
550
- /^\s*<command-(message|name|args)>/i,
551
- ];
552
442
  function stripTags(text) {
553
443
  let cleaned = text.replace(/<(system-reminder|environment_context|permissions[^>]*)>[\s\S]*?<\/\1>/gi, '');
554
444
  cleaned = cleaned.replace(/<\/?[a-z_-]+[^>]*>/gi, '');
@@ -557,96 +447,6 @@ function stripTags(text) {
557
447
  const LAST_RESPONSE_MAX_LINES = 15;
558
448
  const LAST_RESPONSE_MAX_LINES_WITH_TODOS = 8;
559
449
  const TODOS_MAX_ITEMS = 5;
560
- const DIRS_TOUCHED_MAX = 5;
561
- const CHANGED_FILES_MAX = 200;
562
- const PREVIEW_DIGEST_MAX_PARSE_BYTES = 4 * 1024 * 1024;
563
- export function buildSessionPreviewDigest(events, session) {
564
- let firstUser = '';
565
- let lastAssistant = '';
566
- const filesRead = new Set();
567
- const toolCounts = {};
568
- let toolCalls = 0;
569
- let planFile = '';
570
- let latestTodos;
571
- let subAgentCount = 0;
572
- let backgroundShellCount = harnessTracksBackgroundShells(session.agent)
573
- ? 0
574
- : undefined;
575
- const toolTags = new Set();
576
- const knownToolUsage = session.usedBrowser !== undefined;
577
- for (const event of events) {
578
- if (event.type === 'message') {
579
- if (event.role === 'user' && !event._synthetic && !firstUser && event.content) {
580
- if (!SYSTEM_MESSAGE_PATTERNS.some(p => p.test(event.content))) {
581
- firstUser = event.content;
582
- }
583
- }
584
- if (event.role === 'assistant' && event.content) {
585
- lastAssistant = event.content;
586
- }
587
- }
588
- else if (event.type === 'tool_use' && !event._local) {
589
- const tool = event.tool || '';
590
- const command = event.command || '';
591
- if (!knownToolUsage) {
592
- for (const tag of classifySessionTool(tool, command))
593
- toolTags.add(tag);
594
- }
595
- if (isSubAgentTool(tool, command))
596
- subAgentCount++;
597
- if (backgroundShellCount !== undefined && isBackgroundShellStart(event))
598
- backgroundShellCount++;
599
- const p = event.path || event.args?.file_path || event.args?.path || '';
600
- if (['Read', 'read_file', 'view_file', 'cat_file', 'get_file'].includes(tool) && p) {
601
- filesRead.add(p);
602
- }
603
- if (!planFile && p && /\/plans\/[^/]+\.md$/.test(p)) {
604
- planFile = p;
605
- }
606
- if (SNAPSHOT_TODO_TOOLS.has(tool)) {
607
- const progress = extractTodoProgress(event.args);
608
- if (progress)
609
- latestTodos = progress;
610
- }
611
- if (tool)
612
- toolCounts[tool] = (toolCounts[tool] ?? 0) + 1;
613
- toolCalls++;
614
- }
615
- }
616
- if (session.usedBrowser)
617
- toolTags.add('browser');
618
- if (session.usedComputer)
619
- toolTags.add('computer');
620
- const todos = latestTodos ?? session.todos;
621
- const changes = classifyFileChanges(events);
622
- const chg = changeCounts(changes);
623
- const errorEvents = events.filter(e => e.type === 'error');
624
- return {
625
- schemaVersion: 1,
626
- firstUser,
627
- lastAssistant,
628
- filesRead: filesRead.size,
629
- toolCalls,
630
- planFile,
631
- todos,
632
- subAgentCount,
633
- backgroundShellCount,
634
- toolTags: [...toolTags],
635
- changes: chg,
636
- changedFiles: changes.slice(0, CHANGED_FILES_MAX),
637
- dirs: directoriesTouched(session, events, changes),
638
- repos: extractRepos(events, session.cwd),
639
- artifacts: extractArtifacts(changes),
640
- skills: extractSkills(events),
641
- plugins: getSessionPlugins(session.id),
642
- hooks: extractHooks(events),
643
- links: extractLinks(events),
644
- errorCount: errorEvents.length,
645
- firstError: errorEvents[0]?.tool,
646
- toolHistogram: toolHistogram(toolCounts, 4),
647
- test: detectTestResult(events),
648
- };
649
- }
650
450
  const VERB_GUTTER = 9;
651
451
  function verbLabel(v) {
652
452
  return chalk.cyan(v.padEnd(VERB_GUTTER)) + ' ';
@@ -756,55 +556,6 @@ function formatCompactPreview(digest, session, events) {
756
556
  lines.push(verbLabel('Details ▸') + joinWidthCapped(details, valueWidth));
757
557
  return lines.map(l => ' ' + l).join('\n');
758
558
  }
759
- function classifySessionTool(tool, command) {
760
- const toolName = tool.toLowerCase();
761
- const commandUses = (surface) => (new RegExp(`\\b(?:agents|ag)\\b[^\\n;&|]*\\b${surface}\\b`).test(command.toLowerCase()));
762
- const tags = [];
763
- if (/browser|webfetch|websearch/.test(toolName) || commandUses('browser'))
764
- tags.push('browser');
765
- if (/computer/.test(toolName) || commandUses('computer'))
766
- tags.push('computer');
767
- return tags;
768
- }
769
- function directoriesTouched(session, events, changes) {
770
- const fromMeta = session.recentDirectoriesTouched;
771
- if (Array.isArray(fromMeta) && fromMeta.length > 0) {
772
- const seen = new Set();
773
- for (const raw of fromMeta) {
774
- const dir = relativizeDir(sanitizeForTerminal(String(raw).trim()), session.cwd);
775
- if (dir)
776
- seen.add(dir);
777
- if (seen.size >= DIRS_TOUCHED_MAX)
778
- break;
779
- }
780
- if (seen.size > 0)
781
- return [...seen];
782
- }
783
- const counts = new Map();
784
- const bump = (raw) => {
785
- const dir = relativizeDir(raw, session.cwd);
786
- if (!dir)
787
- return;
788
- counts.set(dir, (counts.get(dir) ?? 0) + 1);
789
- };
790
- for (const ch of changes)
791
- bump(ch.path);
792
- for (const event of events) {
793
- if (event.type !== 'tool_use' || event._local)
794
- continue;
795
- const p = event.path || event.args?.file_path || event.args?.path || '';
796
- if (p)
797
- bump(p);
798
- }
799
- return [...counts.entries()]
800
- .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
801
- .map(([d]) => d)
802
- .slice(0, DIRS_TOUCHED_MAX);
803
- }
804
- function encodeClaudeSlug(absPath) {
805
- return absPath.replace(/[/.]/g, '-');
806
- }
807
- const SLUG_WORKTREE_RE = /--agents-worktrees-(.+)$/;
808
559
  function joinWidthCapped(items, maxWidth) {
809
560
  let out = '';
810
561
  let width = 0;
@@ -821,51 +572,6 @@ function joinWidthCapped(items, maxWidth) {
821
572
  const remaining = items.length - shown;
822
573
  return out + (remaining > 0 ? chalk.gray(` … +${remaining} more`) : '');
823
574
  }
824
- export function relativizeDir(filePath, cwd) {
825
- const norm = filePath.replace(/\\/g, '/');
826
- if (!norm || norm.includes('node_modules') || norm.includes('/.git/') || norm.includes('/plans/')) {
827
- return undefined;
828
- }
829
- const normBase = cwd?.replace(/\\/g, '/').replace(/\/$/, '');
830
- const underCwd = normBase && (norm === normBase || norm.startsWith(normBase + '/'));
831
- if (!underCwd && (norm.includes('/.agents/.history/') || /\/\.agents\/worktrees(\/[^/]+)?\/?$/.test(norm))) {
832
- return undefined;
833
- }
834
- let dir = path.posix.dirname(norm);
835
- if (dir.startsWith('-')) {
836
- const slash = dir.indexOf('/');
837
- const slug = slash === -1 ? dir : dir.slice(0, slash);
838
- if (cwd) {
839
- const cwdSlug = encodeClaudeSlug(cwd.replace(/\\/g, '/').replace(/\/$/, ''));
840
- if (slug === cwdSlug || slug.startsWith(cwdSlug + '-'))
841
- return undefined;
842
- }
843
- const wtSlug = slug.match(SLUG_WORKTREE_RE);
844
- if (wtSlug)
845
- return `⧉ ${wtSlug[1]}`;
846
- const segs = slug.split('-').filter(Boolean);
847
- return segs.length ? segs[segs.length - 1] : undefined;
848
- }
849
- if (cwd) {
850
- const base = cwd.replace(/\\/g, '/').replace(/\/$/, '');
851
- if (dir === base)
852
- return '.';
853
- if (dir.startsWith(base + '/'))
854
- return dir.slice(base.length + 1);
855
- }
856
- const wt = dir.match(WORKTREE_RE);
857
- if (wt) {
858
- const after = dir.slice(dir.indexOf(wt[0]) + wt[0].length).replace(/^\//, '');
859
- return after ? `⧉ ${wt[1]}/${after}` : `⧉ ${wt[1]}`;
860
- }
861
- const home = (process.env.HOME || '').replace(/\\/g, '/');
862
- if (home && dir.startsWith(home + '/'))
863
- dir = '~' + dir.slice(home.length);
864
- const parts = dir.split('/').filter(Boolean);
865
- if (parts.length > 3 && dir.startsWith('/'))
866
- dir = parts.slice(-3).join('/');
867
- return dir || undefined;
868
- }
869
575
  export function renderLastResponse(content, maxLines = LAST_RESPONSE_MAX_LINES, width = terminalWidth()) {
870
576
  const cleaned = stripTags(content).trim();
871
577
  if (!cleaned)
@@ -50,10 +50,10 @@ async function stopSessionAction(id, opts = {}) {
50
50
  if (target.kind === 'remote') {
51
51
  console.log(chalk.gray(`${short} lives on ${target.machine} — stopping it there over SSH…`));
52
52
  const rc = await runOnPeer(['ps', 'stop', target.sessionId, '--local'], target.machine);
53
- if (rc === 'no-target') {
53
+ if (rc === 'no-target')
54
54
  console.error(chalk.red(`Can't reach ${target.machine} to stop ${short}.`));
55
+ if (rc !== 'ok')
55
56
  process.exitCode = 1;
56
- }
57
57
  return;
58
58
  }
59
59
  await stopInteractive(s);
@@ -42,6 +42,9 @@ export declare function parseAccountSelector(input: string): {
42
42
  export declare function assertUnambiguousNativeAccount(meta: Pick<Meta, 'accounts' | 'deviceAccounts'>, name: string, agent?: AgentId): void;
43
43
  export declare function assertNativeAccountNameAvailable(name: string, agent: AgentId): void;
44
44
  export declare function addNativeAccount(name: string, agent: AgentId, identityKey: string, identityLabel: string | undefined, scope: 'version' | 'device'): NativeAccount;
45
+ export declare const PEER_ACCOUNT_ROW_LIMIT = 256;
46
+ export declare function peerAccountRow(record: NativeAccountRecord): NativeAccountRecord;
47
+ export declare function adoptPeerNativeAccounts(records: readonly NativeAccountRecord[]): string[];
45
48
  export declare function labelNativeAccount(agent: AgentId, identityKey: string, identityLabel: string | undefined, label: string | undefined, scope: 'version' | 'device'): NativeAccount;
46
49
  export declare function nativeAccountHome(accountId: string, meta: Pick<Meta, 'deviceAccounts'>): string | null;
47
50
  export declare function setDefaultAccountIfAbsent(agent: AgentId, name: string): boolean;
@@ -213,6 +213,46 @@ export function addNativeAccount(name, agent, identityKey, identityLabel, scope)
213
213
  }
214
214
  return account;
215
215
  }
216
+ export const PEER_ACCOUNT_ROW_LIMIT = 256;
217
+ const PEER_ACCOUNT_ID = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$/;
218
+ export function peerAccountRow(record) {
219
+ const { id, name, agent, identityKey, identityLabel, createdOn } = record;
220
+ return {
221
+ id, name, agent, identityKey, scope: 'version', provisioning: 'per-device',
222
+ ...(identityLabel ? { identityLabel } : {}),
223
+ ...(createdOn ? { createdOn } : {}),
224
+ };
225
+ }
226
+ function missingPeerRows(meta, records) {
227
+ const known = listNativeAccounts(meta);
228
+ const missing = [];
229
+ for (const record of records.slice(0, PEER_ACCOUNT_ROW_LIMIT)) {
230
+ if (record.scope !== 'version' || record.provisioning !== 'per-device' || !PEER_ACCOUNT_ID.test(record.id))
231
+ continue;
232
+ if (Object.hasOwn(meta.accounts?.native ?? {}, record.id))
233
+ continue;
234
+ const taken = [...known, ...missing].some(account => account.id === record.id || account.agent === record.agent
235
+ && (account.identityKey === record.identityKey || account.name === record.name));
236
+ if (!taken)
237
+ missing.push(peerAccountRow(record));
238
+ }
239
+ return missing;
240
+ }
241
+ export function adoptPeerNativeAccounts(records) {
242
+ if (missingPeerRows(readMeta(), records).length === 0)
243
+ return [];
244
+ let adopted = [];
245
+ updateMeta(current => {
246
+ adopted = missingPeerRows(current, records);
247
+ if (adopted.length === 0)
248
+ return current;
249
+ const native = { ...current.accounts?.native };
250
+ for (const row of adopted)
251
+ native[row.id] = row;
252
+ return { ...current, accounts: { ...current.accounts, native } };
253
+ });
254
+ return adopted.map(row => row.id);
255
+ }
216
256
  export function labelNativeAccount(agent, identityKey, identityLabel, label, scope) {
217
257
  const resolvedLabel = label ?? identityLabel;
218
258
  if (!resolvedLabel)
@@ -6,5 +6,5 @@ export interface RunCandidateInputs {
6
6
  records: RegistryAccountRecord[];
7
7
  runVersion: string | undefined;
8
8
  }
9
- export declare function foldRegistryCandidates(agent: AgentId, inputs: RunCandidateInputs): RotateCandidate[];
10
- export declare function collectRunCandidatesForRun(agent: AgentId): Promise<RotateCandidate[]>;
9
+ export declare function foldRegistryCandidates(agent: AgentId, inputs: RunCandidateInputs, includeKeyed?: boolean): RotateCandidate[];
10
+ export declare function collectRunCandidatesForRun(agent: AgentId, includeKeyed?: boolean): Promise<RotateCandidate[]>;
@@ -15,12 +15,12 @@ function localRegistryRecords() {
15
15
  throw err;
16
16
  }
17
17
  }
18
- export function foldRegistryCandidates(agent, inputs) {
18
+ export function foldRegistryCandidates(agent, inputs, includeKeyed = false) {
19
19
  const { native, records, runVersion } = inputs;
20
20
  if (!runVersion)
21
21
  return native;
22
22
  const seen = new Set(native.filter((c) => c.accountKey).map((c) => c.accountKey));
23
- const extra = registryPoolCandidates(records, agent)
23
+ const extra = registryPoolCandidates(records, agent, includeKeyed)
24
24
  .filter((r) => !seen.has(r.accountKey))
25
25
  .map((r) => ({
26
26
  agent,
@@ -42,8 +42,8 @@ export function foldRegistryCandidates(agent, inputs) {
42
42
  }));
43
43
  return [...native, ...extra];
44
44
  }
45
- export async function collectRunCandidatesForRun(agent) {
45
+ export async function collectRunCandidatesForRun(agent, includeKeyed = false) {
46
46
  const native = await collectRunCandidates(agent);
47
47
  const runVersion = getGlobalDefault(agent) ?? listInstalledVersions(agent)[0];
48
- return foldRegistryCandidates(agent, { native, records: localRegistryRecords(), runVersion });
48
+ return foldRegistryCandidates(agent, { native, records: localRegistryRecords(), runVersion }, includeKeyed);
49
49
  }
@@ -16,5 +16,5 @@ interface RegistryAccountInput {
16
16
  auth: AccountAuthKind;
17
17
  secretPresent: boolean;
18
18
  }
19
- export declare function registryPoolCandidates(records: RegistryAccountRecord[], agent: AgentId): RegistryAccountInput[];
19
+ export declare function registryPoolCandidates(records: RegistryAccountRecord[], agent: AgentId, includeKeyed?: boolean): RegistryAccountInput[];
20
20
  export {};
@@ -1,7 +1,9 @@
1
1
  import { providerAuthenticatesHarness } from '../account-provider-registry.js';
2
- export function registryPoolCandidates(records, agent) {
2
+ export function registryPoolCandidates(records, agent, includeKeyed = false) {
3
3
  const out = [];
4
4
  for (const r of records) {
5
+ if (r.auth !== 'setup-token' && !includeKeyed)
6
+ continue;
5
7
  if (!providerAuthenticatesHarness(r.provider, r.auth, agent))
6
8
  continue;
7
9
  out.push({
@@ -88,6 +88,7 @@ interface ApplyPeerStateOptions {
88
88
  export interface ApplyPeerStateResult {
89
89
  path: string;
90
90
  merged: number;
91
+ adoptedAccounts: string[];
91
92
  receivedAt: number;
92
93
  }
93
94
  export declare function applyPeerFleetState(state: FleetSharedDeviceState, options?: ApplyPeerStateOptions): Promise<ApplyPeerStateResult>;
@@ -20,10 +20,11 @@
20
20
  * scheduled because a repo was bloated. Git now carries human-authored
21
21
  * resources only; `devices/<device>/daemon-state.json` is untracked.
22
22
  */
23
- import { isHeadedDeviceRole, selfConfiguredDeviceRole } from '../device-config.js';
23
+ import { configuredDeviceRole, isHeadedDeviceRole, selfConfiguredDeviceRole } from '../device-config.js';
24
24
  import { FLEET_SHARED_STATE_VERSION, parseFleetSharedDeviceStateEnvelope, readFleetSharedDeviceStates, readOwnFleetSharedDeviceState, storePeerFleetSharedDeviceState, updateFleetSharedDeviceStateAsync, } from '../fleet-shared-state.js';
25
25
  import { getUserAgentsDir } from '../state.js';
26
26
  import { machineId, normalizeHost } from '../session/sync/config.js';
27
+ import { resolveDeviceProfile } from '../devices/resolve-profile.js';
27
28
  import { exportClaudeUsageCacheRows, ingestPeerClaudeUsageRows, } from './usage.js';
28
29
  export const USAGE_SYNC_INTERVAL_MS = 15 * 60_000;
29
30
  export const USAGE_PUBLISH_HEARTBEAT_MS = 10 * 60_000;
@@ -193,6 +194,21 @@ function stampSyncRows(rows, sender) {
193
194
  }
194
195
  return out;
195
196
  }
197
+ async function adoptHeadedPeerAccounts(state) {
198
+ const native = state.accounts?.native;
199
+ if (!native?.length)
200
+ return [];
201
+ if (!isHeadedDeviceRole(configuredDeviceRole(state.device)))
202
+ return [];
203
+ const { isAgentId } = await import('../types.js');
204
+ const records = native.filter((record) => typeof record?.id === 'string' && typeof record.name === 'string'
205
+ && isAgentId(record.agent) && typeof record.identityKey === 'string' && record.scope === 'version'
206
+ && normalizeHost(record.createdOn ?? '') === normalizeHost(state.device));
207
+ if (records.length === 0)
208
+ return [];
209
+ const { adoptPeerNativeAccounts } = await import('../account-registry.js');
210
+ return adoptPeerNativeAccounts(records);
211
+ }
196
212
  // Peer state is newest-wins and can never overwrite this device's own publisher file.
197
213
  export async function applyPeerFleetState(state, options = {}) {
198
214
  const self = normalizeHost(options.device ?? machineId());
@@ -204,7 +220,8 @@ export async function applyPeerFleetState(state, options = {}) {
204
220
  const merged = state.usage
205
221
  ? await ingestPeerClaudeUsageRows(stampSyncRows(state.usage.rows, state.device), options.cachePath)
206
222
  : 0;
207
- return { path: write.path, merged, receivedAt };
223
+ const adoptedAccounts = await adoptHeadedPeerAccounts(state);
224
+ return { path: write.path, merged, adoptedAccounts, receivedAt };
208
225
  }
209
226
  export async function buildFleetStateExchangeCommand(os) {
210
227
  const { buildRemoteAgentsInvocation, buildWindowsStdinAgentsCommand, remoteShellFor } = await import('../hosts/remote-cmd.js');
@@ -241,7 +258,7 @@ export async function exchangeFleetStateWithPeers(options = {}) {
241
258
  const outcomes = await Promise.all(peers.map(async (peer) => {
242
259
  const outcome = { device: peer.name, delivered: false, receivedAt: null, merged: 0, error: null, peerErrors: [] };
243
260
  try {
244
- const remoteCmd = await buildFleetStateExchangeCommand(peer.shell === 'powershell' ? 'windows' : undefined);
261
+ const remoteCmd = await buildFleetStateExchangeCommand(resolveDeviceProfile(peer).shell === 'powershell' ? 'windows' : undefined);
245
262
  const res = await dial(peer, remoteCmd, input);
246
263
  if (res.timedOut)
247
264
  throw new Error(`timed out after ${Math.round(timeoutMs / 1000)}s`);
@@ -53,6 +53,7 @@ export interface UsageSnapshot {
53
53
  unavailable?: {
54
54
  reason: 'session_limit' | 'out_of_credits';
55
55
  resetsAt?: Date;
56
+ notedAt?: Date;
56
57
  };
57
58
  freshness?: {
58
59
  source: UsageCaptureSource;
@@ -125,6 +126,7 @@ export interface CachedUsageSnapshot {
125
126
  unavailable?: {
126
127
  reason: 'session_limit' | 'out_of_credits';
127
128
  resetsAt?: string;
129
+ notedAt?: string;
128
130
  };
129
131
  modelRefusals?: Record<string, CachedModelRefusal>;
130
132
  freshnessSource?: UsageCaptureSource;
@@ -317,7 +319,8 @@ export declare function writeClaudeUsageCache(usageKey: string, snapshot: UsageS
317
319
  export declare function mergeClaudeUsageCacheWindows(usageKey: string, snapshot: UsageSnapshot, cachePath?: string): void;
318
320
  export declare function exportClaudeUsageCacheRows(cachePath?: string): Record<string, CachedUsageSnapshot>;
319
321
  export declare function ingestPeerClaudeUsageRows(rows: Record<string, CachedUsageSnapshot>, cachePath?: string): Promise<number>;
320
- export declare function noteClaudeOutOfCredits(usageKey: string, cachePath?: string): void;
322
+ export declare const OUT_OF_CREDITS_REPROBE_MS: number;
323
+ export declare function noteClaudeOutOfCredits(usageKey: string, cachePath?: string, now?: Date): void;
321
324
  export declare function clearClaudeAccountRefusal(usageKey: string, cachePath?: string): void;
322
325
  export declare function noteClaudeSessionLimit(usageKey: string, resetsAt: Date, cachePath?: string): void;
323
326
  export declare function claudeModelRefusalKey(accountId?: string | null, home?: string | null): string | undefined;