@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.
- package/CHANGELOG.md +261 -0
- package/README.md +49 -10
- package/dist/bootstrap.js +22 -17
- package/dist/cli/command-registry.d.ts +0 -1
- package/dist/cli/command-registry.js +2 -10
- package/dist/commands/auth.js +13 -4
- package/dist/commands/browser.js +3 -4
- package/dist/commands/cloud-transcripts.d.ts +7 -0
- package/dist/commands/cloud-transcripts.js +100 -0
- package/dist/commands/cloud.js +5 -0
- package/dist/commands/computer.d.ts +0 -12
- package/dist/commands/computer.js +14 -124
- package/dist/commands/config.js +5 -4
- package/dist/commands/daemon-index.d.ts +2 -0
- package/dist/commands/daemon-index.js +44 -0
- package/dist/commands/daemon.js +6 -0
- package/dist/commands/doctor.js +3 -4
- package/dist/commands/exec.d.ts +5 -0
- package/dist/commands/exec.js +35 -7
- package/dist/commands/feed-watch.js +12 -0
- package/dist/commands/feed.d.ts +1 -1
- package/dist/commands/feed.js +7 -4
- package/dist/commands/insights.js +3 -1
- package/dist/commands/inspect.js +1 -1
- package/dist/commands/logs.js +2 -1
- package/dist/commands/models.js +1 -1
- package/dist/commands/prune.js +6 -28
- package/dist/commands/ps-roster.d.ts +0 -1
- package/dist/commands/ps-roster.js +2 -21
- package/dist/commands/ps.js +13 -1
- package/dist/commands/recordings.d.ts +2 -0
- package/dist/commands/recordings.js +117 -0
- package/dist/commands/routines.js +1 -1
- package/dist/commands/secrets-passthrough.js +3 -3
- package/dist/commands/send.js +33 -20
- package/dist/commands/sessions-backfill.d.ts +1 -0
- package/dist/commands/sessions-backfill.js +48 -13
- package/dist/commands/sessions-migrate.d.ts +1 -1
- package/dist/commands/sessions-migrate.js +11 -10
- package/dist/commands/sessions-optimize.d.ts +1 -0
- package/dist/commands/sessions-optimize.js +7 -4
- package/dist/commands/sessions-resume.js +8 -1
- package/dist/commands/sessions-stats.d.ts +2 -0
- package/dist/commands/sessions-stats.js +24 -7
- package/dist/commands/sessions.d.ts +5 -11
- package/dist/commands/sessions.js +8 -236
- package/dist/commands/setup-computer.js +1 -2
- package/dist/commands/setup.js +1 -1
- package/dist/commands/teams.js +2 -2
- package/dist/commands/testdata/feed-hub.d.ts +1 -0
- package/dist/commands/testdata/feed-hub.js +11 -0
- package/dist/commands/trash.d.ts +0 -1
- package/dist/commands/trash.js +74 -10
- package/dist/lib/accounting/usage-sync.js +7 -0
- package/dist/lib/agent-modes.d.ts +1 -1
- package/dist/lib/agent-modes.js +11 -5
- package/dist/lib/auth-mint.d.ts +4 -0
- package/dist/lib/auth-mint.js +6 -4
- package/dist/lib/browser/native-history.test-fixture.d.ts +12 -0
- package/dist/lib/browser/native-history.test-fixture.js +43 -0
- package/dist/lib/browser/paths.d.ts +5 -0
- package/dist/lib/browser/paths.js +7 -1
- package/dist/lib/browser/sessions-list.d.ts +28 -1
- package/dist/lib/browser/sessions-list.js +137 -25
- package/dist/lib/channels/providers/rush.d.ts +2 -1
- package/dist/lib/channels/providers/rush.js +2 -2
- package/dist/lib/channels/providers/session.d.ts +1 -0
- package/dist/lib/channels/providers/session.js +23 -12
- package/dist/lib/channels/registry.d.ts +9 -2
- package/dist/lib/channels/send.d.ts +5 -10
- package/dist/lib/channels/send.js +88 -50
- package/dist/lib/cloud/rush.d.ts +6 -0
- package/dist/lib/cloud/rush.js +18 -3
- package/dist/lib/computer-client.d.ts +19 -0
- package/dist/lib/computer-client.js +104 -0
- package/dist/lib/config-keys.d.ts +5 -1
- package/dist/lib/config-keys.js +14 -11
- package/dist/lib/daemon/auth-sync-service.js +13 -0
- package/dist/lib/daemon/daemon.js +20 -8
- package/dist/lib/daemon/owner-device-delivery-service.d.ts +10 -0
- package/dist/lib/daemon/owner-device-delivery-service.js +28 -0
- package/dist/lib/daemon-services.d.ts +2 -1
- package/dist/lib/daemon-services.js +17 -5
- package/dist/lib/device-config.d.ts +4 -1
- package/dist/lib/device-config.js +57 -7
- package/dist/lib/devices/doctor-findings.d.ts +2 -3
- package/dist/lib/devices/doctor-findings.js +10 -19
- package/dist/lib/event-provenance.d.ts +1 -0
- package/dist/lib/event-provenance.js +2 -0
- package/dist/lib/exec.d.ts +1 -0
- package/dist/lib/exec.js +20 -15
- package/dist/lib/feed/pr-status.d.ts +5 -1
- package/dist/lib/feed/pr-status.js +44 -3
- package/dist/lib/feed/tool-activity.js +9 -6
- package/dist/lib/feed/tools.d.ts +4 -1
- package/dist/lib/feed/tools.js +8 -11
- package/dist/lib/feed-broadcast.d.ts +5 -3
- package/dist/lib/feed-broadcast.js +47 -36
- package/dist/lib/fleet-shared-state.d.ts +5 -0
- package/dist/lib/fleet-shared-state.js +8 -0
- package/dist/lib/github/project-prs.d.ts +4 -1
- package/dist/lib/github/project-prs.js +18 -5
- package/dist/lib/help.d.ts +1 -0
- package/dist/lib/help.js +8 -0
- package/dist/lib/helper-versions.js +1 -1
- package/dist/lib/hosts/passthrough.js +5 -8
- package/dist/lib/hosts/remote-cmd.d.ts +2 -7
- package/dist/lib/hosts/remote-cmd.js +14 -22
- package/dist/lib/hosts/routing-flag.d.ts +22 -0
- package/dist/lib/hosts/routing-flag.js +127 -14
- package/dist/lib/identity/index.d.ts +22 -0
- package/dist/lib/identity/index.js +3 -0
- package/dist/lib/installations/migrate.d.ts +7 -0
- package/dist/lib/installations/migrate.js +99 -88
- package/dist/lib/installations/versions.js +2 -2
- package/dist/lib/launch-identity.d.ts +6 -1
- package/dist/lib/launch-identity.js +12 -2
- package/dist/lib/menubar/install-menubar.d.ts +1 -0
- package/dist/lib/menubar/install-menubar.js +8 -5
- package/dist/lib/menubar/snapshot.js +2 -3
- package/dist/lib/notify.d.ts +7 -14
- package/dist/lib/notify.js +29 -75
- package/dist/lib/owner-message.d.ts +4 -6
- package/dist/lib/owner-message.js +12 -11
- package/dist/lib/owner-notify-tokens.d.ts +49 -0
- package/dist/lib/owner-notify-tokens.js +214 -0
- package/dist/lib/owner-notify.d.ts +75 -0
- package/dist/lib/owner-notify.js +144 -0
- package/dist/lib/recordings/config.d.ts +11 -0
- package/dist/lib/recordings/config.js +54 -0
- package/dist/lib/recordings/identity.d.ts +12 -0
- package/dist/lib/recordings/identity.js +57 -0
- package/dist/lib/recordings/ledger.d.ts +16 -0
- package/dist/lib/recordings/ledger.js +141 -0
- package/dist/lib/recordings/model.d.ts +29 -0
- package/dist/lib/recordings/model.js +28 -0
- package/dist/lib/recordings/pipeline.d.ts +44 -0
- package/dist/lib/recordings/pipeline.js +272 -0
- package/dist/lib/recordings/process.d.ts +17 -0
- package/dist/lib/recordings/process.js +94 -0
- package/dist/lib/recordings/service.d.ts +15 -0
- package/dist/lib/recordings/service.js +45 -0
- package/dist/lib/recordings/settle.d.ts +21 -0
- package/dist/lib/recordings/settle.js +92 -0
- package/dist/lib/recordings/transcode.d.ts +13 -0
- package/dist/lib/recordings/transcode.js +44 -0
- package/dist/lib/reminders.d.ts +0 -1
- package/dist/lib/reminders.js +1 -1
- package/dist/lib/reserved-stores.d.ts +3 -0
- package/dist/lib/reserved-stores.js +13 -0
- package/dist/lib/routine-notify-owner.d.ts +3 -23
- package/dist/lib/routine-notify-owner.js +26 -107
- package/dist/lib/rush-api.d.ts +1 -0
- package/dist/lib/rush-api.js +1 -0
- package/dist/lib/session/active.d.ts +18 -2
- package/dist/lib/session/active.js +47 -37
- package/dist/lib/session/cloud.js +18 -45
- package/dist/lib/session/db.d.ts +2 -0
- package/dist/lib/session/db.js +13 -4
- package/dist/lib/session/glance-files.d.ts +4 -3
- package/dist/lib/session/glance-files.js +31 -0
- package/dist/lib/session/inject-target.js +12 -2
- package/dist/lib/session/pid-registry.d.ts +2 -0
- package/dist/lib/session/pid-registry.js +6 -2
- package/dist/lib/session/presentation.d.ts +21 -0
- package/dist/lib/session/presentation.js +198 -0
- package/dist/lib/session/projection.js +9 -2
- package/dist/lib/sqlite.d.ts +3 -1
- package/dist/lib/sqlite.js +7 -3
- package/dist/lib/standalone-tools.js +1 -1
- package/dist/lib/startup/command-registry.js +9 -4
- package/dist/lib/state.d.ts +2 -2
- package/dist/lib/state.js +3 -5
- package/dist/lib/terminal/inject.js +1 -1
- package/dist/lib/testdata/owner-notify-api.d.ts +36 -0
- package/dist/lib/testdata/owner-notify-api.js +102 -0
- package/dist/lib/trash.d.ts +14 -0
- package/dist/lib/trash.js +75 -0
- package/dist/lib/types.d.ts +0 -34
- package/package.json +1 -1
- package/dist/commands/feedback.d.ts +0 -2
- package/dist/commands/feedback.js +0 -68
- package/dist/commands/humans.d.ts +0 -2
- package/dist/commands/humans.js +0 -83
- package/dist/commands/modes.d.ts +0 -2
- package/dist/commands/modes.js +0 -134
- package/dist/commands/reminders.d.ts +0 -2
- package/dist/commands/reminders.js +0 -49
- package/dist/lib/channels/owner-forward.d.ts +0 -25
- package/dist/lib/channels/owner-forward.js +0 -78
- package/dist/lib/channels/owner-sink.d.ts +0 -10
- package/dist/lib/channels/owner-sink.js +0 -26
- package/dist/lib/humans.d.ts +0 -12
- package/dist/lib/humans.js +0 -64
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { deleteBundleSync, deleteKeychainTokenSync, pushBundleToHostAsync, secretsKeychainItem } from './secrets-client.js';
|
|
4
|
+
import { readReservedCredential } from './claude-account-token.js';
|
|
5
|
+
import { writeReservedStoreItem } from './auth-mint.js';
|
|
6
|
+
import { OWNER_NOTIFY_TOKEN_KEY, canHoldOwnerNotifyToken, ownerNotifyStoreName } from './reserved-stores.js';
|
|
7
|
+
import { PhoenixApiError, readSession } from './identity/client.js';
|
|
8
|
+
import { listApiTokens, mintDeviceToken, revokeApiToken } from './identity/index.js';
|
|
9
|
+
import { isDialableDevice, loadDevicesSync } from './devices/registry.js';
|
|
10
|
+
import { sshTargetFor } from './devices/connect.js';
|
|
11
|
+
import { isDevicePinned, isHostPinned, managedKnownHostsPath } from './devices/known-hosts.js';
|
|
12
|
+
import { machineId, normalizeHost } from './machine-id.js';
|
|
13
|
+
import { configuredDeviceRole, isHeadedDeviceRole, selfConfiguredDeviceRole } from './device-config.js';
|
|
14
|
+
import { readFleetSharedDeviceStates, updateFleetSharedDeviceStateAsync } from './fleet-shared-state.js';
|
|
15
|
+
import { getCacheDir, getUserAgentsDir } from './state.js';
|
|
16
|
+
import { atomicWriteFileSync } from './fs-atomic.js';
|
|
17
|
+
import { hasUsableDeviceToken } from './owner-notify.js';
|
|
18
|
+
import { USAGE_SYNC_INTERVAL_MS } from './accounting/usage-sync.js';
|
|
19
|
+
const OWNER_NOTIFY_PUSH_DEADLINE_MS = 20_000;
|
|
20
|
+
export const OWNER_NOTIFY_PEER_FRESH_MS = 3 * USAGE_SYNC_INTERVAL_MS;
|
|
21
|
+
export async function publishOwnerNotifyState(opts = {}) {
|
|
22
|
+
const device = opts.device ?? machineId();
|
|
23
|
+
const signedIn = Boolean(readSession()?.access_token);
|
|
24
|
+
const deviceToken = hasUsableDeviceToken(device);
|
|
25
|
+
const write = await updateFleetSharedDeviceStateAsync(device, { ownerNotify: { signedIn, deviceToken } }, opts.userAgentsDir ?? getUserAgentsDir());
|
|
26
|
+
return { signedIn, deviceToken, changed: write.changed };
|
|
27
|
+
}
|
|
28
|
+
export function electOwnerNotifyMinter(signedInHeaded) {
|
|
29
|
+
return [...signedInHeaded].sort((a, b) => normalizeHost(a).localeCompare(normalizeHost(b)))[0] ?? null;
|
|
30
|
+
}
|
|
31
|
+
function memoPath(root) {
|
|
32
|
+
return path.join(root, 'owner-notify-minted.json');
|
|
33
|
+
}
|
|
34
|
+
function readMemo(root) {
|
|
35
|
+
try {
|
|
36
|
+
const parsed = JSON.parse(fs.readFileSync(memoPath(root), 'utf-8'));
|
|
37
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
38
|
+
return Object.fromEntries(Object.entries(parsed)
|
|
39
|
+
.filter((e) => typeof e[1]?.id === 'string'));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
catch { }
|
|
43
|
+
return {};
|
|
44
|
+
}
|
|
45
|
+
function writeMemo(root, memo) {
|
|
46
|
+
fs.mkdirSync(root, { recursive: true });
|
|
47
|
+
atomicWriteFileSync(memoPath(root), `${JSON.stringify(memo, null, 2)}\n`, { encoding: 'utf-8', mode: 0o600 });
|
|
48
|
+
}
|
|
49
|
+
export async function syncOwnerNotifyTokens(deps = {}) {
|
|
50
|
+
const result = { minter: null, minted: [], pushed: [], revoked: [], skipped: [], errors: [] };
|
|
51
|
+
const localName = deps.localName ?? machineId();
|
|
52
|
+
const localNorm = normalizeHost(localName);
|
|
53
|
+
const selfRole = (deps.selfRole ?? selfConfiguredDeviceRole)();
|
|
54
|
+
if (!isHeadedDeviceRole(selfRole) || !readSession()?.access_token)
|
|
55
|
+
return result;
|
|
56
|
+
const devices = (deps.listDevices ?? (() => Object.values(loadDevicesSync())))()
|
|
57
|
+
.filter((d) => normalizeHost(d.name) !== localNorm);
|
|
58
|
+
const roles = new Map(devices.map((d) => {
|
|
59
|
+
try {
|
|
60
|
+
return [d.name, (deps.peerRole ?? configuredDeviceRole)(d.name)];
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return [d.name, undefined];
|
|
64
|
+
}
|
|
65
|
+
}));
|
|
66
|
+
const peerRole = (name) => roles.get(name);
|
|
67
|
+
const read = readFleetSharedDeviceStates(deps.userAgentsDir ?? getUserAgentsDir());
|
|
68
|
+
result.errors.push(...read.errors);
|
|
69
|
+
const stateByDevice = new Map(read.states.map((s) => [normalizeHost(s.device), s]));
|
|
70
|
+
const now = (deps.now ?? Date.now)();
|
|
71
|
+
const signedInHeaded = [localName, ...devices
|
|
72
|
+
.filter((d) => {
|
|
73
|
+
const state = stateByDevice.get(normalizeHost(d.name));
|
|
74
|
+
return isHeadedDeviceRole(peerRole(d.name))
|
|
75
|
+
&& state?.ownerNotify?.signedIn === true
|
|
76
|
+
&& state.receivedAt !== undefined
|
|
77
|
+
&& now - state.receivedAt <= OWNER_NOTIFY_PEER_FRESH_MS;
|
|
78
|
+
})
|
|
79
|
+
.map((d) => d.name)];
|
|
80
|
+
result.minter = electOwnerNotifyMinter(signedInHeaded);
|
|
81
|
+
const workers = devices.filter((d) => peerRole(d.name) === 'worker');
|
|
82
|
+
const cacheDir = deps.cacheDir ?? getCacheDir();
|
|
83
|
+
const memo = readMemo(cacheDir);
|
|
84
|
+
if (devices.length === 0 || [...roles.values()].some((r) => r === undefined)) {
|
|
85
|
+
result.skipped.push({ device: localName, reason: 'stale-token revocation needs a device registry with every role readable' });
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
const workerNames = new Set(workers.map((w) => normalizeHost(w.name)));
|
|
89
|
+
for (const [name, minted] of Object.entries(memo).filter(([n]) => !workerNames.has(n))) {
|
|
90
|
+
try {
|
|
91
|
+
await revokeOwnerNotifyToken(name, minted.id, memo);
|
|
92
|
+
result.revoked.push(name);
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
result.errors.push({ device: name, message: `revoke token of a device that is no longer a worker: ${err.message}` });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (result.revoked.length > 0)
|
|
99
|
+
writeMemo(cacheDir, memo);
|
|
100
|
+
}
|
|
101
|
+
if (normalizeHost(result.minter ?? '') !== localNorm) {
|
|
102
|
+
for (const d of workers)
|
|
103
|
+
result.skipped.push({ device: d.name, reason: `${result.minter} mints owner-notify tokens` });
|
|
104
|
+
return result;
|
|
105
|
+
}
|
|
106
|
+
const pinned = deps.isPinned ?? ((name) => isHostPinned(name, managedKnownHostsPath()));
|
|
107
|
+
const push = deps.push ?? ((bundle, host) => pushBundleToHostAsync(bundle, host, {
|
|
108
|
+
remoteBackend: 'file', operation: 'owner-notify-sync', agentOnly: true, timeoutMs: OWNER_NOTIFY_PUSH_DEADLINE_MS,
|
|
109
|
+
}));
|
|
110
|
+
const sshTarget = deps.sshTarget ?? sshTargetFor;
|
|
111
|
+
let tokens;
|
|
112
|
+
try {
|
|
113
|
+
tokens = (await listApiTokens()).filter((t) => t.kind === 'device' && t.device !== null && t.scopes.includes('notify'));
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
result.errors.push({ device: localName, message: `list device tokens: ${err.message}` });
|
|
117
|
+
return result;
|
|
118
|
+
}
|
|
119
|
+
for (const worker of workers) {
|
|
120
|
+
const name = normalizeHost(worker.name);
|
|
121
|
+
const store = ownerNotifyStoreName(name);
|
|
122
|
+
const peer = stateByDevice.get(name);
|
|
123
|
+
const peerState = peer?.ownerNotify;
|
|
124
|
+
if (!peerState) {
|
|
125
|
+
result.skipped.push({ device: worker.name, reason: 'no owner-notify state from this peer yet' });
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (!isDialableDevice(worker)) {
|
|
129
|
+
result.skipped.push({ device: worker.name, reason: 'unreachable' });
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (!isDevicePinned(worker, pinned)) {
|
|
133
|
+
result.skipped.push({ device: worker.name, reason: `host key not pinned; run \`agents ssh ${worker.name}\` once` });
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (peerState.deviceToken) {
|
|
137
|
+
result.skipped.push({ device: worker.name, reason: 'token present' });
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
let onServer = tokens.find((t) => normalizeHost(t.device) === name);
|
|
141
|
+
const held = memo[name];
|
|
142
|
+
try {
|
|
143
|
+
const holdsLive = onServer !== undefined && held?.id === onServer.id
|
|
144
|
+
&& readReservedCredential(store, OWNER_NOTIFY_TOKEN_KEY) !== null;
|
|
145
|
+
if (holdsLive && held.pushedAt !== undefined && (peer?.receivedAt ?? 0) <= held.pushedAt) {
|
|
146
|
+
result.skipped.push({ device: worker.name, reason: 'waiting for the worker to report the pushed token' });
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (onServer && !(holdsLive && held.pushedAt === undefined)) {
|
|
150
|
+
await revokeApiToken(onServer.id);
|
|
151
|
+
onServer = undefined;
|
|
152
|
+
}
|
|
153
|
+
if (!onServer) {
|
|
154
|
+
const minted = await mintDeviceToken(name, ['notify']);
|
|
155
|
+
try {
|
|
156
|
+
writeReservedStoreItem(store, OWNER_NOTIFY_TOKEN_KEY, minted.token, `Owner-notify device token for ${name} (scope notify); pushed only to that worker by the daemon.`);
|
|
157
|
+
}
|
|
158
|
+
catch (err) {
|
|
159
|
+
await revokeApiToken(minted.id);
|
|
160
|
+
throw err;
|
|
161
|
+
}
|
|
162
|
+
memo[name] = { id: minted.id };
|
|
163
|
+
writeMemo(cacheDir, memo);
|
|
164
|
+
result.minted.push(worker.name);
|
|
165
|
+
}
|
|
166
|
+
const out = await push(store, sshTarget(worker));
|
|
167
|
+
if (out.ok) {
|
|
168
|
+
memo[name] = { ...memo[name], pushedAt: now };
|
|
169
|
+
writeMemo(cacheDir, memo);
|
|
170
|
+
result.pushed.push(worker.name);
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
result.errors.push({ device: worker.name, message: out.message });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
result.errors.push({ device: worker.name, message: err.message });
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return result;
|
|
181
|
+
}
|
|
182
|
+
async function revokeOwnerNotifyToken(name, id, memo) {
|
|
183
|
+
try {
|
|
184
|
+
await revokeApiToken(id);
|
|
185
|
+
}
|
|
186
|
+
catch (err) {
|
|
187
|
+
if (!(err instanceof PhoenixApiError && err.status === 404))
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
190
|
+
if (memo[name]?.id === id) {
|
|
191
|
+
delete memo[name];
|
|
192
|
+
if (canHoldOwnerNotifyToken(name)) {
|
|
193
|
+
const store = ownerNotifyStoreName(name);
|
|
194
|
+
deleteKeychainTokenSync(secretsKeychainItem(store, OWNER_NOTIFY_TOKEN_KEY));
|
|
195
|
+
deleteBundleSync(store);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
export async function revokeMintedOwnerNotifyTokens(cacheDir = getCacheDir()) {
|
|
200
|
+
const out = { revoked: [], errors: [] };
|
|
201
|
+
const memo = readMemo(cacheDir);
|
|
202
|
+
for (const [name, { id }] of Object.entries(memo)) {
|
|
203
|
+
try {
|
|
204
|
+
await revokeOwnerNotifyToken(name, id, memo);
|
|
205
|
+
out.revoked.push(name);
|
|
206
|
+
}
|
|
207
|
+
catch (err) {
|
|
208
|
+
out.errors.push({ device: name, message: err.message });
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (Object.keys(memo).length > 0 || out.revoked.length > 0)
|
|
212
|
+
writeMemo(cacheDir, memo);
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
export declare const OWNER_EVENTS: readonly ["needs_you", "completed", "failed", "spend_threshold", "message"];
|
|
2
|
+
export type OwnerEvent = (typeof OWNER_EVENTS)[number];
|
|
3
|
+
export type OwnerChannel = 'email' | 'slack' | 'imessage';
|
|
4
|
+
export interface OwnerNotification {
|
|
5
|
+
event: OwnerEvent;
|
|
6
|
+
title: string;
|
|
7
|
+
body: string;
|
|
8
|
+
url?: string;
|
|
9
|
+
sessionId?: string;
|
|
10
|
+
ticket?: string;
|
|
11
|
+
dedupKey: string;
|
|
12
|
+
source?: {
|
|
13
|
+
device?: string;
|
|
14
|
+
agent?: string;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
export interface OwnerNotifyResult {
|
|
18
|
+
dispatchId: string | null;
|
|
19
|
+
delivered: OwnerChannel[];
|
|
20
|
+
queued: OwnerChannel[];
|
|
21
|
+
skipped: Array<{
|
|
22
|
+
channel: OwnerChannel;
|
|
23
|
+
reason: string;
|
|
24
|
+
}>;
|
|
25
|
+
suppressed: null | 'duplicate' | 'quiet_hours';
|
|
26
|
+
}
|
|
27
|
+
export interface DeviceDelivery {
|
|
28
|
+
id: string;
|
|
29
|
+
channel: 'imessage';
|
|
30
|
+
address: string;
|
|
31
|
+
body: string;
|
|
32
|
+
createdAt: string;
|
|
33
|
+
}
|
|
34
|
+
export interface OwnerPreferencesPatch {
|
|
35
|
+
preferences?: Array<{
|
|
36
|
+
event: OwnerEvent;
|
|
37
|
+
channel: OwnerChannel;
|
|
38
|
+
enabled: boolean;
|
|
39
|
+
}>;
|
|
40
|
+
settings?: {
|
|
41
|
+
timezone?: string;
|
|
42
|
+
quietStart?: string | null;
|
|
43
|
+
quietEnd?: string | null;
|
|
44
|
+
};
|
|
45
|
+
destinations?: {
|
|
46
|
+
imessage?: {
|
|
47
|
+
address: string;
|
|
48
|
+
} | null;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export declare class OwnerNotSignedInError extends Error {
|
|
52
|
+
readonly code = "OWNER_NOT_SIGNED_IN";
|
|
53
|
+
constructor();
|
|
54
|
+
}
|
|
55
|
+
export declare class OwnerNotifyApiError extends Error {
|
|
56
|
+
readonly status: number;
|
|
57
|
+
readonly code?: string | undefined;
|
|
58
|
+
constructor(message: string, status: number, code?: string | undefined);
|
|
59
|
+
}
|
|
60
|
+
export interface OwnerCredential {
|
|
61
|
+
kind: 'session' | 'device';
|
|
62
|
+
token: string;
|
|
63
|
+
}
|
|
64
|
+
export declare function selfDeviceName(): string;
|
|
65
|
+
export declare function resolveOwnerCredential(): OwnerCredential | null;
|
|
66
|
+
export declare const OWNER_DEDUP_PREFIX = "owner:";
|
|
67
|
+
export declare function hasUsableDeviceToken(device: string, cacheDir?: string): boolean;
|
|
68
|
+
export declare function postOwnerNotification(notification: OwnerNotification): Promise<OwnerNotifyResult>;
|
|
69
|
+
export declare function claimDeviceDeliveries(device: string, limit?: number): Promise<DeviceDelivery[]>;
|
|
70
|
+
export declare function reportDeviceDelivery(id: string, result: {
|
|
71
|
+
ok: boolean;
|
|
72
|
+
error?: string;
|
|
73
|
+
}): Promise<void>;
|
|
74
|
+
export declare function putOwnerPreferences(patch: OwnerPreferencesPatch): Promise<void>;
|
|
75
|
+
export declare function describeOwnerResult(result: OwnerNotifyResult): string;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
import * as path from 'node:path';
|
|
4
|
+
import { readSession } from './identity/client.js';
|
|
5
|
+
import { readReservedCredential } from './claude-account-token.js';
|
|
6
|
+
import { machineId, normalizeHost } from './machine-id.js';
|
|
7
|
+
import { OWNER_NOTIFY_TOKEN_KEY, canHoldOwnerNotifyToken, ownerNotifyStoreName } from './reserved-stores.js';
|
|
8
|
+
import { RUSH_API_BASE } from './rush-api.js';
|
|
9
|
+
import { getCacheDir } from './state.js';
|
|
10
|
+
export const OWNER_EVENTS = ['needs_you', 'completed', 'failed', 'spend_threshold', 'message'];
|
|
11
|
+
export class OwnerNotSignedInError extends Error {
|
|
12
|
+
code = 'OWNER_NOT_SIGNED_IN';
|
|
13
|
+
constructor() {
|
|
14
|
+
super("This box cannot reach the owner: no Phoenix session and no device token. Run 'agents auth login' (a worker receives its device token from a signed-in personal device).");
|
|
15
|
+
this.name = 'OwnerNotSignedInError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export class OwnerNotifyApiError extends Error {
|
|
19
|
+
status;
|
|
20
|
+
code;
|
|
21
|
+
constructor(message, status, code) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.status = status;
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.name = 'OwnerNotifyApiError';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function selfDeviceName() {
|
|
29
|
+
return normalizeHost(machineId());
|
|
30
|
+
}
|
|
31
|
+
export function resolveOwnerCredential() {
|
|
32
|
+
const session = readSession()?.access_token?.trim();
|
|
33
|
+
if (session)
|
|
34
|
+
return { kind: 'session', token: session };
|
|
35
|
+
const self = selfDeviceName();
|
|
36
|
+
if (!canHoldOwnerNotifyToken(self))
|
|
37
|
+
return null;
|
|
38
|
+
const device = readReservedCredential(ownerNotifyStoreName(self), OWNER_NOTIFY_TOKEN_KEY);
|
|
39
|
+
return device ? { kind: 'device', token: device } : null;
|
|
40
|
+
}
|
|
41
|
+
export const OWNER_DEDUP_PREFIX = 'owner:';
|
|
42
|
+
function rejectedTokenPath(cacheDir) {
|
|
43
|
+
return path.join(cacheDir, 'owner-notify-rejected.json');
|
|
44
|
+
}
|
|
45
|
+
function tokenFingerprint(token) {
|
|
46
|
+
return createHash('sha256').update(token).digest('hex');
|
|
47
|
+
}
|
|
48
|
+
function markDeviceTokenRejected(token, cacheDir = getCacheDir()) {
|
|
49
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
50
|
+
fs.writeFileSync(rejectedTokenPath(cacheDir), `${JSON.stringify({ sha256: tokenFingerprint(token), at: new Date().toISOString() })}\n`, { mode: 0o600 });
|
|
51
|
+
}
|
|
52
|
+
function isDeviceTokenRejected(token, cacheDir) {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(fs.readFileSync(rejectedTokenPath(cacheDir), 'utf-8'));
|
|
55
|
+
return parsed.sha256 === tokenFingerprint(token);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
export function hasUsableDeviceToken(device, cacheDir = getCacheDir()) {
|
|
62
|
+
const self = normalizeHost(device);
|
|
63
|
+
if (!canHoldOwnerNotifyToken(self))
|
|
64
|
+
return false;
|
|
65
|
+
const token = readReservedCredential(ownerNotifyStoreName(self), OWNER_NOTIFY_TOKEN_KEY);
|
|
66
|
+
return token !== null && !isDeviceTokenRejected(token, cacheDir);
|
|
67
|
+
}
|
|
68
|
+
function requireOwnerCredential() {
|
|
69
|
+
const credential = resolveOwnerCredential();
|
|
70
|
+
if (!credential)
|
|
71
|
+
throw new OwnerNotSignedInError();
|
|
72
|
+
return credential;
|
|
73
|
+
}
|
|
74
|
+
async function rushRequest(method, route, body) {
|
|
75
|
+
const credential = requireOwnerCredential();
|
|
76
|
+
let response;
|
|
77
|
+
try {
|
|
78
|
+
response = await fetch(`${RUSH_API_BASE}${route}`, {
|
|
79
|
+
method,
|
|
80
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${credential.token}` },
|
|
81
|
+
body: JSON.stringify(body),
|
|
82
|
+
signal: AbortSignal.timeout(15_000),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
throw new OwnerNotifyApiError(`Could not reach ${RUSH_API_BASE} (${err.message}).`, 0);
|
|
87
|
+
}
|
|
88
|
+
if (response.ok && credential.kind === 'device')
|
|
89
|
+
fs.rmSync(rejectedTokenPath(getCacheDir()), { force: true });
|
|
90
|
+
if (response.status === 204)
|
|
91
|
+
return undefined;
|
|
92
|
+
const text = await response.text();
|
|
93
|
+
let payload = null;
|
|
94
|
+
try {
|
|
95
|
+
payload = text ? JSON.parse(text) : null;
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
payload = null;
|
|
99
|
+
}
|
|
100
|
+
if (!response.ok) {
|
|
101
|
+
const fields = payload && typeof payload === 'object' ? payload : {};
|
|
102
|
+
const detail = typeof fields.error === 'string' ? fields.error : `${response.status} ${response.statusText}`;
|
|
103
|
+
const code = typeof fields.code === 'string' ? fields.code : undefined;
|
|
104
|
+
if (response.status === 401 && credential.kind === 'device')
|
|
105
|
+
markDeviceTokenRejected(credential.token);
|
|
106
|
+
const hint = response.status === 401
|
|
107
|
+
? (credential.kind === 'session'
|
|
108
|
+
? " Run 'agents auth login'."
|
|
109
|
+
: ' The device token was rejected; a signed-in personal device re-mints it on its next auth-sync tick.')
|
|
110
|
+
: '';
|
|
111
|
+
throw new OwnerNotifyApiError(`rush/api ${route}: ${detail}.${hint}`, response.status, code);
|
|
112
|
+
}
|
|
113
|
+
return payload;
|
|
114
|
+
}
|
|
115
|
+
export function postOwnerNotification(notification) {
|
|
116
|
+
return rushRequest('POST', '/me/notifications', {
|
|
117
|
+
...notification,
|
|
118
|
+
dedupKey: `${OWNER_DEDUP_PREFIX}${notification.dedupKey}`,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
export async function claimDeviceDeliveries(device, limit = 10) {
|
|
122
|
+
const out = await rushRequest('POST', '/me/device-deliveries/claim', { device, limit });
|
|
123
|
+
return out.deliveries;
|
|
124
|
+
}
|
|
125
|
+
export async function reportDeviceDelivery(id, result) {
|
|
126
|
+
await rushRequest('POST', `/me/device-deliveries/${encodeURIComponent(id)}/result`, result);
|
|
127
|
+
}
|
|
128
|
+
export async function putOwnerPreferences(patch) {
|
|
129
|
+
await rushRequest('PUT', '/me/preferences', patch);
|
|
130
|
+
}
|
|
131
|
+
export function describeOwnerResult(result) {
|
|
132
|
+
if (result.suppressed === 'duplicate')
|
|
133
|
+
return 'suppressed: already sent';
|
|
134
|
+
if (result.suppressed === 'quiet_hours')
|
|
135
|
+
return 'suppressed: quiet hours';
|
|
136
|
+
const parts = [];
|
|
137
|
+
if (result.delivered.length)
|
|
138
|
+
parts.push(`delivered ${result.delivered.join(', ')}`);
|
|
139
|
+
if (result.queued.length)
|
|
140
|
+
parts.push(`queued ${result.queued.join(', ')}`);
|
|
141
|
+
for (const s of result.skipped)
|
|
142
|
+
parts.push(`skipped ${s.channel} (${s.reason})`);
|
|
143
|
+
return parts.join('; ') || 'no channel enabled for this event';
|
|
144
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface RecordingsConfig {
|
|
2
|
+
directory?: string;
|
|
3
|
+
watchedSince?: string;
|
|
4
|
+
}
|
|
5
|
+
export declare function recordingsStateDir(): string;
|
|
6
|
+
export declare function recordingsConfigPath(): string;
|
|
7
|
+
export declare function recordingsLedgerPath(): string;
|
|
8
|
+
export declare function readRecordingsConfig(): Promise<RecordingsConfig>;
|
|
9
|
+
export declare function writeRecordingDirectory(directory: string): Promise<void>;
|
|
10
|
+
export declare function defaultCleanShotDirectory(): Promise<string>;
|
|
11
|
+
export declare function resolveRecordingDirectory(override?: string): Promise<string>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { getUserAgentsDir } from '../state.js';
|
|
4
|
+
import { atomicWriteFile } from '../fs-atomic.js';
|
|
5
|
+
import { runProcess } from './process.js';
|
|
6
|
+
export function recordingsStateDir() {
|
|
7
|
+
return path.join(getUserAgentsDir(), 'recordings');
|
|
8
|
+
}
|
|
9
|
+
export function recordingsConfigPath() {
|
|
10
|
+
return path.join(recordingsStateDir(), 'config.json');
|
|
11
|
+
}
|
|
12
|
+
export function recordingsLedgerPath() {
|
|
13
|
+
return path.join(recordingsStateDir(), 'ledger.json');
|
|
14
|
+
}
|
|
15
|
+
export async function readRecordingsConfig() {
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(await fs.readFile(recordingsConfigPath(), 'utf8'));
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return {};
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export async function writeRecordingDirectory(directory) {
|
|
24
|
+
const resolved = path.resolve(directory);
|
|
25
|
+
const stat = await fs.stat(resolved).catch(() => null);
|
|
26
|
+
if (!stat?.isDirectory())
|
|
27
|
+
throw new Error(`Recording directory does not exist: ${resolved}`);
|
|
28
|
+
await fs.mkdir(recordingsStateDir(), { recursive: true, mode: 0o700 });
|
|
29
|
+
const config = { directory: resolved, watchedSince: new Date().toISOString() };
|
|
30
|
+
await atomicWriteFile(recordingsConfigPath(), `${JSON.stringify(config, null, 2)}\n`, {
|
|
31
|
+
encoding: 'utf8',
|
|
32
|
+
mode: 0o600,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
export async function defaultCleanShotDirectory() {
|
|
36
|
+
if (process.platform !== 'darwin') {
|
|
37
|
+
throw new Error('CleanShot export directory auto-detection is available only on macOS. Pass --dir <path>.');
|
|
38
|
+
}
|
|
39
|
+
const result = await runProcess('defaults', ['read', 'pl.maketheweb.cleanshotx', 'exportPath'], { timeoutMs: 5_000 });
|
|
40
|
+
const directory = result.stdout.trim();
|
|
41
|
+
if (result.exitCode !== 0 || !directory) {
|
|
42
|
+
throw new Error('Could not read CleanShot exportPath. Set it in CleanShot or pass --dir <path>.');
|
|
43
|
+
}
|
|
44
|
+
return directory;
|
|
45
|
+
}
|
|
46
|
+
export async function resolveRecordingDirectory(override) {
|
|
47
|
+
const configured = (await readRecordingsConfig()).directory;
|
|
48
|
+
const directory = override || configured || await defaultCleanShotDirectory();
|
|
49
|
+
const resolved = path.resolve(directory);
|
|
50
|
+
const stat = await fs.stat(resolved).catch(() => null);
|
|
51
|
+
if (!stat?.isDirectory())
|
|
52
|
+
throw new Error(`Recording directory does not exist: ${resolved}`);
|
|
53
|
+
return resolved;
|
|
54
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type RecordingIdentityErrorCode = 'AUTH_REQUIRED' | 'PUBLIC_INBOX' | 'AUTH_UNAVAILABLE';
|
|
2
|
+
export declare class RecordingIdentityError extends Error {
|
|
3
|
+
readonly code: RecordingIdentityErrorCode;
|
|
4
|
+
constructor(code: RecordingIdentityErrorCode, message: string);
|
|
5
|
+
}
|
|
6
|
+
export declare function isPublicInboxEmail(email: string): boolean;
|
|
7
|
+
export declare function verifyOrganizationIdentity(signal?: AbortSignal, options?: {
|
|
8
|
+
artifactsBin?: string;
|
|
9
|
+
env?: NodeJS.ProcessEnv;
|
|
10
|
+
}): Promise<{
|
|
11
|
+
email: string;
|
|
12
|
+
}>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { invocation, resolveArtifactsBin } from '../artifacts-client.js';
|
|
2
|
+
import { processFailure, runProcess } from './process.js';
|
|
3
|
+
const PUBLIC_INBOX_DOMAINS = new Set([
|
|
4
|
+
'aol.com', 'fastmail.com', 'gmail.com', 'googlemail.com', 'hey.com', 'hotmail.com',
|
|
5
|
+
'icloud.com', 'live.com', 'mac.com', 'mail.com', 'me.com', 'msn.com', 'outlook.com',
|
|
6
|
+
'pm.me', 'proton.me', 'protonmail.com', 'rocketmail.com', 'yahoo.com', 'ymail.com',
|
|
7
|
+
'zoho.com', 'gmx.com', 'gmx.net',
|
|
8
|
+
]);
|
|
9
|
+
export class RecordingIdentityError extends Error {
|
|
10
|
+
code;
|
|
11
|
+
constructor(code, message) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.name = 'RecordingIdentityError';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function isPublicInboxEmail(email) {
|
|
18
|
+
const domain = email.trim().toLowerCase().split('@').at(-1) ?? '';
|
|
19
|
+
return PUBLIC_INBOX_DOMAINS.has(domain);
|
|
20
|
+
}
|
|
21
|
+
function readIdentity(value) {
|
|
22
|
+
if (!value || typeof value !== 'object')
|
|
23
|
+
return { signedIn: false };
|
|
24
|
+
const record = value;
|
|
25
|
+
const me = record.me && typeof record.me === 'object' ? record.me : record;
|
|
26
|
+
return {
|
|
27
|
+
signedIn: record.signedIn === true || typeof me.email === 'string',
|
|
28
|
+
email: typeof me.email === 'string' ? me.email : undefined,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export async function verifyOrganizationIdentity(signal, options = {}) {
|
|
32
|
+
const bin = options.artifactsBin ?? resolveArtifactsBin();
|
|
33
|
+
const launch = invocation(bin);
|
|
34
|
+
const args = [...launch.prefix, 'auth', 'whoami', '--json'];
|
|
35
|
+
const result = await runProcess(launch.command, args, { signal, env: options.env, timeoutMs: 15_000 });
|
|
36
|
+
if (result.exitCode !== 0) {
|
|
37
|
+
const detail = `${result.stderr}\n${result.stdout}`;
|
|
38
|
+
if (result.exitCode === 401 || /\b401\b|sign(?:ed)?[ -]?out|not signed in|unauthori[sz]ed/i.test(detail)) {
|
|
39
|
+
throw new RecordingIdentityError('AUTH_REQUIRED', 'Artifacts authentication expired. Run `artifacts auth login`; recordings remain queued.');
|
|
40
|
+
}
|
|
41
|
+
throw new RecordingIdentityError('AUTH_UNAVAILABLE', processFailure('artifacts', args, result).message);
|
|
42
|
+
}
|
|
43
|
+
let identity;
|
|
44
|
+
try {
|
|
45
|
+
identity = readIdentity(JSON.parse(result.stdout));
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new RecordingIdentityError('AUTH_UNAVAILABLE', 'artifacts auth whoami returned invalid JSON.');
|
|
49
|
+
}
|
|
50
|
+
if (!identity.signedIn || !identity.email) {
|
|
51
|
+
throw new RecordingIdentityError('AUTH_REQUIRED', 'Artifacts is not signed in. Run `artifacts auth login`; recordings remain queued.');
|
|
52
|
+
}
|
|
53
|
+
if (isPublicInboxEmail(identity.email)) {
|
|
54
|
+
throw new RecordingIdentityError('PUBLIC_INBOX', `Refusing org recording uploads for public-inbox identity ${identity.email}. Sign in with an organization email.`);
|
|
55
|
+
}
|
|
56
|
+
return { email: identity.email };
|
|
57
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { RecordingCandidate, RecordingLedgerRow } from './model.js';
|
|
2
|
+
export declare class RecordingLedger {
|
|
3
|
+
readonly filePath: string;
|
|
4
|
+
constructor(filePath?: string);
|
|
5
|
+
private ensure;
|
|
6
|
+
private readUnlocked;
|
|
7
|
+
private transaction;
|
|
8
|
+
list(): Promise<RecordingLedgerRow[]>;
|
|
9
|
+
queue(candidate: RecordingCandidate): Promise<RecordingLedgerRow>;
|
|
10
|
+
update(stem: string, sourcePath: string, patch: Partial<RecordingLedgerRow>): Promise<RecordingLedgerRow | null>;
|
|
11
|
+
claim(stem: string, sourcePath: string, now?: number): Promise<boolean>;
|
|
12
|
+
recoverInterrupted(now?: number): Promise<void>;
|
|
13
|
+
pending(now?: number): Promise<RecordingLedgerRow[]>;
|
|
14
|
+
shouldPostAttention(reason: string): Promise<boolean>;
|
|
15
|
+
clearAttention(): Promise<void>;
|
|
16
|
+
}
|