@phnx-labs/agents-cli 1.23.18 → 1.23.19

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 (71) hide show
  1. package/CHANGELOG.md +173 -0
  2. package/dist/bootstrap.js +1 -1
  3. package/dist/commands/cloud.js +1 -1
  4. package/dist/commands/config.js +1 -1
  5. package/dist/commands/detach.js +5 -1
  6. package/dist/commands/doctor.js +11 -7
  7. package/dist/commands/exec.d.ts +0 -17
  8. package/dist/commands/exec.js +16 -50
  9. package/dist/commands/focus.d.ts +10 -2
  10. package/dist/commands/focus.js +80 -19
  11. package/dist/commands/projects-todo.js +10 -5
  12. package/dist/commands/ps.d.ts +8 -2
  13. package/dist/commands/ps.js +175 -92
  14. package/dist/commands/sessions-picker.d.ts +0 -7
  15. package/dist/commands/sessions-picker.js +5 -299
  16. package/dist/commands/sessions-stop.js +2 -2
  17. package/dist/lib/account-registry.d.ts +3 -0
  18. package/dist/lib/account-registry.js +40 -0
  19. package/dist/lib/accounting/usage-sync.d.ts +1 -0
  20. package/dist/lib/accounting/usage-sync.js +20 -3
  21. package/dist/lib/accounting/usage.d.ts +4 -1
  22. package/dist/lib/accounting/usage.js +38 -6
  23. package/dist/lib/agent-spec/agents.js +12 -11
  24. package/dist/lib/cloud/store.d.ts +5 -1
  25. package/dist/lib/cloud/store.js +10 -3
  26. package/dist/lib/config-keys.d.ts +1 -1
  27. package/dist/lib/config-keys.js +1 -0
  28. package/dist/lib/daemon/account-state-daemon-service.js +9 -2
  29. package/dist/lib/daemon/self-update-service.js +1 -1
  30. package/dist/lib/device-config.d.ts +2 -1
  31. package/dist/lib/device-config.js +21 -11
  32. package/dist/lib/devices/health.d.ts +6 -0
  33. package/dist/lib/devices/health.js +11 -4
  34. package/dist/lib/feed/watch.js +2 -1
  35. package/dist/lib/fleet/apply.d.ts +1 -1
  36. package/dist/lib/fleet/apply.js +5 -2
  37. package/dist/lib/fleet-shared-state.d.ts +2 -0
  38. package/dist/lib/fleet-shared-state.js +3 -1
  39. package/dist/lib/github/project-prs.js +14 -1
  40. package/dist/lib/helper-versions.js +1 -1
  41. package/dist/lib/installations/versions.js +4 -3
  42. package/dist/lib/project-root.d.ts +1 -0
  43. package/dist/lib/project-root.js +11 -3
  44. package/dist/lib/projects.js +2 -2
  45. package/dist/lib/quick-todo.d.ts +5 -1
  46. package/dist/lib/quick-todo.js +14 -1
  47. package/dist/lib/remote-agents-json.js +4 -2
  48. package/dist/lib/self-update.d.ts +1 -1
  49. package/dist/lib/self-update.js +59 -2
  50. package/dist/lib/session/db.js +1 -1
  51. package/dist/lib/session/glance-files.d.ts +21 -0
  52. package/dist/lib/session/glance-files.js +123 -0
  53. package/dist/lib/session/presentation.d.ts +3 -0
  54. package/dist/lib/session/preview-digest.d.ts +13 -0
  55. package/dist/lib/session/preview-digest.js +328 -0
  56. package/dist/lib/session/remote/remote-list.d.ts +3 -2
  57. package/dist/lib/session/remote/remote-list.js +12 -6
  58. package/dist/lib/session/remote/watch.d.ts +2 -0
  59. package/dist/lib/session/remote/watch.js +86 -5
  60. package/dist/lib/smart-launch.js +6 -1
  61. package/dist/lib/teams/placement-probe.d.ts +2 -0
  62. package/dist/lib/teams/placement-probe.js +8 -3
  63. package/dist/lib/terminal/engine.d.ts +2 -0
  64. package/dist/lib/terminal/engine.js +5 -3
  65. package/dist/lib/terminal/index.d.ts +1 -1
  66. package/dist/lib/terminal/index.js +1 -1
  67. package/dist/lib/terminal/run-surface.d.ts +1 -0
  68. package/dist/lib/terminal/run-surface.js +9 -0
  69. package/package.json +1 -1
  70. package/dist/lib/onepassword.d.ts +0 -57
  71. package/dist/lib/onepassword.js +0 -140
