@phnx-labs/agents-cli 1.23.13 → 1.23.15

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.
Files changed (164) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +30 -59
  3. package/dist/cli/command-registry.js +0 -24
  4. package/dist/commands/accounts.js +3 -3
  5. package/dist/commands/daemon.js +5 -147
  6. package/dist/commands/doctor.js +7 -0
  7. package/dist/commands/events-logs.d.ts +2 -0
  8. package/dist/commands/{logs.js → events-logs.js} +28 -127
  9. package/dist/commands/events.js +3 -1
  10. package/dist/commands/exec.d.ts +0 -1
  11. package/dist/commands/exec.js +3 -11
  12. package/dist/commands/feed.d.ts +1 -1
  13. package/dist/commands/feed.js +4 -7
  14. package/dist/commands/mcp.js +1 -1
  15. package/dist/commands/menubar.js +12 -226
  16. package/dist/commands/projects.js +1 -2
  17. package/dist/commands/{trash.d.ts → prune-trash.d.ts} +1 -1
  18. package/dist/commands/{trash.js → prune-trash.js} +8 -8
  19. package/dist/commands/prune.js +3 -1
  20. package/dist/commands/send.js +2 -5
  21. package/dist/commands/sessions.js +1 -1
  22. package/dist/commands/ssh.js +2 -2
  23. package/dist/commands/utils.d.ts +1 -5
  24. package/dist/commands/utils.js +1 -7
  25. package/dist/lib/agent-spec/agents.d.ts +0 -2
  26. package/dist/lib/agent-spec/agents.js +0 -12
  27. package/dist/lib/agent-spec/index.d.ts +0 -4
  28. package/dist/lib/agent-spec/index.js +0 -4
  29. package/dist/lib/commands.d.ts +1 -5
  30. package/dist/lib/commands.js +2 -69
  31. package/dist/lib/comms-render.d.ts +0 -7
  32. package/dist/lib/comms-render.js +0 -41
  33. package/dist/lib/config-keys.d.ts +1 -1
  34. package/dist/lib/config-keys.js +8 -0
  35. package/dist/lib/daemon/daemon.js +1 -6
  36. package/dist/lib/daemon-services.d.ts +1 -1
  37. package/dist/lib/daemon-services.js +0 -5
  38. package/dist/lib/device-config.d.ts +2 -0
  39. package/dist/lib/device-config.js +81 -8
  40. package/dist/lib/devices/doctor-findings.d.ts +6 -1
  41. package/dist/lib/devices/doctor-findings.js +34 -1
  42. package/dist/lib/git.d.ts +1 -0
  43. package/dist/lib/git.js +5 -0
  44. package/dist/lib/hooks/install.d.ts +0 -7
  45. package/dist/lib/hooks/install.js +0 -55
  46. package/dist/lib/hosts/passthrough.js +2 -4
  47. package/dist/lib/hosts/progress.js +2 -2
  48. package/dist/lib/hosts/remote-cmd.js +0 -1
  49. package/dist/lib/installations/migrate.d.ts +1 -0
  50. package/dist/lib/installations/migrate.js +18 -1
  51. package/dist/lib/installations/versions.js +2 -2
  52. package/dist/lib/loop.js +1 -1
  53. package/dist/lib/mailbox-target.d.ts +0 -31
  54. package/dist/lib/mailbox-target.js +0 -37
  55. package/dist/lib/mcp-lookup.d.ts +7 -0
  56. package/dist/lib/mcp-lookup.js +71 -0
  57. package/dist/lib/mcp.d.ts +0 -8
  58. package/dist/lib/mcp.js +0 -47
  59. package/dist/lib/menubar/install-menubar.d.ts +0 -15
  60. package/dist/lib/menubar/install-menubar.js +24 -118
  61. package/dist/lib/menubar/resolve-version.d.ts +9 -10
  62. package/dist/lib/menubar/resolve-version.js +70 -30
  63. package/dist/lib/paths.d.ts +0 -1
  64. package/dist/lib/paths.js +0 -18
  65. package/dist/lib/plugins/skills.d.ts +0 -10
  66. package/dist/lib/plugins/skills.js +2 -165
  67. package/dist/lib/project-pull.js +1 -2
  68. package/dist/lib/resources.d.ts +1 -1
  69. package/dist/lib/routines-project.js +1 -1
  70. package/dist/lib/session/local-tmux-attach.js +2 -2
  71. package/dist/lib/startup/command-registry.js +20 -7
  72. package/dist/lib/teams/agents.js +1 -1
  73. package/dist/lib/teams/placement-probe.d.ts +9 -0
  74. package/dist/lib/teams/placement-probe.js +20 -15
  75. package/dist/lib/triggers/webhook.d.ts +2 -59
  76. package/dist/lib/triggers/webhook.js +2 -422
  77. package/package.json +2 -1
  78. package/dist/commands/funnel.d.ts +0 -2
  79. package/dist/commands/funnel.js +0 -77
  80. package/dist/commands/logs.d.ts +0 -2
  81. package/dist/commands/mailboxes.d.ts +0 -2
  82. package/dist/commands/mailboxes.js +0 -400
  83. package/dist/commands/message.d.ts +0 -2
  84. package/dist/commands/message.js +0 -259
  85. package/dist/commands/packages-materialize.d.ts +0 -6
  86. package/dist/commands/packages-materialize.js +0 -90
  87. package/dist/commands/packages.d.ts +0 -5
  88. package/dist/commands/packages.js +0 -763
  89. package/dist/commands/route.d.ts +0 -2
  90. package/dist/commands/route.js +0 -259
  91. package/dist/commands/testdata/feed-hub.d.ts +0 -1
  92. package/dist/commands/testdata/feed-hub.js +0 -11
  93. package/dist/commands/tmux.d.ts +0 -7
  94. package/dist/commands/tmux.js +0 -529
  95. package/dist/commands/traces.d.ts +0 -2
  96. package/dist/commands/traces.js +0 -204
  97. package/dist/commands/webhook.d.ts +0 -5
  98. package/dist/commands/webhook.js +0 -105
  99. package/dist/lib/agent-spec/materialize.d.ts +0 -3
  100. package/dist/lib/agent-spec/materialize.js +0 -277
  101. package/dist/lib/agent-spec/package-resolve.d.ts +0 -4
  102. package/dist/lib/agent-spec/package-resolve.js +0 -231
  103. package/dist/lib/agent-spec/package-schema.d.ts +0 -3
  104. package/dist/lib/agent-spec/package-schema.js +0 -136
  105. package/dist/lib/agent-spec/package-types.d.ts +0 -94
  106. package/dist/lib/agent-spec/package-types.js +0 -10
  107. package/dist/lib/daemon/testdata/process-view-daemon.d.ts +0 -1
  108. package/dist/lib/daemon/testdata/process-view-daemon.js +0 -12
  109. package/dist/lib/daemon/testdata/process-view-start.d.ts +0 -1
  110. package/dist/lib/daemon/testdata/process-view-start.js +0 -41
  111. package/dist/lib/daemon/webhook-receiver-service.d.ts +0 -8
  112. package/dist/lib/daemon/webhook-receiver-service.js +0 -16
  113. package/dist/lib/daemon-webhooks.d.ts +0 -48
  114. package/dist/lib/daemon-webhooks.js +0 -177
  115. package/dist/lib/funnel.d.ts +0 -6
  116. package/dist/lib/funnel.js +0 -31
  117. package/dist/lib/net-close.d.ts +0 -2
  118. package/dist/lib/net-close.js +0 -20
  119. package/dist/lib/packages/output-home.d.ts +0 -9
  120. package/dist/lib/packages/output-home.js +0 -89
  121. package/dist/lib/registry.d.ts +0 -65
  122. package/dist/lib/registry.js +0 -432
  123. package/dist/lib/routers.d.ts +0 -25
  124. package/dist/lib/routers.js +0 -122
  125. package/dist/lib/run-trace-sync.d.ts +0 -7
  126. package/dist/lib/run-trace-sync.js +0 -35
  127. package/dist/lib/session/testdata/pid-registry-namespace.d.ts +0 -1
  128. package/dist/lib/session/testdata/pid-registry-namespace.js +0 -25
  129. package/dist/lib/session/testdata/process-view-namespace.d.ts +0 -1
  130. package/dist/lib/session/testdata/process-view-namespace.js +0 -56
  131. package/dist/lib/session/testdata/process-view-private.d.ts +0 -1
  132. package/dist/lib/session/testdata/process-view-private.js +0 -11
  133. package/dist/lib/testdata/daemon-health-writer.d.ts +0 -1
  134. package/dist/lib/testdata/daemon-health-writer.js +0 -8
  135. package/dist/lib/testdata/owner-notify-api.d.ts +0 -23
  136. package/dist/lib/testdata/owner-notify-api.js +0 -82
  137. package/dist/lib/testdata/refresh-coordinator-worker.d.ts +0 -1
  138. package/dist/lib/testdata/refresh-coordinator-worker.js +0 -23
  139. package/dist/lib/traces/backend.d.ts +0 -8
  140. package/dist/lib/traces/backend.js +0 -33
  141. package/dist/lib/traces/classify.d.ts +0 -40
  142. package/dist/lib/traces/classify.js +0 -70
  143. package/dist/lib/traces/config.d.ts +0 -2
  144. package/dist/lib/traces/config.js +0 -2
  145. package/dist/lib/traces/insights.d.ts +0 -30
  146. package/dist/lib/traces/insights.js +0 -198
  147. package/dist/lib/traces/phenotype.d.ts +0 -18
  148. package/dist/lib/traces/phenotype.js +0 -335
  149. package/dist/lib/traces/provision.d.ts +0 -16
  150. package/dist/lib/traces/provision.js +0 -25
  151. package/dist/lib/traces/schema2-build.d.ts +0 -28
  152. package/dist/lib/traces/schema2-build.js +0 -496
  153. package/dist/lib/traces/schema2-danger.d.ts +0 -7
  154. package/dist/lib/traces/schema2-danger.js +0 -123
  155. package/dist/lib/traces/schema2.d.ts +0 -139
  156. package/dist/lib/traces/schema2.js +0 -20
  157. package/dist/lib/traces/segments.d.ts +0 -73
  158. package/dist/lib/traces/segments.js +0 -236
  159. package/dist/lib/traces/sync.d.ts +0 -197
  160. package/dist/lib/traces/sync.js +0 -654
  161. package/dist/lib/traces/worker-template.d.ts +0 -1
  162. package/dist/lib/traces/worker-template.js +0 -292
  163. package/dist/lib/triggers/handlers.d.ts +0 -66
  164. package/dist/lib/triggers/handlers.js +0 -383
