@phnx-labs/agents-cli 1.23.20 → 1.23.22
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 +126 -0
- package/README.md +17 -0
- package/dist/bootstrap.js +5 -4
- package/dist/cli/command-registry.js +2 -0
- package/dist/commands/config.js +16 -0
- package/dist/commands/daemon.js +3 -3
- package/dist/commands/doctor.js +10 -19
- package/dist/commands/events.js +1 -14
- package/dist/commands/feed-watch.js +5 -2
- package/dist/commands/go.js +2 -2
- package/dist/commands/lead.d.ts +3 -0
- package/dist/commands/lead.js +280 -0
- package/dist/commands/projects.js +3 -2
- package/dist/commands/ps-roster.d.ts +2 -12
- package/dist/commands/ps-roster.js +5 -87
- package/dist/commands/ps.js +3 -1
- package/dist/commands/repo.js +12 -12
- package/dist/commands/resource-view.js +5 -5
- package/dist/commands/sessions-browser.js +2 -2
- package/dist/commands/sessions-watch.js +5 -2
- package/dist/commands/setup-secrets.d.ts +3 -4
- package/dist/commands/setup-secrets.js +15 -46
- package/dist/commands/setup-session-backup.js +1 -1
- package/dist/commands/ssh.d.ts +0 -4
- package/dist/commands/ssh.js +14 -81
- package/dist/commands/teams-picker.js +1 -12
- package/dist/commands/teams.js +1 -13
- package/dist/commands/view.d.ts +1 -40
- package/dist/commands/view.js +9 -330
- package/dist/commands/watchdog.js +4 -4
- package/dist/index.js +4 -0
- package/dist/lib/accounting/usage.d.ts +0 -1
- package/dist/lib/accounting/usage.js +1 -112
- package/dist/lib/accounts/add.js +1 -1
- package/dist/lib/accounts/migrate.js +1 -1
- package/dist/lib/auto-pull-worker.js +2 -16
- package/dist/lib/auto-pull.d.ts +1 -0
- package/dist/lib/auto-pull.js +27 -0
- package/dist/lib/browser-client.js +2 -11
- package/dist/lib/cloud/codex.js +3 -0
- package/dist/lib/commands.d.ts +0 -6
- package/dist/lib/commands.js +3 -116
- package/dist/lib/comms-render.d.ts +1 -7
- package/dist/lib/comms-render.js +0 -19
- package/dist/lib/computer-client.js +2 -11
- package/dist/lib/config-keys.d.ts +7 -3
- package/dist/lib/config-keys.js +15 -2
- package/dist/lib/crabbox/runtimes.d.ts +0 -14
- package/dist/lib/crabbox/runtimes.js +0 -80
- package/dist/lib/daemon/attention-notify-service.d.ts +51 -28
- package/dist/lib/daemon/attention-notify-service.js +219 -53
- package/dist/lib/daemon/daemon.js +1 -2
- package/dist/lib/daemon/feed-stream-service.js +2 -4
- package/dist/lib/device-config.d.ts +0 -5
- package/dist/lib/device-config.js +20 -27
- package/dist/lib/devices/doctor-findings.d.ts +2 -1
- package/dist/lib/devices/doctor-findings.js +12 -1
- package/dist/lib/devices/fleet.d.ts +6 -0
- package/dist/lib/devices/fleet.js +15 -0
- package/dist/lib/devices/harness-inventory.d.ts +9 -0
- package/dist/lib/devices/harness-inventory.js +66 -0
- package/dist/lib/exec.js +1 -3
- package/dist/lib/feed/attention.d.ts +16 -1
- package/dist/lib/feed/attention.js +63 -1
- package/dist/lib/feed/feed.d.ts +1 -1
- package/dist/lib/feed/feed.js +12 -2
- package/dist/lib/feed/hub.d.ts +9 -0
- package/dist/lib/feed/hub.js +27 -1
- package/dist/lib/feed/notify-schedule.d.ts +16 -0
- package/dist/lib/feed/notify-schedule.js +62 -0
- package/dist/lib/feed/ticket-priority.d.ts +4 -0
- package/dist/lib/feed/ticket-priority.js +30 -0
- package/dist/lib/feed/watch.d.ts +1 -0
- package/dist/lib/feed/watch.js +27 -3
- package/dist/lib/feed-ranking.d.ts +1 -0
- package/dist/lib/feed-ranking.js +3 -1
- package/dist/lib/format.d.ts +0 -2
- package/dist/lib/format.js +0 -8
- package/dist/lib/github/open-prs.d.ts +0 -2
- package/dist/lib/github/open-prs.js +17 -35
- package/dist/lib/github/project-prs.d.ts +5 -0
- package/dist/lib/github/project-prs.js +73 -32
- package/dist/lib/helper-versions.js +1 -1
- package/dist/lib/hooks/cache.d.ts +1 -0
- package/dist/lib/hooks/cache.js +12 -1
- package/dist/lib/installations/duplicate-prune.d.ts +37 -0
- package/dist/lib/installations/duplicate-prune.js +85 -0
- package/dist/lib/installations/inventory-json.d.ts +20 -0
- package/dist/lib/installations/inventory-json.js +252 -0
- package/dist/lib/installations/shims.d.ts +0 -18
- package/dist/lib/installations/shims.js +1 -257
- package/dist/lib/lead/brief.d.ts +49 -0
- package/dist/lib/lead/brief.js +173 -0
- package/dist/lib/lead/client.d.ts +21 -0
- package/dist/lib/lead/client.js +167 -0
- package/dist/lib/lead/confirm.d.ts +22 -0
- package/dist/lib/lead/confirm.js +73 -0
- package/dist/lib/lead/events.d.ts +106 -0
- package/dist/lib/lead/events.js +188 -0
- package/dist/lib/lead/harness.d.ts +29 -0
- package/dist/lib/lead/harness.js +107 -0
- package/dist/lib/lead/host.d.ts +132 -0
- package/dist/lib/lead/host.js +675 -0
- package/dist/lib/lead/paths.d.ts +22 -0
- package/dist/lib/lead/paths.js +69 -0
- package/dist/lib/lead/refs.d.ts +17 -0
- package/dist/lib/lead/refs.js +75 -0
- package/dist/lib/lead/roster.d.ts +26 -0
- package/dist/lib/lead/roster.js +121 -0
- package/dist/lib/lead/shapes.d.ts +23 -0
- package/dist/lib/lead/shapes.js +95 -0
- package/dist/lib/lead/store.d.ts +46 -0
- package/dist/lib/lead/store.js +77 -0
- package/dist/lib/lead/tools.d.ts +18 -0
- package/dist/lib/lead/tools.js +106 -0
- package/dist/lib/lead/visibility.d.ts +16 -0
- package/dist/lib/lead/visibility.js +77 -0
- package/dist/lib/mailbox.d.ts +0 -18
- package/dist/lib/mailbox.js +0 -170
- package/dist/lib/menubar/notify-desktop.d.ts +5 -0
- package/dist/lib/menubar/notify-desktop.js +24 -0
- package/dist/lib/models.js +1 -19
- package/dist/lib/permissions.d.ts +0 -6
- package/dist/lib/permissions.js +0 -140
- package/dist/lib/platform/process.d.ts +1 -0
- package/dist/lib/platform/process.js +5 -0
- package/dist/lib/probe.js +13 -1
- package/dist/lib/project-status.js +4 -3
- package/dist/lib/projects.d.ts +9 -0
- package/dist/lib/projects.js +61 -3
- package/dist/lib/scheduling/routines.d.ts +1 -13
- package/dist/lib/scheduling/routines.js +1 -37
- package/dist/lib/secrets-cli.d.ts +3 -3
- package/dist/lib/secrets-cli.js +1 -1
- package/dist/lib/secrets-client.d.ts +4 -37
- package/dist/lib/secrets-client.js +19 -265
- package/dist/lib/session/active.d.ts +18 -8
- package/dist/lib/session/active.js +94 -18
- package/dist/lib/session/db.d.ts +0 -16
- package/dist/lib/session/db.js +1 -134
- package/dist/lib/session/detached.d.ts +0 -1
- package/dist/lib/session/detached.js +0 -18
- package/dist/lib/session/pending-work.d.ts +21 -0
- package/dist/lib/session/pending-work.js +284 -0
- package/dist/lib/session/remote/remote-list.d.ts +0 -3
- package/dist/lib/session/remote/remote-list.js +1 -23
- package/dist/lib/session/remote/watch.d.ts +5 -0
- package/dist/lib/session/remote/watch.js +19 -2
- package/dist/lib/session/session-cache.d.ts +1 -1
- package/dist/lib/session/session-cache.js +12 -5
- package/dist/lib/session/sync/provision.js +1 -2
- package/dist/lib/smart-launch.js +7 -2
- package/dist/lib/snapshot.js +3 -4
- package/dist/lib/ssh-exec.d.ts +0 -40
- package/dist/lib/ssh-exec.js +0 -108
- package/dist/lib/ssh-tunnel.d.ts +0 -6
- package/dist/lib/ssh-tunnel.js +0 -42
- package/dist/lib/standalone-tools.js +12 -1
- package/dist/lib/startup/command-registry.js +1 -1
- package/dist/lib/startup/spellcheck.d.ts +0 -1
- package/dist/lib/startup/spellcheck.js +1 -20
- package/dist/lib/state.d.ts +0 -6
- package/dist/lib/state.js +1 -14
- package/dist/lib/teams/delivery.d.ts +1 -0
- package/dist/lib/teams/delivery.js +13 -0
- package/dist/lib/types.d.ts +0 -37
- package/dist/lib/types.js +0 -9
- package/dist/lib/watchdog/log.d.ts +1 -1
- package/dist/lib/watchdog/log.js +6 -4
- package/package.json +2 -1
- package/dist/lib/artifact-actions.d.ts +0 -7
- package/dist/lib/artifact-actions.js +0 -39
- package/dist/lib/session/sync/managed-config.d.ts +0 -3
- package/dist/lib/session/sync/managed-config.js +0 -3
- package/dist/lib/session/sync/worker-template.d.ts +0 -1
- package/dist/lib/session/sync/worker-template.js +0 -807
- package/dist/lib/storage/selection.d.ts +0 -8
- package/dist/lib/storage/selection.js +0 -10
- package/dist/lib/watchdog/index.d.ts +0 -3
- package/dist/lib/watchdog/index.js +0 -3
|
@@ -8,6 +8,12 @@ import { authCacheKey, readAuthHealthCache } from '../auth-health.js';
|
|
|
8
8
|
import { machineId } from '../machine-id.js';
|
|
9
9
|
import { fixFor } from '../signin-badge.js';
|
|
10
10
|
import { harnessWorkerIsPerDevice } from '../harness-auth-capabilities.js';
|
|
11
|
+
import { loadDevices } from './registry.js';
|
|
12
|
+
import { resolveDeviceProfile } from './resolve-profile.js';
|
|
13
|
+
import { deviceIdentityArgs, fleetDialTarget } from './connect.js';
|
|
14
|
+
import { fanOutDevices, planFleetTargets, raceFleetPingDeadline, remoteFleetTargets, } from './fleet.js';
|
|
15
|
+
import { buildRemoteAgentsInvocation } from '../hosts/remote-cmd.js';
|
|
16
|
+
import { sshExecAsync } from '../ssh-exec.js';
|
|
11
17
|
export function summarizeQuota(snapshot, unavailableReason = null, accountStatus = null) {
|
|
12
18
|
if (!snapshot || snapshot.windows.length === 0) {
|
|
13
19
|
const marker = snapshot?.unavailable;
|
|
@@ -154,6 +160,66 @@ export async function collectLocalHarnessInventory(opts) {
|
|
|
154
160
|
};
|
|
155
161
|
});
|
|
156
162
|
}
|
|
163
|
+
async function probeRemoteHarnesses(target, refresh) {
|
|
164
|
+
const isWin = /^win/i.test((target.platform ?? '').trim());
|
|
165
|
+
const env = isWin ? undefined : { PATH: '$HOME/.agents/.cache/shims:$HOME/.local/bin:$PATH' };
|
|
166
|
+
const args = ['devices', 'harnesses', '--local', '--json'];
|
|
167
|
+
if (refresh)
|
|
168
|
+
args.push('--refresh');
|
|
169
|
+
const cmd = buildRemoteAgentsInvocation(args, undefined, isWin ? 'windows' : undefined, env);
|
|
170
|
+
const res = await sshExecAsync(target.dialTarget, cmd, { timeoutMs: 15000, multiplex: true, extraSshArgs: target.extraSshArgs });
|
|
171
|
+
if (res.code !== 0) {
|
|
172
|
+
throw new Error(res.timedOut ? 'timed out' : (res.stderr.trim() || `exit ${res.code ?? 'unknown'}`));
|
|
173
|
+
}
|
|
174
|
+
const parsed = JSON.parse(res.stdout);
|
|
175
|
+
return parsed.rows ?? [];
|
|
176
|
+
}
|
|
177
|
+
export async function collectFleetHarnesses(opts) {
|
|
178
|
+
const self = machineId();
|
|
179
|
+
const want = opts.devices?.length ? new Set(opts.devices) : null;
|
|
180
|
+
const results = [];
|
|
181
|
+
if (!want || want.has(self)) {
|
|
182
|
+
const localRows = await collectLocalHarnessInventory({ agents: opts.agents, refresh: opts.refresh });
|
|
183
|
+
results.push({ host: self, rows: localRows });
|
|
184
|
+
}
|
|
185
|
+
const reg = await loadDevices();
|
|
186
|
+
const planned = planFleetTargets(reg);
|
|
187
|
+
let remoteTargets = remoteFleetTargets(planned, self).map((t) => ({
|
|
188
|
+
name: t.device.name,
|
|
189
|
+
platform: resolveDeviceProfile(t.device).platform,
|
|
190
|
+
skip: t.skip,
|
|
191
|
+
dialTarget: fleetDialTarget(t.device),
|
|
192
|
+
extraSshArgs: deviceIdentityArgs(t.device),
|
|
193
|
+
}));
|
|
194
|
+
if (want)
|
|
195
|
+
remoteTargets = remoteTargets.filter((t) => want.has(t.name));
|
|
196
|
+
if (remoteTargets.length > 0) {
|
|
197
|
+
const probeable = remoteTargets.filter((t) => !t.skip).length;
|
|
198
|
+
const spinner = opts.spinner?.(`Probing ${probeable} device${probeable === 1 ? '' : 's'}…`);
|
|
199
|
+
let remote;
|
|
200
|
+
try {
|
|
201
|
+
const fanOut = fanOutDevices(remoteTargets, (t) => probeRemoteHarnesses(t, !!opts.refresh), { perDeviceTimeoutMs: 15_000 });
|
|
202
|
+
remote = await raceFleetPingDeadline(fanOut, remoteTargets, 30_000);
|
|
203
|
+
}
|
|
204
|
+
finally {
|
|
205
|
+
spinner?.stop();
|
|
206
|
+
}
|
|
207
|
+
for (const r of remote) {
|
|
208
|
+
if (r.status === 'ok' && r.value) {
|
|
209
|
+
results.push({ host: r.name, rows: r.value });
|
|
210
|
+
}
|
|
211
|
+
else {
|
|
212
|
+
results.push({
|
|
213
|
+
host: r.name,
|
|
214
|
+
rows: [],
|
|
215
|
+
error: r.error,
|
|
216
|
+
skipped: r.reason ? String(r.reason) : undefined,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return results;
|
|
222
|
+
}
|
|
157
223
|
export function groupByAccount(rows) {
|
|
158
224
|
const order = [];
|
|
159
225
|
const groups = new Map();
|
package/dist/lib/exec.js
CHANGED
|
@@ -15,7 +15,7 @@ import { sanitizeProcessEnv } from './secrets-client.js';
|
|
|
15
15
|
import { resolveActor, actorEnv } from './actor.js';
|
|
16
16
|
import { launchIdentityEnv, launchOrigin, LAUNCH_IDENTITY_KEYS } from './launch-identity.js';
|
|
17
17
|
import { expandLocalHome } from './project-root.js';
|
|
18
|
-
import { getShimsDir, getHistoryDir,
|
|
18
|
+
import { getShimsDir, getHistoryDir, getRuntimeStateDir } from './state.js';
|
|
19
19
|
import { readCodexConfiguredModel } from './installations/shims.js';
|
|
20
20
|
import { withInstallationLease } from './installations/launch-gate.js';
|
|
21
21
|
import { getCliLaunch, getAgentsBinPath } from './cli-entry.js';
|
|
@@ -262,8 +262,6 @@ export function buildExecEnv(options) {
|
|
|
262
262
|
result.AGENTS_PARENT_SESSION_ID = spawnerSessionId;
|
|
263
263
|
}
|
|
264
264
|
result.AGENTS_RUNTIME = resolveInteractive(options) ? 'terminal' : 'headless';
|
|
265
|
-
// Bind the standalone secrets client to the same store agents-cli resolved.
|
|
266
|
-
result.SECRETS_HOME = result.SECRETS_HOME ?? getUserAgentsDir();
|
|
267
265
|
if (inheritsHarnessMode(options)) {
|
|
268
266
|
delete result.AGENTS_RUN_MODE;
|
|
269
267
|
}
|
|
@@ -2,6 +2,8 @@ import type { ActiveSession } from '../session/active.js';
|
|
|
2
2
|
import { type AttentionResolution, type AttentionSource, type AttentionState, type BlockOption, type BlockQuestion, type OpenBlock, type SourceCursor } from './feed.js';
|
|
3
3
|
export type AttentionKind = 'question' | 'permission' | 'plan_review' | 'declared' | 'failure' | 'stall' | 'review' | 'unverified';
|
|
4
4
|
export type ReplyCapability = 'terminal' | 'tmux' | 'cloud' | 'team' | 'none';
|
|
5
|
+
export declare const ATTENTION_URGENCIES: readonly ["urgent", "high", "normal", "low"];
|
|
6
|
+
export type AttentionUrgency = (typeof ATTENTION_URGENCIES)[number];
|
|
5
7
|
export interface AttentionChoice extends BlockOption {
|
|
6
8
|
id: string;
|
|
7
9
|
deliveryKey?: string;
|
|
@@ -22,6 +24,8 @@ export interface AttentionItem {
|
|
|
22
24
|
safeDefault?: string;
|
|
23
25
|
fingerprint: string;
|
|
24
26
|
sourceCursor?: SourceCursor;
|
|
27
|
+
urgency: AttentionUrgency;
|
|
28
|
+
urgencyReason?: string;
|
|
25
29
|
}
|
|
26
30
|
export interface PullRequestAttentionSignal {
|
|
27
31
|
number: number;
|
|
@@ -33,13 +37,24 @@ export interface PullRequestAttentionSignal {
|
|
|
33
37
|
state?: string;
|
|
34
38
|
isDraft?: boolean;
|
|
35
39
|
}
|
|
40
|
+
type UnrankedAttentionItem = Omit<AttentionItem, 'urgency' | 'urgencyReason'>;
|
|
36
41
|
export declare function attentionFingerprint(kind: AttentionKind, question?: BlockQuestion): string;
|
|
37
|
-
export declare function harnessOf(session: ActiveSession): string;
|
|
42
|
+
export declare function harnessOf(session: Partial<Pick<ActiveSession, 'harness' | 'kind'>>): string;
|
|
38
43
|
export declare const UNVERIFIED_PROMPT_AGE_MS: number;
|
|
44
|
+
export declare function attentionUrgency(item: UnrankedAttentionItem, ticket?: {
|
|
45
|
+
id: string;
|
|
46
|
+
priority?: number;
|
|
47
|
+
}): {
|
|
48
|
+
urgency: AttentionUrgency;
|
|
49
|
+
urgencyReason?: string;
|
|
50
|
+
};
|
|
51
|
+
export declare function attentionTicketId(session: ActiveSession, block?: OpenBlock): string | undefined;
|
|
39
52
|
export declare function reconcileAttention(input: {
|
|
40
53
|
block?: OpenBlock;
|
|
41
54
|
session: ActiveSession;
|
|
42
55
|
pullRequest?: PullRequestAttentionSignal;
|
|
43
56
|
resolution?: AttentionResolution;
|
|
57
|
+
ticketPriority?: (ticketId: string) => number | undefined;
|
|
44
58
|
nowMs: number;
|
|
45
59
|
}): AttentionItem | undefined;
|
|
60
|
+
export {};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { blockGeneration, blockIdForSession, blockSource, deriveBlockState, } from './feed.js';
|
|
3
|
+
export const ATTENTION_URGENCIES = ['urgent', 'high', 'normal', 'low'];
|
|
3
4
|
function attentionKey(host, sessionId, generation) {
|
|
4
5
|
return `${host}/${sessionId}/${generation}`;
|
|
5
6
|
}
|
|
@@ -229,6 +230,65 @@ function coveredByResolution(candidate, resolution) {
|
|
|
229
230
|
return candidateCursor <= fence;
|
|
230
231
|
return true;
|
|
231
232
|
}
|
|
233
|
+
const TICKET_PRIORITY = {
|
|
234
|
+
1: { urgency: 'urgent', name: 'Urgent' },
|
|
235
|
+
2: { urgency: 'high', name: 'High' },
|
|
236
|
+
3: { urgency: 'normal', name: 'Medium' },
|
|
237
|
+
4: { urgency: 'low', name: 'Low' },
|
|
238
|
+
};
|
|
239
|
+
const RELEASE_COMMAND = new RegExp([
|
|
240
|
+
String.raw `(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:publish|release|deploy)`,
|
|
241
|
+
String.raw `(?:cargo|vsce|ovsx)\s+publish`,
|
|
242
|
+
String.raw `twine\s+upload`,
|
|
243
|
+
String.raw `gh\s+pr\s+merge`,
|
|
244
|
+
String.raw `gh\s+release\s+create`,
|
|
245
|
+
String.raw `release\.sh`,
|
|
246
|
+
String.raw `(?:wrangler|fly|flyctl|railway|vercel)\s+deploy`,
|
|
247
|
+
String.raw `terraform\s+apply`,
|
|
248
|
+
String.raw `kubectl\s+apply`,
|
|
249
|
+
String.raw `helm\s+(?:upgrade|install)`,
|
|
250
|
+
String.raw `docker\s+push`,
|
|
251
|
+
].map((p) => String.raw `\b${p}\b`).join('|'), 'i');
|
|
252
|
+
const RELEASE_WORD = /\b(?:publish(?:es|ing)?|releas(?:e|es|ing)|deploy(?:s|ing)?|merg(?:e|es|ing))\b/i;
|
|
253
|
+
// A command ask is matched on its command only: a path such as src/merge.ts is not a merge.
|
|
254
|
+
const COMMAND_KINDS = new Set(['permission', 'unverified']);
|
|
255
|
+
const PROSE_KINDS = new Set(['question', 'plan_review', 'declared']);
|
|
256
|
+
function releaseNoun(match) {
|
|
257
|
+
const m = match.toLowerCase();
|
|
258
|
+
if (/deploy|terraform|kubectl|helm|docker/.test(m))
|
|
259
|
+
return 'a deploy';
|
|
260
|
+
if (/merg/.test(m))
|
|
261
|
+
return 'a merge';
|
|
262
|
+
return 'a release';
|
|
263
|
+
}
|
|
264
|
+
function releaseBlocker(item) {
|
|
265
|
+
const text = item.question?.text ?? '';
|
|
266
|
+
if (!COMMAND_KINDS.has(item.kind) && !PROSE_KINDS.has(item.kind))
|
|
267
|
+
return undefined;
|
|
268
|
+
const command = RELEASE_COMMAND.exec(text);
|
|
269
|
+
if (command)
|
|
270
|
+
return `Blocks ${releaseNoun(command[0])} (${command[0].replace(/\s+/g, ' ')})`;
|
|
271
|
+
if (!PROSE_KINDS.has(item.kind))
|
|
272
|
+
return undefined;
|
|
273
|
+
const word = RELEASE_WORD.exec(text);
|
|
274
|
+
return word ? `Blocks ${releaseNoun(word[0])}` : undefined;
|
|
275
|
+
}
|
|
276
|
+
// costOfDelay is not an input: every declared block carries `high`, so it cannot single out a release.
|
|
277
|
+
export function attentionUrgency(item, ticket) {
|
|
278
|
+
const release = releaseBlocker(item);
|
|
279
|
+
if (release)
|
|
280
|
+
return { urgency: 'urgent', urgencyReason: release };
|
|
281
|
+
const known = ticket?.priority !== undefined ? TICKET_PRIORITY[ticket.priority] : undefined;
|
|
282
|
+
if (ticket && known) {
|
|
283
|
+
return known.urgency === 'normal'
|
|
284
|
+
? { urgency: 'normal' }
|
|
285
|
+
: { urgency: known.urgency, urgencyReason: `${known.name} ticket ${ticket.id}` };
|
|
286
|
+
}
|
|
287
|
+
return { urgency: 'normal' };
|
|
288
|
+
}
|
|
289
|
+
export function attentionTicketId(session, block) {
|
|
290
|
+
return session.ticket?.id ?? block?.ticket ?? undefined;
|
|
291
|
+
}
|
|
232
292
|
export function reconcileAttention(input) {
|
|
233
293
|
const fromBlock = input.block && deriveBlockState(input.block) === 'open'
|
|
234
294
|
? attentionFromBlock(input.block, input.session, input.nowMs)
|
|
@@ -240,5 +300,7 @@ export function reconcileAttention(input) {
|
|
|
240
300
|
return undefined;
|
|
241
301
|
if (coveredByResolution(candidate, input.resolution))
|
|
242
302
|
return undefined;
|
|
243
|
-
|
|
303
|
+
const ticketId = attentionTicketId(input.session, input.block);
|
|
304
|
+
const ticket = ticketId ? { id: ticketId, priority: input.ticketPriority?.(ticketId) } : undefined;
|
|
305
|
+
return { ...candidate.item, ...attentionUrgency(candidate.item, ticket) };
|
|
244
306
|
}
|
package/dist/lib/feed/feed.d.ts
CHANGED
|
@@ -163,7 +163,7 @@ export declare function publishBlock(block: OpenBlock, root?: string): void;
|
|
|
163
163
|
export declare function listBlocks(root?: string): OpenBlock[];
|
|
164
164
|
export declare function listAskStats(root?: string): FeedAskStats[];
|
|
165
165
|
export declare function removeBlock(blockId: string, root?: string): boolean;
|
|
166
|
-
export declare const FEED_PUBLISH_HOOK_SCRIPT = "#!/usr/bin/env python3\n\"\"\"Publish and clear open-block records for `agents feed`.\n\nThe manifest invokes this script for top-level AskUserQuestion calls, waiting\nnotifications, question answers, and session lifecycle events. One atomic file\nper session means a new block replaces the previous block. Answer/resume/stop\nevents remove it so `agents feed` only lists decisions that are still open.\n\nSub-agent gate: when the PreToolUse payload carries `agent_type`, this is a\nTask/Agent subagent -- skip. Only the top-level agent publishes. Verified on\nClaude Code 2.1.170 (2026-07).\n\nFail-open: ANY error is swallowed so a feed hiccup never blocks a tool call.\n\"\"\"\nimport os\nimport sys\nimport json\nimport re\nimport socket\nimport tempfile\nfrom datetime import datetime, timezone\n\nWAITING_NOTIFICATION_TYPES = {\n \"permission_prompt\",\n \"elicitation_dialog\",\n}\nCLEAR_EVENTS = {\n \"PostToolUse\",\n \"Stop\",\n \"SessionEnd\",\n}\n\n\ndef read_json(path):\n try:\n with open(path) as f:\n return json.load(f)\n except Exception:\n return None\n\n\ndef write_json(path, value):\n dir_name = os.path.dirname(path)\n os.makedirs(dir_name, exist_ok=True)\n fd, tmp = tempfile.mkstemp(dir=dir_name, suffix=\".tmp\")\n try:\n with os.fdopen(fd, \"w\") as f:\n json.dump(value, f, indent=2)\n os.replace(tmp, path)\n except Exception:\n try:\n os.unlink(tmp)\n except Exception:\n pass\n\n\ndef project_from_cwd(cwd):\n \"\"\"Basename of cwd, with worktree paths resolved to their repo name.\"\"\"\n if not cwd:\n return None\n norm = cwd.replace(\"\\\\\", \"/\").rstrip(\"/\")\n if not norm:\n return None\n marker = \"/.agents/worktrees/\"\n idx = norm.find(marker)\n if idx > 0:\n repo_path = norm[:idx]\n base = repo_path[repo_path.rfind(\"/\") + 1:]\n if base:\n return base\n base = norm[norm.rfind(\"/\") + 1:]\n return base or None\n\n\ndef main():\n raw = sys.stdin.read()\n try:\n payload = json.loads(raw) if raw.strip() else {}\n except Exception:\n return\n\n if payload.get(\"agent_type\"):\n return\n\n session_id = payload.get(\"session_id\", \"\")\n if not session_id:\n return\n\n safe_session_id = re.sub(r\"[^A-Za-z0-9._-]\", \"-\", session_id)\n block_id = f\"block-{safe_session_id}\"\n home = os.environ.get(\"HOME\") or os.path.expanduser(\"~\")\n feed_dir = os.path.join(home, \".agents\", \".history\", \"feed\")\n answered_dir = os.path.join(feed_dir, \"answered\")\n asks_dir = os.path.join(feed_dir, \"asks\")\n target = os.path.join(feed_dir, f\"{block_id}.json\")\n hook_event = payload.get(\"hook_event_name\", \"PreToolUse\")\n\n if hook_event in CLEAR_EVENTS:\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n answered = os.path.exists(os.path.join(answered_dir, f\"{block_id}.json\"))\n\n # Ordinary lifecycle hooks cannot clear a declared block before it is answered.\n if existing.get(\"kind\") == \"declared\" and not answered:\n return\n except Exception:\n pass\n if hook_event == \"PostToolUse\":\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n if existing.get(\"kind\") == \"question\" and payload.get(\"tool_name\") != \"AskUserQuestion\":\n return\n except Exception:\n pass\n try:\n os.unlink(target)\n except FileNotFoundError:\n pass\n except Exception:\n pass\n try:\n os.unlink(os.path.join(answered_dir, f\"{block_id}.json\"))\n except FileNotFoundError:\n pass\n except Exception:\n pass\n return\n\n if hook_event == \"UserPromptSubmit\":\n os.makedirs(answered_dir, exist_ok=True)\n marker = os.path.join(answered_dir, f\"{block_id}.json\")\n now_iso = datetime.now(timezone.utc).isoformat()\n try:\n fd = os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)\n record = {\n \"answeredAt\": now_iso,\n \"answeredFrom\": \"terminal\",\n }\n with os.fdopen(fd, \"w\") as f:\n json.dump(record, f, indent=2)\n except FileExistsError:\n pass\n except Exception:\n pass\n existing = read_json(target)\n if isinstance(existing, dict):\n generation = existing.get(\"generation\") or existing.get(\"ts\")\n if generation:\n tombstone = {\n \"blockId\": block_id,\n \"generation\": generation,\n \"resolvedAt\": now_iso,\n \"reason\": \"answered\",\n }\n source_cursor = existing.get(\"sourceCursor\")\n if source_cursor:\n tombstone[\"sourceCursor\"] = source_cursor\n write_json(\n os.path.join(feed_dir, \"resolutions\", f\"{block_id}.json\"),\n tombstone,\n )\n try:\n os.unlink(target)\n except FileNotFoundError:\n pass\n except Exception:\n pass\n return\n\n notification_type = None\n codex_approval = False\n if hook_event == \"Notification\":\n notification_type = payload.get(\"notification_type\", \"\")\n if notification_type not in WAITING_NOTIFICATION_TYPES:\n return\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n if existing.get(\"kind\") == \"question\":\n return\n except Exception:\n pass\n message = payload.get(\"message\", \"\")\n if not message:\n return\n normalized_questions = [{\n \"text\": message,\n \"header\": payload.get(\"title\") or notification_type.replace(\"_\", \" \").title(),\n \"multiSelect\": False,\n }]\n kind = \"notification\"\n elif hook_event == \"PermissionRequest\":\n tool_name = payload.get(\"tool_name\") or \"a tool\"\n tool_input = payload.get(\"tool_input\", {})\n command = \"\"\n if isinstance(tool_input, dict):\n command = (\n tool_input.get(\"command\")\n or tool_input.get(\"cmd\")\n or tool_input.get(\"path\")\n or \"\"\n )\n if isinstance(command, list):\n command = \" \".join(str(c) for c in command)\n detail = f\": {command}\" if command else \"\"\n normalized_questions = [{\n \"text\": f\"Codex needs approval to run {tool_name}{detail}\",\n \"header\": \"Approval needed\",\n \"multiSelect\": False,\n }]\n kind = \"notification\"\n notification_type = \"permission_prompt\"\n codex_approval = True\n else:\n tool_input = payload.get(\"tool_input\", {})\n questions = tool_input.get(\"questions\", [])\n if not questions:\n return\n normalized_questions = []\n for q in questions:\n if not isinstance(q, dict):\n continue\n question = {\n \"text\": q.get(\"question\", q.get(\"header\", \"\")),\n \"header\": q.get(\"header\"),\n \"multiSelect\": q.get(\"multiSelect\", False),\n }\n raw_opts = q.get(\"options\", [])\n if raw_opts:\n question[\"options\"] = [\n {\"label\": o.get(\"label\", \"\"), \"description\": o.get(\"description\")}\n for o in raw_opts\n if isinstance(o, dict)\n ]\n normalized_questions.append(question)\n if not normalized_questions:\n return\n kind = \"question\"\n\n mailbox_id = os.path.basename(\n os.environ.get(\"AGENTS_MAILBOX_DIR\", \"\").rstrip(\"/\")\n ) or session_id\n\n now = datetime.now(timezone.utc)\n now_iso = now.isoformat()\n now_ms = int(now.timestamp() * 1000)\n stats_path = os.path.join(asks_dir, f\"{safe_session_id}.json\")\n stats = read_json(stats_path) or {}\n recent = stats.get(\"recentAskTimestamps\") if isinstance(stats, dict) else []\n if not isinstance(recent, list):\n recent = []\n recent.append(now_iso)\n recent = recent[-200:]\n write_json(stats_path, {\n \"sessionId\": session_id,\n \"mailboxId\": mailbox_id,\n \"firstAskAt\": stats.get(\"firstAskAt\") or now_iso,\n \"lastAskAt\": now_iso,\n \"totalAskCount\": int(stats.get(\"totalAskCount\") or 0) + 1,\n \"recentAskTimestamps\": recent,\n })\n\n hostname = os.environ.get(\"AGENTS_SYNC_MACHINE_ID\") or socket.gethostname()\n host = hostname.split(\".\")[0].strip().lower()\n host = re.sub(r\"[^a-z0-9_-]\", \"-\", host) or \"unknown\"\n\n runtime = os.environ.get(\"AGENTS_RUNTIME\", \"headless\")\n cwd = payload.get(\"cwd\") or os.environ.get(\"AGENTS_CWD\")\n project = project_from_cwd(cwd)\n\n block = {\n \"blockId\": block_id,\n \"sessionId\": session_id,\n \"mailboxId\": mailbox_id,\n \"host\": host,\n \"runtime\": runtime,\n \"ts\": now_iso,\n \"sourceCursor\": {\"lastActivityMs\": now_ms},\n \"questions\": normalized_questions,\n \"kind\": kind,\n }\n if project:\n block[\"project\"] = project\n if notification_type:\n block[\"notificationType\"] = notification_type\n\n if codex_approval:\n block[\"blockClass\"] = \"approval\"\n block[\"costOfDelay\"] = \"high\"\n block[\"safeDefault\"] = \"deny\"\n\n controls = payload.get(\"tool_input\", {}) if hook_event not in (\"Notification\", \"PermissionRequest\") else {}\n block_class = controls.get(\"blockClass\") if isinstance(controls, dict) else None\n if block_class in (\"approval\", \"decision\"):\n block[\"blockClass\"] = block_class\n consequence = controls.get(\"consequence\") if isinstance(controls, dict) else None\n if consequence:\n block[\"consequence\"] = consequence\n allowed = controls.get(\"allowedOperators\") if isinstance(controls, dict) else None\n if isinstance(allowed, list):\n block[\"allowedOperators\"] = [str(a) for a in allowed]\n timeout = controls.get(\"timeoutMinutes\") if isinstance(controls, dict) else None\n if isinstance(timeout, (int, float)) and timeout > 0:\n block[\"timeoutMinutes\"] = int(timeout)\n safe_default = controls.get(\"safeDefault\") if isinstance(controls, dict) else None\n if isinstance(safe_default, str):\n block[\"safeDefault\"] = safe_default\n cost = controls.get(\"costOfDelay\") if isinstance(controls, dict) else None\n if cost in (\"low\", \"medium\", \"high\"):\n block[\"costOfDelay\"] = cost\n\n try:\n os.unlink(os.path.join(answered_dir, f\"{block_id}.json\"))\n except FileNotFoundError:\n pass\n except Exception:\n pass\n\n os.makedirs(feed_dir, exist_ok=True)\n\n fd, tmp = tempfile.mkstemp(dir=feed_dir, suffix=\".tmp\")\n try:\n with os.fdopen(fd, \"w\") as f:\n json.dump(block, f, indent=2)\n os.replace(tmp, target)\n except Exception:\n try:\n os.unlink(tmp)\n except Exception:\n pass\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception:\n pass\n";
|
|
166
|
+
export declare const FEED_PUBLISH_HOOK_SCRIPT = "#!/usr/bin/env python3\n\"\"\"Publish and clear open-block records for `agents feed`.\n\nThe manifest invokes this script for top-level AskUserQuestion calls, waiting\nnotifications, question answers, and session lifecycle events. One atomic file\nper session means a new block replaces the previous block. Answer/resume/stop\nevents remove it so `agents feed` only lists decisions that are still open.\n\nSub-agent gate: when the PreToolUse payload carries `agent_type`, this is a\nTask/Agent subagent -- skip. Only the top-level agent publishes. Verified on\nClaude Code 2.1.170 (2026-07).\n\nFail-open: ANY error is swallowed so a feed hiccup never blocks a tool call.\n\"\"\"\nimport os\nimport sys\nimport json\nimport re\nimport socket\nimport tempfile\nfrom datetime import datetime, timezone\n\nWAITING_NOTIFICATION_TYPES = {\n \"permission_prompt\",\n \"elicitation_dialog\",\n}\nCLEAR_EVENTS = {\n \"PostToolUse\",\n \"Stop\",\n \"SessionEnd\",\n}\n\n\ndef read_json(path):\n try:\n with open(path) as f:\n return json.load(f)\n except Exception:\n return None\n\n\ndef write_json(path, value):\n dir_name = os.path.dirname(path)\n os.makedirs(dir_name, exist_ok=True)\n fd, tmp = tempfile.mkstemp(dir=dir_name, suffix=\".tmp\")\n try:\n with os.fdopen(fd, \"w\") as f:\n json.dump(value, f, indent=2)\n os.replace(tmp, path)\n except Exception:\n try:\n os.unlink(tmp)\n except Exception:\n pass\n\n\ndef project_from_cwd(cwd):\n \"\"\"Basename of cwd, with worktree paths resolved to their repo name.\"\"\"\n if not cwd:\n return None\n norm = cwd.replace(\"\\\\\", \"/\").rstrip(\"/\")\n if not norm:\n return None\n marker = \"/.agents/worktrees/\"\n idx = norm.find(marker)\n if idx > 0:\n repo_path = norm[:idx]\n base = repo_path[repo_path.rfind(\"/\") + 1:]\n if base:\n return base\n base = norm[norm.rfind(\"/\") + 1:]\n return base or None\n\n\ndef main():\n raw = sys.stdin.read()\n try:\n payload = json.loads(raw) if raw.strip() else {}\n except Exception:\n return\n\n if payload.get(\"agent_type\"):\n return\n\n session_id = payload.get(\"session_id\", \"\")\n if not session_id:\n return\n\n safe_session_id = re.sub(r\"[^A-Za-z0-9._-]\", \"-\", session_id)\n block_id = f\"block-{safe_session_id}\"\n home = os.environ.get(\"HOME\") or os.path.expanduser(\"~\")\n feed_dir = os.path.join(home, \".agents\", \".history\", \"feed\")\n answered_dir = os.path.join(feed_dir, \"answered\")\n asks_dir = os.path.join(feed_dir, \"asks\")\n target = os.path.join(feed_dir, f\"{block_id}.json\")\n hook_event = payload.get(\"hook_event_name\", \"PreToolUse\")\n\n if hook_event in CLEAR_EVENTS:\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n answered = os.path.exists(os.path.join(answered_dir, f\"{block_id}.json\"))\n\n # Ordinary lifecycle hooks cannot clear a declared block before it is answered.\n if existing.get(\"kind\") == \"declared\" and not answered:\n return\n except Exception:\n pass\n if hook_event == \"PostToolUse\":\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n if existing.get(\"kind\") == \"question\" and payload.get(\"tool_name\") != \"AskUserQuestion\":\n return\n except Exception:\n pass\n try:\n os.unlink(target)\n except FileNotFoundError:\n pass\n except Exception:\n pass\n try:\n os.unlink(os.path.join(answered_dir, f\"{block_id}.json\"))\n except FileNotFoundError:\n pass\n except Exception:\n pass\n return\n\n if hook_event == \"UserPromptSubmit\":\n os.makedirs(answered_dir, exist_ok=True)\n marker = os.path.join(answered_dir, f\"{block_id}.json\")\n now_iso = datetime.now(timezone.utc).isoformat()\n try:\n fd = os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)\n record = {\n \"answeredAt\": now_iso,\n \"answeredFrom\": \"terminal\",\n }\n with os.fdopen(fd, \"w\") as f:\n json.dump(record, f, indent=2)\n except FileExistsError:\n pass\n except Exception:\n pass\n existing = read_json(target)\n if isinstance(existing, dict):\n generation = existing.get(\"generation\") or existing.get(\"ts\")\n if generation:\n tombstone = {\n \"blockId\": block_id,\n \"generation\": generation,\n \"resolvedAt\": now_iso,\n \"reason\": \"answered\",\n }\n source_cursor = existing.get(\"sourceCursor\")\n if source_cursor:\n tombstone[\"sourceCursor\"] = source_cursor\n write_json(\n os.path.join(feed_dir, \"resolutions\", f\"{block_id}.json\"),\n tombstone,\n )\n try:\n os.unlink(target)\n except FileNotFoundError:\n pass\n except Exception:\n pass\n return\n\n notification_type = None\n codex_approval = False\n if hook_event == \"Notification\":\n notification_type = payload.get(\"notification_type\", \"\")\n if notification_type not in WAITING_NOTIFICATION_TYPES:\n return\n try:\n with open(target) as existing_file:\n existing = json.load(existing_file)\n if existing.get(\"kind\") == \"question\":\n return\n if (\n notification_type == \"permission_prompt\"\n and existing.get(\"notificationType\") == \"permission_prompt\"\n and (existing.get(\"questions\") or [{}])[0].get(\"header\") == \"Approval needed\"\n ):\n return\n except Exception:\n pass\n message = payload.get(\"message\", \"\")\n if not message:\n return\n normalized_questions = [{\n \"text\": message,\n \"header\": payload.get(\"title\") or notification_type.replace(\"_\", \" \").title(),\n \"multiSelect\": False,\n }]\n kind = \"notification\"\n elif hook_event == \"PermissionRequest\":\n tool_name = payload.get(\"tool_name\") or \"a tool\"\n tool_input = payload.get(\"tool_input\", {})\n transcript_path = str(payload.get(\"transcript_path\") or \"\")\n is_claude = \"permission_suggestions\" in payload or \"/.claude/\" in transcript_path.replace(os.sep, \"/\")\n command = \"\"\n if isinstance(tool_input, dict):\n command = (\n tool_input.get(\"command\")\n or tool_input.get(\"cmd\")\n or tool_input.get(\"path\")\n or (tool_input.get(\"file_path\") or tool_input.get(\"url\") or tool_input.get(\"pattern\") if is_claude else \"\")\n or \"\"\n )\n if isinstance(command, list):\n command = \" \".join(str(c) for c in command)\n detail = f\": {command}\" if command else \"\"\n who = \"Claude\" if is_claude else \"Codex\"\n normalized_questions = [{\n \"text\": f\"{who} needs approval to run {tool_name}{detail}\",\n \"header\": \"Approval needed\",\n \"multiSelect\": False,\n }]\n kind = \"notification\"\n notification_type = \"permission_prompt\"\n codex_approval = not is_claude\n else:\n tool_input = payload.get(\"tool_input\", {})\n questions = tool_input.get(\"questions\", [])\n if not questions:\n return\n normalized_questions = []\n for q in questions:\n if not isinstance(q, dict):\n continue\n question = {\n \"text\": q.get(\"question\", q.get(\"header\", \"\")),\n \"header\": q.get(\"header\"),\n \"multiSelect\": q.get(\"multiSelect\", False),\n }\n raw_opts = q.get(\"options\", [])\n if raw_opts:\n question[\"options\"] = [\n {\"label\": o.get(\"label\", \"\"), \"description\": o.get(\"description\")}\n for o in raw_opts\n if isinstance(o, dict)\n ]\n normalized_questions.append(question)\n if not normalized_questions:\n return\n kind = \"question\"\n\n mailbox_id = os.path.basename(\n os.environ.get(\"AGENTS_MAILBOX_DIR\", \"\").rstrip(\"/\")\n ) or session_id\n\n now = datetime.now(timezone.utc)\n now_iso = now.isoformat()\n now_ms = int(now.timestamp() * 1000)\n stats_path = os.path.join(asks_dir, f\"{safe_session_id}.json\")\n stats = read_json(stats_path) or {}\n recent = stats.get(\"recentAskTimestamps\") if isinstance(stats, dict) else []\n if not isinstance(recent, list):\n recent = []\n recent.append(now_iso)\n recent = recent[-200:]\n write_json(stats_path, {\n \"sessionId\": session_id,\n \"mailboxId\": mailbox_id,\n \"firstAskAt\": stats.get(\"firstAskAt\") or now_iso,\n \"lastAskAt\": now_iso,\n \"totalAskCount\": int(stats.get(\"totalAskCount\") or 0) + 1,\n \"recentAskTimestamps\": recent,\n })\n\n hostname = os.environ.get(\"AGENTS_SYNC_MACHINE_ID\") or socket.gethostname()\n host = hostname.split(\".\")[0].strip().lower()\n host = re.sub(r\"[^a-z0-9_-]\", \"-\", host) or \"unknown\"\n\n runtime = os.environ.get(\"AGENTS_RUNTIME\", \"headless\")\n cwd = payload.get(\"cwd\") or os.environ.get(\"AGENTS_CWD\")\n project = project_from_cwd(cwd)\n\n block = {\n \"blockId\": block_id,\n \"sessionId\": session_id,\n \"mailboxId\": mailbox_id,\n \"host\": host,\n \"runtime\": runtime,\n \"ts\": now_iso,\n \"sourceCursor\": {\"lastActivityMs\": now_ms},\n \"questions\": normalized_questions,\n \"kind\": kind,\n }\n if project:\n block[\"project\"] = project\n if notification_type:\n block[\"notificationType\"] = notification_type\n\n if codex_approval:\n block[\"blockClass\"] = \"approval\"\n block[\"costOfDelay\"] = \"high\"\n block[\"safeDefault\"] = \"deny\"\n\n controls = payload.get(\"tool_input\", {}) if hook_event not in (\"Notification\", \"PermissionRequest\") else {}\n block_class = controls.get(\"blockClass\") if isinstance(controls, dict) else None\n if block_class in (\"approval\", \"decision\"):\n block[\"blockClass\"] = block_class\n consequence = controls.get(\"consequence\") if isinstance(controls, dict) else None\n if consequence:\n block[\"consequence\"] = consequence\n allowed = controls.get(\"allowedOperators\") if isinstance(controls, dict) else None\n if isinstance(allowed, list):\n block[\"allowedOperators\"] = [str(a) for a in allowed]\n timeout = controls.get(\"timeoutMinutes\") if isinstance(controls, dict) else None\n if isinstance(timeout, (int, float)) and timeout > 0:\n block[\"timeoutMinutes\"] = int(timeout)\n safe_default = controls.get(\"safeDefault\") if isinstance(controls, dict) else None\n if isinstance(safe_default, str):\n block[\"safeDefault\"] = safe_default\n cost = controls.get(\"costOfDelay\") if isinstance(controls, dict) else None\n if cost in (\"low\", \"medium\", \"high\"):\n block[\"costOfDelay\"] = cost\n\n try:\n os.unlink(os.path.join(answered_dir, f\"{block_id}.json\"))\n except FileNotFoundError:\n pass\n except Exception:\n pass\n\n os.makedirs(feed_dir, exist_ok=True)\n\n fd, tmp = tempfile.mkstemp(dir=feed_dir, suffix=\".tmp\")\n try:\n with os.fdopen(fd, \"w\") as f:\n json.dump(block, f, indent=2)\n os.replace(tmp, target)\n except Exception:\n try:\n os.unlink(tmp)\n except Exception:\n pass\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception:\n pass\n";
|
|
167
167
|
export declare function ensureFeedPublishHook(userAgentsDir?: string): {
|
|
168
168
|
installed: boolean;
|
|
169
169
|
error?: string;
|
package/dist/lib/feed/feed.js
CHANGED
|
@@ -664,6 +664,12 @@ def main():
|
|
|
664
664
|
existing = json.load(existing_file)
|
|
665
665
|
if existing.get("kind") == "question":
|
|
666
666
|
return
|
|
667
|
+
if (
|
|
668
|
+
notification_type == "permission_prompt"
|
|
669
|
+
and existing.get("notificationType") == "permission_prompt"
|
|
670
|
+
and (existing.get("questions") or [{}])[0].get("header") == "Approval needed"
|
|
671
|
+
):
|
|
672
|
+
return
|
|
667
673
|
except Exception:
|
|
668
674
|
pass
|
|
669
675
|
message = payload.get("message", "")
|
|
@@ -678,25 +684,29 @@ def main():
|
|
|
678
684
|
elif hook_event == "PermissionRequest":
|
|
679
685
|
tool_name = payload.get("tool_name") or "a tool"
|
|
680
686
|
tool_input = payload.get("tool_input", {})
|
|
687
|
+
transcript_path = str(payload.get("transcript_path") or "")
|
|
688
|
+
is_claude = "permission_suggestions" in payload or "/.claude/" in transcript_path.replace(os.sep, "/")
|
|
681
689
|
command = ""
|
|
682
690
|
if isinstance(tool_input, dict):
|
|
683
691
|
command = (
|
|
684
692
|
tool_input.get("command")
|
|
685
693
|
or tool_input.get("cmd")
|
|
686
694
|
or tool_input.get("path")
|
|
695
|
+
or (tool_input.get("file_path") or tool_input.get("url") or tool_input.get("pattern") if is_claude else "")
|
|
687
696
|
or ""
|
|
688
697
|
)
|
|
689
698
|
if isinstance(command, list):
|
|
690
699
|
command = " ".join(str(c) for c in command)
|
|
691
700
|
detail = f": {command}" if command else ""
|
|
701
|
+
who = "Claude" if is_claude else "Codex"
|
|
692
702
|
normalized_questions = [{
|
|
693
|
-
"text": f"
|
|
703
|
+
"text": f"{who} needs approval to run {tool_name}{detail}",
|
|
694
704
|
"header": "Approval needed",
|
|
695
705
|
"multiSelect": False,
|
|
696
706
|
}]
|
|
697
707
|
kind = "notification"
|
|
698
708
|
notification_type = "permission_prompt"
|
|
699
|
-
codex_approval =
|
|
709
|
+
codex_approval = not is_claude
|
|
700
710
|
else:
|
|
701
711
|
tool_input = payload.get("tool_input", {})
|
|
702
712
|
questions = tool_input.get("questions", [])
|
package/dist/lib/feed/hub.d.ts
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
1
|
+
import type { SessionWatchRow } from '../session/watch.js';
|
|
2
|
+
import type { AttentionItem } from './attention.js';
|
|
1
3
|
import { FeedWatchState, type FeedWatchEnvelope } from './envelope.js';
|
|
2
4
|
export declare const HUB_ACTIVITY_REPLAY = 50;
|
|
3
5
|
export declare class FeedHubState {
|
|
4
6
|
private readonly scopes;
|
|
5
7
|
private readonly activity;
|
|
8
|
+
private order;
|
|
6
9
|
private scope;
|
|
7
10
|
apply(event: FeedWatchEnvelope): void;
|
|
8
11
|
snapshot(state: FeedWatchState): FeedWatchEnvelope[];
|
|
9
12
|
get scopeNames(): string[];
|
|
13
|
+
get reportingScopes(): Set<string>;
|
|
14
|
+
attention(): Array<{
|
|
15
|
+
scope: string;
|
|
16
|
+
item: AttentionItem;
|
|
17
|
+
agent?: SessionWatchRow;
|
|
18
|
+
}>;
|
|
10
19
|
}
|
|
11
20
|
export type HubFanOut = (options: {
|
|
12
21
|
signal: AbortSignal;
|
package/dist/lib/feed/hub.js
CHANGED
|
@@ -2,11 +2,12 @@ import { machineId, normalizeHost } from '../machine-id.js';
|
|
|
2
2
|
import { FeedWatchState } from './envelope.js';
|
|
3
3
|
export const HUB_ACTIVITY_REPLAY = 50;
|
|
4
4
|
function emptyScope() {
|
|
5
|
-
return { agents: new Map(), attention: new Map(), tools: new Map(), setup: [], capturedAt: 0 };
|
|
5
|
+
return { agents: new Map(), attention: new Map(), tools: new Map(), setup: [], capturedAt: 0, resetOrder: 0, unavailableOrder: 0 };
|
|
6
6
|
}
|
|
7
7
|
export class FeedHubState {
|
|
8
8
|
scopes = new Map();
|
|
9
9
|
activity = [];
|
|
10
|
+
order = 0;
|
|
10
11
|
scope(name) {
|
|
11
12
|
const key = normalizeHost(name);
|
|
12
13
|
let scope = this.scopes.get(key);
|
|
@@ -25,6 +26,7 @@ export class FeedHubState {
|
|
|
25
26
|
scope.tools = new Map(event.tools.map((tool) => [tool.rowKey, tool]));
|
|
26
27
|
scope.setup = event.setup;
|
|
27
28
|
scope.capturedAt = event.capturedAt;
|
|
29
|
+
scope.resetOrder = ++this.order;
|
|
28
30
|
break;
|
|
29
31
|
case 'agent.upsert':
|
|
30
32
|
scope.agents.set(event.rowKey, event.agent);
|
|
@@ -49,6 +51,8 @@ export class FeedHubState {
|
|
|
49
51
|
break;
|
|
50
52
|
case 'scope':
|
|
51
53
|
scope.status = { status: event.status, ...(event.reason ? { reason: event.reason } : {}) };
|
|
54
|
+
if (event.status === 'unavailable')
|
|
55
|
+
scope.unavailableOrder = ++this.order;
|
|
52
56
|
break;
|
|
53
57
|
case 'activity.append':
|
|
54
58
|
this.activity.push(event.event);
|
|
@@ -75,6 +79,28 @@ export class FeedHubState {
|
|
|
75
79
|
return out;
|
|
76
80
|
}
|
|
77
81
|
get scopeNames() { return [...this.scopes.keys()]; }
|
|
82
|
+
// A scope whose rows can be trusted as complete: it sent a reset, and no unavailable since.
|
|
83
|
+
get reportingScopes() {
|
|
84
|
+
const out = new Set();
|
|
85
|
+
for (const [name, scope] of this.scopes)
|
|
86
|
+
if (scope.resetOrder > scope.unavailableOrder)
|
|
87
|
+
out.add(name);
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
attention() {
|
|
91
|
+
const out = [];
|
|
92
|
+
for (const [scope, state] of this.scopes) {
|
|
93
|
+
const seen = new Set();
|
|
94
|
+
for (const item of state.attention.values()) {
|
|
95
|
+
if (seen.has(item.key))
|
|
96
|
+
continue;
|
|
97
|
+
seen.add(item.key);
|
|
98
|
+
const agent = [...state.agents.values()].find((row) => row.sessionId === item.sessionId && !row.previous);
|
|
99
|
+
out.push({ scope, item, ...(agent ? { agent } : {}) });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
78
104
|
}
|
|
79
105
|
export class FeedHub {
|
|
80
106
|
options;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { AttentionUrgency } from './attention.js';
|
|
2
|
+
export declare const NOTIFY_LEVELS: readonly AttentionUrgency[];
|
|
3
|
+
export declare const NOTIFY_LEVEL_KEYS: Record<AttentionUrgency, string>;
|
|
4
|
+
export declare const DEFAULT_NOTIFY_SCHEDULES: Record<AttentionUrgency, readonly string[]>;
|
|
5
|
+
export type NotifySchedule = {
|
|
6
|
+
sidebar: true;
|
|
7
|
+
} | {
|
|
8
|
+
sidebar: false;
|
|
9
|
+
atMs: number[];
|
|
10
|
+
stay: boolean;
|
|
11
|
+
sound: boolean;
|
|
12
|
+
};
|
|
13
|
+
export declare function parseNotifySchedule(tokens: readonly string[]): NotifySchedule | string;
|
|
14
|
+
export declare function validateNotifySchedule(name: string): (value: unknown) => string | null;
|
|
15
|
+
export declare function notifyScheduleDescription(level: AttentionUrgency): string;
|
|
16
|
+
export declare function formatWaited(ms: number): string;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
export const NOTIFY_LEVELS = ['urgent', 'high', 'normal', 'low'];
|
|
2
|
+
export const NOTIFY_LEVEL_KEYS = {
|
|
3
|
+
urgent: 'menubar.menu.notifyUrgent',
|
|
4
|
+
high: 'menubar.menu.notifyHigh',
|
|
5
|
+
normal: 'menubar.menu.notifyNormal',
|
|
6
|
+
low: 'menubar.menu.notifyLow',
|
|
7
|
+
};
|
|
8
|
+
export const DEFAULT_NOTIFY_SCHEDULES = {
|
|
9
|
+
urgent: ['0m', '15m', '30m', 'stay', 'sound'],
|
|
10
|
+
high: ['0m', '30m', 'stay'],
|
|
11
|
+
normal: ['5m', '1h'],
|
|
12
|
+
low: ['sidebar'],
|
|
13
|
+
};
|
|
14
|
+
const DURATION = /^(\d+)(m|h)$/;
|
|
15
|
+
export function parseNotifySchedule(tokens) {
|
|
16
|
+
if (tokens.length === 1 && tokens[0] === 'sidebar')
|
|
17
|
+
return { sidebar: true };
|
|
18
|
+
if (tokens.includes('sidebar'))
|
|
19
|
+
return '"sidebar" must be the only token.';
|
|
20
|
+
const atMs = [];
|
|
21
|
+
let stay = false;
|
|
22
|
+
let sound = false;
|
|
23
|
+
for (const token of tokens) {
|
|
24
|
+
const duration = DURATION.exec(token);
|
|
25
|
+
if (duration) {
|
|
26
|
+
const ms = Number(duration[1]) * (duration[2] === 'h' ? 3_600_000 : 60_000);
|
|
27
|
+
if (atMs.length && ms <= atMs[atMs.length - 1])
|
|
28
|
+
return `"${token}" is not later than the time before it; list the times in increasing order.`;
|
|
29
|
+
atMs.push(ms);
|
|
30
|
+
}
|
|
31
|
+
else if (token === 'stay' && !stay)
|
|
32
|
+
stay = true;
|
|
33
|
+
else if (token === 'sound' && !sound)
|
|
34
|
+
sound = true;
|
|
35
|
+
else if (token === 'stay' || token === 'sound')
|
|
36
|
+
return `"${token}" is listed twice.`;
|
|
37
|
+
else
|
|
38
|
+
return `"${token}" is not a time (5m, 1h), stay, sound or sidebar.`;
|
|
39
|
+
}
|
|
40
|
+
if (atMs.length === 0)
|
|
41
|
+
return 'list at least one time (e.g. 0m), or sidebar for no banner.';
|
|
42
|
+
return { sidebar: false, atMs, stay, sound };
|
|
43
|
+
}
|
|
44
|
+
export function validateNotifySchedule(name) {
|
|
45
|
+
return (value) => {
|
|
46
|
+
const parsed = parseNotifySchedule(value);
|
|
47
|
+
return typeof parsed === 'string' ? `${name}: ${parsed}` : null;
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export function notifyScheduleDescription(level) {
|
|
51
|
+
return (`AGI Menu: when a ${level}-urgency agent ask posts a Mac banner. Times (5m, 1h) are measured from when the ask ` +
|
|
52
|
+
'opened: the first posts the banner, each later one a reminder. Add stay to keep the banner on screen and sound ' +
|
|
53
|
+
`to play a sound, or set just sidebar for no banner. Default ${JSON.stringify(DEFAULT_NOTIFY_SCHEDULES[level])}.`);
|
|
54
|
+
}
|
|
55
|
+
export function formatWaited(ms) {
|
|
56
|
+
const minutes = Math.round(ms / 60_000);
|
|
57
|
+
if (minutes < 60)
|
|
58
|
+
return `${minutes} min`;
|
|
59
|
+
const hours = Math.floor(minutes / 60);
|
|
60
|
+
const rest = minutes % 60;
|
|
61
|
+
return rest ? `${hours} h ${rest} min` : `${hours} h`;
|
|
62
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type LinearExec } from '../quick-todo.js';
|
|
2
|
+
export declare const TICKET_PRIORITY_TTL_MS: number;
|
|
3
|
+
export declare function refreshTicketPriority(ticketId: string, nowMs: number, linear?: LinearExec): Promise<number | null>;
|
|
4
|
+
export declare function cachedTicketPriority(ticketId: string | undefined, nowMs: number, linear?: LinearExec): number | undefined;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Synchronous disk read; a miss starts one background Linear read per ticket per TTL, failures cached as null.
|
|
2
|
+
import { isRateLimited, readCached, writeCached } from '../linear-cache.js';
|
|
3
|
+
import { linearExec } from '../quick-todo.js';
|
|
4
|
+
export const TICKET_PRIORITY_TTL_MS = 30 * 60_000;
|
|
5
|
+
const inFlight = new Set();
|
|
6
|
+
function cacheKey(ticketId) {
|
|
7
|
+
return `issue-${ticketId}`;
|
|
8
|
+
}
|
|
9
|
+
export async function refreshTicketPriority(ticketId, nowMs, linear = linearExec) {
|
|
10
|
+
let priority = null;
|
|
11
|
+
try {
|
|
12
|
+
const issue = JSON.parse((await linear(['tasks', ticketId, '--json'])).stdout);
|
|
13
|
+
priority = typeof issue.priority === 'number' ? issue.priority : null;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
priority = null;
|
|
17
|
+
}
|
|
18
|
+
writeCached(cacheKey(ticketId), priority, nowMs);
|
|
19
|
+
return priority;
|
|
20
|
+
}
|
|
21
|
+
export function cachedTicketPriority(ticketId, nowMs, linear = linearExec) {
|
|
22
|
+
if (!ticketId)
|
|
23
|
+
return undefined;
|
|
24
|
+
const hit = readCached(cacheKey(ticketId), nowMs);
|
|
25
|
+
if ((!hit || hit.ageMs > TICKET_PRIORITY_TTL_MS) && !inFlight.has(ticketId) && !isRateLimited(nowMs)) {
|
|
26
|
+
inFlight.add(ticketId);
|
|
27
|
+
void refreshTicketPriority(ticketId, nowMs, linear).finally(() => inFlight.delete(ticketId));
|
|
28
|
+
}
|
|
29
|
+
return typeof hit?.value === 'number' ? hit.value : undefined;
|
|
30
|
+
}
|
package/dist/lib/feed/watch.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ interface WatchLocalFeedOptions {
|
|
|
33
33
|
}
|
|
34
34
|
export declare function watchLocalFeed(options: WatchLocalFeedOptions): Promise<void>;
|
|
35
35
|
export declare function normalizePeerEnvelope(event: FeedWatchEnvelope): FeedWatchEnvelope;
|
|
36
|
+
export declare function sharedFleetFeedHub(): FeedHub;
|
|
36
37
|
export declare function sharedLocalFeedHub(): FeedHub;
|
|
37
38
|
export declare function resetSharedLocalFeedHub(): Promise<void>;
|
|
38
39
|
export declare function subscribeSharedLocalFeed(options: {
|
package/dist/lib/feed/watch.js
CHANGED
|
@@ -8,10 +8,12 @@ import { machineId, normalizeHost } from '../machine-id.js';
|
|
|
8
8
|
import { shellQuote } from '../ssh-exec.js';
|
|
9
9
|
import { buildWindowsAgentsCommand, remoteShellFor } from '../hosts/remote-cmd.js';
|
|
10
10
|
import { getFeedDir } from '../state.js';
|
|
11
|
+
import { listProjectDefsCached } from '../projects.js';
|
|
11
12
|
import { streamFromPeer } from '../session/remote/peer-stream.js';
|
|
12
|
-
import { watchLocalSessions } from '../session/watch.js';
|
|
13
|
+
import { watchLocalSessions, withCanonicalProject } from '../session/watch.js';
|
|
13
14
|
import { readBlock, readResolution, blockIdForSession } from './feed.js';
|
|
14
15
|
import { reconcileAttention } from './attention.js';
|
|
16
|
+
import { cachedTicketPriority } from './ticket-priority.js';
|
|
15
17
|
import { ActivityStream } from './activity-stream.js';
|
|
16
18
|
import { watchToolActivity } from './tool-activity.js';
|
|
17
19
|
import { FeedWatchState } from './envelope.js';
|
|
@@ -135,6 +137,7 @@ function attentionFor(agent, pullRequest) {
|
|
|
135
137
|
block: readBlock(blockId), session: reconcilerSession(agent),
|
|
136
138
|
resolution: readResolution(blockId),
|
|
137
139
|
pullRequest, nowMs: Date.now(),
|
|
140
|
+
ticketPriority: (ticketId) => cachedTicketPriority(ticketId, Date.now()),
|
|
138
141
|
});
|
|
139
142
|
}
|
|
140
143
|
async function projectAgent(agent, gh) {
|
|
@@ -312,14 +315,35 @@ function remoteFeedWatchCommand(os) {
|
|
|
312
315
|
? buildWindowsAgentsCommand({ args })
|
|
313
316
|
: `bash -lc ${shellQuote(`agents ${args.map(shellQuote).join(' ')}`)}`;
|
|
314
317
|
}
|
|
318
|
+
function withUrgency(item) {
|
|
319
|
+
// A peer on a CLI older than PHNX-4369 sends no urgency; its asks rank as normal.
|
|
320
|
+
return item.urgency ? item : { ...item, urgency: 'normal' };
|
|
321
|
+
}
|
|
315
322
|
export function normalizePeerEnvelope(event) {
|
|
323
|
+
if (event.type === 'agent.upsert') {
|
|
324
|
+
const agent = withCanonicalProject(event.agent);
|
|
325
|
+
return agent === event.agent ? event : { ...event, agent };
|
|
326
|
+
}
|
|
327
|
+
if (event.type === 'attention.upsert') {
|
|
328
|
+
const attention = withUrgency(event.attention);
|
|
329
|
+
return attention === event.attention ? event : { ...event, attention };
|
|
330
|
+
}
|
|
316
331
|
if (event.type !== 'reset')
|
|
317
332
|
return event;
|
|
318
|
-
|
|
333
|
+
const defs = listProjectDefsCached();
|
|
334
|
+
const agents = event.agents.map((agent) => withCanonicalProject(agent, defs));
|
|
335
|
+
const attention = event.attention.map(withUrgency);
|
|
336
|
+
const renamed = agents.some((agent, i) => agent !== event.agents[i]);
|
|
337
|
+
const ranked = attention.some((item, i) => item !== event.attention[i]);
|
|
338
|
+
if (!renamed && !ranked && Array.isArray(event.tools) && Array.isArray(event.setup))
|
|
319
339
|
return event;
|
|
320
|
-
return { ...event, tools: event.tools ?? [], setup: event.setup ?? [] };
|
|
340
|
+
return { ...event, agents, attention, tools: event.tools ?? [], setup: event.setup ?? [] };
|
|
321
341
|
}
|
|
322
342
|
let sharedLocal = null;
|
|
343
|
+
let sharedFleet = null;
|
|
344
|
+
export function sharedFleetFeedHub() {
|
|
345
|
+
return sharedFleet ??= new FeedHub({ watch: watchFleetFeed });
|
|
346
|
+
}
|
|
323
347
|
export function sharedLocalFeedHub() {
|
|
324
348
|
return sharedLocal ??= new FeedHub({
|
|
325
349
|
watch: (hubOptions) => watchLocalFeed({
|
|
@@ -2,6 +2,7 @@ import type { OpenBlock, FeedAskStats } from './feed/feed.js';
|
|
|
2
2
|
import type { Classification } from './ask-classifier.js';
|
|
3
3
|
import type { ActiveSession } from './session/active.js';
|
|
4
4
|
import type { SessionMeta } from '@phnx-labs/sessions-cli/reader';
|
|
5
|
+
export declare const MAX_IDLE_MINUTES: number;
|
|
5
6
|
export interface FeedSessionSignal {
|
|
6
7
|
sessionId?: string;
|
|
7
8
|
mailboxId?: string;
|
package/dist/lib/feed-ranking.js
CHANGED
|
@@ -7,6 +7,8 @@ const RUNAWAY_TOK_PER_SEC = 250;
|
|
|
7
7
|
const RUNAWAY_BURN_USD_PER_HOUR = 25;
|
|
8
8
|
const RELAUNCH_LOOP_COUNT = 3;
|
|
9
9
|
const RELAUNCH_LOOP_WINDOW_MS = 10 * 60_000;
|
|
10
|
+
// Past a day an ask is stale, not more urgent: uncapped, a 40-day-old ask outranked every live one.
|
|
11
|
+
export const MAX_IDLE_MINUTES = 24 * 60;
|
|
10
12
|
function finiteNumber(value) {
|
|
11
13
|
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
12
14
|
}
|
|
@@ -84,7 +86,7 @@ function idleMinutes(block, nowMs) {
|
|
|
84
86
|
const ts = Date.parse(block.ts);
|
|
85
87
|
if (!Number.isFinite(ts))
|
|
86
88
|
return 0;
|
|
87
|
-
return Math.max(0, (nowMs - ts) / 60_000);
|
|
89
|
+
return Math.min(MAX_IDLE_MINUTES, Math.max(0, (nowMs - ts) / 60_000));
|
|
88
90
|
}
|
|
89
91
|
function blastRadii(blocks) {
|
|
90
92
|
const counts = new Map();
|
package/dist/lib/format.d.ts
CHANGED
|
@@ -16,9 +16,7 @@ export declare function formatBytes(n: number): string;
|
|
|
16
16
|
export declare function isPromptCancelled(err: unknown): boolean;
|
|
17
17
|
export declare function isInteractiveTerminal(): boolean;
|
|
18
18
|
export declare function parseCommaSeparatedList(value: string | undefined): string[];
|
|
19
|
-
export declare function visibleWidth(s: string): number;
|
|
20
19
|
export declare function padRight(s: string, width: number): string;
|
|
21
|
-
export declare function padVisible(s: string, width: number): string;
|
|
22
20
|
export declare function isJsonMode(opts: {
|
|
23
21
|
json?: boolean;
|
|
24
22
|
}): boolean;
|