@@ -82,6 +82,7 @@ export declare class SessionWatchState {
82
82
  reset(scope: string, sourceRows: ActiveSession[], indexedRows?: SessionMeta[]): SessionWatchEnvelope;
83
83
  update(scope: string, sourceRows: ActiveSession[]): SessionWatchEnvelope[];
84
84
  patch(scope: string, upserts: ActiveSession[], removes: string[]): SessionWatchEnvelope[];
85
+ refreshPrevious(scope: string, session: SessionMeta, accounts?: import("../../account-registry.js").NativeAccount[]): SessionWatchEnvelope | undefined;
85
86
  scope(scope: string, status: SessionWatchScopeStatus, reason?: string): SessionWatchEnvelope;
86
87
  heartbeat(scope: string, capturedAt?: number): SessionWatchEnvelope;
87
88
  }
@@ -97,6 +98,7 @@ export interface WatchLocalOptions {
97
98
  journalPollMs?: number;
98
99
  }
99
100
  export declare function readPreviousSessionsForWatch(scope: string): SessionMeta[];
101
+ export declare function previewDigestBuildsForTest(): number;
100
102
  export declare function watchLocalSessions(options: WatchLocalOptions): Promise<void>;
101
103
  interface WatchFleetOptions {
102
104
  signal: AbortSignal;
@@ -4,13 +4,16 @@ import { createHash, randomUUID } from 'node:crypto';
4
4
  import * as fs from 'node:fs';
5
5
  import * as path from 'node:path';
6
6
  import { loadDevices, isDialableDevice } from '../../devices/registry.js';
7
+ import { resolveDeviceProfile } from '../../devices/resolve-profile.js';
7
8
  import { machineId, normalizeHost } from '../../machine-id.js';
8
9
  import { shellQuote } from '../../ssh-exec.js';
9
10
  import { streamFromPeer } from './peer-stream.js';
10
11
  import { buildWindowsAgentsCommand, remoteShellFor } from '../../hosts/remote-cmd.js';
11
- import { isReapableOrphan, sessionAccountLabel } from '../active.js';
12
+ import { artifactKind, deriveImportantMessage, deriveSessionRecap, isReapableOrphan, sessionAccountLabel } from '../active.js';
13
+ import { loadSessionPreviewDigest, readCachedPreviewDigest } from '../preview-digest.js';
14
+ import { indexArtifactSidecars, mergeArtifacts } from '@phnx-labs/sessions-cli/reader';
12
15
  import { listNativeAccounts } from '../../account-registry.js';
13
- import { readMeta } from '../../state.js';
16
+ import { getUserAgentsDir, readMeta } from '../../state.js';
14
17
  import { querySessions, readSessionSummaryAny, readSessionTimelineAny } from '../db.js';
15
18
  import { linearIssueUrl } from '@phnx-labs/sessions-cli/reader';
16
19
  import { sessionAgentSupportsResume } from '../recovery.js';
@@ -57,6 +60,28 @@ function previousSessionWatchRowKey(scope, sessionId) {
57
60
  function previousRowTitle(session, foldedHeadline) {
58
61
  return session.label || session.generatedTitle || foldedHeadline || session.topic || undefined;
59
62
  }
63
+ function previousRowCard(session, request, attachments) {
64
+ const digest = readCachedPreviewDigest(session);
65
+ const recap = deriveSessionRecap({
66
+ ...session,
67
+ tail: digest?.lastAssistant ? [digest.lastAssistant] : undefined,
68
+ attachments,
69
+ request,
70
+ });
71
+ const sidecars = indexArtifactSidecars(path.join(getUserAgentsDir(), 'artifacts')).get(session.id) ?? [];
72
+ const artifacts = mergeArtifacts(digest?.producedArtifacts ?? [], sidecars).map((artifact) => ({ ...artifact, kind: artifactKind(artifact.path) }));
73
+ const todos = digest?.todos ?? session.todos;
74
+ const importantMessage = deriveImportantMessage({ status: 'closed', lastAgentLine: recap.lastAgentLine });
75
+ return {
76
+ ...(recap.lastAgentLine ? { lastAgentLine: recap.lastAgentLine } : {}),
77
+ ...(recap.request ? { request: recap.request } : {}),
78
+ ...(recap.userPromptClean ? { userPromptClean: recap.userPromptClean } : {}),
79
+ ...(recap.userPromptKind ? { userPromptKind: recap.userPromptKind } : {}),
80
+ ...(todos?.total ? { todos } : {}),
81
+ ...(artifacts.length ? { artifacts } : {}),
82
+ ...(importantMessage ? { importantMessage } : {}),
83
+ };
84
+ }
60
85
  export function toPreviousSessionWatchRow(scope, session, accounts = listNativeAccounts(readMeta())) {
61
86
  const resumable = sessionAgentSupportsResume(session.agent);
62
87
  const sourceDevice = normalizeHost(session.machine ?? scope);
@@ -76,6 +101,7 @@ export function toPreviousSessionWatchRow(scope, session, accounts = listNativeA
76
101
  const folded = readSessionTimelineAny(session.id);
77
102
  const model = folded?.model ?? session.model;
78
103
  const title = previousRowTitle(session, folded?.request?.headline);
104
+ const card = previousRowCard(session, folded?.request, folded?.attachments);
79
105
  return {
80
106
  context: 'recent',
81
107
  kind: session.agent,
@@ -105,7 +131,7 @@ export function toPreviousSessionWatchRow(scope, session, accounts = listNativeA
105
131
  ...(summary?.checkpoints ? { checkpoints: summary.checkpoints } : {}),
106
132
  ...(summary?.summaryChecklist ? { summaryChecklist: summary.summaryChecklist } : {}),
107
133
  summaryState: resolveStreamSummaryState(summary?.summaryState),
108
- ...(folded?.request ? { request: folded.request } : {}),
134
+ ...card,
109
135
  ...(folded?.timeline ? { timeline: folded.timeline } : {}),
110
136
  ...(folded?.files ? { files: folded.files } : {}),
111
137
  ...(model ? { model } : {}),
@@ -272,6 +298,18 @@ export class SessionWatchState {
272
298
  this.rows.set(scope, current);
273
299
  return events;
274
300
  }
301
+ refreshPrevious(scope, session, accounts = listNativeAccounts(readMeta())) {
302
+ const rows = this.rows.get(scope);
303
+ const rowKey = previousSessionWatchRowKey(scope, session.id);
304
+ const current = rows?.get(rowKey);
305
+ if (!rows || !current)
306
+ return undefined;
307
+ const row = toPreviousSessionWatchRow(scope, session, accounts);
308
+ if (sameRow(current, row))
309
+ return undefined;
310
+ rows.set(rowKey, row);
311
+ return { ...this.base('upsert'), scope, rowKey, row };
312
+ }
275
313
  scope(scope, status, reason) {
276
314
  return { ...this.base('scope'), scope, status, ...(reason ? { reason } : {}) };
277
315
  }
@@ -294,6 +332,47 @@ export function readPreviousSessionsForWatch(scope) {
294
332
  return [];
295
333
  }
296
334
  }
335
+ const failedPreviewDigests = new Map();
336
+ let previewDigestBuilds = 0;
337
+ export function previewDigestBuildsForTest() {
338
+ return previewDigestBuilds;
339
+ }
340
+ function transcriptStamp(session) {
341
+ try {
342
+ const stat = fs.statSync(session.filePath);
343
+ return `${stat.mtimeMs}:${stat.size}`;
344
+ }
345
+ catch {
346
+ return 'missing';
347
+ }
348
+ }
349
+ async function fillPreviousCards(state, options, sessions) {
350
+ const accounts = sessions.length ? listNativeAccounts(readMeta()) : [];
351
+ for (const session of sessions) {
352
+ if (options.signal.aborted)
353
+ return;
354
+ const stamp = transcriptStamp(session);
355
+ if (failedPreviewDigests.get(session.id) === stamp || readCachedPreviewDigest(session))
356
+ continue;
357
+ await new Promise((resolve) => setImmediate(resolve));
358
+ if (options.signal.aborted)
359
+ return;
360
+ try {
361
+ previewDigestBuilds++;
362
+ if (!loadSessionPreviewDigest(session).digest) {
363
+ failedPreviewDigests.set(session.id, stamp);
364
+ continue;
365
+ }
366
+ failedPreviewDigests.delete(session.id);
367
+ const event = state.refreshPrevious(options.scope, session, accounts);
368
+ if (event)
369
+ options.emit(event);
370
+ }
371
+ catch {
372
+ failedPreviewDigests.set(session.id, stamp);
373
+ }
374
+ }
375
+ }
297
376
  export async function watchLocalSessions(options) {
298
377
  const state = new SessionWatchState();
299
378
  const readCache = options.readCache ?? readActiveSessionsCache;
@@ -306,10 +385,12 @@ export async function watchLocalSessions(options) {
306
385
  }
307
386
  catch { }
308
387
  const initial = readCache('local');
309
- options.emit(state.reset(options.scope, initial?.sessions ?? [], readPrevious(options.scope)));
388
+ const previous = readPrevious(options.scope);
389
+ options.emit(state.reset(options.scope, initial?.sessions ?? [], previous));
310
390
  options.emit(state.scope(options.scope, initial ? 'available' : 'unavailable', initial ? undefined : 'awaiting publisher'));
311
391
  if (options.signal.aborted)
312
392
  return;
393
+ void fillPreviousCards(state, options, previous);
313
394
  noteActiveSessionsJournalReader();
314
395
  await new Promise((resolve) => {
315
396
  let partial = '';
@@ -388,7 +469,7 @@ export async function watchFleetSessions(options) {
388
469
  return;
389
470
  }
390
471
  const self = machineId();
391
- const peers = Object.values(devices).filter((device) => isDialableDevice(device)
472
+ const peers = Object.values(devices).map(resolveDeviceProfile).filter((device) => isDialableDevice(device)
392
473
  && normalizeHost(device.name) !== self
393
474
  && ['windows', 'linux', 'macos'].includes(device.platform));
394
475
  const peerTasks = peers.map(async (device) => {
@@ -56,7 +56,12 @@ export function formatNoHealthyDeviceError(pool, signals, agent) {
56
56
  const excluded = pool.map((key) => {
57
57
  const signal = signals.get(key);
58
58
  let reason;
59
- if (signal?.reachable === true) {
59
+ if (signal?.reachable === true && signal.headroom !== 'loaded' && signal.installed === undefined) {
60
+ if (signal.timedOut)
61
+ timedOutCount++;
62
+ reason = signal.timedOut ? 'readiness probe timed out' : 'readiness probe did not answer';
63
+ }
64
+ else if (signal?.reachable === true) {
60
65
  reason = signal.headroom === 'loaded'
61
66
  ? 'overloaded'
62
67
  : signal.installed !== true || signal.signedIn !== true
@@ -9,6 +9,8 @@ interface ReadinessInfo {
9
9
  installed: boolean | undefined;
10
10
  signedIn: boolean | undefined;
11
11
  pickerEligible: boolean | undefined;
12
+ reason?: string;
13
+ timedOut?: boolean;
12
14
  }
13
15
  export declare function mergePlacementSignal(stats: DeviceStats | undefined, readiness: ReadinessInfo | undefined): DevicePlacementSignal;
14
16
  export declare function probePoolSignals(pool: string[], agent?: AgentType, opts?: {
@@ -3,6 +3,7 @@ import { buildFleetStatePayload } from '../accounting/usage-sync.js';
3
3
  import { probeFleetStats, headroom } from '../devices/health.js';
4
4
  import { loadDevicesSync } from '../devices/registry.js';
5
5
  import { buildSshInvocation, writeAskpassShim } from '../devices/connect.js';
6
+ import { resolveDeviceProfile } from '../devices/resolve-profile.js';
6
7
  import { buildReadyProbeCommand, parseReadyProbe, viewAgentAccountEligibility, viewHasAgent, } from '../hosts/ready.js';
7
8
  import { collectRunCandidates, isSignInRecoverable, readinessFromCandidate, } from '../accounting/rotate.js';
8
9
  import { localMachineId } from '../origin-machine.js';
@@ -23,7 +24,7 @@ function probeRemoteReadiness(device, agent, usagePayload) {
23
24
  let env;
24
25
  try {
25
26
  const shim = writeAskpassShim();
26
- const cmd = buildReadyProbeCommand(device.shell === 'powershell' ? 'windows' : undefined, { ingestUsage: true });
27
+ const cmd = buildReadyProbeCommand(resolveDeviceProfile(device).shell === 'powershell' ? 'windows' : undefined, { ingestUsage: true });
27
28
  ({ args, env } = buildSshInvocation(device, [cmd], shim, {}, { agentOnly: true }));
28
29
  }
29
30
  catch {
@@ -45,7 +46,8 @@ function probeRemoteReadiness(device, agent, usagePayload) {
45
46
  clearTimeout(killTimer);
46
47
  resolve(value);
47
48
  };
48
- const timer = setTimeout(() => child.kill('SIGTERM'), READY_PROBE_TIMEOUT_MS);
49
+ let timedOut = false;
50
+ const timer = setTimeout(() => { timedOut = true; child.kill('SIGTERM'); }, READY_PROBE_TIMEOUT_MS);
49
51
  const killTimer = setTimeout(() => { if (!settled)
50
52
  child.kill('SIGKILL'); }, READY_PROBE_TIMEOUT_MS + 250);
51
53
  killTimer.unref?.();
@@ -54,6 +56,8 @@ function probeRemoteReadiness(device, agent, usagePayload) {
54
56
  child.stderr.resume();
55
57
  child.on('error', () => finish(unknown));
56
58
  child.on('close', (code) => {
59
+ if (timedOut)
60
+ return finish({ ...unknown, timedOut: true });
57
61
  if (code !== 0 || !stdout)
58
62
  return finish(unknown);
59
63
  const probe = parseReadyProbe(stdout);
@@ -75,13 +79,14 @@ export function mergePlacementSignal(stats, readiness) {
75
79
  const reachable = readiness?.answered === true ? true : stats?.reachable;
76
80
  return {
77
81
  reachable,
78
- timedOut: reachable === true ? undefined : stats?.timedOut,
82
+ timedOut: reachable === true ? readiness?.timedOut : stats?.timedOut,
79
83
  headroom: stats ? headroom(stats) : undefined,
80
84
  loadPercent: stats?.loadPercent,
81
85
  memPercent: stats?.memPercent,
82
86
  installed: readiness?.installed,
83
87
  signedIn: readiness?.signedIn,
84
88
  pickerEligible: readiness?.pickerEligible,
89
+ reason: readiness?.reason,
85
90
  };
86
91
  }
87
92
  export async function probePoolSignals(pool, agent, opts = {}) {
@@ -1,12 +1,14 @@
1
1
  import type { Backend, EngineContext, LaunchRequest, LaunchResult, LaunchSpec } from './types.js';
2
2
  import { type Packing } from './policy.js';
3
3
  import { type HostResolver } from './transport.js';
4
+ import { type SpawnAck } from './backends/vscodium-agent.js';
4
5
  export declare function specsForRequest(req: LaunchRequest, nonce?: string): LaunchSpec[];
5
6
  export interface OpenOptions {
6
7
  resolveHost?: HostResolver;
7
8
  ctx?: EngineContext;
8
9
  ackTimeoutMs?: number;
9
10
  }
11
+ export declare function ackFailure(ack: SpawnAck | undefined, req: LaunchRequest, timeoutMs: number): string | undefined;
10
12
  export declare function openSurface(req: LaunchRequest, opts?: OpenOptions): Promise<LaunchResult>;
11
13
  export interface SurfaceItem {
12
14
  cwd: string;
@@ -31,9 +31,11 @@ function ackReader(nonce) {
31
31
  }
32
32
  };
33
33
  }
34
- function ackFailure(ack, req, timeoutMs) {
35
- if (!ack)
36
- return `VSCodium didn't confirm a tab within ${Math.round(timeoutMs / 1000)}s`;
34
+ export function ackFailure(ack, req, timeoutMs) {
35
+ if (!ack) {
36
+ return `VSCodium did not confirm the tab within ${Math.round(timeoutMs / 1000)}s; ` +
37
+ `if VSCodium is asking "Allow 'Agents' extension to open this URI?", approve it and try again`;
38
+ }
37
39
  if (!ackLandedIn(ack, req.project)) {
38
40
  const where = ack.workspaceName ?? (ack.windowFolders.join(', ') || 'an unknown window');
39
41
  const why = ack.reason ? ` (${ack.reason})` : '';
@@ -10,5 +10,5 @@ export { backendCarriesPaste, injectIntoTerminal, tmuxSendKeysArgv, tmuxInjectSp
10
10
  export { resolveInjectTarget, resolveInjectTargetForSession, type InjectResolution, type InjectRail, type ResolveOptions, } from './resolve.js';
11
11
  export { iLoginShell } from './shell.js';
12
12
  export { shellQuote } from './quote.js';
13
- export { parseTerminalFlag, stripTerminalFlag, buildRunCommand, openRunInTerminal, toHostSamples, TERMINAL_FLAG_BACKENDS } from './run-surface.js';
13
+ export { parseTerminalFlag, stripTerminalFlag, buildRunCommand, openRunInTerminal, toHostSamples, liveHostSamples, TERMINAL_FLAG_BACKENDS } from './run-surface.js';
14
14
  export type { OpenRunSurfaceParams, OpenRunSurfaceResult } from './run-surface.js';
@@ -9,4 +9,4 @@ export { backendCarriesPaste, injectIntoTerminal, tmuxSendKeysArgv, tmuxInjectSp
9
9
  export { resolveInjectTarget, resolveInjectTargetForSession, } from './resolve.js';
10
10
  export { iLoginShell } from './shell.js';
11
11
  export { shellQuote } from './quote.js';
12
- export { parseTerminalFlag, stripTerminalFlag, buildRunCommand, openRunInTerminal, toHostSamples, TERMINAL_FLAG_BACKENDS } from './run-surface.js';
12
+ export { parseTerminalFlag, stripTerminalFlag, buildRunCommand, openRunInTerminal, toHostSamples, liveHostSamples, TERMINAL_FLAG_BACKENDS } from './run-surface.js';
@@ -9,6 +9,7 @@ export declare function parseTerminalFlag(value: unknown): {
9
9
  export declare function stripTerminalFlag(argv: string[], consumedValue?: string): string[];
10
10
  export declare function buildRunCommand(argv: string[]): string[];
11
11
  export declare function toHostSamples(sessions: ActiveSession[]): Promise<SessionHostSample[]>;
12
+ export declare function liveHostSamples(): Promise<SessionHostSample[]>;
12
13
  export interface OpenRunSurfaceParams {
13
14
  argv: string[];
14
15
  forced?: Backend;
@@ -76,6 +76,15 @@ export async function toHostSamples(sessions) {
76
76
  }
77
77
  return samples;
78
78
  }
79
+ export async function liveHostSamples() {
80
+ try {
81
+ const { getActiveSessions } = await import('../session/active.js');
82
+ return await toHostSamples(await getActiveSessions());
83
+ }
84
+ catch {
85
+ return [];
86
+ }
87
+ }
79
88
  export async function openRunInTerminal(params) {
80
89
  const choice = params.forced
81
90
  ? { backend: params.forced, source: 'forced' }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phnx-labs/agents-cli",
3
- "version": "1.23.18",
3
+ "version": "1.23.19",
4
4
  "description": "One CLI for all your AI coding agents - versions, config, cloud dispatch, sessions, and teams (now with first-class Grok Build CLI support)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1,57 +0,0 @@
1
- interface OpItemSummary {
2
- id: string;
3
- title: string;
4
- category: string;
5
- vault: {
6
- id: string;
7
- name: string;
8
- };
9
- }
10
- export interface OpField {
11
- id: string;
12
- label: string;
13
- type: string;
14
- value?: string;
15
- purpose?: string;
16
- }
17
- export interface OpItem extends OpItemSummary {
18
- fields: OpField[];
19
- }
20
- interface ImportableSecret {
21
- envKey: string;
22
- itemTitle: string;
23
- fieldLabel: string;
24
- value: string;
25
- description?: string;
26
- }
27
- interface SkippedField {
28
- itemTitle: string;
29
- fieldLabel: string;
30
- reason: string;
31
- }
32
- export declare function getItem(itemId: string, vaultName: string): OpItem;
33
- export declare function toEnvKey(title: string): string;
34
- export declare function slugify(name: string): string;
35
- export declare function itemToSecret(item: OpItem): {
36
- secret: ImportableSecret;
37
- } | {
38
- skipped: SkippedField;
39
- };
40
- export declare function extractSecrets(items: OpItemSummary[], vaultName: string): {
41
- secrets: ImportableSecret[];
42
- skipped: SkippedField[];
43
- };
44
- interface PasswordItemTemplate {
45
- title: string;
46
- category: 'PASSWORD';
47
- tags: string[];
48
- fields: Array<{
49
- id: string;
50
- type: 'CONCEALED';
51
- purpose: 'PASSWORD';
52
- label: string;
53
- value: string;
54
- }>;
55
- }
56
- export declare function buildPasswordItemTemplate(title: string, value: string): PasswordItemTemplate;
57
- export {};
@@ -1,140 +0,0 @@
1
- import { spawnSync } from 'child_process';
2
- function runOp(args, input) {
3
- const result = spawnSync('op', args, {
4
- stdio: [input !== undefined ? 'pipe' : 'ignore', 'pipe', 'pipe'],
5
- encoding: 'utf-8',
6
- maxBuffer: 10 * 1024 * 1024,
7
- input,
8
- });
9
- if (result.error) {
10
- if (result.error.code === 'ENOENT') {
11
- return { ok: false, error: '1Password CLI not found. Install: brew install 1password-cli' };
12
- }
13
- return { ok: false, error: result.error.message };
14
- }
15
- if (result.status !== 0) {
16
- const stderr = result.stderr?.trim() || '';
17
- if (stderr.includes('not signed in') || stderr.includes('sign in') || stderr.includes('no active session')) {
18
- return { ok: false, error: 'Not signed in to 1Password. Run: op signin' };
19
- }
20
- return { ok: false, error: stderr || `op exited with code ${result.status}` };
21
- }
22
- return { ok: true, stdout: result.stdout };
23
- }
24
- export function getItem(itemId, vaultName) {
25
- const result = runOp(['item', 'get', itemId, '--vault', vaultName, '--format=json', '--reveal']);
26
- if (!result.ok)
27
- throw new Error(result.error);
28
- return JSON.parse(result.stdout);
29
- }
30
- export function toEnvKey(title) {
31
- return title
32
- .toUpperCase()
33
- .replace(/[^A-Z0-9]+/g, '_')
34
- .replace(/^_+|_+$/g, '')
35
- .replace(/^(\d)/, '_$1');
36
- }
37
- export function slugify(name) {
38
- return name
39
- .toLowerCase()
40
- .replace(/[^a-z0-9]+/g, '-')
41
- .replace(/^-+|-+$/g, '');
42
- }
43
- const IMPORTABLE_FIELD_TYPES = new Set([
44
- 'CONCEALED', 'concealed',
45
- 'STRING', 'string', 'text', 'TEXT',
46
- 'URL', 'url',
47
- ]);
48
- const SKIP_FIELD_LABELS = new Set(['username', 'notesPlain', 'notes']);
49
- const NOTES_FIELD_LABELS = new Set(['notesplain', 'notes']);
50
- function pickBestField(fields) {
51
- const dominated = fields.filter((f) => IMPORTABLE_FIELD_TYPES.has(f.type) &&
52
- f.value &&
53
- !SKIP_FIELD_LABELS.has(f.label?.toLowerCase() || ''));
54
- if (dominated.length === 0)
55
- return null;
56
- const concealed = dominated.find((f) => f.type.toLowerCase() === 'concealed');
57
- if (concealed)
58
- return concealed;
59
- const secretLabels = ['credential', 'password', 'secret', 'key', 'token', 'api_key', 'apikey'];
60
- const labeled = dominated.find((f) => secretLabels.includes(f.label?.toLowerCase() || ''));
61
- if (labeled)
62
- return labeled;
63
- return dominated[0];
64
- }
65
- /**
66
- * The item's notes, if any — a NOTES-purpose field (1Password's `notesPlain`)
67
- * or a field labelled notes/notesPlain, whichever carries a non-empty value.
68
- * Returns undefined when the item has no notes. This is descriptive metadata
69
- * only; it is deliberately independent of value selection and is never picked
70
- * as the secret value (see SKIP_FIELD_LABELS / pickBestField).
71
- */
72
- function pickNotes(fields) {
73
- const notes = fields.find((f) => f.value != null &&
74
- f.value.trim() !== '' &&
75
- (f.purpose?.toUpperCase() === 'NOTES' ||
76
- NOTES_FIELD_LABELS.has(f.label?.toLowerCase() || '')));
77
- const value = notes?.value?.trim();
78
- return value ? value : undefined;
79
- }
80
- export function itemToSecret(item) {
81
- const field = pickBestField(item.fields || []);
82
- if (!field) {
83
- return { skipped: { itemTitle: item.title, fieldLabel: '*', reason: 'no importable fields' } };
84
- }
85
- if (field.value.includes('\n')) {
86
- return {
87
- skipped: {
88
- itemTitle: item.title,
89
- fieldLabel: field.label,
90
- reason: 'contains newlines (keychain limitation)',
91
- },
92
- };
93
- }
94
- const secret = {
95
- envKey: toEnvKey(item.title),
96
- itemTitle: item.title,
97
- fieldLabel: field.label,
98
- value: field.value,
99
- };
100
- const description = pickNotes(item.fields || []);
101
- if (description)
102
- secret.description = description;
103
- return { secret };
104
- }
105
- export function extractSecrets(items, vaultName) {
106
- const secrets = [];
107
- const skipped = [];
108
- for (const summary of items) {
109
- let item;
110
- try {
111
- item = getItem(summary.id, vaultName);
112
- }
113
- catch (err) {
114
- skipped.push({
115
- itemTitle: summary.title,
116
- fieldLabel: '*',
117
- reason: err.message,
118
- });
119
- continue;
120
- }
121
- const result = itemToSecret(item);
122
- if ('skipped' in result) {
123
- skipped.push(result.skipped);
124
- }
125
- else {
126
- secrets.push(result.secret);
127
- }
128
- }
129
- return { secrets, skipped };
130
- }
131
- export function buildPasswordItemTemplate(title, value) {
132
- return {
133
- title,
134
- category: 'PASSWORD',
135
- tags: ['agents-cli'],
136
- fields: [
137
- { id: 'password', type: 'CONCEALED', purpose: 'PASSWORD', label: 'password', value },
138
- ],
139
- };
140
- }