@phnx-labs/agents-cli 1.22.122 → 1.22.123

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 (194) hide show
  1. package/CHANGELOG.md +261 -0
  2. package/README.md +49 -10
  3. package/dist/bootstrap.js +22 -17
  4. package/dist/cli/command-registry.d.ts +0 -1
  5. package/dist/cli/command-registry.js +2 -10
  6. package/dist/commands/auth.js +13 -4
  7. package/dist/commands/browser.js +3 -4
  8. package/dist/commands/cloud-transcripts.d.ts +7 -0
  9. package/dist/commands/cloud-transcripts.js +100 -0
  10. package/dist/commands/cloud.js +5 -0
  11. package/dist/commands/computer.d.ts +0 -12
  12. package/dist/commands/computer.js +14 -124
  13. package/dist/commands/config.js +5 -4
  14. package/dist/commands/daemon-index.d.ts +2 -0
  15. package/dist/commands/daemon-index.js +44 -0
  16. package/dist/commands/daemon.js +6 -0
  17. package/dist/commands/doctor.js +3 -4
  18. package/dist/commands/exec.d.ts +5 -0
  19. package/dist/commands/exec.js +35 -7
  20. package/dist/commands/feed-watch.js +12 -0
  21. package/dist/commands/feed.d.ts +1 -1
  22. package/dist/commands/feed.js +7 -4
  23. package/dist/commands/insights.js +3 -1
  24. package/dist/commands/inspect.js +1 -1
  25. package/dist/commands/logs.js +2 -1
  26. package/dist/commands/models.js +1 -1
  27. package/dist/commands/prune.js +6 -28
  28. package/dist/commands/ps-roster.d.ts +0 -1
  29. package/dist/commands/ps-roster.js +2 -21
  30. package/dist/commands/ps.js +13 -1
  31. package/dist/commands/recordings.d.ts +2 -0
  32. package/dist/commands/recordings.js +117 -0
  33. package/dist/commands/routines.js +1 -1
  34. package/dist/commands/secrets-passthrough.js +3 -3
  35. package/dist/commands/send.js +33 -20
  36. package/dist/commands/sessions-backfill.d.ts +1 -0
  37. package/dist/commands/sessions-backfill.js +48 -13
  38. package/dist/commands/sessions-migrate.d.ts +1 -1
  39. package/dist/commands/sessions-migrate.js +11 -10
  40. package/dist/commands/sessions-optimize.d.ts +1 -0
  41. package/dist/commands/sessions-optimize.js +7 -4
  42. package/dist/commands/sessions-resume.js +8 -1
  43. package/dist/commands/sessions-stats.d.ts +2 -0
  44. package/dist/commands/sessions-stats.js +24 -7
  45. package/dist/commands/sessions.d.ts +5 -11
  46. package/dist/commands/sessions.js +8 -236
  47. package/dist/commands/setup-computer.js +1 -2
  48. package/dist/commands/setup.js +1 -1
  49. package/dist/commands/teams.js +2 -2
  50. package/dist/commands/testdata/feed-hub.d.ts +1 -0
  51. package/dist/commands/testdata/feed-hub.js +11 -0
  52. package/dist/commands/trash.d.ts +0 -1
  53. package/dist/commands/trash.js +74 -10
  54. package/dist/lib/accounting/usage-sync.js +7 -0
  55. package/dist/lib/agent-modes.d.ts +1 -1
  56. package/dist/lib/agent-modes.js +11 -5
  57. package/dist/lib/auth-mint.d.ts +4 -0
  58. package/dist/lib/auth-mint.js +6 -4
  59. package/dist/lib/browser/native-history.test-fixture.d.ts +12 -0
  60. package/dist/lib/browser/native-history.test-fixture.js +43 -0
  61. package/dist/lib/browser/paths.d.ts +5 -0
  62. package/dist/lib/browser/paths.js +7 -1
  63. package/dist/lib/browser/sessions-list.d.ts +28 -1
  64. package/dist/lib/browser/sessions-list.js +137 -25
  65. package/dist/lib/channels/providers/rush.d.ts +2 -1
  66. package/dist/lib/channels/providers/rush.js +2 -2
  67. package/dist/lib/channels/providers/session.d.ts +1 -0
  68. package/dist/lib/channels/providers/session.js +23 -12
  69. package/dist/lib/channels/registry.d.ts +9 -2
  70. package/dist/lib/channels/send.d.ts +5 -10
  71. package/dist/lib/channels/send.js +88 -50
  72. package/dist/lib/cloud/rush.d.ts +6 -0
  73. package/dist/lib/cloud/rush.js +18 -3
  74. package/dist/lib/computer-client.d.ts +19 -0
  75. package/dist/lib/computer-client.js +104 -0
  76. package/dist/lib/config-keys.d.ts +5 -1
  77. package/dist/lib/config-keys.js +14 -11
  78. package/dist/lib/daemon/auth-sync-service.js +13 -0
  79. package/dist/lib/daemon/daemon.js +20 -8
  80. package/dist/lib/daemon/owner-device-delivery-service.d.ts +10 -0
  81. package/dist/lib/daemon/owner-device-delivery-service.js +28 -0
  82. package/dist/lib/daemon-services.d.ts +2 -1
  83. package/dist/lib/daemon-services.js +17 -5
  84. package/dist/lib/device-config.d.ts +4 -1
  85. package/dist/lib/device-config.js +57 -7
  86. package/dist/lib/devices/doctor-findings.d.ts +2 -3
  87. package/dist/lib/devices/doctor-findings.js +10 -19
  88. package/dist/lib/event-provenance.d.ts +1 -0
  89. package/dist/lib/event-provenance.js +2 -0
  90. package/dist/lib/exec.d.ts +1 -0
  91. package/dist/lib/exec.js +20 -15
  92. package/dist/lib/feed/pr-status.d.ts +5 -1
  93. package/dist/lib/feed/pr-status.js +44 -3
  94. package/dist/lib/feed/tool-activity.js +9 -6
  95. package/dist/lib/feed/tools.d.ts +4 -1
  96. package/dist/lib/feed/tools.js +8 -11
  97. package/dist/lib/feed-broadcast.d.ts +5 -3
  98. package/dist/lib/feed-broadcast.js +47 -36
  99. package/dist/lib/fleet-shared-state.d.ts +5 -0
  100. package/dist/lib/fleet-shared-state.js +8 -0
  101. package/dist/lib/github/project-prs.d.ts +4 -1
  102. package/dist/lib/github/project-prs.js +18 -5
  103. package/dist/lib/help.d.ts +1 -0
  104. package/dist/lib/help.js +8 -0
  105. package/dist/lib/helper-versions.js +1 -1
  106. package/dist/lib/hosts/passthrough.js +5 -8
  107. package/dist/lib/hosts/remote-cmd.d.ts +2 -7
  108. package/dist/lib/hosts/remote-cmd.js +14 -22
  109. package/dist/lib/hosts/routing-flag.d.ts +22 -0
  110. package/dist/lib/hosts/routing-flag.js +127 -14
  111. package/dist/lib/identity/index.d.ts +22 -0
  112. package/dist/lib/identity/index.js +3 -0
  113. package/dist/lib/installations/migrate.d.ts +7 -0
  114. package/dist/lib/installations/migrate.js +99 -88
  115. package/dist/lib/installations/versions.js +2 -2
  116. package/dist/lib/launch-identity.d.ts +6 -1
  117. package/dist/lib/launch-identity.js +12 -2
  118. package/dist/lib/menubar/install-menubar.d.ts +1 -0
  119. package/dist/lib/menubar/install-menubar.js +8 -5
  120. package/dist/lib/menubar/snapshot.js +2 -3
  121. package/dist/lib/notify.d.ts +7 -14
  122. package/dist/lib/notify.js +29 -75
  123. package/dist/lib/owner-message.d.ts +4 -6
  124. package/dist/lib/owner-message.js +12 -11
  125. package/dist/lib/owner-notify-tokens.d.ts +49 -0
  126. package/dist/lib/owner-notify-tokens.js +214 -0
  127. package/dist/lib/owner-notify.d.ts +75 -0
  128. package/dist/lib/owner-notify.js +144 -0
  129. package/dist/lib/recordings/config.d.ts +11 -0
  130. package/dist/lib/recordings/config.js +54 -0
  131. package/dist/lib/recordings/identity.d.ts +12 -0
  132. package/dist/lib/recordings/identity.js +57 -0
  133. package/dist/lib/recordings/ledger.d.ts +16 -0
  134. package/dist/lib/recordings/ledger.js +141 -0
  135. package/dist/lib/recordings/model.d.ts +29 -0
  136. package/dist/lib/recordings/model.js +28 -0
  137. package/dist/lib/recordings/pipeline.d.ts +44 -0
  138. package/dist/lib/recordings/pipeline.js +272 -0
  139. package/dist/lib/recordings/process.d.ts +17 -0
  140. package/dist/lib/recordings/process.js +94 -0
  141. package/dist/lib/recordings/service.d.ts +15 -0
  142. package/dist/lib/recordings/service.js +45 -0
  143. package/dist/lib/recordings/settle.d.ts +21 -0
  144. package/dist/lib/recordings/settle.js +92 -0
  145. package/dist/lib/recordings/transcode.d.ts +13 -0
  146. package/dist/lib/recordings/transcode.js +44 -0
  147. package/dist/lib/reminders.d.ts +0 -1
  148. package/dist/lib/reminders.js +1 -1
  149. package/dist/lib/reserved-stores.d.ts +3 -0
  150. package/dist/lib/reserved-stores.js +13 -0
  151. package/dist/lib/routine-notify-owner.d.ts +3 -23
  152. package/dist/lib/routine-notify-owner.js +26 -107
  153. package/dist/lib/rush-api.d.ts +1 -0
  154. package/dist/lib/rush-api.js +1 -0
  155. package/dist/lib/session/active.d.ts +18 -2
  156. package/dist/lib/session/active.js +47 -37
  157. package/dist/lib/session/cloud.js +18 -45
  158. package/dist/lib/session/db.d.ts +2 -0
  159. package/dist/lib/session/db.js +13 -4
  160. package/dist/lib/session/glance-files.d.ts +4 -3
  161. package/dist/lib/session/glance-files.js +31 -0
  162. package/dist/lib/session/inject-target.js +12 -2
  163. package/dist/lib/session/pid-registry.d.ts +2 -0
  164. package/dist/lib/session/pid-registry.js +6 -2
  165. package/dist/lib/session/presentation.d.ts +21 -0
  166. package/dist/lib/session/presentation.js +198 -0
  167. package/dist/lib/session/projection.js +9 -2
  168. package/dist/lib/sqlite.d.ts +3 -1
  169. package/dist/lib/sqlite.js +7 -3
  170. package/dist/lib/standalone-tools.js +1 -1
  171. package/dist/lib/startup/command-registry.js +9 -4
  172. package/dist/lib/state.d.ts +2 -2
  173. package/dist/lib/state.js +3 -5
  174. package/dist/lib/terminal/inject.js +1 -1
  175. package/dist/lib/testdata/owner-notify-api.d.ts +36 -0
  176. package/dist/lib/testdata/owner-notify-api.js +102 -0
  177. package/dist/lib/trash.d.ts +14 -0
  178. package/dist/lib/trash.js +75 -0
  179. package/dist/lib/types.d.ts +0 -34
  180. package/package.json +1 -1
  181. package/dist/commands/feedback.d.ts +0 -2
  182. package/dist/commands/feedback.js +0 -68
  183. package/dist/commands/humans.d.ts +0 -2
  184. package/dist/commands/humans.js +0 -83
  185. package/dist/commands/modes.d.ts +0 -2
  186. package/dist/commands/modes.js +0 -134
  187. package/dist/commands/reminders.d.ts +0 -2
  188. package/dist/commands/reminders.js +0 -49
  189. package/dist/lib/channels/owner-forward.d.ts +0 -25
  190. package/dist/lib/channels/owner-forward.js +0 -78
  191. package/dist/lib/channels/owner-sink.d.ts +0 -10
  192. package/dist/lib/channels/owner-sink.js +0 -26
  193. package/dist/lib/humans.d.ts +0 -12
  194. package/dist/lib/humans.js +0 -64
