@phnx-labs/agents-cli 1.23.10 → 1.23.11

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.23.11
4
+
5
+ - **The daemon no longer restarts when a service tick runs slow (PHNX-4225).** A
6
+ tick past its deadline is now aborted, logged as `tick.breach`, and skipped until
7
+ it settles; the daemon exits for a supervised restart only when a tick is still
8
+ unsettled at 10 times its deadline. On a loaded laptop the old exit-on-overrun
9
+ policy restarted the daemon about 200 times a day. Source:
10
+ `cli/src/lib/daemon/supervisor.ts`.
11
+ - **Recordings encode one video at a time and stop encodes a dead daemon left
12
+ running (PHNX-4225).** Each daemon exit used to leave its `ffmpeg` running and
13
+ the next start re-encoded every queued recording at once, so encodes of the same
14
+ file piled up. The ledger now records each encode's process and work directory,
15
+ a restarted daemon stops a leftover encode and deletes its directory before
16
+ requeueing, and only one recording is processed at a time. Source:
17
+ `cli/src/lib/recordings/pipeline.ts`.
18
+
3
19
  ## 1.23.10
4
20
 
5
21
  - **A desktop tab showing a session that runs on another machine is listed once, as that session.** An ssh tab opened by `agents sessions resume` (AGI EXT opens remote sessions this way) used to appear in `agents feed watch` and `agents ps` as a second session on the desktop with status `unknown` and nothing to read, beside the real one on the worker. The resume hop now records the owner machine for its tab, and the stream projection folds a tab with no transcript of its own into the device that reports the session's transcript, so the tab shows up in that session's `observerTerminals`. Tabs opened before this release fold in the same way. Source: `cli/src/commands/resume.ts`, `cli/src/lib/session/active.ts`, `cli/src/lib/session/projection.ts`.
@@ -37,6 +37,8 @@ export declare class ServiceSupervisor {
37
37
  private stopOne;
38
38
  private scheduleTimer;
39
39
  private runTick;
40
+ private recordOverrun;
41
+ private clearTickTimers;
40
42
  private recordFailure;
41
43
  private breachSnapshot;
42
44
  private exitForRestart;
@@ -3,6 +3,7 @@ import { isPeriodicService } from './service.js';
3
3
  import { syncSpansBetween } from './diagnostics.js';
4
4
  import { performance } from 'perf_hooks';
5
5
  const DEADLINE_EXIT_CODE = 70;
6
+ const HANG_DEADLINES = 10;
6
7
  const DEFAULT_LIFECYCLE_DEADLINE_MS = 30_000;
7
8
  export class ServiceSupervisor {
8
9
  registry = new Map();
@@ -47,6 +48,7 @@ export class ServiceSupervisor {
47
48
  inFlight: false,
48
49
  everStarted: false,
49
50
  idleWaiters: [],
51
+ skippedTicks: 0,
50
52
  });
51
53
  }
52
54
  // Resolve idle waiters in the same step that clears inFlight, so reload cannot race the active tick.