@@ -1,204 +0,0 @@
1
- import chalk from 'chalk';
2
- import { setHelpSections } from '../lib/help.js';
3
- import { readSyncLedger, syncTraces } from '../lib/traces/sync.js';
4
- import { managedTracesBaseUrl, resolveTracesBackend } from '../lib/traces/backend.js';
5
- import { showUrl } from '../lib/open-url.js';
6
- import { DEFAULT_CF_BUNDLE, readCloudflareCreds } from '../lib/cloudflare/creds.js';
7
- import { PHOENIX_ID_BASE } from '../lib/identity/client.js';
8
- import { DEFAULT_BUCKET_NAME, DEFAULT_WORKER_NAME } from '../lib/traces/config.js';
9
- import { DEFAULT_TRACES_DOMAIN } from '../lib/traces/backend.js';
10
- import { provisionTraces } from '../lib/traces/provision.js';
11
- const SYNC_EXAMPLES = `
12
- $ agents traces sync
13
- Push this device's derived, redacted trajectories to your Phoenix account.
14
-
15
- $ agents traces sync --limit 20
16
- Sync at most 20 sessions (useful for a first run on a large fleet device).
17
-
18
- $ agents traces sync --dry-run --out ./trace-preview
19
- Compute the shards from your real sessions.db and WRITE them locally — no
20
- Phoenix sign-in, no worker, no upload. Point a console at ./trace-preview to
21
- see your real trajectories before wiring the hosted path.
22
- `.trimStart();
23
- const SYNC_NOTES = `
24
- Reads from the local sessions.db, computes a derived SessionTrajectory (steps +
25
- gaps + stats, no raw transcript text), redacts secrets, and PUTs each to
26
- the agents-traces store.
27
-
28
- An incremental gate (traces-sync.json ledger) means re-runs only upload
29
- sessions whose file_mtime_ms changed since the last sync.
30
-
31
- On a real (non-dry-run) sync with the managed Phoenix backend, also
32
- fire-and-forget registers this session with Prix (api.prix.dev) so the
33
- console can serve live trajectories — a link failure never blocks sync.
34
-
35
- Sign in first with: agents auth login
36
- `.trimStart();
37
- const STATUS_EXAMPLES = `
38
- $ agents traces status
39
- Show what's been synced — session count and last sync time for this device.
40
- `.trimStart();
41
- const OPEN_EXAMPLES = `
42
- $ agents traces open
43
- Open the Phoenix Evals console for your account.
44
- `.trimStart();
45
- const SETUP_EXAMPLES = `
46
- $ agents traces setup
47
- Provision the private agents-traces Worker, R2 bucket, and managed domain.
48
-
49
- $ agents traces setup --account <id> --token <token>
50
- Provision non-interactively with explicit Cloudflare credentials.
51
- `.trimStart();
52
- async function handleSync(opts) {
53
- const limit = opts.limit !== undefined ? parseInt(opts.limit, 10) : undefined;
54
- const dryRun = opts.dryRun === true;
55
- if (dryRun && !opts.out) {
56
- console.error(chalk.red('traces sync --dry-run requires --out <dir>'));
57
- process.exitCode = 1;
58
- return;
59
- }
60
- if (!dryRun) {
61
- try {
62
- resolveTracesBackend();
63
- }
64
- catch (err) {
65
- console.error(chalk.red(err.message));
66
- process.exitCode = 1;
67
- return;
68
- }
69
- }
70
- console.log(chalk.dim(dryRun ? `Computing traces locally → ${opts.out}` : 'Syncing traces…'));
71
- let result;
72
- try {
73
- result = await syncTraces({ limit, dryRun, outDir: opts.out });
74
- }
75
- catch (err) {
76
- console.error(chalk.red(`Sync failed: ${err.message}`));
77
- process.exitCode = 1;
78
- return;
79
- }
80
- const parts = [];
81
- if (result.uploaded > 0) {
82
- parts.push(chalk.green(`${result.uploaded} ${dryRun ? 'written' : 'uploaded'}`));
83
- }
84
- if (result.skipped > 0) {
85
- parts.push(chalk.dim(`${result.skipped} skipped`));
86
- }
87
- if (result.errors > 0) {
88
- const detail = [];
89
- if (result.transcriptUnavailable > 0) {
90
- detail.push(`${result.transcriptUnavailable} transcripts no longer on disk`);
91
- }
92
- const retryable = result.parseFailed + result.uploadFailed;
93
- if (retryable > 0) {
94
- detail.push(`${retryable} parse/upload failures — will retry`);
95
- }
96
- parts.push(chalk.yellow(`${result.errors} errors`) +
97
- (detail.length ? chalk.dim(` (${detail.join(' · ')})`) : ''));
98
- }
99
- if (parts.length === 0) {
100
- parts.push(chalk.dim('nothing new'));
101
- }
102
- console.log(parts.join(chalk.dim(' · ')));
103
- if (result.indexError) {
104
- console.log(chalk.yellow(' ⚠ console index not refreshed') +
105
- chalk.dim(` (${result.indexError}) — dashboard may be stale; it will retry next sync`));
106
- }
107
- }
108
- async function handleStatus() {
109
- const ledger = readSyncLedger();
110
- if (!ledger.lastSyncMtime) {
111
- console.log(chalk.dim('No sync recorded on this device. Run: agents traces sync'));
112
- return;
113
- }
114
- const when = new Date(ledger.lastSyncMtime).toLocaleString();
115
- console.log(`Last sync: ${chalk.bold(when)}`);
116
- const failures = ledger.failures ?? [];
117
- if (failures.length > 0) {
118
- const byKind = new Map();
119
- for (const f of failures) {
120
- const list = byKind.get(f.kind) ?? [];
121
- list.push(f);
122
- byKind.set(f.kind, list);
123
- }
124
- console.log(chalk.yellow(`\n${failures.length} unresolved failure${failures.length === 1 ? '' : 's'}:`));
125
- for (const [kind, list] of byKind) {
126
- const retry = kind === 'transcript-unavailable' ? chalk.dim(' (not retried)') : chalk.dim(' (retried each sync)');
127
- console.log(` ${chalk.bold(list.length)} ${kind}${retry}`);
128
- const example = list[0];
129
- if (example?.detail) {
130
- console.log(chalk.dim(` e.g. ${example.id.slice(0, 8)} · ${example.detail}`));
131
- }
132
- }
133
- }
134
- console.log(chalk.dim('\nRun `agents traces sync` to push new sessions.'));
135
- }
136
- async function handleOpen() {
137
- const url = managedTracesBaseUrl();
138
- console.log(chalk.dim(`Opening ${url}`));
139
- const outcome = await showUrl(url);
140
- if (outcome.via === 'none') {
141
- console.log(url);
142
- }
143
- }
144
- async function handleSetup(opts) {
145
- const { input } = await import('@inquirer/prompts');
146
- const { apiToken, accountId: bundledAccountId } = readCloudflareCreds(opts.bundle, {
147
- apiToken: opts.token,
148
- accountId: opts.account,
149
- });
150
- const accountId = opts.account ?? bundledAccountId ?? await input({ message: 'Cloudflare account id' });
151
- if (!accountId)
152
- throw new Error('A Cloudflare account id is required.');
153
- const result = await provisionTraces({
154
- apiToken,
155
- accountId,
156
- workerName: opts.worker,
157
- bucketName: opts.bucket,
158
- domain: opts.domain,
159
- phoenixIdBase: PHOENIX_ID_BASE,
160
- });
161
- console.log(chalk.green(`Traces endpoint ready → ${chalk.bold(result.baseUrl)}`));
162
- }
163
- export function registerTracesCommands(program) {
164
- const tracesCmd = program
165
- .command('traces')
166
- .description("Sync this device's derived, redacted trajectories to your Phoenix account");
167
- const setupCmd = tracesCmd
168
- .command('setup')
169
- .description('(advanced) Provision a self-hosted Cloudflare Worker + R2 bucket for traces — NOT required; `agents auth login` syncs to the managed endpoint with zero setup')
170
- .option('--bundle <name>', 'secrets bundle holding the Cloudflare API token', DEFAULT_CF_BUNDLE)
171
- .option('--worker <name>', 'Worker name', DEFAULT_WORKER_NAME)
172
- .option('--bucket <name>', 'R2 bucket name', DEFAULT_BUCKET_NAME)
173
- .option('--account <id>', 'Cloudflare account id (else read from the bundle / prompt)')
174
- .option('--token <token>', 'Cloudflare API token (else read from the --bundle)')
175
- .option('--domain <host>', 'custom domain to map', DEFAULT_TRACES_DOMAIN)
176
- .action(async (opts) => {
177
- try {
178
- await handleSetup(opts);
179
- }
180
- catch (err) {
181
- console.error(chalk.red(err.message));
182
- process.exitCode = 1;
183
- }
184
- });
185
- setHelpSections(setupCmd, { examples: SETUP_EXAMPLES });
186
- const syncCmd = tracesCmd
187
- .command('sync')
188
- .description('Push derived, redacted trajectories (incremental)')
189
- .option('--limit <n>', 'Maximum number of sessions to sync in this run')
190
- .option('--dry-run', 'Compute the shards from real sessions.db and WRITE them locally (no auth, no upload)')
191
- .option('--out <dir>', 'Directory to write index.json + sessions/<id>.json (required with --dry-run)')
192
- .action(handleSync);
193
- setHelpSections(syncCmd, { examples: SYNC_EXAMPLES, notes: SYNC_NOTES });
194
- const statusCmd = tracesCmd
195
- .command('status')
196
- .description('Show last sync time for this device')
197
- .action(handleStatus);
198
- setHelpSections(statusCmd, { examples: STATUS_EXAMPLES });
199
- const openCmd = tracesCmd
200
- .command('open')
201
- .description('Open the Phoenix Evals console')
202
- .action(handleOpen);
203
- setHelpSections(openCmd, { examples: OPEN_EXAMPLES });
204
- }
@@ -1,5 +0,0 @@
1
- import type { Command } from 'commander';
2
- import type { Server } from 'http';
3
- import type { Socket } from 'net';
4
- export declare function closeWebhookServer(server: Server, sockets: Set<Socket>): Promise<void>;
5
- export declare function registerWebhooksCommand(program: Command): void;
@@ -1,105 +0,0 @@
1
- import * as path from 'path';
2
- import chalk from 'chalk';
3
- import { readAndResolveBundleEnv } from '../lib/secrets-client.js';
4
- import { closeServerBounded } from '../lib/net-close.js';
5
- import { createFileDeliveryStore, startWebhookServer, waitForListening } from '../lib/triggers/webhook.js';
6
- import { getRuntimeStateDir } from '../lib/state.js';
7
- const DEFAULT_HOST = '127.0.0.1';
8
- const DEFAULT_PORT = 8787;
9
- function positiveInt(value, fallback) {
10
- const parsed = Number.parseInt(value ?? '', 10);
11
- return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
12
- }
13
- async function readWebhookSecrets(bundleName) {
14
- const { env } = await readAndResolveBundleEnv(bundleName, {
15
- caller: 'webhooks serve',
16
- agentOnly: true,
17
- });
18
- const secrets = {};
19
- if (env.GITHUB_WEBHOOK_SECRET)
20
- secrets.github = env.GITHUB_WEBHOOK_SECRET;
21
- if (env.LINEAR_WEBHOOK_SECRET)
22
- secrets.linear = env.LINEAR_WEBHOOK_SECRET;
23
- if (env.SLACK_SIGNING_SECRET)
24
- secrets.slack = env.SLACK_SIGNING_SECRET;
25
- if (!secrets.github && !secrets.linear && !secrets.slack) {
26
- throw new Error(`Bundle '${bundleName}' must contain GITHUB_WEBHOOK_SECRET, LINEAR_WEBHOOK_SECRET, or SLACK_SIGNING_SECRET.`);
27
- }
28
- return secrets;
29
- }
30
- export async function closeWebhookServer(server, sockets) {
31
- const closing = closeServerBounded(server);
32
- for (const socket of sockets)
33
- socket.destroy();
34
- await closing;
35
- }
36
- export function registerWebhooksCommand(program) {
37
- const webhooks = program
38
- .command('webhooks')
39
- .description('Run a localhost signed webhook receiver for routine triggers.');
40
- webhooks
41
- .command('serve')
42
- .description('Receive signed GitHub/Linear/Slack webhooks on /hooks/<source> and fire matching routines and handlers.')
43
- .requiredOption('--secrets-bundle <name>', 'agents secrets bundle containing GITHUB_WEBHOOK_SECRET, LINEAR_WEBHOOK_SECRET, and/or SLACK_SIGNING_SECRET')
44
- .option('--bind <addr>', `Bind address (default ${DEFAULT_HOST})`, DEFAULT_HOST)
45
- .option('-p, --port <n>', `Local port (default ${DEFAULT_PORT})`, String(DEFAULT_PORT))
46
- .option('--rate-limit <n>', 'Accepted deliveries per source per minute', '60')
47
- .action(async (opts) => {
48
- let secrets;
49
- try {
50
- secrets = await readWebhookSecrets(opts.secretsBundle);
51
- }
52
- catch (err) {
53
- console.error(chalk.red(err.message));
54
- process.exit(1);
55
- }
56
- const port = positiveInt(opts.port, DEFAULT_PORT);
57
- const rateLimit = positiveInt(opts.rateLimit, 60);
58
- try {
59
- const server = startWebhookServer({
60
- host: opts.bind ?? DEFAULT_HOST,
61
- port,
62
- secrets,
63
- rateLimitPerMinute: rateLimit,
64
- deliveryStore: createFileDeliveryStore(path.join(getRuntimeStateDir(), 'webhook', 'deliveries.json')),
65
- onMatch: (webhook, matchedJobNames, matchedHandlerNames) => {
66
- const parts = [];
67
- if (matchedJobNames.length)
68
- parts.push(`routines ${matchedJobNames.join(', ')}`);
69
- if (matchedHandlerNames.length)
70
- parts.push(`handlers ${matchedHandlerNames.join(', ')}`);
71
- console.log(`${new Date().toISOString()} ${webhook.source}:${webhook.event} ` +
72
- (parts.length ? `fired ${parts.join('; ')}` : 'no match'));
73
- },
74
- onDeliveryError: (webhook, err) => {
75
- console.error(chalk.red(`${new Date().toISOString()} ${webhook.source}:${webhook.event} dispatch failed after ack: ${err.message}`));
76
- },
77
- });
78
- const sockets = new Set();
79
- server.on('connection', (socket) => {
80
- sockets.add(socket);
81
- socket.once('close', () => sockets.delete(socket));
82
- });
83
- await waitForListening(server);
84
- const address = server.address();
85
- const bound = typeof address === 'object' && address ? address.port : port;
86
- console.log(`${chalk.green('agents webhooks')} ${chalk.dim('→')} ${chalk.cyan(`http://${opts.bind ?? DEFAULT_HOST}:${bound}`)}`);
87
- console.log(chalk.dim('signed · localhost by default · endpoints: /hooks/github, /hooks/linear, /hooks/slack · acks 202 then dispatches · Ctrl-C to stop'));
88
- console.log(chalk.dim('for a supervised receiver that survives reboot: agents daemon webhooks add --secrets-bundle <name>'));
89
- let shuttingDown = false;
90
- const shutdown = async () => {
91
- if (shuttingDown)
92
- return;
93
- shuttingDown = true;
94
- await closeWebhookServer(server, sockets);
95
- process.exit(0);
96
- };
97
- process.on('SIGINT', () => { void shutdown(); });
98
- process.on('SIGTERM', () => { void shutdown(); });
99
- }
100
- catch (err) {
101
- console.error(chalk.red(`Could not start webhook receiver: ${err.message}`));
102
- process.exit(1);
103
- }
104
- });
105
- }
@@ -1,3 +0,0 @@
1
- import type { MaterializationReceipt, MaterializeOptions, ResolvedAgentPackage } from './package-types.js';
2
- export declare function materializeAgentPackage(resolved: ResolvedAgentPackage, options: MaterializeOptions): MaterializationReceipt;
3
- export declare function sha256OfReceiptFile(receiptPath: string): string;
@@ -1,277 +0,0 @@
1
- import * as crypto from 'crypto';
2
- import * as fs from 'fs';
3
- import * as path from 'path';
4
- import { supports } from '../capabilities.js';
5
- import { AGENTS, agentConfigDirName, getMcpConfigPathForHome } from './agents.js';
6
- import { getHooksDirInHome } from '../hooks/install.js';
7
- import { registerHooksToSettings, hookRegistrationTargets } from '../hooks/install.js';
8
- import { writeMcpConfig } from '../mcp.js';
9
- import { subagentTarget } from '../subagents-registry.js';
10
- import { isSafeSegmentName, realpathExistingPrefix } from '../paths.js';
11
- import { AgentPackageError } from './package-types.js';
12
- import { effectiveResources } from './package-resolve.js';
13
- const RECEIPT_FILE = 'materialization-receipt.json';
14
- const KIND_TO_CAPABILITY = {
15
- instructions: 'rules',
16
- skills: 'skills',
17
- subagents: 'subagents',
18
- mcp: 'mcp',
19
- hooks: 'hooks',
20
- };
21
- const COPY_IGNORE = new Set(['.DS_Store', '.git', '.gitignore', 'node_modules']);
22
- function copyDir(src, dest) {
23
- fs.mkdirSync(dest, { recursive: true });
24
- for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
25
- if (entry.isSymbolicLink() || COPY_IGNORE.has(entry.name))
26
- continue;
27
- const s = path.join(src, entry.name);
28
- const d = path.join(dest, entry.name);
29
- if (entry.isDirectory())
30
- copyDir(s, d);
31
- else if (entry.isFile())
32
- fs.copyFileSync(s, d);
33
- }
34
- }
35
- function removePath(p) {
36
- try {
37
- const stat = fs.lstatSync(p);
38
- if (stat.isDirectory())
39
- fs.rmSync(p, { recursive: true, force: true });
40
- else
41
- fs.unlinkSync(p);
42
- }
43
- catch {
44
- }
45
- }
46
- function assertCapabilitiesSupported(resources, harness, harnessVersion) {
47
- const unsupported = [];
48
- for (const r of resources) {
49
- const cap = KIND_TO_CAPABILITY[r.kind];
50
- const result = supports(harness, cap, harnessVersion);
51
- if (!result.ok) {
52
- const need = 'need' in result && result.need ? ` (need ${result.need})` : '';
53
- unsupported.push(`${r.kind} '${r.name}' requires capability '${cap}' on ${harness}${need}`);
54
- }
55
- if (r.kind === 'mcp' && r.mcp) {
56
- const isRemote = r.mcp.transport === 'http' || r.mcp.transport === 'sse';
57
- if (isRemote && !supports(harness, 'mcpHttp', harnessVersion).ok) {
58
- unsupported.push(`mcp '${r.name}' declares transport '${r.mcp.transport}' but ${harness} does not support capability 'mcpHttp'`);
59
- }
60
- const hasHeaders = r.mcp.headers && Object.keys(r.mcp.headers).length > 0;
61
- if (isRemote && hasHeaders && !supports(harness, 'mcpHeaders', harnessVersion).ok) {
62
- unsupported.push(`mcp '${r.name}' declares headers but ${harness} does not support capability 'mcpHeaders'`);
63
- }
64
- }
65
- }
66
- if (unsupported.length > 0) {
67
- throw new AgentPackageError(`${harness}@${harnessVersion} cannot materialize this package: ${unsupported.length} unsupported capability request(s)`, 'unsupported-capability', unsupported);
68
- }
69
- }
70
- function assertTargetContained(realOutputHome, target, label) {
71
- const canonical = realpathExistingPrefix(target);
72
- if (canonical !== realOutputHome && !canonical.startsWith(realOutputHome + path.sep)) {
73
- throw new AgentPackageError(`${label}: refusing to write outside the output home — '${target}' resolves outside '${realOutputHome}'`, 'path-escape');
74
- }
75
- }
76
- function assertLeafSafe(realOutputHome, leaf, label) {
77
- assertTargetContained(realOutputHome, leaf, label);
78
- let lst;
79
- try {
80
- lst = fs.lstatSync(leaf);
81
- }
82
- catch {
83
- return;
84
- }
85
- if (lst.isSymbolicLink()) {
86
- throw new AgentPackageError(`${label}: refusing to write through a symlink at '${leaf}'`, 'path-escape');
87
- }
88
- }
89
- function materializeInstructions(resource, harness, outputHome, realOutputHome) {
90
- const cap = AGENTS[harness].capabilities.rules;
91
- if (cap === false) {
92
- throw new AgentPackageError(`${harness} has no instructions target (rules capability is false)`, 'unsupported-capability');
93
- }
94
- const agentDir = path.join(outputHome, agentConfigDirName(harness));
95
- const destFile = path.join(agentDir, cap.file);
96
- assertTargetContained(realOutputHome, destFile, `${harness} instructions`);
97
- fs.mkdirSync(path.dirname(destFile), { recursive: true });
98
- assertLeafSafe(realOutputHome, destFile, `${harness} instructions`);
99
- fs.copyFileSync(resource.sourcePath, destFile);
100
- return path.relative(outputHome, destFile);
101
- }
102
- function materializeSkill(resource, harness, outputHome, realOutputHome) {
103
- const agentDir = path.join(outputHome, agentConfigDirName(harness));
104
- const destDir = path.join(agentDir, 'skills', resource.name);
105
- assertTargetContained(realOutputHome, destDir, `${harness} skill '${resource.name}'`);
106
- removePath(destDir);
107
- copyDir(resource.sourcePath, destDir);
108
- return path.relative(outputHome, destDir);
109
- }
110
- function materializeSubagent(resource, harness, outputHome, realOutputHome) {
111
- const target = subagentTarget(harness);
112
- if (!target) {
113
- throw new AgentPackageError(`${harness} has no subagent target registered`, 'unsupported-capability');
114
- }
115
- const dir = target.dir(outputHome);
116
- assertTargetContained(realOutputHome, dir, `${harness} subagent '${resource.name}'`);
117
- fs.mkdirSync(dir, { recursive: true });
118
- const occupied = target.occupied(dir, resource.name)[0];
119
- assertLeafSafe(realOutputHome, occupied.path, `${harness} subagent '${resource.name}'`);
120
- target.write(dir, { name: resource.name, path: resource.sourcePath });
121
- return path.relative(outputHome, occupied.path);
122
- }
123
- function materializeMcp(resources, harness, outputHome, realOutputHome) {
124
- const configPath = getMcpConfigPathForHome(harness, outputHome);
125
- if (resources.length === 0 && !fs.existsSync(configPath))
126
- return [];
127
- assertTargetContained(realOutputHome, configPath, `${harness} mcp config`);
128
- const servers = resources.map((r) => ({
129
- name: r.mcp.name,
130
- transport: r.mcp.transport,
131
- command: r.mcp.command,
132
- args: r.mcp.args,
133
- env: r.mcp.env,
134
- url: r.mcp.url,
135
- headers: r.mcp.headers,
136
- }));
137
- fs.mkdirSync(path.dirname(configPath), { recursive: true });
138
- assertLeafSafe(realOutputHome, configPath, `${harness} mcp config`);
139
- try {
140
- writeMcpConfig(harness, configPath, servers, 'overwrite', { allowEmpty: true });
141
- }
142
- catch (err) {
143
- throw new AgentPackageError(`${harness}: cannot write mcp config — ${err.message}`, 'unsupported-capability');
144
- }
145
- const rel = path.relative(outputHome, configPath);
146
- return resources.map(() => rel);
147
- }
148
- function materializeHooks(resources, harness, outputHome, realOutputHome) {
149
- const targets = new Map();
150
- if (resources.length === 0)
151
- return targets;
152
- const hooksDir = getHooksDirInHome(harness, outputHome);
153
- assertTargetContained(realOutputHome, hooksDir, `${harness} hooks dir`);
154
- fs.mkdirSync(hooksDir, { recursive: true });
155
- for (const settingsLeaf of hookRegistrationTargets(harness, outputHome)) {
156
- assertLeafSafe(realOutputHome, settingsLeaf, `${harness} hook settings`);
157
- }
158
- const manifest = {};
159
- for (const r of resources) {
160
- const { def, scriptPath } = r.hook;
161
- if (!isSafeSegmentName(r.name)) {
162
- throw new AgentPackageError(`${harness}: hook name '${r.name}' is not a safe single path segment`, 'invalid-resource');
163
- }
164
- const hooksDirResolved = path.resolve(hooksDir);
165
- const destScript = path.join(hooksDirResolved, `${r.name}${path.extname(scriptPath)}`);
166
- if (!destScript.startsWith(hooksDirResolved + path.sep)) {
167
- throw new AgentPackageError(`${harness}: hook '${r.name}' resolves outside the hooks directory`, 'invalid-resource');
168
- }
169
- assertLeafSafe(realOutputHome, destScript, `${harness} hook '${r.name}'`);
170
- fs.copyFileSync(scriptPath, destScript);
171
- fs.chmodSync(destScript, 0o755);
172
- manifest[r.name] = { script: destScript, events: def.events, matcher: def.matcher, timeout: def.timeout };
173
- targets.set(r.name, path.relative(outputHome, destScript));
174
- }
175
- const result = registerHooksToSettings(harness, outputHome, manifest, undefined, { skipGlobalShimSweep: true });
176
- if (result.errors.length > 0) {
177
- throw new AgentPackageError(`${harness}: failed to register hook(s) — ${result.errors.join('; ')}`, 'invalid-resource');
178
- }
179
- return targets;
180
- }
181
- function packageRef(resolved) {
182
- return `${resolved.manifest.slug}@${resolved.digest.slice(0, 12)}`;
183
- }
184
- function isSafeContainedTarget(realOutputHome, outputHome, rel) {
185
- if (typeof rel !== 'string' || rel.length === 0 || rel.includes('\0'))
186
- return false;
187
- if (path.isAbsolute(rel))
188
- return false;
189
- if (rel.split(/[\\/]/).includes('..'))
190
- return false;
191
- const canonical = realpathExistingPrefix(path.resolve(outputHome, rel));
192
- return canonical.startsWith(realOutputHome + path.sep);
193
- }
194
- function pruneStaleManagedPaths(realOutputHome, outputHome, previousTargets, currentTargets) {
195
- for (const rel of previousTargets) {
196
- if (currentTargets.has(rel))
197
- continue;
198
- if (!isSafeContainedTarget(realOutputHome, outputHome, rel))
199
- continue;
200
- removePath(path.join(outputHome, rel));
201
- }
202
- }
203
- function isValidReceipt(value) {
204
- if (!value || typeof value !== 'object')
205
- return false;
206
- const v = value;
207
- if (v.schemaVersion !== 1)
208
- return false;
209
- if (!Array.isArray(v.resources))
210
- return false;
211
- return v.resources.every((r) => r && typeof r === 'object' && typeof r.kind === 'string' && typeof r.target === 'string');
212
- }
213
- function readPriorReceipt(outputHome) {
214
- const receiptPath = path.join(outputHome, RECEIPT_FILE);
215
- try {
216
- if (fs.lstatSync(receiptPath).isSymbolicLink())
217
- return null;
218
- }
219
- catch {
220
- return null;
221
- }
222
- let parsed;
223
- try {
224
- parsed = JSON.parse(fs.readFileSync(receiptPath, 'utf-8'));
225
- }
226
- catch {
227
- return null;
228
- }
229
- return isValidReceipt(parsed) ? parsed : null;
230
- }
231
- export function materializeAgentPackage(resolved, options) {
232
- const { harness, harnessVersion, outputHome } = options;
233
- if (!resolved.manifest.execution.harnesses.supported.includes(harness)) {
234
- throw new AgentPackageError(`package '${resolved.manifest.slug}' does not declare '${harness}' as a supported harness`, 'unsupported-harness', resolved.manifest.execution.harnesses.supported);
235
- }
236
- const resources = effectiveResources(resolved, harness);
237
- assertCapabilitiesSupported(resources, harness, harnessVersion);
238
- fs.mkdirSync(outputHome, { recursive: true });
239
- const realOutputHome = fs.realpathSync(outputHome);
240
- const prior = readPriorReceipt(outputHome);
241
- const previousTargets = new Set((prior?.resources ?? []).filter((r) => r.kind !== 'mcp').map((r) => r.target));
242
- const entries = [];
243
- const mcpResources = resources.filter((r) => r.kind === 'mcp');
244
- const hookResources = resources.filter((r) => r.kind === 'hooks');
245
- const mcpTargets = materializeMcp(mcpResources, harness, outputHome, realOutputHome);
246
- const hookTargets = materializeHooks(hookResources, harness, outputHome, realOutputHome);
247
- for (const r of resources) {
248
- let target;
249
- if (r.kind === 'instructions')
250
- target = materializeInstructions(r, harness, outputHome, realOutputHome);
251
- else if (r.kind === 'skills')
252
- target = materializeSkill(r, harness, outputHome, realOutputHome);
253
- else if (r.kind === 'subagents')
254
- target = materializeSubagent(r, harness, outputHome, realOutputHome);
255
- else if (r.kind === 'mcp')
256
- target = mcpTargets[mcpResources.indexOf(r)];
257
- else
258
- target = hookTargets.get(r.name);
259
- entries.push({ kind: r.kind, name: r.name, target, sha256: r.sha256, provenance: r.provenance });
260
- }
261
- const currentTargets = new Set(entries.map((e) => e.target));
262
- pruneStaleManagedPaths(realOutputHome, outputHome, previousTargets, currentTargets);
263
- const receipt = {
264
- schemaVersion: 1,
265
- agent: { ref: packageRef(resolved), digest: `sha256:${resolved.digest}` },
266
- harness: { id: harness, version: harnessVersion },
267
- resources: entries,
268
- warnings: [],
269
- };
270
- const receiptPath = path.join(outputHome, RECEIPT_FILE);
271
- assertLeafSafe(realOutputHome, receiptPath, 'materialization receipt');
272
- fs.writeFileSync(receiptPath, JSON.stringify(receipt, null, 2) + '\n');
273
- return receipt;
274
- }
275
- export function sha256OfReceiptFile(receiptPath) {
276
- return crypto.createHash('sha256').update(fs.readFileSync(receiptPath)).digest('hex');
277
- }
@@ -1,4 +0,0 @@
1
- import type { AgentId } from '../types.js';
2
- import type { ResolvedAgentPackage, ResolvedResource } from './package-types.js';
3
- export declare function resolveAgentPackage(packageDir: string): ResolvedAgentPackage;
4
- export declare function effectiveResources(resolved: ResolvedAgentPackage, harness: AgentId): ResolvedResource[];