@phnx-labs/agents-cli 1.23.38 → 1.23.40
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 +22 -0
- package/README.md +7 -20
- package/dist/cli/command-registry.js +0 -2
- package/dist/commands/config.js +0 -4
- package/dist/commands/daemon.js +5 -5
- package/dist/commands/events.js +1 -1
- package/dist/commands/exec.d.ts +4 -0
- package/dist/commands/exec.js +14 -1
- package/dist/commands/lead.js +4 -3
- package/dist/commands/setup.d.ts +1 -1
- package/dist/commands/setup.js +1 -9
- package/dist/commands/ssh.js +4 -5
- package/dist/lib/accounting/account-pool-collect.d.ts +1 -0
- package/dist/lib/accounting/account-pool-collect.js +13 -7
- package/dist/lib/accounting/account-pool.d.ts +1 -0
- package/dist/lib/accounting/account-pool.js +4 -3
- package/dist/lib/accounting/usage.d.ts +1 -1
- package/dist/lib/answer-router.d.ts +1 -1
- package/dist/lib/answer-router.js +16 -6
- package/dist/lib/channels/providers/session.js +13 -0
- package/dist/lib/channels/registry.d.ts +1 -1
- package/dist/lib/config-keys.d.ts +1 -1
- package/dist/lib/config-keys.js +1 -4
- package/dist/lib/daemon/daemon.js +1 -6
- package/dist/lib/daemon/device-probe-service.js +8 -0
- package/dist/lib/daemon-services.d.ts +1 -1
- package/dist/lib/daemon-services.js +1 -6
- package/dist/lib/device-config.js +2 -11
- package/dist/lib/devices/stats-cache.d.ts +24 -1
- package/dist/lib/devices/stats-cache.js +52 -18
- package/dist/lib/devices/worker-pick.d.ts +1 -1
- package/dist/lib/devices/worker-pick.js +8 -1
- package/dist/lib/feed/answer.js +25 -1
- package/dist/lib/feed/attention.d.ts +8 -0
- package/dist/lib/feed/attention.js +39 -0
- package/dist/lib/feed/tab-delivery.d.ts +27 -0
- package/dist/lib/feed/tab-delivery.js +102 -0
- package/dist/lib/feed/watch.d.ts +3 -0
- package/dist/lib/feed/watch.js +63 -13
- package/dist/lib/hosts/passthrough.js +0 -1
- package/dist/lib/hosts/ready.d.ts +3 -0
- package/dist/lib/hosts/ready.js +41 -1
- package/dist/lib/installations/migrate.d.ts +0 -1
- package/dist/lib/installations/migrate.js +0 -17
- package/dist/lib/lead/drafts.d.ts +11 -0
- package/dist/lib/lead/drafts.js +34 -0
- package/dist/lib/lead/host.d.ts +5 -0
- package/dist/lib/lead/host.js +52 -1
- package/dist/lib/lead/paths.js +1 -1
- package/dist/lib/lead/tools.d.ts +1 -0
- package/dist/lib/lead/tools.js +22 -0
- package/dist/lib/menubar/snapshot.d.ts +0 -6
- package/dist/lib/menubar/snapshot.js +0 -18
- package/dist/lib/session/active.d.ts +2 -1
- package/dist/lib/session/active.js +21 -9
- package/dist/lib/session/hook-sessions.d.ts +10 -0
- package/dist/lib/session/hook-sessions.js +22 -10
- package/dist/lib/session/inject-target.d.ts +1 -0
- package/dist/lib/session/inject-target.js +2 -1
- package/dist/lib/session/pid-registry.d.ts +1 -0
- package/dist/lib/session/remote/watch.d.ts +1 -0
- package/dist/lib/smart-launch.d.ts +5 -1
- package/dist/lib/smart-launch.js +41 -20
- package/dist/lib/startup/command-registry.js +2 -1
- package/dist/lib/state.js +0 -1
- package/dist/lib/teams/placement-probe.d.ts +5 -2
- package/dist/lib/teams/placement-probe.js +119 -57
- package/dist/lib/teams/scheduler.d.ts +1 -0
- package/dist/lib/terminal/index.d.ts +1 -1
- package/dist/lib/terminal/index.js +1 -1
- package/dist/lib/terminal/inject.d.ts +0 -15
- package/dist/lib/terminal/inject.js +2 -16
- package/dist/lib/terminal/resolve.d.ts +2 -1
- package/dist/lib/terminal/resolve.js +13 -18
- package/dist/lib/types.d.ts +0 -3
- package/package.json +1 -1
- package/dist/commands/setup-watchdog.d.ts +0 -3
- package/dist/commands/setup-watchdog.js +0 -49
- package/dist/commands/watchdog.d.ts +0 -4
- package/dist/commands/watchdog.js +0 -361
- package/dist/lib/daemon/watchdog-service.d.ts +0 -10
- package/dist/lib/daemon/watchdog-service.js +0 -27
- package/dist/lib/session/presence.d.ts +0 -47
- package/dist/lib/session/presence.js +0 -100
- package/dist/lib/watchdog/history.d.ts +0 -20
- package/dist/lib/watchdog/history.js +0 -43
- package/dist/lib/watchdog/log.d.ts +0 -33
- package/dist/lib/watchdog/log.js +0 -117
- package/dist/lib/watchdog/read.d.ts +0 -8
- package/dist/lib/watchdog/read.js +0 -93
- package/dist/lib/watchdog/rotate.d.ts +0 -55
- package/dist/lib/watchdog/rotate.js +0 -220
- package/dist/lib/watchdog/runner.d.ts +0 -100
- package/dist/lib/watchdog/runner.js +0 -727
- package/dist/lib/watchdog/service.d.ts +0 -15
- package/dist/lib/watchdog/service.js +0 -36
- package/dist/lib/watchdog/watchdog-agent.d.ts +0 -8
- package/dist/lib/watchdog/watchdog-agent.js +0 -32
- package/dist/lib/watchdog/watchdog.d.ts +0 -43
- package/dist/lib/watchdog/watchdog.js +0 -116
- package/dist/lib/watchdog/watchdogTail.d.ts +0 -6
- package/dist/lib/watchdog/watchdogTail.js +0 -116
|
@@ -526,12 +526,11 @@ export function assertTestDaemonHome(daemonDir = getDaemonDir(), testHome = proc
|
|
|
526
526
|
}
|
|
527
527
|
export async function runDaemon() {
|
|
528
528
|
assertTestDaemonHome();
|
|
529
|
-
const [{ SessionIndexService }, { SessionSummarizerService }, { SessionTitleService }, { AccountUsageService, AccountAuthService }, {
|
|
529
|
+
const [{ SessionIndexService }, { SessionSummarizerService }, { SessionTitleService }, { AccountUsageService, AccountAuthService }, { DeviceProbeService }, { SelfHealService }, { SelfUpdateService }, { HarnessUpdateService }, { AuthSyncService }, { UsageSyncService }, { StateDirCheckService }, { SessionStateService }, { FeedStreamService }, { AttentionNotifyService }, { RecordingsService }, { HeartbeatService }, { TmuxReapService },] = await Promise.all([
|
|
530
530
|
import('./session-index-service.js'),
|
|
531
531
|
import('./session-summarizer-service.js'),
|
|
532
532
|
import('./session-title-service.js'),
|
|
533
533
|
import('./account-state-daemon-service.js'),
|
|
534
|
-
import('./watchdog-service.js'),
|
|
535
534
|
import('./device-probe-service.js'),
|
|
536
535
|
import('./self-heal-service.js'),
|
|
537
536
|
import('./self-update-service.js'),
|
|
@@ -653,10 +652,6 @@ export async function runDaemon() {
|
|
|
653
652
|
supervisor.register(new SessionTitleService());
|
|
654
653
|
else
|
|
655
654
|
log('INFO', 'Session-title service disabled');
|
|
656
|
-
if (isEnabled('watchdog'))
|
|
657
|
-
supervisor.register(new WatchdogService());
|
|
658
|
-
else
|
|
659
|
-
log('INFO', 'Watchdog service disabled');
|
|
660
655
|
if (isEnabled('device-probe'))
|
|
661
656
|
supervisor.register(new DeviceProbeService());
|
|
662
657
|
else
|
|
@@ -10,6 +10,14 @@ export class DeviceProbeService extends BasePeriodicService {
|
|
|
10
10
|
async onStop() {
|
|
11
11
|
}
|
|
12
12
|
async onTick(ctx) {
|
|
13
|
+
const { listOnlineDeviceNames } = await import('../smart-launch.js');
|
|
14
|
+
const { refreshPlacementSnapshot } = await import('../teams/placement-probe.js');
|
|
15
|
+
const refreshed = await refreshPlacementSnapshot(listOnlineDeviceNames()).catch((err) => {
|
|
16
|
+
ctx.log('WARN', `placement snapshot refresh failed: ${err.message}`);
|
|
17
|
+
return null;
|
|
18
|
+
});
|
|
19
|
+
if (refreshed !== null)
|
|
20
|
+
ctx.log('DEBUG', `placement snapshot: probed ${refreshed} device(s)`);
|
|
13
21
|
const { runDeviceSync } = await import('../devices/sync.js');
|
|
14
22
|
const { reconcilePendingSentinels, pruneDismissedPendingSentinels } = await import('../devices/pending.js');
|
|
15
23
|
const dev = await runDeviceSync({ soft: true, mode: 'refresh' });
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type LogLevel } from './daemon/diagnostics.js';
|
|
2
|
-
export type DaemonServiceId = 'self-heal' | 'self-update' | 'account-state' | 'account-auth' | '
|
|
2
|
+
export type DaemonServiceId = 'self-heal' | 'self-update' | 'account-state' | 'account-auth' | 'device-probe' | 'state-dir-check' | 'session-index' | 'session-title' | 'auth-sync' | 'usage-sync' | 'daemon-heartbeat' | 'tmux-reap' | 'session-state' | 'feed-stream' | 'session-summarizer' | 'attention-notify' | 'recordings' | 'harness-update';
|
|
3
3
|
interface DaemonServiceDef {
|
|
4
4
|
id: DaemonServiceId;
|
|
5
5
|
title: string;
|
|
@@ -25,15 +25,10 @@ export const DAEMON_SERVICES = [
|
|
|
25
25
|
title: 'Account auth refresh',
|
|
26
26
|
description: 'Publishes this host\'s fleet-status row and refreshes auth health on its own slower tick (PHNX-3608: independent circuit breaker from account-state).',
|
|
27
27
|
},
|
|
28
|
-
{
|
|
29
|
-
id: 'watchdog',
|
|
30
|
-
title: 'Watchdog',
|
|
31
|
-
description: 'Nudges stalled agent sessions on this host when opted in via watchdog.enabled.',
|
|
32
|
-
},
|
|
33
28
|
{
|
|
34
29
|
id: 'device-probe',
|
|
35
30
|
title: 'Device probe',
|
|
36
|
-
description: 'Discovers Tailscale devices and surfaces pending ones for registration.',
|
|
31
|
+
description: 'Discovers Tailscale devices and surfaces pending ones for registration, and keeps the placement snapshot `--device auto` reads current while placement was used in the last day.',
|
|
37
32
|
},
|
|
38
33
|
{
|
|
39
34
|
id: 'state-dir-check',
|
|
@@ -172,20 +172,11 @@ export const CONFIG_KEYS = [
|
|
|
172
172
|
visibility: 'machine',
|
|
173
173
|
type: 'bool',
|
|
174
174
|
defaultValue: true,
|
|
175
|
-
description: 'Whether the daemon may run on this device at all (
|
|
175
|
+
description: 'Whether the daemon may run on this device at all (session/usage sync, the feed stream, and the ' +
|
|
176
176
|
'other daemon services). Disabling is the top-level kill switch: nothing auto-starts the daemon while it ' +
|
|
177
|
-
'is set, including `feed watch
|
|
177
|
+
'is set, including `feed watch` and `recordings`. ' +
|
|
178
178
|
'`agents daemon start` still starts it explicitly.',
|
|
179
179
|
},
|
|
180
|
-
{
|
|
181
|
-
name: 'watchdog.enabled',
|
|
182
|
-
yamlKey: 'watchdogEnabled',
|
|
183
|
-
scope: 'device',
|
|
184
|
-
visibility: 'shared',
|
|
185
|
-
type: 'bool',
|
|
186
|
-
defaultValue: false,
|
|
187
|
-
description: 'Whether the daemon runs the watchdog pass on this device.',
|
|
188
|
-
},
|
|
189
180
|
{
|
|
190
181
|
name: 'tmux.enabled',
|
|
191
182
|
yamlKey: 'tmuxEnabled',
|
|
@@ -3,10 +3,33 @@ import type { DeviceProfile } from './registry.js';
|
|
|
3
3
|
export declare const STATS_STALE_MS: number;
|
|
4
4
|
export declare function isFreshDeviceStats(stats: DeviceStats, now?: number): boolean;
|
|
5
5
|
export declare function retainHardwareFacts(probed: DeviceStats, prior: DeviceStats | undefined): DeviceStats;
|
|
6
|
+
export declare const PLACEMENT_SNAPSHOT_MAX_AGE_MS: number;
|
|
7
|
+
export declare const PLACEMENT_DEMAND_WINDOW_MS: number;
|
|
8
|
+
export interface ReadyProbeEntry {
|
|
9
|
+
answered: boolean;
|
|
10
|
+
timedOut?: boolean;
|
|
11
|
+
version: string | null;
|
|
12
|
+
view: string;
|
|
13
|
+
fetchedAt: number;
|
|
14
|
+
}
|
|
15
|
+
export interface PlacementSnapshot {
|
|
16
|
+
stats: Record<string, DeviceStats>;
|
|
17
|
+
readiness: Record<string, ReadyProbeEntry>;
|
|
18
|
+
demandAt?: number;
|
|
19
|
+
}
|
|
6
20
|
export declare function readStatsCache(): Record<string, DeviceStats>;
|
|
7
21
|
export declare function writeStatsCache(entries: Record<string, DeviceStats>): void;
|
|
22
|
+
export declare function readPlacementSnapshot(): PlacementSnapshot;
|
|
23
|
+
export declare function writePlacementSnapshot(update: {
|
|
24
|
+
stats?: Record<string, DeviceStats>;
|
|
25
|
+
readiness?: Record<string, ReadyProbeEntry>;
|
|
26
|
+
demandAt?: number;
|
|
27
|
+
}): void;
|
|
28
|
+
export declare function freshReadyProbe(snapshot: PlacementSnapshot, name: string, now?: number): ReadyProbeEntry | undefined;
|
|
29
|
+
export declare function freshSnapshotStats(snapshot: PlacementSnapshot, name: string, now?: number): DeviceStats | undefined;
|
|
30
|
+
export declare function placementDemandIsRecent(snapshot: PlacementSnapshot, now?: number): boolean;
|
|
8
31
|
export declare function removeStatsCacheEntry(name: string): void;
|
|
9
|
-
export declare function pruneStatsCache(entries: Record<string,
|
|
32
|
+
export declare function pruneStatsCache<T>(entries: Record<string, T>, name: string): Record<string, T>;
|
|
10
33
|
interface FleetStatsResult {
|
|
11
34
|
stats: Map<string, DeviceStats>;
|
|
12
35
|
oldestFetchedAt: number | null;
|
|
@@ -26,43 +26,77 @@ export function retainHardwareFacts(probed, prior) {
|
|
|
26
26
|
specsFetchedAt: prior.specsFetchedAt ?? prior.fetchedAt,
|
|
27
27
|
};
|
|
28
28
|
}
|
|
29
|
+
export const PLACEMENT_SNAPSHOT_MAX_AGE_MS = 5 * 60_000;
|
|
30
|
+
export const PLACEMENT_DEMAND_WINDOW_MS = 24 * 60 * 60_000;
|
|
29
31
|
function cacheFilePath() {
|
|
30
32
|
return path.join(getCacheDir(), CACHE_FILE);
|
|
31
33
|
}
|
|
32
|
-
|
|
34
|
+
function readCacheFile() {
|
|
33
35
|
try {
|
|
34
36
|
const parsed = JSON.parse(fs.readFileSync(cacheFilePath(), 'utf-8'));
|
|
35
37
|
if (parsed && parsed.entries && typeof parsed.entries === 'object')
|
|
36
|
-
return parsed
|
|
38
|
+
return parsed;
|
|
37
39
|
}
|
|
38
40
|
catch {
|
|
39
41
|
}
|
|
40
|
-
return {};
|
|
42
|
+
return { version: 1, entries: {} };
|
|
41
43
|
}
|
|
42
|
-
|
|
44
|
+
function updateCacheFile(update) {
|
|
43
45
|
try {
|
|
44
46
|
const dir = getCacheDir();
|
|
45
47
|
if (!fs.existsSync(dir))
|
|
46
48
|
fs.mkdirSync(dir, { recursive: true });
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
49
|
+
const file = cacheFilePath();
|
|
50
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
51
|
+
try {
|
|
52
|
+
fs.writeFileSync(tmp, JSON.stringify(update(readCacheFile()), null, 2));
|
|
53
|
+
fs.renameSync(tmp, file);
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
fs.rmSync(tmp, { force: true });
|
|
57
|
+
}
|
|
52
58
|
}
|
|
53
59
|
catch {
|
|
54
60
|
}
|
|
55
61
|
}
|
|
62
|
+
export function readStatsCache() {
|
|
63
|
+
return readCacheFile().entries;
|
|
64
|
+
}
|
|
65
|
+
export function writeStatsCache(entries) {
|
|
66
|
+
updateCacheFile((current) => ({ ...current, entries: { ...current.entries, ...entries } }));
|
|
67
|
+
}
|
|
68
|
+
export function readPlacementSnapshot() {
|
|
69
|
+
const file = readCacheFile();
|
|
70
|
+
return { stats: file.entries, readiness: file.readiness ?? {}, demandAt: file.placementDemandAt };
|
|
71
|
+
}
|
|
72
|
+
export function writePlacementSnapshot(update) {
|
|
73
|
+
updateCacheFile((current) => ({
|
|
74
|
+
...current,
|
|
75
|
+
entries: { ...current.entries, ...update.stats },
|
|
76
|
+
readiness: { ...current.readiness, ...update.readiness },
|
|
77
|
+
placementDemandAt: update.demandAt ?? current.placementDemandAt,
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
export function freshReadyProbe(snapshot, name, now = Date.now()) {
|
|
81
|
+
const entry = snapshot.readiness[name];
|
|
82
|
+
return entry && now - entry.fetchedAt <= PLACEMENT_SNAPSHOT_MAX_AGE_MS ? entry : undefined;
|
|
83
|
+
}
|
|
84
|
+
export function freshSnapshotStats(snapshot, name, now = Date.now()) {
|
|
85
|
+
const stats = snapshot.stats[name];
|
|
86
|
+
return stats && now - stats.fetchedAt <= PLACEMENT_SNAPSHOT_MAX_AGE_MS ? stats : undefined;
|
|
87
|
+
}
|
|
88
|
+
export function placementDemandIsRecent(snapshot, now = Date.now()) {
|
|
89
|
+
return snapshot.demandAt !== undefined && now - snapshot.demandAt <= PLACEMENT_DEMAND_WINDOW_MS;
|
|
90
|
+
}
|
|
56
91
|
export function removeStatsCacheEntry(name) {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
}
|
|
92
|
+
const current = readCacheFile();
|
|
93
|
+
if (!(name in current.entries) && !(current.readiness && name in current.readiness))
|
|
94
|
+
return;
|
|
95
|
+
updateCacheFile((file) => ({
|
|
96
|
+
...file,
|
|
97
|
+
entries: pruneStatsCache(file.entries, name),
|
|
98
|
+
readiness: file.readiness ? pruneStatsCache(file.readiness, name) : undefined,
|
|
99
|
+
}));
|
|
66
100
|
}
|
|
67
101
|
export function pruneStatsCache(entries, name) {
|
|
68
102
|
const { [name]: _removed, ...remaining } = entries;
|
|
@@ -17,7 +17,7 @@ interface WorkerPickOptions {
|
|
|
17
17
|
platforms?: string[];
|
|
18
18
|
eligibleHosts?: string[];
|
|
19
19
|
localMachine?: string;
|
|
20
|
-
probe?: (pool: string[]) => Promise<Map<string, DevicePlacementSignal>>;
|
|
20
|
+
probe?: (pool: string[], force?: boolean) => Promise<Map<string, DevicePlacementSignal>>;
|
|
21
21
|
preferred?: ReadonlySet<string>;
|
|
22
22
|
}
|
|
23
23
|
export declare function resolveWorkerDevice(opts?: WorkerPickOptions): Promise<WorkerPickPlan>;
|
|
@@ -32,7 +32,11 @@ export async function resolveWorkerDevice(opts = {}) {
|
|
|
32
32
|
});
|
|
33
33
|
if (onPlatform.length === 0)
|
|
34
34
|
throw new Error(formatNoWorkerError(excluded, wanted));
|
|
35
|
-
const
|
|
35
|
+
const probe = opts.probe ?? ((p, force) => probePoolSignals(p, undefined, { force }));
|
|
36
|
+
let signals = await probe(onPlatform);
|
|
37
|
+
if (!onPlatform.some((device) => isWorkerEligible(signals.get(device))) && [...signals.values()].some((s) => s.fromSnapshot)) {
|
|
38
|
+
signals = await probe(onPlatform, true);
|
|
39
|
+
}
|
|
36
40
|
const eligible = onPlatform.filter((device) => {
|
|
37
41
|
const signal = signals.get(device);
|
|
38
42
|
if (signal?.reachable !== true) {
|
|
@@ -60,6 +64,9 @@ export async function resolveWorkerDevice(opts = {}) {
|
|
|
60
64
|
excluded,
|
|
61
65
|
};
|
|
62
66
|
}
|
|
67
|
+
function isWorkerEligible(signal) {
|
|
68
|
+
return signal?.reachable === true && !blocksPlacement(signal.headroom);
|
|
69
|
+
}
|
|
63
70
|
export function formatNoWorkerError(excluded, platforms) {
|
|
64
71
|
const detail = excluded.length
|
|
65
72
|
? excluded.map((e) => `${e.device} (${e.reason})`).join(', ')
|
package/dist/lib/feed/answer.js
CHANGED
|
@@ -9,6 +9,7 @@ import { shellQuote, sshExecAsync, SSH_CONN_FAILURE_CODE, SSH_TIMEOUT_KILL_GRACE
|
|
|
9
9
|
import { blockGeneration, blockIdForSession, confirmAnswerResolution, getAnswerRecord, latestMessageReceipt, publishBlock, readBlock, readResolution, recordAnswer, recordMessageReceipt, rollbackAnswerClaim, } from './feed.js';
|
|
10
10
|
import { reconcileAttention } from './attention.js';
|
|
11
11
|
import { readPullRequestStatus } from './pr-status.js';
|
|
12
|
+
import { deliverToTab } from './tab-delivery.js';
|
|
12
13
|
import { getAgentsInvocation } from '../daemon/daemon.js';
|
|
13
14
|
export const ANSWER_DEADLINE_MS = 20_000;
|
|
14
15
|
export const PR_ENRICHMENT_BUDGET_MS = 4_000;
|
|
@@ -272,11 +273,32 @@ async function deliverInject(route, block, answer, claimedAt, operator, origin,
|
|
|
272
273
|
}
|
|
273
274
|
return { receipt: { msgId: `inject-${block.blockId}-${claimedAt}`, status: 'queued', at: new Date().toISOString(), from: operator.label, ...origin } };
|
|
274
275
|
}
|
|
276
|
+
async function deliverTab(route, block, session, operator, origin, deadline, feedRoot) {
|
|
277
|
+
const result = await deliverToTab({
|
|
278
|
+
sessionId: block.sessionId,
|
|
279
|
+
text: route.payload,
|
|
280
|
+
enter: route.enter ?? true,
|
|
281
|
+
transcript: session?.sessionFile,
|
|
282
|
+
root: feedRoot,
|
|
283
|
+
timeoutMs: Math.max(0, remainingMs(deadline) - 500),
|
|
284
|
+
});
|
|
285
|
+
if (!result.delivered) {
|
|
286
|
+
if (!result.touched)
|
|
287
|
+
throw new AnswerError(`${result.reason} Nothing reached the session, so the answer can be sent again.`, 'rail_failed');
|
|
288
|
+
throw new AnswerUnknownError(result.reason);
|
|
289
|
+
}
|
|
290
|
+
return { receipt: { msgId: result.id, status: 'consumed', at: new Date().toISOString(), from: operator.label, ...origin } };
|
|
291
|
+
}
|
|
275
292
|
function preflightRoute(route, answer, attentionKey) {
|
|
276
293
|
if (route.kind === 'refuse')
|
|
277
294
|
throw new AnswerError(route.reason, 'refused');
|
|
278
295
|
if (route.kind === 'mailbox' || route.kind === 'resume')
|
|
279
296
|
return;
|
|
297
|
+
if (route.kind === 'tab') {
|
|
298
|
+
if (route.payload == null)
|
|
299
|
+
throw new AnswerError(`Incomplete tab reply rail for '${attentionKey}'.`, 'refused');
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
280
302
|
if (!route.inject || route.payload == null)
|
|
281
303
|
throw new AnswerError(`Incomplete ${route.kind} reply rail.`, 'refused');
|
|
282
304
|
if (isMultilineFreeText(route, answer) && !backendCarriesPaste(route.inject.backend)) {
|
|
@@ -366,7 +388,9 @@ export async function claimAndRouteAttentionAnswer(input) {
|
|
|
366
388
|
? deliverMailbox(block, answer, input.operator, outcome.adopted, origin, input.mailboxRoot)
|
|
367
389
|
: route.kind === 'resume'
|
|
368
390
|
? deliverResume(route, block, claim.answeredAt, input.operator, input.attentionKey, deadline, origin)
|
|
369
|
-
:
|
|
391
|
+
: route.kind === 'tab'
|
|
392
|
+
? deliverTab(route, block, session, input.operator, origin, deadline, input.feedRoot)
|
|
393
|
+
: deliverInject(route, block, answer, claim.answeredAt, input.operator, origin, deadline), deadline, `Delivering '${input.attentionKey}' over ${route.kind}`);
|
|
370
394
|
}
|
|
371
395
|
catch (error) {
|
|
372
396
|
if (error instanceof AnswerError) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ActiveSession } from '../session/active.js';
|
|
2
|
+
import type { TurnVerdict } from '../session/hook-sessions.js';
|
|
2
3
|
import { type AttentionResolution, type AttentionSource, type AttentionState, type BlockOption, type BlockQuestion, type OpenBlock, type SourceCursor } from './feed.js';
|
|
3
4
|
export type AttentionKind = 'question' | 'permission' | 'plan_review' | 'declared' | 'failure' | 'stall' | 'review' | 'unverified';
|
|
4
5
|
export type ReplyCapability = 'terminal' | 'tmux' | 'cloud' | 'team' | 'none';
|
|
@@ -26,6 +27,12 @@ export interface AttentionItem {
|
|
|
26
27
|
sourceCursor?: SourceCursor;
|
|
27
28
|
urgency: AttentionUrgency;
|
|
28
29
|
urgencyReason?: string;
|
|
30
|
+
draft?: {
|
|
31
|
+
text?: string;
|
|
32
|
+
choiceId?: string;
|
|
33
|
+
label: string;
|
|
34
|
+
at: string;
|
|
35
|
+
};
|
|
29
36
|
}
|
|
30
37
|
export interface PullRequestAttentionSignal {
|
|
31
38
|
number: number;
|
|
@@ -41,6 +48,7 @@ type UnrankedAttentionItem = Omit<AttentionItem, 'urgency' | 'urgencyReason'>;
|
|
|
41
48
|
export declare function attentionFingerprint(kind: AttentionKind, question?: BlockQuestion): string;
|
|
42
49
|
export declare function harnessOf(session: Partial<Pick<ActiveSession, 'harness' | 'kind'>>): string;
|
|
43
50
|
export declare const UNVERIFIED_PROMPT_AGE_MS: number;
|
|
51
|
+
export declare function currentTurnVerdict(session: ActiveSession): TurnVerdict | undefined;
|
|
44
52
|
export declare function attentionUrgency(item: UnrankedAttentionItem, ticket?: {
|
|
45
53
|
id: string;
|
|
46
54
|
priority?: number;
|
|
@@ -151,6 +151,42 @@ function attentionFromBlock(block, session, nowMs) {
|
|
|
151
151
|
};
|
|
152
152
|
return { item, generation };
|
|
153
153
|
}
|
|
154
|
+
export function currentTurnVerdict(session) {
|
|
155
|
+
const v = session.turnVerdict;
|
|
156
|
+
if (!v || session.activity === 'working')
|
|
157
|
+
return undefined;
|
|
158
|
+
if (session.lastEventMs != null && session.lastEventMs > v.atMs)
|
|
159
|
+
return undefined;
|
|
160
|
+
return v;
|
|
161
|
+
}
|
|
162
|
+
function attentionFromTurnVerdict(session) {
|
|
163
|
+
const v = currentTurnVerdict(session);
|
|
164
|
+
if (!v || (v.kind !== 'asks' && v.kind !== 'not_done'))
|
|
165
|
+
return undefined;
|
|
166
|
+
const question = v.kind === 'asks'
|
|
167
|
+
? { text: v.quote || 'The agent is waiting for your answer.', ...(v.choices.length ? { options: v.choices.map((label) => ({ label })) } : {}) }
|
|
168
|
+
: { text: v.quote || 'The agent stopped before finishing.', header: 'Not done' };
|
|
169
|
+
const host = session.host ?? 'unknown';
|
|
170
|
+
const sessionId = session.sessionId ?? '';
|
|
171
|
+
const generation = `v${v.atMs}`;
|
|
172
|
+
const item = {
|
|
173
|
+
key: attentionKey(host, sessionId, generation),
|
|
174
|
+
sessionId,
|
|
175
|
+
mailboxId: sessionId,
|
|
176
|
+
host,
|
|
177
|
+
project: session.project ?? undefined,
|
|
178
|
+
kind: 'question',
|
|
179
|
+
source: 'lifecycle',
|
|
180
|
+
state: 'open',
|
|
181
|
+
openedAt: new Date(v.atMs).toISOString(),
|
|
182
|
+
question,
|
|
183
|
+
choices: questionChoices(question),
|
|
184
|
+
replyCapability: replyCapabilityForSession(session),
|
|
185
|
+
fingerprint: attentionFingerprint('question', question),
|
|
186
|
+
sourceCursor: { lastActivityMs: v.atMs },
|
|
187
|
+
};
|
|
188
|
+
return { item, generation };
|
|
189
|
+
}
|
|
154
190
|
function attentionFromSession(session, nowMs) {
|
|
155
191
|
if (session.activity !== 'waiting_input')
|
|
156
192
|
return undefined;
|
|
@@ -160,6 +196,8 @@ function attentionFromSession(session, nowMs) {
|
|
|
160
196
|
const kind = reason === 'plan_review' ? 'plan_review' : reason === 'permission' ? 'unverified' : 'question';
|
|
161
197
|
const sq = session.question;
|
|
162
198
|
const structural = kind === 'plan_review' || (kind === 'question' && (sq?.options?.length ?? 0) > 0);
|
|
199
|
+
if (!structural && kind === 'question' && currentTurnVerdict(session))
|
|
200
|
+
return undefined;
|
|
163
201
|
const source = structural ? 'lifecycle' : 'heuristic';
|
|
164
202
|
const question = sq ? structuredToBlockQuestion(sq) : undefined;
|
|
165
203
|
const host = session.host ?? 'unknown';
|
|
@@ -295,6 +333,7 @@ export function reconcileAttention(input) {
|
|
|
295
333
|
: undefined;
|
|
296
334
|
const candidate = fromBlock ??
|
|
297
335
|
attentionFromSession(input.session, input.nowMs) ??
|
|
336
|
+
attentionFromTurnVerdict(input.session) ??
|
|
298
337
|
attentionFromPullRequest(input.session, input.nowMs, input.pullRequest);
|
|
299
338
|
if (!candidate)
|
|
300
339
|
return undefined;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface TabDelivery {
|
|
2
|
+
id: string;
|
|
3
|
+
sessionId: string;
|
|
4
|
+
text: string;
|
|
5
|
+
enter: boolean;
|
|
6
|
+
at: string;
|
|
7
|
+
}
|
|
8
|
+
export declare const TAB_DELIVERY_TTL_MS = 15000;
|
|
9
|
+
export declare function tabDeliveryDir(root?: string): string;
|
|
10
|
+
export declare function readTabDelivery(sessionId: string, root?: string, nowMs?: number): TabDelivery | undefined;
|
|
11
|
+
export type TabDeliveryResult = {
|
|
12
|
+
delivered: true;
|
|
13
|
+
id: string;
|
|
14
|
+
} | {
|
|
15
|
+
delivered: false;
|
|
16
|
+
id: string;
|
|
17
|
+
reason: string;
|
|
18
|
+
touched: boolean;
|
|
19
|
+
};
|
|
20
|
+
export declare function deliverToTab(input: {
|
|
21
|
+
sessionId: string;
|
|
22
|
+
text: string;
|
|
23
|
+
enter?: boolean;
|
|
24
|
+
transcript?: string;
|
|
25
|
+
root?: string;
|
|
26
|
+
timeoutMs?: number;
|
|
27
|
+
}): Promise<TabDeliveryResult>;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { getFeedDir } from '../state.js';
|
|
4
|
+
export const TAB_DELIVERY_TTL_MS = 15_000;
|
|
5
|
+
const POLL_MS = 250;
|
|
6
|
+
function deliveryDir(root) {
|
|
7
|
+
return path.join(root ?? getFeedDir(), 'deliveries');
|
|
8
|
+
}
|
|
9
|
+
function deliveryPath(sessionId, root) {
|
|
10
|
+
return path.join(deliveryDir(root), `${sessionId.replace(/[^A-Za-z0-9._-]/g, '-')}.json`);
|
|
11
|
+
}
|
|
12
|
+
export function tabDeliveryDir(root) {
|
|
13
|
+
return deliveryDir(root);
|
|
14
|
+
}
|
|
15
|
+
export function readTabDelivery(sessionId, root, nowMs = Date.now()) {
|
|
16
|
+
try {
|
|
17
|
+
const d = JSON.parse(fs.readFileSync(deliveryPath(sessionId, root), 'utf8'));
|
|
18
|
+
if (!d || d.sessionId !== sessionId || typeof d.text !== 'string')
|
|
19
|
+
return undefined;
|
|
20
|
+
return nowMs - Date.parse(d.at) <= TAB_DELIVERY_TTL_MS ? d : undefined;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function removeTabDelivery(d, root) {
|
|
27
|
+
const current = readTabDelivery(d.sessionId, root, Number.NEGATIVE_INFINITY);
|
|
28
|
+
if (current && current.id !== d.id)
|
|
29
|
+
return;
|
|
30
|
+
try {
|
|
31
|
+
fs.unlinkSync(deliveryPath(d.sessionId, root));
|
|
32
|
+
}
|
|
33
|
+
catch { }
|
|
34
|
+
}
|
|
35
|
+
function sizeOf(file) {
|
|
36
|
+
if (!file)
|
|
37
|
+
return 0;
|
|
38
|
+
try {
|
|
39
|
+
return fs.statSync(file).size;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return 0;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function appendedSince(file, from) {
|
|
46
|
+
const fd = fs.openSync(file, 'r');
|
|
47
|
+
try {
|
|
48
|
+
const size = fs.fstatSync(fd).size;
|
|
49
|
+
if (size <= from)
|
|
50
|
+
return '';
|
|
51
|
+
const buf = Buffer.alloc(size - from);
|
|
52
|
+
fs.readSync(fd, buf, 0, buf.length, from);
|
|
53
|
+
return buf.toString('utf8');
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
fs.closeSync(fd);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function received(appended, text) {
|
|
60
|
+
if (!appended)
|
|
61
|
+
return false;
|
|
62
|
+
const probe = Array.from(text.trim()).slice(0, 60).join('');
|
|
63
|
+
if (probe.length <= 1)
|
|
64
|
+
return appended.includes('"tool_result"');
|
|
65
|
+
return appended.includes(JSON.stringify(probe).slice(1, -1));
|
|
66
|
+
}
|
|
67
|
+
export async function deliverToTab(input) {
|
|
68
|
+
if (!input.transcript) {
|
|
69
|
+
return { delivered: false, id: '', touched: false, reason: 'This session has no transcript to confirm a delivery, so nothing was sent.' };
|
|
70
|
+
}
|
|
71
|
+
const at = new Date();
|
|
72
|
+
const delivery = {
|
|
73
|
+
id: `tab-${input.sessionId.slice(0, 8)}-${at.getTime()}`,
|
|
74
|
+
sessionId: input.sessionId,
|
|
75
|
+
text: input.text,
|
|
76
|
+
enter: input.enter !== false,
|
|
77
|
+
at: at.toISOString(),
|
|
78
|
+
};
|
|
79
|
+
const from = sizeOf(input.transcript);
|
|
80
|
+
fs.mkdirSync(deliveryDir(input.root), { recursive: true, mode: 0o700 });
|
|
81
|
+
const file = deliveryPath(input.sessionId, input.root);
|
|
82
|
+
fs.writeFileSync(`${file}.tmp`, JSON.stringify(delivery), { mode: 0o600 });
|
|
83
|
+
fs.renameSync(`${file}.tmp`, file);
|
|
84
|
+
const deadline = at.getTime() + Math.min(input.timeoutMs ?? TAB_DELIVERY_TTL_MS, TAB_DELIVERY_TTL_MS);
|
|
85
|
+
try {
|
|
86
|
+
while (Date.now() < deadline) {
|
|
87
|
+
if (input.transcript && received(appendedSince(input.transcript, from), input.text)) {
|
|
88
|
+
return { delivered: true, id: delivery.id };
|
|
89
|
+
}
|
|
90
|
+
await new Promise((r) => setTimeout(r, POLL_MS));
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
delivered: false,
|
|
94
|
+
id: delivery.id,
|
|
95
|
+
touched: sizeOf(input.transcript) > from,
|
|
96
|
+
reason: `No editor window holding this session's tab typed it within ${Math.round(TAB_DELIVERY_TTL_MS / 1000)} seconds.`,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
removeTabDelivery(delivery, input.root);
|
|
101
|
+
}
|
|
102
|
+
}
|
package/dist/lib/feed/watch.d.ts
CHANGED
|
@@ -15,6 +15,9 @@ export declare class FeedSessionProjection {
|
|
|
15
15
|
private readonly setupByScope;
|
|
16
16
|
constructor(state?: FeedWatchState);
|
|
17
17
|
apply(event: FeedWatchEnvelope): FeedWatchEnvelope[];
|
|
18
|
+
redraft(): FeedWatchEnvelope[];
|
|
19
|
+
private currentAttention;
|
|
20
|
+
private upsertChanged;
|
|
18
21
|
}
|
|
19
22
|
export declare function projectSessionEnvelope(event: SessionWatchEnvelope, state: FeedWatchState, gh?: GhExec, tools?: ToolRow[], setup?: ToolSetupRow[]): Promise<FeedWatchEnvelope[]>;
|
|
20
23
|
interface WatchLocalFeedOptions {
|