@phnx-labs/agents-cli 1.23.28 → 1.23.30
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 +10 -0
- package/README.md +33 -82
- package/dist/bootstrap.js +0 -17
- package/dist/cli/command-registry.js +0 -2
- package/dist/commands/cloud.js +0 -58
- package/dist/commands/config.js +0 -4
- package/dist/commands/daemon-index.js +1 -1
- package/dist/commands/daemon.js +14 -63
- package/dist/commands/doctor.js +0 -12
- package/dist/commands/events.js +1 -1
- package/dist/commands/feed.d.ts +1 -3
- package/dist/commands/feed.js +1 -6
- package/dist/commands/fleet-capture.js +2 -4
- package/dist/commands/focus.d.ts +0 -1
- package/dist/commands/focus.js +2 -4
- package/dist/commands/inspect.d.ts +1 -19
- package/dist/commands/inspect.js +8 -474
- package/dist/commands/mine.js +1 -1
- package/dist/commands/prune.js +2 -64
- package/dist/commands/ps-roster.d.ts +0 -4
- package/dist/commands/ps-roster.js +2 -30
- package/dist/commands/ps.js +1 -4
- package/dist/commands/repo.d.ts +1 -1
- package/dist/commands/repo.js +4 -4
- package/dist/commands/sessions-browser.d.ts +0 -2
- package/dist/commands/sessions-browser.js +2 -32
- package/dist/commands/sessions-optimize.js +3 -4
- package/dist/commands/setup-mine.js +0 -1
- package/dist/commands/ssh.js +8 -9
- package/dist/commands/sync.js +1 -1
- package/dist/commands/update.js +2 -2
- package/dist/commands/watchdog.js +3 -4
- package/dist/lib/accounting/rotate.d.ts +0 -2
- package/dist/lib/accounting/rotate.js +1 -4
- package/dist/lib/agent-spec/agents.d.ts +0 -1
- package/dist/lib/agent-spec/agents.js +0 -8
- package/dist/lib/answer-router.d.ts +1 -1
- package/dist/lib/answer-router.js +9 -10
- package/dist/lib/auth-health.d.ts +0 -1
- package/dist/lib/auth-health.js +0 -3
- package/dist/lib/cli-entry.d.ts +0 -1
- package/dist/lib/cli-entry.js +0 -36
- package/dist/lib/cloud/types.d.ts +0 -2
- package/dist/lib/config-keys.d.ts +1 -1
- package/dist/lib/config-keys.js +1 -4
- package/dist/lib/daemon/daemon.d.ts +0 -4
- package/dist/lib/daemon/daemon.js +6 -202
- package/dist/lib/daemon/heartbeat-service.d.ts +1 -1
- package/dist/lib/daemon/heartbeat-service.js +1 -8
- package/dist/lib/daemon-services.d.ts +1 -1
- package/dist/lib/daemon-services.js +1 -11
- package/dist/lib/device-config.d.ts +0 -2
- package/dist/lib/device-config.js +4 -22
- package/dist/lib/devices/config-migration.js +1 -3
- package/dist/lib/exec.d.ts +2 -5
- package/dist/lib/exec.js +18 -18
- package/dist/lib/factory/snapshot.d.ts +0 -5
- package/dist/lib/factory/snapshot.js +1 -28
- package/dist/lib/feed/events.d.ts +1 -11
- package/dist/lib/feed/events.js +0 -20
- package/dist/lib/feed/feed.d.ts +1 -3
- package/dist/lib/feed/feed.js +18 -1
- package/dist/lib/feed-outcome.d.ts +0 -2
- package/dist/lib/feed-outcome.js +0 -5
- package/dist/lib/fleet/capture.d.ts +0 -1
- package/dist/lib/fleet/capture.js +0 -3
- package/dist/lib/fleet/manifest.js +0 -6
- package/dist/lib/fleet/types.d.ts +0 -1
- package/dist/lib/harness/adapter.d.ts +0 -7
- package/dist/lib/harness/adapters/claude.js +0 -18
- package/dist/lib/harness/adapters/codex.js +0 -10
- package/dist/lib/harness/adapters/cursor.js +0 -11
- package/dist/lib/harness/adapters/kimi.js +0 -3
- package/dist/lib/harness/adapters/muse.js +0 -11
- package/dist/lib/harness/index.d.ts +1 -1
- package/dist/lib/harness/index.js +0 -2
- package/dist/lib/hosts/passthrough.js +2 -10
- package/dist/lib/hosts/ready.d.ts +0 -4
- package/dist/lib/hosts/ready.js +0 -9
- package/dist/lib/hosts/reconcile.d.ts +0 -1
- package/dist/lib/hosts/reconcile.js +0 -8
- package/dist/lib/installations/migrate.d.ts +0 -2
- package/dist/lib/installations/migrate.js +0 -145
- package/dist/lib/loop.js +1 -2
- package/dist/lib/menubar/snapshot.d.ts +0 -1
- package/dist/lib/menubar/snapshot.js +1 -4
- package/dist/lib/placement.d.ts +1 -2
- package/dist/lib/placement.js +4 -24
- package/dist/lib/profiles.d.ts +0 -1
- package/dist/lib/profiles.js +0 -6
- package/dist/lib/session/active.d.ts +4 -3
- package/dist/lib/session/active.js +3 -4
- package/dist/lib/session/db.d.ts +7 -5
- package/dist/lib/session/db.js +11 -14
- package/dist/lib/session/discover.d.ts +3 -2
- package/dist/lib/session/discover.js +12 -129
- package/dist/lib/session/live-metadata.js +0 -2
- package/dist/lib/session/presentation.d.ts +0 -1
- package/dist/lib/session/presentation.js +3 -8
- package/dist/lib/session/selection.d.ts +0 -2
- package/dist/lib/session/selection.js +2 -12
- package/dist/lib/session/session-cache.d.ts +2 -1
- package/dist/lib/session/session-cache.js +1 -0
- package/dist/lib/session/title.d.ts +10 -0
- package/dist/lib/session/title.js +9 -0
- package/dist/lib/staleness/detectors/commands.d.ts +1 -1
- package/dist/lib/staleness/detectors/hooks.d.ts +1 -1
- package/dist/lib/staleness/detectors/mcp.d.ts +1 -1
- package/dist/lib/staleness/detectors/permissions.d.ts +1 -1
- package/dist/lib/staleness/detectors/plugins.d.ts +1 -1
- package/dist/lib/staleness/detectors/rules.d.ts +1 -1
- package/dist/lib/staleness/detectors/skills.d.ts +1 -1
- package/dist/lib/staleness/detectors/subagents.d.ts +1 -1
- package/dist/lib/staleness/detectors/workflows.d.ts +1 -1
- package/dist/lib/staleness/writers/commands.d.ts +1 -1
- package/dist/lib/staleness/writers/hooks.d.ts +1 -1
- package/dist/lib/staleness/writers/mcp.d.ts +1 -1
- package/dist/lib/staleness/writers/permissions.d.ts +1 -1
- package/dist/lib/staleness/writers/plugins.d.ts +1 -1
- package/dist/lib/staleness/writers/rules.d.ts +1 -1
- package/dist/lib/staleness/writers/skills.d.ts +1 -1
- package/dist/lib/staleness/writers/subagents.d.ts +1 -1
- package/dist/lib/staleness/writers/workflows.d.ts +1 -1
- package/dist/lib/startup/command-registry.js +5 -2
- package/dist/lib/state.d.ts +0 -3
- package/dist/lib/state.js +2 -25
- package/dist/lib/types.d.ts +0 -1
- package/dist/lib/watchdog/runner.d.ts +0 -2
- package/dist/lib/watchdog/runner.js +0 -2
- package/package.json +2 -2
- package/scripts/postinstall.js +2 -2
- package/dist/commands/routines.d.ts +0 -14
- package/dist/commands/routines.js +0 -2149
- package/dist/commands/routines.test-fixture.d.ts +0 -52
- package/dist/commands/routines.test-fixture.js +0 -254
- package/dist/lib/catchup.d.ts +0 -19
- package/dist/lib/catchup.js +0 -83
- package/dist/lib/daemon/catchup-service.d.ts +0 -18
- package/dist/lib/daemon/catchup-service.js +0 -21
- package/dist/lib/daemon/runner.d.ts +0 -91
- package/dist/lib/daemon/runner.js +0 -1927
- package/dist/lib/harness/adapters/droid.d.ts +0 -2
- package/dist/lib/harness/adapters/droid.js +0 -14
- package/dist/lib/overdue.d.ts +0 -9
- package/dist/lib/overdue.js +0 -74
- package/dist/lib/routine-activation.d.ts +0 -13
- package/dist/lib/routine-activation.js +0 -117
- package/dist/lib/routine-context.d.ts +0 -59
- package/dist/lib/routine-context.js +0 -181
- package/dist/lib/routine-notify-owner.d.ts +0 -4
- package/dist/lib/routine-notify-owner.js +0 -49
- package/dist/lib/routine-notify.d.ts +0 -17
- package/dist/lib/routine-notify.js +0 -138
- package/dist/lib/routine-process-cleanup.d.ts +0 -9
- package/dist/lib/routine-process-cleanup.js +0 -81
- package/dist/lib/routine-readiness.d.ts +0 -31
- package/dist/lib/routine-readiness.js +0 -256
- package/dist/lib/routines-format.d.ts +0 -7
- package/dist/lib/routines-format.js +0 -127
- package/dist/lib/routines-placement.d.ts +0 -16
- package/dist/lib/routines-placement.js +0 -60
- package/dist/lib/routines-project.d.ts +0 -49
- package/dist/lib/routines-project.js +0 -306
- package/dist/lib/sandbox.d.ts +0 -15
- package/dist/lib/sandbox.js +0 -309
- package/dist/lib/scheduler.d.ts +0 -23
- package/dist/lib/scheduler.js +0 -106
- package/dist/lib/scheduling/routines.d.ts +0 -264
- package/dist/lib/scheduling/routines.js +0 -1292
- package/dist/lib/triggers/webhook.d.ts +0 -26
- package/dist/lib/triggers/webhook.js +0 -181
|
@@ -201,7 +201,6 @@ export function migrateDeviceConfigStores() {
|
|
|
201
201
|
const fleetIsEmpty = Object.keys(nextDevices).length === 0 &&
|
|
202
202
|
!fleet.defaults &&
|
|
203
203
|
!fleet.secrets &&
|
|
204
|
-
!fleet.routines &&
|
|
205
204
|
!fleet.discovery &&
|
|
206
205
|
!(fleet.ignored && fleet.ignored.length > 0);
|
|
207
206
|
if (fleetIsEmpty) {
|
|
@@ -269,8 +268,7 @@ export function migrateDeviceConfigStores() {
|
|
|
269
268
|
((fleet.devices === undefined ||
|
|
270
269
|
(fleet.devices !== 'all' && Object.keys(fleet.devices).length === 0)) &&
|
|
271
270
|
!fleet.defaults &&
|
|
272
|
-
!fleet.secrets
|
|
273
|
-
!fleet.routines);
|
|
271
|
+
!fleet.secrets);
|
|
274
272
|
if (fleetEmpty) {
|
|
275
273
|
const { fleet: _drop, ...rest } = m;
|
|
276
274
|
void _drop;
|
package/dist/lib/exec.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { AgentId, Mode, RunStrategy } from './types.js';
|
|
|
2
2
|
import { type EventPayload } from './feed/events.js';
|
|
3
3
|
import { type UsernsStatus } from './linux-userns.js';
|
|
4
4
|
export type ExecMode = Mode;
|
|
5
|
+
export declare function parseTimeout(timeout: string): number | null;
|
|
5
6
|
export declare function normalizeMode(input: string | null | undefined): Mode;
|
|
6
7
|
export declare function headlessPlanStallCommand(args: {
|
|
7
8
|
prompt: string | undefined;
|
|
@@ -22,7 +23,7 @@ export declare function resolveMode(agent: AgentId, requested: Mode): Mode;
|
|
|
22
23
|
* one-line stderr warning, mirroring the graceful plan→edit degrade antigravity
|
|
23
24
|
* get for having no plan flag at all. Interactive runs are never
|
|
24
25
|
* downgraded. This is the single source of truth shared by buildExecCommand
|
|
25
|
-
* (agents run / teams)
|
|
26
|
+
* (agents run / teams).
|
|
26
27
|
*/
|
|
27
28
|
export declare function resolveHeadlessMode(agent: AgentId, requested: Mode, interactive: boolean, warningContext?: string, warningState?: ModeWarningState): Mode;
|
|
28
29
|
export interface ModeWarningState {
|
|
@@ -215,10 +216,6 @@ export declare function detectAuthFailure(text: string): boolean;
|
|
|
215
216
|
* callers pass their agent so unrelated stream formats cannot match by accident.
|
|
216
217
|
*/
|
|
217
218
|
export declare function detectAuthFailureEvent(logText: string, agent: AgentId): boolean;
|
|
218
|
-
export declare function authFailureReason(text: string): string | null;
|
|
219
|
-
export declare function isAuthFailureFromLog(logText: string, agent: AgentId, opts: {
|
|
220
|
-
processFailed: boolean;
|
|
221
|
-
}): boolean;
|
|
222
219
|
export interface FallbackEntry {
|
|
223
220
|
agent: AgentId;
|
|
224
221
|
version?: string;
|
package/dist/lib/exec.js
CHANGED
|
@@ -6,7 +6,6 @@ import * as path from 'path';
|
|
|
6
6
|
import { ALL_MODES, PEER_HOP_ENV, REMOTE_INTERACTIVE_ENV } from './types.js';
|
|
7
7
|
import { LAUNCH_LOG_ENV, markAgentStarted } from './launch-log.js';
|
|
8
8
|
import { AGENTS, agentConfigDirName, findInPath } from './agents.js';
|
|
9
|
-
import { parseTimeout } from './scheduling/routines.js';
|
|
10
9
|
import { compareVersions, getBinaryPath, getVersionHomePath, isVersionInstalled, listInstalledVersions, resolveVersion } from './installations/versions.js';
|
|
11
10
|
import { resolveModel, buildReasoningFlags } from './models.js';
|
|
12
11
|
import { isTierToken, resolveTier } from './model-tiers.js';
|
|
@@ -44,6 +43,22 @@ import { getAccountInfo } from './agents.js';
|
|
|
44
43
|
import { getUsageLookupKey, noteClaudeSessionLimit, noteClaudeOutOfCredits, clearClaudeAccountRefusal, parseClaudeSessionLimitReset, noteClaudeModelRefusal, clearClaudeModelRefusal, parseClaudeModelRefusal, claudeModelRefusalKey, } from './accounting/usage.js';
|
|
45
44
|
import { claudeProjectDirName, realCwd } from './project-key.js';
|
|
46
45
|
import { bootMark, flushBootProfile } from './boot-profile.js';
|
|
46
|
+
export function parseTimeout(timeout) {
|
|
47
|
+
const match = timeout.match(/^(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?$/);
|
|
48
|
+
if (!match)
|
|
49
|
+
return null;
|
|
50
|
+
const weeks = parseInt(match[1] || '0', 10);
|
|
51
|
+
const days = parseInt(match[2] || '0', 10);
|
|
52
|
+
const hours = parseInt(match[3] || '0', 10);
|
|
53
|
+
const minutes = parseInt(match[4] || '0', 10);
|
|
54
|
+
const ms = ((weeks * 7 + days) * 24 * 60 + hours * 60 + minutes) * 60 * 1000;
|
|
55
|
+
if (ms <= 0)
|
|
56
|
+
return null;
|
|
57
|
+
const ONE_WEEK_MS = 7 * 24 * 60 * 60 * 1000;
|
|
58
|
+
if (ms > ONE_WEEK_MS)
|
|
59
|
+
return null;
|
|
60
|
+
return ms;
|
|
61
|
+
}
|
|
47
62
|
export function normalizeMode(input) {
|
|
48
63
|
if (!input) {
|
|
49
64
|
throw new Error(`Mode is required. Use one of: ${ALL_MODES.join(', ')}.`);
|
|
@@ -92,7 +107,7 @@ export function resolveMode(agent, requested) {
|
|
|
92
107
|
* one-line stderr warning, mirroring the graceful plan→edit degrade antigravity
|
|
93
108
|
* get for having no plan flag at all. Interactive runs are never
|
|
94
109
|
* downgraded. This is the single source of truth shared by buildExecCommand
|
|
95
|
-
* (agents run / teams)
|
|
110
|
+
* (agents run / teams).
|
|
96
111
|
*/
|
|
97
112
|
export function resolveHeadlessMode(agent, requested, interactive, warningContext, warningState) {
|
|
98
113
|
const mode = resolveMode(agent, requested);
|
|
@@ -1481,7 +1496,7 @@ export function classifyCodexRunRefusal(output, exitCode, nowMs = Date.now()) {
|
|
|
1481
1496
|
/**
|
|
1482
1497
|
* Patterns that indicate an authentication failure — the agent is logged out,
|
|
1483
1498
|
* its token was revoked, or the session expired. These are the user-visible
|
|
1484
|
-
* strings a logged-out agent surfaces (observed across
|
|
1499
|
+
* strings a logged-out agent surfaces (observed across headless runs).
|
|
1485
1500
|
* Unlike a rate limit, an auth failure is NOT self-healing by failover — every
|
|
1486
1501
|
* chain entry on the same account fails identically — so it is classified
|
|
1487
1502
|
* separately and never triggers a fallback attempt.
|
|
@@ -1542,21 +1557,6 @@ export function detectAuthFailureEvent(logText, agent) {
|
|
|
1542
1557
|
}
|
|
1543
1558
|
return false;
|
|
1544
1559
|
}
|
|
1545
|
-
export function authFailureReason(text) {
|
|
1546
|
-
for (const pattern of AUTH_FAILURE_PATTERNS) {
|
|
1547
|
-
const m = text.match(pattern);
|
|
1548
|
-
if (m)
|
|
1549
|
-
return m[0];
|
|
1550
|
-
}
|
|
1551
|
-
return null;
|
|
1552
|
-
}
|
|
1553
|
-
export function isAuthFailureFromLog(logText, agent, opts) {
|
|
1554
|
-
if (detectAuthFailureEvent(logText, agent))
|
|
1555
|
-
return true;
|
|
1556
|
-
if (opts.processFailed && detectAuthFailure(logText))
|
|
1557
|
-
return true;
|
|
1558
|
-
return false;
|
|
1559
|
-
}
|
|
1560
1560
|
export function buildFallbackPrompt(prevAgent, prevSessionId, nextAgent, originalPrompt) {
|
|
1561
1561
|
if (nextAgent === 'claude' && prevSessionId) {
|
|
1562
1562
|
return `/continue ${prevSessionId}`;
|
|
@@ -126,33 +126,6 @@ export function parseDevices(payload, cached = {}) {
|
|
|
126
126
|
return { name, load, idle: row.idle === true || (load !== null && load < 20) };
|
|
127
127
|
}).filter((row) => row.name.length > 0);
|
|
128
128
|
}
|
|
129
|
-
function readRecentRuns(home, limit = 3) {
|
|
130
|
-
const root = path.join(home, '.agents', '.history', 'runs');
|
|
131
|
-
if (!fs.existsSync(root))
|
|
132
|
-
return [];
|
|
133
|
-
const found = [];
|
|
134
|
-
for (const routine of fs.readdirSync(root)) {
|
|
135
|
-
const routineDir = path.join(root, routine);
|
|
136
|
-
if (!fs.statSync(routineDir).isDirectory())
|
|
137
|
-
continue;
|
|
138
|
-
const routineRuns = [];
|
|
139
|
-
for (const run of fs.readdirSync(routineDir)) {
|
|
140
|
-
const file = path.join(routineDir, run, 'meta.json');
|
|
141
|
-
if (!fs.existsSync(file))
|
|
142
|
-
continue;
|
|
143
|
-
try {
|
|
144
|
-
const meta = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
145
|
-
const started = Date.parse(String(meta.startedAt ?? meta.createdAt ?? ''));
|
|
146
|
-
const ended = Date.parse(String(meta.finishedAt ?? meta.completedAt ?? meta.updatedAt ?? ''));
|
|
147
|
-
const duration = typeof meta.durationMs === 'number' ? meta.durationMs : Number.isFinite(started) && Number.isFinite(ended) ? ended - started : null;
|
|
148
|
-
routineRuns.push({ routine, status: String(meta.status ?? 'unknown'), durationMs: duration, mtime: fs.statSync(file).mtimeMs });
|
|
149
|
-
}
|
|
150
|
-
catch { }
|
|
151
|
-
}
|
|
152
|
-
found.push(...routineRuns.sort((a, b) => b.mtime - a.mtime).slice(0, limit));
|
|
153
|
-
}
|
|
154
|
-
return found.sort((a, b) => b.mtime - a.mtime).map(({ mtime: _, ...run }) => run);
|
|
155
|
-
}
|
|
156
129
|
function latestClaudeVerdict(entries) {
|
|
157
130
|
return Object.entries(entries)
|
|
158
131
|
.filter(([key]) => key.split(':').includes('claude'))
|
|
@@ -189,7 +162,7 @@ export async function buildFactorySnapshot(overrides = {}) {
|
|
|
189
162
|
const [sessions, queues, prs, devices] = await Promise.all([sessionsPromise, queuePromise, prsPromise, devicesPromise]);
|
|
190
163
|
return {
|
|
191
164
|
generatedAt: deps.now().toISOString(), sessions, queues, prs, devices,
|
|
192
|
-
|
|
165
|
+
auth: { claude: latestClaudeVerdict(deps.readAuth()) },
|
|
193
166
|
config: readFactoryConfig(deps.home),
|
|
194
167
|
};
|
|
195
168
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ActorKind } from '../actor.js';
|
|
2
2
|
export declare function getEventsDir(): string;
|
|
3
3
|
export type EventLevel = 'audit' | 'warn' | 'info' | 'debug';
|
|
4
|
-
export type EventType = 'agent.run.start' | 'agent.run.end' | 'agent.spawn.start' | 'agent.spawn.end' | 'run.dispatched' | 'run.launch' | 'daemon.start' | 'daemon.stop' | 'daemon.error' | 'daemon.info' | '
|
|
4
|
+
export type EventType = 'agent.run.start' | 'agent.run.end' | 'agent.spawn.start' | 'agent.spawn.end' | 'run.dispatched' | 'run.launch' | 'daemon.start' | 'daemon.stop' | 'daemon.error' | 'daemon.info' | 'watchdog.action' | 'version.install' | 'version.switch' | 'version.remove' | 'skill.install' | 'skill.remove' | 'browser.launch' | 'browser.close' | 'browser.navigate' | 'browser.screenshot' | 'computer.action' | 'secrets.get' | 'secrets.unlocked' | 'secrets.create' | 'secrets.import' | 'secrets.export' | 'secrets.view' | 'secrets.lease-denied' | 'secrets.lease-expire' | 'secrets.set' | 'secrets.delete' | 'secrets.rename' | 'cloud.dispatch' | 'cloud.complete' | 'cloud.cancel' | 'cloud.message' | 'teams.create' | 'teams.add' | 'teams.start' | 'teams.complete' | 'teams.disband' | 'hook.fire' | 'hook.complete' | 'hook.error' | 'mcp.add' | 'mcp.remove' | 'mcp.register' | 'resource.sync' | 'rotation.resolved' | 'rotation.unresolved' | 'command.start' | 'command.end' | 'perf.timing' | 'session.start' | 'session.end' | 'plan.created' | 'pr.opened' | 'pr.merged' | 'worktree.created' | 'worktree.removed' | 'commit.created' | 'pushed' | 'subagent.spawned' | 'artifact.created' | 'task.completed' | 'checklist.created' | 'status.posted' | 'file.edited' | 'factory.command' | 'factory.action' | 'factory.uri' | 'factory.launch' | 'friction' | 'error' | 'warn' | 'info' | 'debug';
|
|
5
5
|
export declare const EVENT_TYPES: readonly EventType[];
|
|
6
6
|
export declare function isEventType(value: string): value is EventType;
|
|
7
7
|
export declare function levelFor(event: EventType): EventLevel;
|
|
@@ -66,16 +66,6 @@ export declare function emitAsync(event: EventType, payload?: EventPayload, over
|
|
|
66
66
|
ts?: string;
|
|
67
67
|
}): Promise<void>;
|
|
68
68
|
export declare function emitStart(startEvent: EventType, payload?: EventPayload): (endPayload?: EventPayload) => void;
|
|
69
|
-
interface RoutineEndMeta {
|
|
70
|
-
jobName: string;
|
|
71
|
-
runId?: string;
|
|
72
|
-
status: string;
|
|
73
|
-
duration?: number;
|
|
74
|
-
exitCode?: number | null;
|
|
75
|
-
detail?: string;
|
|
76
|
-
}
|
|
77
|
-
export declare function emitRoutineEnd(meta: RoutineEndMeta): void;
|
|
78
|
-
export declare function emitRoutineEndAsync(meta: RoutineEndMeta): Promise<void>;
|
|
79
69
|
export declare function time<T>(label: string, fn: () => T, payload?: EventPayload): T;
|
|
80
70
|
export declare function createTimer(label: string, payload?: EventPayload): {
|
|
81
71
|
mark: (phase: string) => number;
|
package/dist/lib/feed/events.js
CHANGED
|
@@ -77,7 +77,6 @@ const EVENT_TYPE_TABLE = {
|
|
|
77
77
|
'run.dispatched': true,
|
|
78
78
|
'run.launch': true,
|
|
79
79
|
'daemon.start': true, 'daemon.stop': true, 'daemon.error': true, 'daemon.info': true,
|
|
80
|
-
'routine.start': true, 'routine.end': true,
|
|
81
80
|
'watchdog.action': true,
|
|
82
81
|
'version.install': true, 'version.switch': true, 'version.remove': true,
|
|
83
82
|
'skill.install': true, 'skill.remove': true,
|
|
@@ -94,8 +93,6 @@ const EVENT_TYPE_TABLE = {
|
|
|
94
93
|
'command.start': true, 'command.end': true,
|
|
95
94
|
'perf.timing': true,
|
|
96
95
|
'session.start': true, 'session.end': true,
|
|
97
|
-
'webhook.received': true, 'webhook.authorized': true, 'webhook.rejected': true, 'webhook.matched': true,
|
|
98
|
-
'webhook.fired': true, 'webhook.failed': true, 'webhook.handler.start': true, 'webhook.handler.end': true,
|
|
99
96
|
'plan.created': true, 'pr.opened': true, 'pr.merged': true, 'worktree.created': true,
|
|
100
97
|
'worktree.removed': true, 'commit.created': true, 'pushed': true, 'subagent.spawned': true,
|
|
101
98
|
'artifact.created': true, 'task.completed': true, 'checklist.created': true, 'status.posted': true,
|
|
@@ -457,23 +454,6 @@ export function emitStart(startEvent, payload = {}) {
|
|
|
457
454
|
emit(startEvent.replace('.start', '.end'), { ...payload, ...endPayload, durationMs: Date.now() - startTime });
|
|
458
455
|
};
|
|
459
456
|
}
|
|
460
|
-
function routineEndPayload(meta) {
|
|
461
|
-
return {
|
|
462
|
-
module: 'routine',
|
|
463
|
-
name: meta.jobName,
|
|
464
|
-
status: meta.status,
|
|
465
|
-
...(meta.runId ? { runId: meta.runId } : {}),
|
|
466
|
-
...(meta.duration != null ? { durationMs: meta.duration } : {}),
|
|
467
|
-
...(meta.exitCode != null ? { exitCode: meta.exitCode } : {}),
|
|
468
|
-
...(meta.detail ? { detail: meta.detail } : {}),
|
|
469
|
-
};
|
|
470
|
-
}
|
|
471
|
-
export function emitRoutineEnd(meta) {
|
|
472
|
-
emit('routine.end', routineEndPayload(meta));
|
|
473
|
-
}
|
|
474
|
-
export async function emitRoutineEndAsync(meta) {
|
|
475
|
-
await emitAsync('routine.end', routineEndPayload(meta));
|
|
476
|
-
}
|
|
477
457
|
export function time(label, fn, payload = {}) {
|
|
478
458
|
const start = Date.now();
|
|
479
459
|
try {
|
package/dist/lib/feed/feed.d.ts
CHANGED
|
@@ -45,8 +45,6 @@ export interface OpenBlock {
|
|
|
45
45
|
source?: AttentionSource;
|
|
46
46
|
state?: AttentionState;
|
|
47
47
|
sourceCursor?: SourceCursor;
|
|
48
|
-
origin?: 'cli' | 'routine';
|
|
49
|
-
routineName?: string;
|
|
50
48
|
project?: string;
|
|
51
49
|
ts: string;
|
|
52
50
|
questions: BlockQuestion[];
|
|
@@ -163,7 +161,7 @@ export declare function publishBlock(block: OpenBlock, root?: string): void;
|
|
|
163
161
|
export declare function listBlocks(root?: string): OpenBlock[];
|
|
164
162
|
export declare function listAskStats(root?: string): FeedAskStats[];
|
|
165
163
|
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 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";
|
|
164
|
+
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 \"PostToolUseFailure\",\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 in (\"PostToolUse\", \"PostToolUseFailure\"):\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 if tool_name == \"AskUserQuestion\":\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 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
165
|
export declare function ensureFeedPublishHook(userAgentsDir?: string): {
|
|
168
166
|
installed: boolean;
|
|
169
167
|
error?: string;
|
package/dist/lib/feed/feed.js
CHANGED
|
@@ -510,6 +510,7 @@ WAITING_NOTIFICATION_TYPES = {
|
|
|
510
510
|
}
|
|
511
511
|
CLEAR_EVENTS = {
|
|
512
512
|
"PostToolUse",
|
|
513
|
+
"PostToolUseFailure",
|
|
513
514
|
"Stop",
|
|
514
515
|
"SessionEnd",
|
|
515
516
|
}
|
|
@@ -590,7 +591,7 @@ def main():
|
|
|
590
591
|
return
|
|
591
592
|
except Exception:
|
|
592
593
|
pass
|
|
593
|
-
if hook_event
|
|
594
|
+
if hook_event in ("PostToolUse", "PostToolUseFailure"):
|
|
594
595
|
try:
|
|
595
596
|
with open(target) as existing_file:
|
|
596
597
|
existing = json.load(existing_file)
|
|
@@ -683,6 +684,15 @@ def main():
|
|
|
683
684
|
kind = "notification"
|
|
684
685
|
elif hook_event == "PermissionRequest":
|
|
685
686
|
tool_name = payload.get("tool_name") or "a tool"
|
|
687
|
+
if tool_name == "AskUserQuestion":
|
|
688
|
+
return
|
|
689
|
+
try:
|
|
690
|
+
with open(target) as existing_file:
|
|
691
|
+
existing = json.load(existing_file)
|
|
692
|
+
if existing.get("kind") == "question":
|
|
693
|
+
return
|
|
694
|
+
except Exception:
|
|
695
|
+
pass
|
|
686
696
|
tool_input = payload.get("tool_input", {})
|
|
687
697
|
transcript_path = str(payload.get("transcript_path") or "")
|
|
688
698
|
is_claude = "permission_suggestions" in payload or "/.claude/" in transcript_path.replace(os.sep, "/")
|
|
@@ -879,6 +889,13 @@ export function ensureFeedPublishHook(userAgentsDir = getUserAgentsDir()) {
|
|
|
879
889
|
script: '10-feed-publish.py',
|
|
880
890
|
timeout: 5,
|
|
881
891
|
},
|
|
892
|
+
'feed-clear-answered-failure': {
|
|
893
|
+
agents: ['claude'],
|
|
894
|
+
events: ['PostToolUseFailure'],
|
|
895
|
+
matcher: 'AskUserQuestion',
|
|
896
|
+
script: '10-feed-publish.py',
|
|
897
|
+
timeout: 5,
|
|
898
|
+
},
|
|
882
899
|
'feed-clear-permission': {
|
|
883
900
|
agents: ['codex'],
|
|
884
901
|
events: ['PostToolUse'],
|
|
@@ -44,8 +44,6 @@ export interface SessionOutcomeHint {
|
|
|
44
44
|
branch?: string | null;
|
|
45
45
|
project?: string | null;
|
|
46
46
|
host?: string | null;
|
|
47
|
-
origin?: 'cli' | 'routine' | null;
|
|
48
|
-
routineName?: string | null;
|
|
49
47
|
}
|
|
50
48
|
export declare function enrichBlockFromSession(block: OpenBlock, hint: SessionOutcomeHint): OpenBlock;
|
|
51
49
|
export declare function enrichBlocksFromSessions(blocks: OpenBlock[], sessions: SessionOutcomeHint[]): OpenBlock[];
|
package/dist/lib/feed-outcome.js
CHANGED
|
@@ -170,11 +170,6 @@ export function enrichBlockFromSession(block, hint) {
|
|
|
170
170
|
next.project = hint.project;
|
|
171
171
|
if (hint.host && hint.host !== 'terminal' && next.runtime === 'terminal')
|
|
172
172
|
next.runtime = hint.host;
|
|
173
|
-
if (hint.origin === 'routine') {
|
|
174
|
-
next.origin = 'routine';
|
|
175
|
-
if (hint.routineName)
|
|
176
|
-
next.routineName = hint.routineName;
|
|
177
|
-
}
|
|
178
173
|
return next;
|
|
179
174
|
}
|
|
180
175
|
export function enrichBlocksFromSessions(blocks, sessions) {
|
|
@@ -4,6 +4,5 @@ export interface CaptureInputs {
|
|
|
4
4
|
agentsByDevice?: Record<string, string[]>;
|
|
5
5
|
defaults?: FleetDefaults;
|
|
6
6
|
secretsBundles?: string[];
|
|
7
|
-
routines?: string[];
|
|
8
7
|
}
|
|
9
8
|
export declare function captureFleet(prev: FleetManifest | undefined, inputs: CaptureInputs): FleetManifest;
|
|
@@ -32,8 +32,5 @@ export function captureFleet(prev, inputs) {
|
|
|
32
32
|
const bundles = inputs.secretsBundles ?? prev?.secrets?.bundles;
|
|
33
33
|
if (bundles && bundles.length > 0)
|
|
34
34
|
manifest.secrets = { bundles: [...bundles].sort() };
|
|
35
|
-
const routines = inputs.routines ?? prev?.routines;
|
|
36
|
-
if (routines && routines.length > 0)
|
|
37
|
-
manifest.routines = [...routines].sort();
|
|
38
35
|
return manifest;
|
|
39
36
|
}
|
|
@@ -82,12 +82,6 @@ export function parseFleetManifest(raw) {
|
|
|
82
82
|
}
|
|
83
83
|
manifest.secrets = { bundles: bundles };
|
|
84
84
|
}
|
|
85
|
-
if (o.routines !== undefined) {
|
|
86
|
-
if (!isStringArray(o.routines)) {
|
|
87
|
-
throw new Error('fleet: routines must be a list of routine names.');
|
|
88
|
-
}
|
|
89
|
-
manifest.routines = o.routines;
|
|
90
|
-
}
|
|
91
85
|
return manifest;
|
|
92
86
|
}
|
|
93
87
|
export function readFleetFile(filePath) {
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { AgentId, Mode } from '../types.js';
|
|
2
|
-
import type { JobConfig } from '../scheduling/routines.js';
|
|
3
2
|
import type { ConfiguredDeviceRole } from '../device-config.js';
|
|
4
3
|
export interface ExecConfigEnvCtx {
|
|
5
4
|
agent: AgentId;
|
|
@@ -18,11 +17,6 @@ export interface ExecLaunchArgsCtx {
|
|
|
18
17
|
cwd: string;
|
|
19
18
|
addDirs: string[];
|
|
20
19
|
}
|
|
21
|
-
export interface RoutineLaunchCtx {
|
|
22
|
-
mode: Mode;
|
|
23
|
-
config: JobConfig;
|
|
24
|
-
resolveHeadlessMode: (agent: AgentId, mode: Mode, interactive: boolean) => void;
|
|
25
|
-
}
|
|
26
20
|
export interface HarnessAdapter {
|
|
27
21
|
id: AgentId;
|
|
28
22
|
applyExecConfigEnv?(result: NodeJS.ProcessEnv, ctx: ExecConfigEnvCtx): void;
|
|
@@ -31,7 +25,6 @@ export interface HarnessAdapter {
|
|
|
31
25
|
shimExecTail?(launchArgs: string): string;
|
|
32
26
|
execPreModeArgs?(ctx: ExecLaunchArgsCtx): string[] | undefined;
|
|
33
27
|
execModeArgs?(ctx: ExecLaunchArgsCtx): string[] | undefined;
|
|
34
|
-
routineModeArgs?(cmd: string[], ctx: RoutineLaunchCtx): void;
|
|
35
28
|
}
|
|
36
29
|
export declare const CONFIG_DIR_ENV_KEYS: readonly ["CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME", "KIMI_CODE_HOME", "GROK_HOME", "OPENCODE_CONFIG_DIR", "XDG_CONFIG_HOME", "XDG_DATA_HOME"];
|
|
37
30
|
export declare function stripForeignConfigDir(result: NodeJS.ProcessEnv, keep?: readonly string[]): void;
|
|
@@ -48,24 +48,6 @@ if [ "\$(uname -s)" = "Linux" ] && [ -z "\${CLAUDE_CODE_OAUTH_TOKEN:-}" ] && [ -
|
|
|
48
48
|
fi
|
|
49
49
|
`;
|
|
50
50
|
},
|
|
51
|
-
routineModeArgs(cmd, ctx) {
|
|
52
|
-
const mode = ctx.mode;
|
|
53
|
-
if (mode === 'edit') {
|
|
54
|
-
const planIndex = cmd.indexOf('plan');
|
|
55
|
-
if (planIndex !== -1)
|
|
56
|
-
cmd[planIndex] = 'acceptEdits';
|
|
57
|
-
}
|
|
58
|
-
else if (mode === 'auto') {
|
|
59
|
-
const planIndex = cmd.indexOf('plan');
|
|
60
|
-
if (planIndex !== -1)
|
|
61
|
-
cmd[planIndex] = 'auto';
|
|
62
|
-
}
|
|
63
|
-
else if (mode === 'skip') {
|
|
64
|
-
const pmIndex = cmd.indexOf('--permission-mode');
|
|
65
|
-
if (pmIndex !== -1)
|
|
66
|
-
cmd.splice(pmIndex, 2, '--dangerously-skip-permissions');
|
|
67
|
-
}
|
|
68
|
-
},
|
|
69
51
|
};
|
|
70
52
|
/**
|
|
71
53
|
* Fail-loud preflight for the worker login-screen trap — the sibling of the
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import * as os from 'os';
|
|
2
1
|
import * as path from 'path';
|
|
3
2
|
import { getHistoryDir } from '../../state.js';
|
|
4
3
|
import { codexHomeShimBash, codexShortKey, resolveCodexHome } from '../../codex-home.js';
|
|
@@ -54,13 +53,4 @@ exec "$BINARY"${launchArgs} "$@"`;
|
|
|
54
53
|
];
|
|
55
54
|
return codexPolicyArgs(ctx.resolvedMode, writableRoots);
|
|
56
55
|
},
|
|
57
|
-
routineModeArgs(cmd, ctx) {
|
|
58
|
-
const routineRoots = (ctx.config.allow?.dirs ?? []).map((dir) => {
|
|
59
|
-
if (dir.startsWith('-')) {
|
|
60
|
-
throw new Error(`allow.dirs entries must not start with '-': ${JSON.stringify(dir)}`);
|
|
61
|
-
}
|
|
62
|
-
return dir.replace(/^~/, os.homedir());
|
|
63
|
-
});
|
|
64
|
-
cmd.push(...codexPolicyArgs(ctx.mode, [...codexEditWritableRoots(), ...routineRoots]));
|
|
65
|
-
},
|
|
66
56
|
};
|
|
@@ -15,15 +15,4 @@ export const cursorAdapter = {
|
|
|
15
15
|
execModeArgs(ctx) {
|
|
16
16
|
return ctx.resolvedMode === 'plan' && !ctx.interactive ? ['--mode', 'ask'] : undefined;
|
|
17
17
|
},
|
|
18
|
-
routineModeArgs(cmd, ctx) {
|
|
19
|
-
if (ctx.mode === 'plan') {
|
|
20
|
-
cmd.push('--mode', 'ask', '--trust');
|
|
21
|
-
}
|
|
22
|
-
else if (ctx.mode === 'skip') {
|
|
23
|
-
cmd.push('-f');
|
|
24
|
-
}
|
|
25
|
-
else {
|
|
26
|
-
cmd.push('--trust');
|
|
27
|
-
}
|
|
28
|
-
},
|
|
29
18
|
};
|
|
@@ -22,15 +22,4 @@ export const museAdapter = {
|
|
|
22
22
|
${slotAwareConfigEnvBash([{ env: 'XDG_CONFIG_HOME', rel: '.config' }, { env: 'XDG_DATA_HOME', rel: '.local/share' }], '$VERSION_DIR/home')}
|
|
23
23
|
`;
|
|
24
24
|
},
|
|
25
|
-
routineModeArgs(cmd, ctx) {
|
|
26
|
-
if (ctx.mode === 'plan') {
|
|
27
|
-
cmd.push('--disable-write');
|
|
28
|
-
}
|
|
29
|
-
else if (ctx.mode === 'auto') {
|
|
30
|
-
cmd.push('--disable-approval');
|
|
31
|
-
}
|
|
32
|
-
else if (ctx.mode === 'skip') {
|
|
33
|
-
cmd.push('--yolo');
|
|
34
|
-
}
|
|
35
|
-
},
|
|
36
25
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { type HarnessAdapter, type ExecConfigEnvCtx, type ShimConfigEnvCtx, type ExecLaunchArgsCtx,
|
|
1
|
+
export { type HarnessAdapter, type ExecConfigEnvCtx, type ShimConfigEnvCtx, type ExecLaunchArgsCtx, CONFIG_DIR_ENV_KEYS, stripForeignConfigDir, registerHarnessAdapter, resolveHarnessAdapter, listHarnessAdapters, } from './adapter.js';
|
|
@@ -7,7 +7,6 @@ import { museAdapter } from './adapters/muse.js';
|
|
|
7
7
|
import { cursorAdapter } from './adapters/cursor.js';
|
|
8
8
|
import { grokAdapter } from './adapters/grok.js';
|
|
9
9
|
import { opencodeAdapter } from './adapters/opencode.js';
|
|
10
|
-
import { droidAdapter } from './adapters/droid.js';
|
|
11
10
|
for (const adapter of [
|
|
12
11
|
claudeAdapter,
|
|
13
12
|
codexAdapter,
|
|
@@ -17,7 +16,6 @@ for (const adapter of [
|
|
|
17
16
|
cursorAdapter,
|
|
18
17
|
grokAdapter,
|
|
19
18
|
opencodeAdapter,
|
|
20
|
-
droidAdapter,
|
|
21
19
|
]) {
|
|
22
20
|
registerHarnessAdapter(adapter);
|
|
23
21
|
}
|
|
@@ -51,9 +51,6 @@ export const REMOTE_PASSTHROUGH = {
|
|
|
51
51
|
update: {},
|
|
52
52
|
teams: {},
|
|
53
53
|
send: {},
|
|
54
|
-
routines: {},
|
|
55
|
-
jobs: {},
|
|
56
|
-
cron: {},
|
|
57
54
|
prune: {},
|
|
58
55
|
restore: {},
|
|
59
56
|
worktree: {},
|
|
@@ -344,13 +341,8 @@ export async function maybeRunOnHost(command, allArgs, opts) {
|
|
|
344
341
|
}
|
|
345
342
|
if (allArgs.includes('--hosts') && hostsFlag?.toLowerCase() !== 'all')
|
|
346
343
|
return false;
|
|
347
|
-
if (allArgs.includes('--devices'))
|
|
348
|
-
|
|
349
|
-
return false;
|
|
350
|
-
const isAll = devicesFlag.toLowerCase() === 'all';
|
|
351
|
-
if (!isAll && command !== 'routines')
|
|
352
|
-
return false;
|
|
353
|
-
}
|
|
344
|
+
if (allArgs.includes('--devices') && devicesFlag?.toLowerCase() !== 'all')
|
|
345
|
+
return false;
|
|
354
346
|
if (!isKnownTopLevelCommand(command))
|
|
355
347
|
return false;
|
|
356
348
|
const spec = REMOTE_PASSTHROUGH[command];
|
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
import type { Host } from './types.js';
|
|
2
2
|
export declare function localCliVersion(): string | null;
|
|
3
3
|
export declare function buildProbeCommand(os?: string): string;
|
|
4
|
-
export declare function probeHost(target: string, os?: string, extraSshArgs?: string[]): {
|
|
5
|
-
reachable: boolean;
|
|
6
|
-
os?: string;
|
|
7
|
-
};
|
|
8
4
|
export declare function buildRemoteVersionCommand(os?: string): string;
|
|
9
5
|
export declare function buildBootstrapCommand(spec: string, os?: string): string;
|
|
10
6
|
export declare function bootstrapAgentsCli(target: string, version: string | null, os?: string, extraSshArgs?: string[]): {
|
package/dist/lib/hosts/ready.js
CHANGED
|
@@ -31,15 +31,6 @@ export function buildProbeCommand(os) {
|
|
|
31
31
|
}
|
|
32
32
|
return 'uname -s 2>/dev/null || echo unknown';
|
|
33
33
|
}
|
|
34
|
-
export function probeHost(target, os, extraSshArgs = []) {
|
|
35
|
-
const r = sshExec(target, buildProbeCommand(os), { timeoutMs: 12000, extraSshArgs });
|
|
36
|
-
if (r.code !== 0)
|
|
37
|
-
return { reachable: false };
|
|
38
|
-
if (remoteShellFor(os) === 'powershell')
|
|
39
|
-
return { reachable: true, os };
|
|
40
|
-
const uname = r.stdout.trim();
|
|
41
|
-
return { reachable: true, os: uname && uname !== 'unknown' ? uname : undefined };
|
|
42
|
-
}
|
|
43
34
|
export function buildRemoteVersionCommand(os) {
|
|
44
35
|
return remoteShellFor(os) === 'powershell'
|
|
45
36
|
? buildWindowsAgentsCommand({ args: ['--version'] })
|