@phnx-labs/agents-cli 1.23.9 → 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 +20 -0
- package/dist/commands/resume.js +11 -1
- package/dist/lib/daemon/supervisor.d.ts +2 -0
- package/dist/lib/daemon/supervisor.js +74 -40
- package/dist/lib/recordings/ledger.d.ts +3 -2
- package/dist/lib/recordings/ledger.js +16 -2
- package/dist/lib/recordings/model.d.ts +6 -0
- package/dist/lib/recordings/pipeline.d.ts +11 -3
- package/dist/lib/recordings/pipeline.js +27 -5
- package/dist/lib/recordings/process.d.ts +1 -0
- package/dist/lib/recordings/process.js +2 -0
- package/dist/lib/recordings/service.js +3 -1
- package/dist/lib/recordings/transcode.d.ts +6 -0
- package/dist/lib/recordings/transcode.js +41 -3
- package/dist/lib/session/active.d.ts +4 -0
- package/dist/lib/session/active.js +5 -0
- package/dist/lib/session/pid-registry.d.ts +1 -0
- package/dist/lib/session/pid-registry.js +2 -2
- package/dist/lib/session/projection.js +15 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
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
|
+
|
|
19
|
+
## 1.23.10
|
|
20
|
+
|
|
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`.
|
|
22
|
+
|
|
3
23
|
## 1.23.9
|
|
4
24
|
|
|
5
25
|
- Session status no longer reads an idle session as working: the bundled sessions reader moves to 0.8.3, which judges working vs idle by event timestamps instead of the transcript's file time (Claude's bookkeeping writes kept old sessions looking active). Formats without per-line timestamps (grok, cursor) still date their last event by the file time, so a waiting grok question still reads as waiting.
|
package/dist/commands/resume.js
CHANGED
|
@@ -4,7 +4,8 @@ import { resolveSessionMetadataValue } from '../lib/session/selection.js';
|
|
|
4
4
|
import { sessionOwnerDevice, consumeResumePinned, RESUME_PINNED_ENV } from '../lib/session/resume-owner.js';
|
|
5
5
|
import { machineId } from '../lib/machine-id.js';
|
|
6
6
|
import { takeOverDetachedSession } from '../lib/session/detached.js';
|
|
7
|
-
import { liveSessionProcesses } from '../lib/session/pid-registry.js';
|
|
7
|
+
import { liveSessionProcesses, writePidSessionEntry } from '../lib/session/pid-registry.js';
|
|
8
|
+
import { launchIdentityEnv } from '../lib/launch-identity.js';
|
|
8
9
|
const RESUME_SOURCE_ENV = 'AGENTS_RESUME_SOURCE_JSON';
|
|
9
10
|
export function resumeLocalFallbackSource(session, self = machineId()) {
|
|
10
11
|
return { ...session, machine: self };
|
|
@@ -103,6 +104,15 @@ export async function runStrictResume(sessionId, prompt, options) {
|
|
|
103
104
|
if (!options.quiet) {
|
|
104
105
|
process.stderr.write(chalk.gray(`[agents] session ${outcome.session.shortId} belongs to ${owner} → resuming there\n`));
|
|
105
106
|
}
|
|
107
|
+
writePidSessionEntry({
|
|
108
|
+
pid: process.pid,
|
|
109
|
+
agent: outcome.session.agent,
|
|
110
|
+
sessionId: outcome.session.id,
|
|
111
|
+
cwd: outcome.session.cwd,
|
|
112
|
+
terminalId: launchIdentityEnv().AGENT_TERMINAL_ID,
|
|
113
|
+
machine: owner,
|
|
114
|
+
startedAtMs: Date.now(),
|
|
115
|
+
});
|
|
106
116
|
const { runOnPeer } = await import('../lib/session/remote-list.js');
|
|
107
117
|
const rc = await runOnPeer(buildResumeRemoteArgs(outcome.session.id, prompt, options), owner, {
|
|
108
118
|
tty: !!process.stdout.isTTY,
|
|
@@ -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
|
-
|
|
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
|
-
//
|
|
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'
|
|
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
|
|
231
|
+
let overran = false;
|
|
226
232
|
ctx.log('DEBUG', `service '${id}' tick start`, { event: 'tick.start', service: id });
|
|
227
|
-
|
|
228
|
-
|
|
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
|
|
231
|
-
|
|
232
|
-
|
|
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
|
|
239
|
-
if (
|
|
240
|
-
ctx.log('WARN', `service '${id}' tick
|
|
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
|
-
|
|
259
|
+
if (!overran) {
|
|
260
|
+
entry.consecutiveFailures = 0;
|
|
261
|
+
entry.lastError = undefined;
|
|
262
|
+
recordSubsystemOk(id);
|
|
263
|
+
}
|
|
249
264
|
}
|
|
250
265
|
catch (err) {
|
|
251
|
-
const
|
|
252
|
-
if (
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
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
|
-
|
|
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}'
|
|
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
|
-
|
|
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<
|
|
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
|
-
|
|
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?:
|
|
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<
|
|
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
|
-
|
|
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).
|
|
236
|
+
const candidates = pending.map(rowCandidate).slice(0, 1);
|
|
215
237
|
if (candidates.length === 0)
|
|
216
238
|
return [];
|
|
217
239
|
try {
|
|
@@ -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(),
|
|
25
|
-
const output = path.join(directory,
|
|
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, {
|
|
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
|
+
}
|
|
@@ -201,6 +201,10 @@ export declare function listTeamsActive(opts?: {
|
|
|
201
201
|
localOnly?: boolean;
|
|
202
202
|
}): Promise<ActiveSession[]>;
|
|
203
203
|
export declare function listTerminalsActive(): Promise<ActiveSession[]>;
|
|
204
|
+
export declare function relayedTo(entry: Pick<PidSessionEntry, 'machine'> | undefined, self: string): {
|
|
205
|
+
machine?: string;
|
|
206
|
+
offloadedFrom?: string;
|
|
207
|
+
};
|
|
204
208
|
interface ProcRow {
|
|
205
209
|
pid: number;
|
|
206
210
|
ppid: number;
|
|
@@ -718,6 +718,7 @@ export async function listTerminalsActive() {
|
|
|
718
718
|
const children = childrenByParent(new Map([...procByPid.values()].map(r => [r.pid, r.ppid])));
|
|
719
719
|
const labelMap = buildClaudeLabelMap();
|
|
720
720
|
const runNameMap = buildRunNameMap();
|
|
721
|
+
const self = machineId();
|
|
721
722
|
return entries.flatMap((t) => {
|
|
722
723
|
const directEntry = readPidSessionEntry(t.pid, procByPid.get(t.pid)?.startTime);
|
|
723
724
|
const candidate = directEntry?.sessionId ? directEntry
|
|
@@ -758,9 +759,13 @@ export async function listTerminalsActive() {
|
|
|
758
759
|
workspaceDir: t.cwd ?? undefined,
|
|
759
760
|
windowHeartbeatMs: t.windowHeartbeatMs,
|
|
760
761
|
owner: resolveOwner(pidEntry?.actor, resolvedId),
|
|
762
|
+
...relayedTo(pidEntry, self),
|
|
761
763
|
}, state, sessionFile, pidAlive)];
|
|
762
764
|
});
|
|
763
765
|
}
|
|
766
|
+
export function relayedTo(entry, self) {
|
|
767
|
+
return entry?.machine && entry.machine !== self ? { machine: entry.machine, offloadedFrom: self } : {};
|
|
768
|
+
}
|
|
764
769
|
function listCloudActive() {
|
|
765
770
|
let tasks;
|
|
766
771
|
try {
|
|
@@ -240,9 +240,9 @@ export function listPidSessionEntries() {
|
|
|
240
240
|
}
|
|
241
241
|
export function liveSessionProcesses(sessionId) {
|
|
242
242
|
return listPidSessionEntries()
|
|
243
|
-
.filter((entry) => entry.sessionId === sessionId)
|
|
243
|
+
.filter((entry) => entry.sessionId === sessionId && !entry.machine)
|
|
244
244
|
.map((entry) => readLivePidSessionEntry(entry.pid))
|
|
245
|
-
.filter((entry) => entry?.sessionId === sessionId);
|
|
245
|
+
.filter((entry) => entry?.sessionId === sessionId && !entry.machine);
|
|
246
246
|
}
|
|
247
247
|
export function prunePidSessionRegistry(isAlive) {
|
|
248
248
|
let files;
|
|
@@ -25,12 +25,24 @@ export class SessionProjection {
|
|
|
25
25
|
if (event.type === 'scope' || event.type === 'heartbeat') {
|
|
26
26
|
return [{ ...event, ...stamp(), scope }];
|
|
27
27
|
}
|
|
28
|
+
const runsIt = new Map();
|
|
29
|
+
for (const [observer, rows] of this.observations)
|
|
30
|
+
for (const row of rows.values()) {
|
|
31
|
+
if (row.sessionId && row.sessionFile && normalizeHost(row.machine || row.sourceDevice || observer) === observer)
|
|
32
|
+
runsIt.set(`${row.kind}\0${row.sessionId}`, observer);
|
|
33
|
+
}
|
|
34
|
+
const ownerOf = (observer, row) => {
|
|
35
|
+
const own = normalizeHost(row.machine || row.sourceDevice || observer);
|
|
36
|
+
if (row.sessionFile || !row.terminalId || !row.sessionId)
|
|
37
|
+
return own;
|
|
38
|
+
return runsIt.get(`${row.kind}\0${row.sessionId}`) ?? own;
|
|
39
|
+
};
|
|
28
40
|
const launchSessions = new Map();
|
|
29
41
|
for (const [observer, rows] of this.observations)
|
|
30
42
|
for (const row of rows.values()) {
|
|
31
43
|
if (!row.launchId || !row.sessionId)
|
|
32
44
|
continue;
|
|
33
|
-
const owner =
|
|
45
|
+
const owner = ownerOf(observer, row);
|
|
34
46
|
const launch = `${owner}\0${row.kind}\0${row.launchId}`;
|
|
35
47
|
const ids = launchSessions.get(launch) ?? new Set();
|
|
36
48
|
ids.add(row.sessionId);
|
|
@@ -39,7 +51,7 @@ export class SessionProjection {
|
|
|
39
51
|
const groups = new Map();
|
|
40
52
|
for (const [observer, rows] of this.observations)
|
|
41
53
|
for (const row of rows.values()) {
|
|
42
|
-
const owner =
|
|
54
|
+
const owner = ownerOf(observer, row);
|
|
43
55
|
const launchIds = row.launchId ? launchSessions.get(`${owner}\0${row.kind}\0${row.launchId}`) : undefined;
|
|
44
56
|
const sessionId = row.sessionId || (launchIds?.size === 1 ? [...launchIds][0] : undefined);
|
|
45
57
|
const identity = sessionId ? `${row.kind}\0${sessionId}` : `${observer}\0${row.rowKey}`;
|
|
@@ -51,7 +63,7 @@ export class SessionProjection {
|
|
|
51
63
|
const next = new Map();
|
|
52
64
|
const selected = new Map();
|
|
53
65
|
for (const [rowKey, observations] of groups) {
|
|
54
|
-
const owner =
|
|
66
|
+
const owner = ownerOf(observations[0].scope, observations[0].row);
|
|
55
67
|
const authoritative = observations.filter(item => item.scope === owner);
|
|
56
68
|
const candidates = authoritative.length ? authoritative : this.observations.has(owner) ? [] : observations;
|
|
57
69
|
candidates.sort((a, b) => Number(a.row.previous) - Number(b.row.previous)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@phnx-labs/agents-cli",
|
|
3
|
-
"version": "1.23.
|
|
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",
|