@@ -0,0 +1,141 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import * as path from 'node:path';
3
+ import { atomicWriteFile, withFileLockAsync } from '../fs-atomic.js';
4
+ import { recordingsLedgerPath } from './config.js';
5
+ const EMPTY_LEDGER = { version: 1, rows: [] };
6
+ export class RecordingLedger {
7
+ filePath;
8
+ constructor(filePath = recordingsLedgerPath()) {
9
+ this.filePath = filePath;
10
+ }
11
+ async ensure() {
12
+ await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 0o700 });
13
+ try {
14
+ const handle = await fs.open(this.filePath, 'wx', 0o600);
15
+ await handle.writeFile(`${JSON.stringify(EMPTY_LEDGER, null, 2)}\n`);
16
+ await handle.close();
17
+ }
18
+ catch (error) {
19
+ if (error.code !== 'EEXIST')
20
+ throw error;
21
+ }
22
+ }
23
+ async readUnlocked() {
24
+ try {
25
+ const contents = await fs.readFile(this.filePath, 'utf8');
26
+ if (contents.trim().length === 0)
27
+ return { ...EMPTY_LEDGER, rows: [] };
28
+ const parsed = JSON.parse(contents);
29
+ if (parsed.version !== 1 || !Array.isArray(parsed.rows))
30
+ throw new Error('unsupported ledger schema');
31
+ return { version: 1, rows: parsed.rows, attention: parsed.attention };
32
+ }
33
+ catch (error) {
34
+ if (error.code === 'ENOENT')
35
+ return { ...EMPTY_LEDGER, rows: [] };
36
+ const detail = error instanceof Error ? error.message : String(error);
37
+ throw new Error(`Recording ledger is unreadable at ${this.filePath}: ${detail}`);
38
+ }
39
+ }
40
+ async transaction(fn) {
41
+ await this.ensure();
42
+ return withFileLockAsync(this.filePath, async () => {
43
+ const ledger = await this.readUnlocked();
44
+ const before = JSON.stringify(ledger);
45
+ const result = await fn(ledger);
46
+ if (JSON.stringify(ledger) !== before) {
47
+ await atomicWriteFile(this.filePath, `${JSON.stringify(ledger, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
48
+ }
49
+ return result;
50
+ });
51
+ }
52
+ async list() {
53
+ await this.ensure();
54
+ return (await this.readUnlocked()).rows.sort((a, b) => b.recordedAt.localeCompare(a.recordedAt));
55
+ }
56
+ async queue(candidate) {
57
+ return this.transaction((ledger) => {
58
+ const existing = ledger.rows.find((row) => row.stem === candidate.stem);
59
+ const sameFile = existing
60
+ && existing.path === candidate.path
61
+ && existing.size === candidate.size
62
+ && existing.mtimeMs === candidate.mtimeMs;
63
+ if (sameFile)
64
+ return existing;
65
+ const row = {
66
+ ...candidate,
67
+ url: null,
68
+ status: 'queued',
69
+ error: null,
70
+ updatedAt: new Date().toISOString(),
71
+ };
72
+ if (existing)
73
+ Object.assign(existing, row, { retryAt: undefined });
74
+ else
75
+ ledger.rows.push(row);
76
+ return existing ?? row;
77
+ });
78
+ }
79
+ async update(stem, sourcePath, patch) {
80
+ return this.transaction((ledger) => {
81
+ const row = ledger.rows.find((entry) => entry.stem === stem && entry.path === sourcePath);
82
+ if (!row)
83
+ return null;
84
+ Object.assign(row, patch, { updatedAt: new Date().toISOString() });
85
+ return row;
86
+ });
87
+ }
88
+ async claim(stem, sourcePath, now = Date.now()) {
89
+ return this.transaction((ledger) => {
90
+ const row = ledger.rows.find((entry) => entry.stem === stem && entry.path === sourcePath);
91
+ if (!row)
92
+ return false;
93
+ if (row.status !== 'queued' && row.status !== 'failed')
94
+ return false;
95
+ if (row.retryAt && Date.parse(row.retryAt) > now)
96
+ return false;
97
+ row.status = 'transcoding';
98
+ row.error = null;
99
+ delete row.retryAt;
100
+ row.updatedAt = new Date(now).toISOString();
101
+ return true;
102
+ });
103
+ }
104
+ async recoverInterrupted(now = Date.now()) {
105
+ await this.transaction((ledger) => {
106
+ for (const row of ledger.rows) {
107
+ if (row.status !== 'transcoding' && row.status !== 'uploading')
108
+ continue;
109
+ row.status = 'queued';
110
+ row.error = 'Interrupted before completion; retrying.';
111
+ row.updatedAt = new Date(now).toISOString();
112
+ }
113
+ });
114
+ }
115
+ async pending(now = Date.now()) {
116
+ await this.ensure();
117
+ return (await this.readUnlocked()).rows.filter((row) => (row.status === 'queued' && (!row.retryAt || Date.parse(row.retryAt) <= now))
118
+ || (row.status === 'failed' && (!row.retryAt || Date.parse(row.retryAt) <= now)));
119
+ }
120
+ async shouldPostAttention(reason) {
121
+ await this.ensure();
122
+ return withFileLockAsync(this.filePath, async () => {
123
+ const ledger = await this.readUnlocked();
124
+ if (ledger.attention?.reason === reason)
125
+ return false;
126
+ ledger.attention = { reason, postedAt: new Date().toISOString() };
127
+ await atomicWriteFile(this.filePath, `${JSON.stringify(ledger, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
128
+ return true;
129
+ });
130
+ }
131
+ async clearAttention() {
132
+ await this.ensure();
133
+ await withFileLockAsync(this.filePath, async () => {
134
+ const ledger = await this.readUnlocked();
135
+ if (!ledger.attention)
136
+ return;
137
+ delete ledger.attention;
138
+ await atomicWriteFile(this.filePath, `${JSON.stringify(ledger, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
139
+ });
140
+ }
141
+ }
@@ -0,0 +1,29 @@
1
+ export type RecordingStatus = 'queued' | 'transcoding' | 'uploading' | 'uploaded' | 'failed';
2
+ export interface RecordingCandidate {
3
+ path: string;
4
+ stem: string;
5
+ slug: string;
6
+ size: number;
7
+ mtimeMs: number;
8
+ recordedAt: string;
9
+ sessionId?: string;
10
+ }
11
+ export interface RecordingLedgerRow {
12
+ path: string;
13
+ stem: string;
14
+ slug: string;
15
+ url: string | null;
16
+ status: RecordingStatus;
17
+ error: string | null;
18
+ size: number;
19
+ mtimeMs: number;
20
+ recordedAt: string;
21
+ sessionId?: string;
22
+ updatedAt: string;
23
+ retryAt?: string;
24
+ }
25
+ export declare function isRecordingFile(filePath: string): boolean;
26
+ export declare function cleanShotStem(filePath: string): string;
27
+ export declare function slugifyRecordingStem(stem: string): string;
28
+ export declare function candidateVersion(candidate: Pick<RecordingCandidate, 'mtimeMs' | 'path'>): string;
29
+ export declare function isNewerRecording(candidate: Pick<RecordingCandidate, 'mtimeMs' | 'path'>, current: Pick<RecordingCandidate, 'mtimeMs' | 'path'>): boolean;
@@ -0,0 +1,28 @@
1
+ import * as path from 'node:path';
2
+ export function isRecordingFile(filePath) {
3
+ const ext = path.extname(filePath).toLowerCase();
4
+ return ext === '.mp4' || ext === '.mov';
5
+ }
6
+ export function cleanShotStem(filePath) {
7
+ const raw = path.basename(filePath, path.extname(filePath));
8
+ const reexport = /^(CleanShot .+?) ([1-9]\d*)$/.exec(raw);
9
+ return reexport?.[1] ?? raw;
10
+ }
11
+ export function slugifyRecordingStem(stem) {
12
+ const slug = stem
13
+ .normalize('NFKD')
14
+ .replace(/[\u0300-\u036f]/g, '')
15
+ .toLowerCase()
16
+ .replace(/[^a-z0-9]+/g, '-')
17
+ .replace(/^-+|-+$/g, '')
18
+ .slice(0, 96)
19
+ .replace(/-+$/g, '');
20
+ return slug || 'recording';
21
+ }
22
+ export function candidateVersion(candidate) {
23
+ return `${candidate.mtimeMs}:${candidate.path}`;
24
+ }
25
+ export function isNewerRecording(candidate, current) {
26
+ return candidate.mtimeMs > current.mtimeMs
27
+ || (candidate.mtimeMs === current.mtimeMs && candidate.path.localeCompare(current.path) > 0);
28
+ }
@@ -0,0 +1,44 @@
1
+ import { RecordingLedger } from './ledger.js';
2
+ import { type RecordingCandidate, type RecordingLedgerRow } from './model.js';
3
+ import { type TranscodedRecording } from './transcode.js';
4
+ export interface RecordingPipelineOptions {
5
+ ledger?: RecordingLedger;
6
+ artifactsBin?: string;
7
+ env?: NodeJS.ProcessEnv;
8
+ transcode?: (sourcePath: string, signal?: AbortSignal) => Promise<TranscodedRecording>;
9
+ verifyIdentity?: (signal?: AbortSignal) => Promise<{
10
+ email: string;
11
+ }>;
12
+ raiseAttention?: (message: string) => Promise<void>;
13
+ reportError?: (message: string) => void;
14
+ retryDelayMs?: number;
15
+ dependencyRetryDelayMs?: number;
16
+ }
17
+ export declare function buildArtifactsRecordingArgs(candidate: RecordingCandidate, transcodedPath: string): string[];
18
+ export declare function buildArtifactsRecordingEnv(candidate: RecordingCandidate, base: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
19
+ export declare class RecordingPipeline {
20
+ readonly ledger: RecordingLedger;
21
+ private readonly active;
22
+ private readonly configuredArtifactsBin?;
23
+ private readonly env;
24
+ private readonly transcode;
25
+ private readonly verifyIdentity;
26
+ private readonly raiseAttention;
27
+ private readonly reportError;
28
+ private readonly retryDelayMs;
29
+ private readonly dependencyRetryDelayMs;
30
+ constructor(options?: RecordingPipelineOptions);
31
+ private artifactsBin;
32
+ observeLatest(candidate: RecordingCandidate): void;
33
+ queue(candidates: RecordingCandidate[]): Promise<void>;
34
+ recoverInterrupted(): Promise<void>;
35
+ private attention;
36
+ private share;
37
+ private start;
38
+ drain(options?: {
39
+ awaitUploads?: boolean;
40
+ signal?: AbortSignal;
41
+ }): Promise<RecordingLedgerRow[]>;
42
+ upload(candidate: RecordingCandidate, signal?: AbortSignal): Promise<RecordingLedgerRow>;
43
+ stop(): Promise<void>;
44
+ }
@@ -0,0 +1,272 @@
1
+ import { getCliLaunch } from '../cli-entry.js';
2
+ import { ArtifactsClientError, invocation, resolveArtifactsBin } from '../artifacts-client.js';
3
+ import { machineId } from '../machine-id.js';
4
+ import { RecordingIdentityError, verifyOrganizationIdentity } from './identity.js';
5
+ import { RecordingLedger } from './ledger.js';
6
+ import { isNewerRecording } from './model.js';
7
+ import { processFailure, runProcess } from './process.js';
8
+ import { RecordingDependencyError, transcodeRecording } from './transcode.js';
9
+ function rowCandidate(row) {
10
+ return {
11
+ path: row.path,
12
+ stem: row.stem,
13
+ slug: row.slug,
14
+ size: row.size,
15
+ mtimeMs: row.mtimeMs,
16
+ recordedAt: row.recordedAt,
17
+ sessionId: row.sessionId,
18
+ };
19
+ }
20
+ function resultUrl(stdout) {
21
+ try {
22
+ const parsed = JSON.parse(stdout);
23
+ if (typeof parsed.url === 'string' && parsed.url.length > 0)
24
+ return parsed.url;
25
+ }
26
+ catch {
27
+ const line = stdout.trim().split(/\r?\n/).find((value) => /^https?:\/\//.test(value));
28
+ if (line)
29
+ return line;
30
+ }
31
+ throw new Error('artifacts share completed without returning a URL.');
32
+ }
33
+ function isUnauthorizedOutput(exitCode, output) {
34
+ return exitCode === 401 || /\b401\b|unauthori[sz]ed|authentication expired|not signed in/i.test(output);
35
+ }
36
+ async function defaultAttention(message) {
37
+ const session = `recordings-${machineId()}`;
38
+ const launch = getCliLaunch([
39
+ 'feed', 'post', '--title', 'Recordings need attention', message, '--blocked', '--session', session,
40
+ ]);
41
+ const result = await runProcess(launch.command, launch.args, { timeoutMs: 30_000 });
42
+ if (result.exitCode !== 0)
43
+ throw processFailure(launch.command, launch.args, result);
44
+ }
45
+ export function buildArtifactsRecordingArgs(candidate, transcodedPath) {
46
+ const args = [
47
+ 'share', transcodedPath,
48
+ '--visibility', 'org',
49
+ '--expire', 'never',
50
+ '--slug', candidate.slug,
51
+ '--meta', 'source=cleanshot',
52
+ '--meta', `recorded-at=${candidate.recordedAt}`,
53
+ '--meta', `stem=${candidate.stem}`,
54
+ ];
55
+ args.push('--json');
56
+ return args;
57
+ }
58
+ export function buildArtifactsRecordingEnv(candidate, base) {
59
+ const env = { ...base };
60
+ delete env.AGENTS_SESSION_ID;
61
+ delete env.AGENT_SESSION_ID;
62
+ if (candidate.sessionId)
63
+ env.AGENTS_SESSION_ID = candidate.sessionId;
64
+ return env;
65
+ }
66
+ export class RecordingPipeline {
67
+ ledger;
68
+ active = new Map();
69
+ configuredArtifactsBin;
70
+ env;
71
+ transcode;
72
+ verifyIdentity;
73
+ raiseAttention;
74
+ reportError;
75
+ retryDelayMs;
76
+ dependencyRetryDelayMs;
77
+ constructor(options = {}) {
78
+ this.ledger = options.ledger ?? new RecordingLedger();
79
+ this.configuredArtifactsBin = options.artifactsBin;
80
+ this.env = options.env ?? process.env;
81
+ this.transcode = options.transcode ?? ((source, signal) => transcodeRecording(source, signal));
82
+ this.verifyIdentity = options.verifyIdentity
83
+ ?? ((signal) => verifyOrganizationIdentity(signal, { artifactsBin: this.artifactsBin(), env: this.env }));
84
+ this.raiseAttention = options.raiseAttention ?? defaultAttention;
85
+ this.reportError = options.reportError ?? (() => undefined);
86
+ this.retryDelayMs = options.retryDelayMs ?? 60_000;
87
+ this.dependencyRetryDelayMs = options.dependencyRetryDelayMs ?? 15 * 60_000;
88
+ }
89
+ artifactsBin() {
90
+ return this.configuredArtifactsBin ?? resolveArtifactsBin();
91
+ }
92
+ observeLatest(candidate) {
93
+ const active = this.active.get(candidate.stem);
94
+ if (!active || active.candidate.path === candidate.path)
95
+ return;
96
+ if (!isNewerRecording(candidate, active.candidate))
97
+ return;
98
+ active.superseded = true;
99
+ active.controller.abort();
100
+ void this.ledger.update(active.candidate.stem, active.candidate.path, {
101
+ status: 'failed',
102
+ error: `Superseded by ${candidate.path}`,
103
+ retryAt: '9999-12-31T23:59:59.999Z',
104
+ }).catch((error) => {
105
+ this.reportError(error instanceof Error ? error.message : String(error));
106
+ });
107
+ }
108
+ async queue(candidates) {
109
+ for (const candidate of candidates)
110
+ await this.ledger.queue(candidate);
111
+ }
112
+ async recoverInterrupted() {
113
+ await this.ledger.recoverInterrupted();
114
+ }
115
+ async attention(message) {
116
+ if (!await this.ledger.shouldPostAttention(message))
117
+ return;
118
+ try {
119
+ await this.raiseAttention(message);
120
+ }
121
+ catch (error) {
122
+ await this.ledger.clearAttention();
123
+ throw error;
124
+ }
125
+ }
126
+ async share(candidate, filePath, signal) {
127
+ const launch = invocation(this.artifactsBin());
128
+ const args = [...launch.prefix, ...buildArtifactsRecordingArgs(candidate, filePath)];
129
+ const env = buildArtifactsRecordingEnv(candidate, this.env);
130
+ const result = await runProcess(launch.command, args, { signal, env });
131
+ if (result.exitCode !== 0) {
132
+ const output = `${result.stderr}\n${result.stdout}`;
133
+ if (isUnauthorizedOutput(result.exitCode, output)) {
134
+ throw new RecordingIdentityError('AUTH_REQUIRED', 'Artifacts authentication expired during upload. Run `artifacts auth login`; recordings remain queued.');
135
+ }
136
+ if (/bad --meta|--meta .+ is reserved|unknown option|invalid choice/i.test(output)) {
137
+ throw new RecordingDependencyError(`The installed artifacts CLI cannot accept the recordings publish contract. ${output.trim()}`);
138
+ }
139
+ throw processFailure('artifacts', args, result);
140
+ }
141
+ return resultUrl(result.stdout);
142
+ }
143
+ start(candidate) {
144
+ const controller = new AbortController();
145
+ const active = {
146
+ candidate,
147
+ controller,
148
+ superseded: false,
149
+ promise: Promise.resolve(null),
150
+ };
151
+ const promise = (async () => {
152
+ let transcoded;
153
+ try {
154
+ if (!await this.ledger.claim(candidate.stem, candidate.path))
155
+ return null;
156
+ transcoded = await this.transcode(candidate.path, controller.signal);
157
+ await this.ledger.update(candidate.stem, candidate.path, { status: 'uploading' });
158
+ const url = await this.share(candidate, transcoded.filePath, controller.signal);
159
+ const row = await this.ledger.update(candidate.stem, candidate.path, {
160
+ status: 'uploaded',
161
+ url,
162
+ error: null,
163
+ retryAt: undefined,
164
+ });
165
+ await this.ledger.clearAttention();
166
+ return row;
167
+ }
168
+ catch (error) {
169
+ if (active.superseded)
170
+ return null;
171
+ if (error instanceof RecordingIdentityError && error.code === 'AUTH_REQUIRED') {
172
+ await this.ledger.update(candidate.stem, candidate.path, {
173
+ status: 'queued',
174
+ error: error.message,
175
+ retryAt: new Date(Date.now() + this.retryDelayMs).toISOString(),
176
+ });
177
+ await this.attention(error.message);
178
+ throw error;
179
+ }
180
+ if (error instanceof RecordingDependencyError) {
181
+ await this.ledger.update(candidate.stem, candidate.path, {
182
+ status: 'failed',
183
+ error: error.message,
184
+ retryAt: new Date(Date.now() + this.dependencyRetryDelayMs).toISOString(),
185
+ });
186
+ await this.attention(error.message);
187
+ throw error;
188
+ }
189
+ const message = error instanceof Error ? error.message : String(error);
190
+ await this.ledger.update(candidate.stem, candidate.path, {
191
+ status: 'failed',
192
+ error: message,
193
+ retryAt: new Date(Date.now() + this.retryDelayMs).toISOString(),
194
+ });
195
+ throw error;
196
+ }
197
+ finally {
198
+ await transcoded?.cleanup();
199
+ }
200
+ })();
201
+ active.promise = promise;
202
+ this.active.set(candidate.stem, active);
203
+ void promise.finally(() => {
204
+ if (this.active.get(candidate.stem) === active)
205
+ this.active.delete(candidate.stem);
206
+ }).catch((error) => {
207
+ if (!active.superseded)
208
+ this.reportError(error instanceof Error ? error.message : String(error));
209
+ });
210
+ return promise;
211
+ }
212
+ async drain(options = {}) {
213
+ const pending = await this.ledger.pending();
214
+ const candidates = pending.map(rowCandidate).filter((candidate) => !this.active.has(candidate.stem));
215
+ if (candidates.length === 0)
216
+ return [];
217
+ try {
218
+ await this.verifyIdentity(options.signal);
219
+ }
220
+ catch (error) {
221
+ const message = error instanceof Error ? error.message : String(error);
222
+ const delay = error instanceof ArtifactsClientError ? this.dependencyRetryDelayMs : this.retryDelayMs;
223
+ const retryAt = new Date(Date.now() + delay).toISOString();
224
+ for (const candidate of candidates) {
225
+ await this.ledger.update(candidate.stem, candidate.path, { status: 'queued', error: message, retryAt });
226
+ }
227
+ await this.attention(message);
228
+ throw error;
229
+ }
230
+ const uploads = candidates.map((candidate) => this.start(candidate));
231
+ if (options.awaitUploads === false)
232
+ return [];
233
+ const rows = await Promise.all(uploads);
234
+ return rows.filter((row) => row !== null);
235
+ }
236
+ async upload(candidate, signal) {
237
+ this.observeLatest(candidate);
238
+ const queued = await this.ledger.queue(candidate);
239
+ if (queued.status === 'uploaded')
240
+ return queued;
241
+ if (queued.status === 'transcoding' || queued.status === 'uploading') {
242
+ throw new Error(`Recording upload is already in progress: ${candidate.path}`);
243
+ }
244
+ if (queued.status === 'failed' || queued.retryAt) {
245
+ await this.ledger.update(candidate.stem, candidate.path, { status: 'queued', retryAt: undefined });
246
+ }
247
+ try {
248
+ await this.verifyIdentity(signal);
249
+ }
250
+ catch (error) {
251
+ const message = error instanceof Error ? error.message : String(error);
252
+ const delay = error instanceof ArtifactsClientError ? this.dependencyRetryDelayMs : this.retryDelayMs;
253
+ await this.ledger.update(candidate.stem, candidate.path, {
254
+ status: 'queued',
255
+ error: message,
256
+ retryAt: new Date(Date.now() + delay).toISOString(),
257
+ });
258
+ await this.attention(message);
259
+ throw error;
260
+ }
261
+ const row = await this.start(candidate);
262
+ if (!row || row.status !== 'uploaded')
263
+ throw new Error(`Recording did not upload: ${candidate.path}`);
264
+ return row;
265
+ }
266
+ async stop() {
267
+ const active = [...this.active.values()];
268
+ for (const upload of active)
269
+ upload.controller.abort();
270
+ await Promise.allSettled(active.map((upload) => upload.promise));
271
+ }
272
+ }
@@ -0,0 +1,17 @@
1
+ export interface ProcessResult {
2
+ exitCode: number;
3
+ stdout: string;
4
+ stderr: string;
5
+ }
6
+ export interface RunProcessOptions {
7
+ cwd?: string;
8
+ env?: NodeJS.ProcessEnv;
9
+ signal?: AbortSignal;
10
+ timeoutMs?: number;
11
+ }
12
+ export declare class RecordingProcessError extends Error {
13
+ readonly result?: ProcessResult | undefined;
14
+ constructor(message: string, result?: ProcessResult | undefined);
15
+ }
16
+ export declare function runProcess(command: string, args: string[], options?: RunProcessOptions): Promise<ProcessResult>;
17
+ export declare function processFailure(command: string, args: string[], result: ProcessResult): RecordingProcessError;
@@ -0,0 +1,94 @@
1
+ import { spawn } from 'node:child_process';
2
+ export class RecordingProcessError extends Error {
3
+ result;
4
+ constructor(message, result) {
5
+ super(message);
6
+ this.result = result;
7
+ this.name = 'RecordingProcessError';
8
+ }
9
+ }
10
+ const MAX_OUTPUT_BYTES = 1024 * 1024;
11
+ function appendBounded(current, chunk) {
12
+ const next = current + chunk.toString('utf8');
13
+ return next.length > MAX_OUTPUT_BYTES ? next.slice(-MAX_OUTPUT_BYTES) : next;
14
+ }
15
+ export async function runProcess(command, args, options = {}) {
16
+ if (options.signal?.aborted)
17
+ throw new DOMException('The operation was aborted', 'AbortError');
18
+ return new Promise((resolve, reject) => {
19
+ const child = spawn(command, args, {
20
+ cwd: options.cwd,
21
+ env: options.env,
22
+ detached: process.platform !== 'win32',
23
+ stdio: ['ignore', 'pipe', 'pipe'],
24
+ });
25
+ let stdout = '';
26
+ let stderr = '';
27
+ let settled = false;
28
+ let timer;
29
+ let killTimer;
30
+ let terminationError;
31
+ const signalChild = (signal) => {
32
+ if (child.exitCode !== null || child.signalCode !== null)
33
+ return;
34
+ try {
35
+ if (process.platform !== 'win32' && child.pid)
36
+ process.kill(-child.pid, signal);
37
+ else
38
+ child.kill(signal);
39
+ }
40
+ catch {
41
+ try {
42
+ child.kill(signal);
43
+ }
44
+ catch { }
45
+ }
46
+ };
47
+ const stop = (error) => {
48
+ if (terminationError)
49
+ return;
50
+ terminationError = error;
51
+ signalChild('SIGTERM');
52
+ killTimer = setTimeout(() => signalChild('SIGKILL'), 2_000);
53
+ };
54
+ const abort = () => stop(new DOMException('The operation was aborted', 'AbortError'));
55
+ const cleanup = () => {
56
+ if (timer)
57
+ clearTimeout(timer);
58
+ if (killTimer)
59
+ clearTimeout(killTimer);
60
+ options.signal?.removeEventListener('abort', abort);
61
+ };
62
+ const finishReject = (error) => {
63
+ if (settled)
64
+ return;
65
+ settled = true;
66
+ cleanup();
67
+ reject(error);
68
+ };
69
+ options.signal?.addEventListener('abort', abort, { once: true });
70
+ if (options.timeoutMs) {
71
+ timer = setTimeout(() => {
72
+ stop(new RecordingProcessError(`Command timed out after ${options.timeoutMs}ms: ${command}`, { exitCode: -1, stdout, stderr }));
73
+ }, options.timeoutMs);
74
+ }
75
+ child.stdout.on('data', (chunk) => { stdout = appendBounded(stdout, chunk); });
76
+ child.stderr.on('data', (chunk) => { stderr = appendBounded(stderr, chunk); });
77
+ child.on('error', (error) => finishReject(error));
78
+ child.on('close', (code) => {
79
+ if (settled)
80
+ return;
81
+ if (terminationError) {
82
+ finishReject(terminationError);
83
+ return;
84
+ }
85
+ settled = true;
86
+ cleanup();
87
+ resolve({ exitCode: code ?? -1, stdout, stderr });
88
+ });
89
+ });
90
+ }
91
+ export function processFailure(command, args, result) {
92
+ const detail = result.stderr.trim() || result.stdout.trim() || `exit ${result.exitCode}`;
93
+ return new RecordingProcessError(`${command} ${args.join(' ')} failed: ${detail}`, result);
94
+ }
@@ -0,0 +1,15 @@
1
+ import type { DaemonContext } from '../daemon/service.js';
2
+ import { BasePeriodicService } from '../daemon/service.js';
3
+ export declare class RecordingsService extends BasePeriodicService {
4
+ readonly id: "recordings";
5
+ readonly intervalMs = 2000;
6
+ readonly deadlineMs = 25000;
7
+ private directory;
8
+ private watchedSinceMs;
9
+ private startedAtMs;
10
+ private pipeline;
11
+ private settler;
12
+ protected onStart(ctx: DaemonContext): Promise<void>;
13
+ protected onTick(ctx: DaemonContext, signal: AbortSignal): Promise<void>;
14
+ protected onStop(): Promise<void>;
15
+ }