@@ -115,7 +117,7 @@ export class ServiceSupervisor {
115
117
  runNow(id) {
116
118
  if (!this.registry.has(id))
117
119
  throw new Error(`service '${id}' is not registered`);
118
- void this.runTick(id);
120
+ void this.runTick(id, false);
119
121
  }
120
122
  health() {
121
123
  const out = {};
@@ -179,10 +181,7 @@ export class ServiceSupervisor {
179
181
  clearTimeout(entry.startupTimer);
180
182
  entry.startupTimer = undefined;
181
183
  }
182
- if (entry.deadlineTimer) {
183
- clearTimeout(entry.deadlineTimer);
184
- entry.deadlineTimer = undefined;
185
- }
184
+ this.clearTickTimers(entry);
186
185
  entry.state = 'stopped';
187
186
  recordSubsystemState(id, 'stopped');
188
187
  entry.activeController?.abort();
@@ -208,66 +207,101 @@ export class ServiceSupervisor {
208
207
  return;
209
208
  entry.timer = setInterval(() => { void this.runTick(id); }, entry.service.intervalMs);
210
209
  }
211
- // Thrown ticks retry; a deadline may never settle, so record it durably and exit 70 for supervised restart instead of parking.
212
- async runTick(id) {
210
+ // Throws retry; an overrun is aborted and skipped until it settles; only a hang (HANG_DEADLINES) exits 70.
211
+ async runTick(id, scheduled = true) {
213
212
  const entry = this.registry.get(id);
214
213
  const ctx = this.ctx;
215
- if (!entry || !ctx || entry.state !== 'running' || entry.inFlight)
214
+ if (!entry || !ctx || entry.state !== 'running')
216
215
  return;
217
216
  if (!isPeriodicService(entry.service))
218
217
  return;
218
+ if (entry.inFlight) {
219
+ if (scheduled)
220
+ entry.skippedTicks += 1;
221
+ return;
222
+ }
219
223
  const periodicService = entry.service;
224
+ const deadlineMs = periodicService.deadlineMs;
220
225
  entry.inFlight = true;
226
+ entry.skippedTicks = 0;
221
227
  const startedAt = performance.now();
222
228
  entry.tickStartedAt = startedAt;
223
229
  const controller = new AbortController();
224
230
  entry.activeController = controller;
225
- let timedOut = false;
231
+ let overran = false;
226
232
  ctx.log('DEBUG', `service '${id}' tick start`, { event: 'tick.start', service: id });
227
- const tickPromise = periodicService.tick(ctx, controller.signal);
228
- entry.activeTick = tickPromise;
233
+ entry.deadlineTimer = setTimeout(() => {
234
+ entry.deadlineTimer = undefined;
235
+ overran = true;
236
+ this.recordOverrun(entry, id, deadlineMs, startedAt);
237
+ controller.abort();
238
+ entry.hangTimer = setTimeout(() => {
239
+ entry.hangTimer = undefined;
240
+ this.exitForRestart(id, new Error(`tick did not settle within ${deadlineMs * HANG_DEADLINES}ms (${HANG_DEADLINES}x its ${deadlineMs}ms deadline)`), startedAt);
241
+ }, deadlineMs * (HANG_DEADLINES - 1));
242
+ }, deadlineMs);
229
243
  try {
230
- const deadline = new Promise((_, reject) => {
231
- entry.deadlineTimer = setTimeout(() => {
232
- timedOut = true;
233
- reject(new Error(`tick exceeded deadline of ${periodicService.deadlineMs}ms`));
234
- }, periodicService.deadlineMs);
235
- });
236
- await Promise.race([tickPromise, deadline]);
244
+ const tickPromise = periodicService.tick(ctx, controller.signal);
245
+ entry.activeTick = tickPromise;
246
+ await tickPromise;
237
247
  const durMs = Math.round(performance.now() - startedAt);
238
- const tickFields = { service: id, durMs, deadlineMs: periodicService.deadlineMs };
239
- if (durMs * 2 > periodicService.deadlineMs) {
240
- ctx.log('WARN', `service '${id}' tick took ${durMs}ms, over half its ${periodicService.deadlineMs}ms deadline`, { event: 'tick.slow', ...tickFields, inFlight: this.inFlightTicks() });
248
+ const tickFields = { service: id, durMs, deadlineMs };
249
+ if (overran) {
250
+ ctx.log('WARN', `service '${id}' overrun tick settled after ${durMs}ms; ${entry.skippedTicks} tick(s) skipped`, { event: 'tick.settled', ...tickFields, skippedTicks: entry.skippedTicks });
251
+ }
252
+ else if (durMs * 2 > deadlineMs) {
253
+ ctx.log('WARN', `service '${id}' tick took ${durMs}ms, over half its ${deadlineMs}ms deadline`, { event: 'tick.slow', ...tickFields, inFlight: this.inFlightTicks() });
241
254
  }
242
255
  else {
243
256
  ctx.log('DEBUG', `service '${id}' tick ok in ${durMs}ms`, { event: 'tick.ok', ...tickFields });
244
257
  }
245
- entry.consecutiveFailures = 0;
246
- entry.lastError = undefined;
247
258
  entry.lastRunMs = Date.now();
248
- recordSubsystemOk(id);
259
+ if (!overran) {
260
+ entry.consecutiveFailures = 0;
261
+ entry.lastError = undefined;
262
+ recordSubsystemOk(id);
263
+ }
249
264
  }
250
265
  catch (err) {
251
- const stoppedDuringTick = this.registry.get(id)?.state === 'stopped';
252
- if (timedOut && !stoppedDuringTick) {
253
- controller.abort();
254
- this.exitForRestart(id, err, startedAt);
255
- return;
266
+ const durMs = Math.round(performance.now() - startedAt);
267
+ if (overran) {
268
+ const message = err instanceof Error ? err.message : String(err);
269
+ ctx.log('WARN', `service '${id}' overrun tick settled after ${durMs}ms by throwing: ${message}; ${entry.skippedTicks} tick(s) skipped`, {
270
+ event: 'tick.settled', service: id, durMs, deadlineMs, skippedTicks: entry.skippedTicks, error: message,
271
+ });
272
+ }
273
+ else {
274
+ this.recordFailure(entry, id, err, durMs);
256
275
  }
257
- if (!timedOut)
258
- this.recordFailure(entry, id, err, Math.round(performance.now() - startedAt));
259
276
  }
260
277
  finally {
261
- if (entry.deadlineTimer) {
262
- clearTimeout(entry.deadlineTimer);
263
- entry.deadlineTimer = undefined;
264
- }
278
+ this.clearTickTimers(entry);
265
279
  entry.activeTick = undefined;
266
280
  entry.activeController = undefined;
267
281
  entry.tickStartedAt = undefined;
268
282
  this.clearInFlight(entry);
269
283
  }
270
284
  }
285
+ recordOverrun(entry, id, deadlineMs, startedAt) {
286
+ const cause = `tick exceeded deadline of ${deadlineMs}ms`;
287
+ entry.consecutiveFailures += 1;
288
+ entry.lastError = cause;
289
+ recordSubsystemError(id, cause);
290
+ this.ctx?.log('ERROR', `service '${id}' breached its deadline (${cause}); aborted it and skipping ticks until it settles`, {
291
+ ...this.breachSnapshot(id, startedAt),
292
+ consecutiveFailures: entry.consecutiveFailures,
293
+ });
294
+ }
295
+ clearTickTimers(entry) {
296
+ if (entry.deadlineTimer) {
297
+ clearTimeout(entry.deadlineTimer);
298
+ entry.deadlineTimer = undefined;
299
+ }
300
+ if (entry.hangTimer) {
301
+ clearTimeout(entry.hangTimer);
302
+ entry.hangTimer = undefined;
303
+ }
304
+ }
271
305
  recordFailure(entry, id, err, durMs) {
272
306
  const message = err instanceof Error ? err.message : String(err);
273
307
  entry.consecutiveFailures += 1;
@@ -301,7 +335,10 @@ export class ServiceSupervisor {
301
335
  }
302
336
  recordSubsystemError(id, cause);
303
337
  recordDaemonRestart(id, cause);
304
- this.ctx?.log('ERROR', `service '${id}' breached its deadline (${cause}); exiting (code ${DEADLINE_EXIT_CODE}) for a supervised restart`, this.breachSnapshot(id, startedAt));
338
+ this.ctx?.log('ERROR', `service '${id}' hung (${cause}); exiting (code ${DEADLINE_EXIT_CODE}) for a supervised restart`, {
339
+ ...this.breachSnapshot(id, startedAt),
340
+ event: 'tick.hang',
341
+ });
305
342
  this.freezeTimers();
306
343
  this.exit(DEADLINE_EXIT_CODE);
307
344
  }
@@ -315,10 +352,7 @@ export class ServiceSupervisor {
315
352
  clearTimeout(entry.startupTimer);
316
353
  entry.startupTimer = undefined;
317
354
  }
318
- if (entry.deadlineTimer) {
319
- clearTimeout(entry.deadlineTimer);
320
- entry.deadlineTimer = undefined;
321
- }
355
+ this.clearTickTimers(entry);
322
356
  }
323
357
  }
324
358
  }
@@ -1,4 +1,4 @@
1
- import type { RecordingCandidate, RecordingLedgerRow } from './model.js';
1
+ import type { RecordingCandidate, RecordingLedgerRow, TranscodeJob } from './model.js';
2
2
  export declare class RecordingLedger {
3
3
  readonly filePath: string;
4
4
  constructor(filePath?: string);
@@ -9,7 +9,8 @@ export declare class RecordingLedger {
9
9
  queue(candidate: RecordingCandidate): Promise<RecordingLedgerRow>;
10
10
  update(stem: string, sourcePath: string, patch: Partial<RecordingLedgerRow>): Promise<RecordingLedgerRow | null>;
11
11
  claim(stem: string, sourcePath: string, now?: number): Promise<boolean>;
12
- recoverInterrupted(now?: number): Promise<void>;
12
+ recoverInterrupted(isOwnerAlive: (pid: number) => boolean, now?: number): Promise<TranscodeJob[]>;
13
+ forgetTranscode(job: TranscodeJob): Promise<void>;
13
14
  pending(now?: number): Promise<RecordingLedgerRow[]>;
14
15
  shouldPostAttention(reason: string): Promise<boolean>;
15
16
  clearAttention(): Promise<void>;
@@ -101,15 +101,29 @@ export class RecordingLedger {
101
101
  return true;
102
102
  });
103
103
  }
104
- async recoverInterrupted(now = Date.now()) {
105
- await this.transaction((ledger) => {
104
+ async recoverInterrupted(isOwnerAlive, now = Date.now()) {
105
+ return this.transaction((ledger) => {
106
+ const orphaned = [];
106
107
  for (const row of ledger.rows) {
108
+ if (row.transcode && isOwnerAlive(row.transcode.ownerPid))
109
+ continue;
110
+ if (row.transcode)
111
+ orphaned.push(row.transcode);
107
112
  if (row.status !== 'transcoding' && row.status !== 'uploading')
108
113
  continue;
109
114
  row.status = 'queued';
110
115
  row.error = 'Interrupted before completion; retrying.';
111
116
  row.updatedAt = new Date(now).toISOString();
112
117
  }
118
+ return orphaned;
119
+ });
120
+ }
121
+ async forgetTranscode(job) {
122
+ await this.transaction((ledger) => {
123
+ for (const row of ledger.rows) {
124
+ if (row.transcode?.workDir === job.workDir)
125
+ delete row.transcode;
126
+ }
113
127
  });
114
128
  }
115
129
  async pending(now = Date.now()) {
@@ -8,6 +8,11 @@ export interface RecordingCandidate {
8
8
  recordedAt: string;
9
9
  sessionId?: string;
10
10
  }
11
+ export interface TranscodeJob {
12
+ pid: number;
13
+ workDir: string;
14
+ ownerPid: number;
15
+ }
11
16
  export interface RecordingLedgerRow {
12
17
  path: string;
13
18
  stem: string;
@@ -21,6 +26,7 @@ export interface RecordingLedgerRow {
21
26
  sessionId?: string;
22
27
  updatedAt: string;
23
28
  retryAt?: string;
29
+ transcode?: TranscodeJob;
24
30
  }
25
31
  export declare function isRecordingFile(filePath: string): boolean;
26
32
  export declare function cleanShotStem(filePath: string): string;
@@ -1,11 +1,15 @@
1
1
  import { RecordingLedger } from './ledger.js';
2
- import { type RecordingCandidate, type RecordingLedgerRow } from './model.js';
2
+ import { type RecordingCandidate, type RecordingLedgerRow, type TranscodeJob } from './model.js';
3
3
  import { type TranscodedRecording } from './transcode.js';
4
+ type Transcode = (sourcePath: string, signal?: AbortSignal, onStart?: (job: TranscodeJob) => void) => Promise<TranscodedRecording>;
4
5
  export interface RecordingPipelineOptions {
5
6
  ledger?: RecordingLedger;
6
7
  artifactsBin?: string;
7
8
  env?: NodeJS.ProcessEnv;
8
- transcode?: (sourcePath: string, signal?: AbortSignal) => Promise<TranscodedRecording>;
9
+ transcode?: Transcode;
10
+ reapTranscode?: (job: TranscodeJob) => Promise<{
11
+ killed: boolean;
12
+ }>;
9
13
  verifyIdentity?: (signal?: AbortSignal) => Promise<{
10
14
  email: string;
11
15
  }>;
@@ -22,6 +26,7 @@ export declare class RecordingPipeline {
22
26
  private readonly configuredArtifactsBin?;
23
27
  private readonly env;
24
28
  private readonly transcode;
29
+ private readonly reapTranscode;
25
30
  private readonly verifyIdentity;
26
31
  private readonly raiseAttention;
27
32
  private readonly reportError;
@@ -31,7 +36,9 @@ export declare class RecordingPipeline {
31
36
  private artifactsBin;
32
37
  observeLatest(candidate: RecordingCandidate): void;
33
38
  queue(candidates: RecordingCandidate[]): Promise<void>;
34
- recoverInterrupted(): Promise<void>;
39
+ recoverInterrupted(): Promise<{
40
+ reaped: number;
41
+ }>;
35
42
  private attention;
36
43
  private share;
37
44
  private start;
@@ -42,3 +49,4 @@ export declare class RecordingPipeline {
42
49
  upload(candidate: RecordingCandidate, signal?: AbortSignal): Promise<RecordingLedgerRow>;
43
50
  stop(): Promise<void>;
44
51
  }
52
+ export {};
@@ -5,7 +5,7 @@ import { RecordingIdentityError, verifyOrganizationIdentity } from './identity.j
5
5
  import { RecordingLedger } from './ledger.js';
6
6
  import { isNewerRecording } from './model.js';
7
7
  import { processFailure, runProcess } from './process.js';
8
- import { RecordingDependencyError, transcodeRecording } from './transcode.js';
8
+ import { isProcessAlive, reapTranscode, RecordingDependencyError, transcodeRecording } from './transcode.js';
9
9
  function rowCandidate(row) {
10
10
  return {
11
11
  path: row.path,
@@ -69,6 +69,7 @@ export class RecordingPipeline {
69
69
  configuredArtifactsBin;
70
70
  env;
71
71
  transcode;
72
+ reapTranscode;
72
73
  verifyIdentity;
73
74
  raiseAttention;
74
75
  reportError;
@@ -78,7 +79,8 @@ export class RecordingPipeline {
78
79
  this.ledger = options.ledger ?? new RecordingLedger();
79
80
  this.configuredArtifactsBin = options.artifactsBin;
80
81
  this.env = options.env ?? process.env;
81
- this.transcode = options.transcode ?? ((source, signal) => transcodeRecording(source, signal));
82
+ this.transcode = options.transcode ?? ((source, signal, onStart) => transcodeRecording(source, signal, { onStart }));
83
+ this.reapTranscode = options.reapTranscode ?? reapTranscode;
82
84
  this.verifyIdentity = options.verifyIdentity
83
85
  ?? ((signal) => verifyOrganizationIdentity(signal, { artifactsBin: this.artifactsBin(), env: this.env }));
84
86
  this.raiseAttention = options.raiseAttention ?? defaultAttention;
@@ -110,7 +112,18 @@ export class RecordingPipeline {
110
112
  await this.ledger.queue(candidate);
111
113
  }
112
114
  async recoverInterrupted() {
113
- await this.ledger.recoverInterrupted();
115
+ let reaped = 0;
116
+ for (const job of await this.ledger.recoverInterrupted(isProcessAlive)) {
117
+ try {
118
+ if ((await this.reapTranscode(job)).killed)
119
+ reaped += 1;
120
+ await this.ledger.forgetTranscode(job);
121
+ }
122
+ catch (error) {
123
+ this.reportError(`could not reap transcode pid ${job.pid}: ${error instanceof Error ? error.message : String(error)}`);
124
+ }
125
+ }
126
+ return { reaped };
114
127
  }
115
128
  async attention(message) {
116
129
  if (!await this.ledger.shouldPostAttention(message))
@@ -150,10 +163,14 @@ export class RecordingPipeline {
150
163
  };
151
164
  const promise = (async () => {
152
165
  let transcoded;
166
+ let recorded;
153
167
  try {
154
168
  if (!await this.ledger.claim(candidate.stem, candidate.path))
155
169
  return null;
156
- transcoded = await this.transcode(candidate.path, controller.signal);
170
+ transcoded = await this.transcode(candidate.path, controller.signal, (job) => {
171
+ recorded = this.ledger.update(candidate.stem, candidate.path, { transcode: job });
172
+ });
173
+ await recorded;
157
174
  await this.ledger.update(candidate.stem, candidate.path, { status: 'uploading' });
158
175
  const url = await this.share(candidate, transcoded.filePath, controller.signal);
159
176
  const row = await this.ledger.update(candidate.stem, candidate.path, {
@@ -195,7 +212,10 @@ export class RecordingPipeline {
195
212
  throw error;
196
213
  }
197
214
  finally {
215
+ await recorded?.catch(() => undefined);
198
216
  await transcoded?.cleanup();
217
+ if (recorded)
218
+ await this.ledger.update(candidate.stem, candidate.path, { transcode: undefined });
199
219
  }
200
220
  })();
201
221
  active.promise = promise;
@@ -210,8 +230,10 @@ export class RecordingPipeline {
210
230
  return promise;
211
231
  }
212
232
  async drain(options = {}) {
233
+ if (this.active.size > 0)
234
+ return [];
213
235
  const pending = await this.ledger.pending();
214
- const candidates = pending.map(rowCandidate).filter((candidate) => !this.active.has(candidate.stem));
236
+ const candidates = pending.map(rowCandidate).slice(0, 1);
215
237
  if (candidates.length === 0)
216
238
  return [];
217
239
  try {
@@ -8,6 +8,7 @@ export interface RunProcessOptions {
8
8
  env?: NodeJS.ProcessEnv;
9
9
  signal?: AbortSignal;
10
10
  timeoutMs?: number;
11
+ onSpawn?: (pid: number) => void;
11
12
  }
12
13
  export declare class RecordingProcessError extends Error {
13
14
  readonly result?: ProcessResult | undefined;
@@ -22,6 +22,8 @@ export async function runProcess(command, args, options = {}) {
22
22
  detached: process.platform !== 'win32',
23
23
  stdio: ['ignore', 'pipe', 'pipe'],
24
24
  });
25
+ if (child.pid !== undefined)
26
+ options.onSpawn?.(child.pid);
25
27
  let stdout = '';
26
28
  let stderr = '';
27
29
  let settled = false;
@@ -17,7 +17,9 @@ export class RecordingsService extends BasePeriodicService {
17
17
  });
18
18
  this.settler = new RecordingSettler();
19
19
  this.startedAtMs = Date.now();
20
- await this.pipeline.recoverInterrupted();
20
+ const { reaped } = await this.pipeline.recoverInterrupted();
21
+ if (reaped > 0)
22
+ ctx.log('WARN', `recordings: stopped ${reaped} transcode(s) a previous daemon left running`, { event: 'recordings.reaped', reaped });
21
23
  }
22
24
  async onTick(ctx, signal) {
23
25
  if (!this.pipeline || !this.settler)
@@ -1,3 +1,4 @@
1
+ import type { TranscodeJob } from './model.js';
1
2
  export declare const FFMPEG_INSTALL_HINT: string;
2
3
  export declare class RecordingDependencyError extends Error {
3
4
  constructor(message: string);
@@ -10,4 +11,9 @@ export interface TranscodedRecording {
10
11
  export declare function transcodeRecording(sourcePath: string, signal?: AbortSignal, options?: {
11
12
  ffmpegBin?: string;
12
13
  platform?: NodeJS.Platform;
14
+ onStart?: (job: TranscodeJob) => void;
13
15
  }): Promise<TranscodedRecording>;
16
+ export declare function reapTranscode(job: TranscodeJob): Promise<{
17
+ killed: boolean;
18
+ }>;
19
+ export declare function isProcessAlive(pid: number): boolean;
@@ -2,7 +2,10 @@ import * as fs from 'node:fs/promises';
2
2
  import * as os from 'node:os';
3
3
  import * as path from 'node:path';
4
4
  import { findInPath } from '../agent-spec/agents.js';
5
+ import { execFileBounded } from '../exec-bounded.js';
5
6
  import { processFailure, runProcess } from './process.js';
7
+ const WORK_DIR_PREFIX = 'agents-recording-';
8
+ const OUTPUT_NAME = 'recording.mp4';
6
9
  export const FFMPEG_INSTALL_HINT = process.platform === 'darwin'
7
10
  ? 'Install it with `brew install ffmpeg`.'
8
11
  : 'Install it with your system package manager (for example `apt install ffmpeg`).';
@@ -21,8 +24,8 @@ export function resolveFfmpegBin() {
21
24
  }
22
25
  export async function transcodeRecording(sourcePath, signal, options = {}) {
23
26
  const ffmpeg = options.ffmpegBin ?? resolveFfmpegBin();
24
- const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'agents-recording-'));
25
- const output = path.join(directory, 'recording.mp4');
27
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), WORK_DIR_PREFIX));
28
+ const output = path.join(directory, OUTPUT_NAME);
26
29
  const codec = (options.platform ?? process.platform) === 'darwin' ? 'h264_videotoolbox' : 'libx264';
27
30
  const args = [
28
31
  '-hide_banner', '-loglevel', 'error', '-y', '-i', sourcePath,
@@ -32,7 +35,10 @@ export async function transcodeRecording(sourcePath, signal, options = {}) {
32
35
  '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', output,
33
36
  ];
34
37
  try {
35
- const result = await runProcess(ffmpeg, args, { signal });
38
+ const result = await runProcess(ffmpeg, args, {
39
+ signal,
40
+ onSpawn: (pid) => options.onStart?.({ pid, workDir: directory, ownerPid: process.pid }),
41
+ });
36
42
  if (result.exitCode !== 0)
37
43
  throw processFailure('ffmpeg', args, result);
38
44
  return { filePath: output, cleanup: () => fs.rm(directory, { recursive: true, force: true }) };
@@ -42,3 +48,35 @@ export async function transcodeRecording(sourcePath, signal, options = {}) {
42
48
  throw error;
43
49
  }
44
50
  }
51
+ export async function reapTranscode(job) {
52
+ if (!path.basename(job.workDir).startsWith(WORK_DIR_PREFIX)) {
53
+ throw new Error(`Refusing to reap a transcode outside an ${WORK_DIR_PREFIX}* work dir: ${job.workDir}`);
54
+ }
55
+ let killed = false;
56
+ if (process.platform !== 'win32') {
57
+ const ps = await execFileBounded('ps', ['-ww', '-o', 'args=', '-p', String(job.pid)], { timeoutMs: 5_000 });
58
+ if (ps.timedOut)
59
+ throw new Error(`ps timed out checking transcode pid ${job.pid}`);
60
+ if (ps.code === 0 && ps.stdout.includes(path.join(job.workDir, OUTPUT_NAME))) {
61
+ try {
62
+ process.kill(-job.pid, 'SIGKILL');
63
+ killed = true;
64
+ }
65
+ catch (error) {
66
+ if (error.code !== 'ESRCH')
67
+ throw error;
68
+ }
69
+ }
70
+ }
71
+ await fs.rm(job.workDir, { recursive: true, force: true });
72
+ return { killed };
73
+ }
74
+ export function isProcessAlive(pid) {
75
+ try {
76
+ process.kill(pid, 0);
77
+ return true;
78
+ }
79
+ catch (error) {
80
+ return error.code === 'EPERM';
81
+ }
82
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phnx-labs/agents-cli",
3
- "version": "1.23.10",
3
+ "version": "1.23.11",
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",