aptly 0.1.8 → 0.1.10

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.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ // Internal command Hook. It never emits decisions/context, calls a provider or loads credentials.
3
+ import { readSync } from 'node:fs';
4
+ async function observe() {
5
+ try {
6
+ if (process.platform === 'win32')
7
+ return;
8
+ const args = process.argv.slice(2);
9
+ let client, policyPath;
10
+ const seen = new Set();
11
+ for (let n = 0; n < args.length; n += 2) {
12
+ const flag = args[n], value = args[n + 1];
13
+ if (seen.has(flag) || !value)
14
+ return;
15
+ seen.add(flag);
16
+ if (flag === '--client' && (value === 'codex' || value === 'claude'))
17
+ client = value;
18
+ else if (flag === '--policy-path')
19
+ policyPath = value;
20
+ else
21
+ return;
22
+ }
23
+ if (!client || !policyPath)
24
+ return;
25
+ const buffer = Buffer.alloc(65537);
26
+ let size = 0;
27
+ while (size < buffer.length) {
28
+ const count = readSync(0, buffer, size, buffer.length - size, null);
29
+ if (!count)
30
+ break;
31
+ size += count;
32
+ }
33
+ if (size > 65536)
34
+ return;
35
+ const event = JSON.parse(buffer.subarray(0, size).toString('utf8'));
36
+ if (!event || typeof event !== 'object' || Array.isArray(event))
37
+ return;
38
+ const value = event;
39
+ if (!['PostToolUse', 'SubagentStart', 'SubagentStop', 'PostModelRequest'].includes(String(value.hook_event_name)))
40
+ return;
41
+ if (value.hook_event_name === 'PostModelRequest' && typeof value.agent_id !== 'string')
42
+ return;
43
+ const { statisticsState } = await import('../src/statistics-policy.js');
44
+ const state = statisticsState(policyPath);
45
+ if (!state)
46
+ return;
47
+ const options = { stateDirectory: state };
48
+ const stats = await import('../src/statistics.js');
49
+ const config = stats.loadStatisticsConfig(options);
50
+ if (!config?.enabled_clients.includes(client))
51
+ return;
52
+ let bridge;
53
+ if (client === 'codex' && config.codex_native_metadata && config.codex_home && typeof value.agent_id === 'string' && typeof value.session_id === 'string') {
54
+ const hash = stats.loadStatisticsHash(options);
55
+ if (hash) {
56
+ const { resolveCodexStatisticsBridge } = await import('../src/statistics-codex.js');
57
+ const result = resolveCodexStatisticsBridge({ codexHome: config.codex_home, childId: value.agent_id, parentId: value.session_id, hash });
58
+ if (result.status === 'matched')
59
+ bridge = result;
60
+ }
61
+ }
62
+ stats.observeStatistics(options, { client, event: value }, bridge);
63
+ }
64
+ catch { /* Statistics never steer the host or expose raw errors. */ }
65
+ }
66
+ await observe();
package/dist/bin/aptly.js CHANGED
@@ -10,9 +10,10 @@ import { exportDiagnosticReport } from '../src/report.js';
10
10
  import { fetchModelInfo, saveModelInfo } from '../src/model-info.js';
11
11
  import { errorCode } from '../src/types.js';
12
12
  import { budgetErrorDetails } from '../src/budget.js';
13
- import { setupHosts, removeSetup, setDefaults, setEnvironment, configurableEnvironmentKeys, migrateLauncher, setTransmission, showTransmission, showBudgetStatus } from '../src/setup.js';
13
+ import { checkSetup, setupHosts, removeSetup, setDefaults, setEnvironment, configurableEnvironmentKeys, migrateLauncher, setTransmission, showTransmission, showBudgetStatus, showStatistics, setStatisticsCollection } from '../src/setup.js';
14
14
  import { readEnvironmentValue, readTransmissionChoice } from '../src/cli-input.js';
15
15
  import { prepareApiKey } from '../src/credential-setup.js';
16
+ import { linuxStoreReadiness } from '../src/linux-store-readiness.js';
16
17
  import { updateGlobalInstallation } from '../src/update.js';
17
18
  import { updateNotification } from '../src/update-notifier.js';
18
19
  import { resolveCliHelp } from '../src/cli-help.js';
@@ -39,6 +40,43 @@ try {
39
40
  if (result.status === 'error')
40
41
  process.exitCode = 1;
41
42
  }
43
+ else if (command === 'stats') {
44
+ let action, start = 0;
45
+ if (args[0] === 'enable' || args[0] === 'disable') {
46
+ action = args[0];
47
+ start = 1;
48
+ }
49
+ let clients = ['codex', 'claude'];
50
+ let today = false, native = false;
51
+ const seen = new Set();
52
+ for (let n = start; n < args.length; n++) {
53
+ const flag = args[n];
54
+ if (seen.has(flag))
55
+ throw new Error('statistics_invalid_options');
56
+ seen.add(flag);
57
+ if (flag === '--today' && !action) {
58
+ today = true;
59
+ continue;
60
+ }
61
+ if (flag === '--codex-native-metadata' && action === 'enable') {
62
+ native = true;
63
+ continue;
64
+ }
65
+ if (flag === '--client' && ['codex', 'claude', 'all'].includes(args[n + 1])) {
66
+ const v = args[++n];
67
+ clients = v === 'all' ? ['codex', 'claude'] : [v];
68
+ continue;
69
+ }
70
+ throw new Error('statistics_invalid_options');
71
+ }
72
+ if (native && !clients.includes('codex'))
73
+ throw new Error('statistics_invalid_options');
74
+ const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
75
+ const result = action ? setStatisticsCollection(action === 'enable', { clients, packageRoot, ...(native ? { codexNativeMetadata: true } : {}) }) : showStatistics({ clients }, today);
76
+ output(result);
77
+ if ('status' in result && result.status === 'partial')
78
+ process.exitCode = 1;
79
+ }
42
80
  else if (command === 'budget') {
43
81
  if (args[0] !== 'status')
44
82
  throw new Error('budget_invalid_options');
@@ -126,6 +164,14 @@ try {
126
164
  if (checkOnly && fromStdin)
127
165
  throw new Error('set_invalid_options');
128
166
  const credential = key === 'OPENAI_API_KEY' ? prepareApiKey({ clients, packageRoot }) : undefined;
167
+ if (credential && credential.result.clients.some(client => client.status !== 'error')) {
168
+ const readiness = linuxStoreReadiness();
169
+ if (readiness) {
170
+ credential.result.clients = credential.result.clients.map(client => client.status === 'error' ? client : ({ ...client, status: readiness.status === 'unavailable' ? 'error' : client.status, codes: [...client.codes, ...(readiness.status === 'unavailable' ? ['secure_store_unavailable'] : []), readiness.code] }));
171
+ if (readiness.status === 'unavailable')
172
+ credential.result.status = 'partial';
173
+ }
174
+ }
129
175
  let value = '';
130
176
  if (credential && (checkOnly || credential.result.status === 'partial')) {
131
177
  output(credential.result);
@@ -159,6 +205,7 @@ try {
159
205
  let mode;
160
206
  let transmission;
161
207
  let automatic = false;
208
+ let check = false;
162
209
  let migrate = false;
163
210
  let dryRun = false;
164
211
  let includeExisting = false;
@@ -168,6 +215,10 @@ try {
168
215
  if (seen.has(flag))
169
216
  throw new Error('setup_invalid_options');
170
217
  seen.add(flag);
218
+ if (flag === '--check' && command === 'setup') {
219
+ check = true;
220
+ continue;
221
+ }
171
222
  if (flag === '--migrate-launcher' && command === 'setup') {
172
223
  migrate = true;
173
224
  continue;
@@ -195,9 +246,9 @@ try {
195
246
  throw new Error('setup_invalid_options');
196
247
  }
197
248
  const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
198
- if ((migrate && (clients.length !== 1 || automatic || seen.has('--mode') || seen.has('--transmission'))) || ((dryRun || includeExisting) && !migrate))
249
+ if ((check && [...seen].some(flag => !['--check', '--client'].includes(flag))) || (migrate && (clients.length !== 1 || automatic || seen.has('--mode') || seen.has('--transmission'))) || ((dryRun || includeExisting) && !migrate))
199
250
  throw new Error('setup_invalid_options');
200
- const result = migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot, transmission }) : removeSetup({ clients });
251
+ const result = check ? checkSetup({ clients, packageRoot }) : migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot, transmission }) : removeSetup({ clients });
201
252
  output(result);
202
253
  if (result.status === 'partial' && !automatic)
203
254
  process.exitCode = 1;
@@ -247,13 +298,13 @@ catch (error) {
247
298
  const budgetCode = [caughtCode, message].find(value => typeof value === 'string' && ['invalid_budget_configuration', 'budget_invalid_options'].includes(value));
248
299
  const configCode = [caughtCode, message].find(value => typeof value === 'string' && safeConfigurationCodes.includes(value));
249
300
  const setCodes = ['set_environment_key_unsupported', 'set_invalid_options', 'set_value_too_large', 'set_interactive_input_required', 'set_input_cancelled'];
250
- const code = command === 'update' ? (message === 'update_invalid_options' ? message : 'update_failed') : command === 'set' ? (setCodes.includes(message ?? '') ? message : 'set_failed') : command === 'report' ? (caughtCode && codes.includes(caughtCode) ? caughtCode : 'report_failed') : budgetCode ?? configCode ?? 'operation_failed';
301
+ const code = command === 'stats' ? 'statistics_invalid_options' : command === 'update' ? (message === 'update_invalid_options' ? message : 'update_failed') : command === 'set' ? (setCodes.includes(message ?? '') ? message : 'set_failed') : command === 'report' ? (caughtCode && codes.includes(caughtCode) ? caughtCode : 'report_failed') : budgetCode ?? configCode ?? 'operation_failed';
251
302
  const budgetDetails = budgetErrorDetails(error);
252
303
  process.stderr.write('aptly: ' + code + (budgetDetails.invalid_budget_keys?.length ? ' [' + budgetDetails.invalid_budget_keys.join(', ') + ']' : '') + (budgetDetails.budget_error ? ' (' + budgetDetails.budget_error + ')' : '') + '\n');
253
304
  process.exitCode = 1;
254
305
  }
255
306
  finally {
256
- if (!process.exitCode && !helpHandled) {
307
+ if (!process.exitCode && !helpHandled && command !== 'stats') {
257
308
  try {
258
309
  const hint = await updateNotification({ command, args, env: process.env, stdinIsTTY: !!process.stdin.isTTY, stderrIsTTY: !!process.stderr.isTTY, stdoutIsTTY: !!process.stdout.isTTY, currentVersion: VERSION });
259
310
  if (hint)
@@ -3,7 +3,7 @@ import { budgetEnvironmentDefaults } from './budget.js';
3
3
  const client = ['codex', 'claude', 'all'];
4
4
  const scope = ['none', 'description', 'excerpt'];
5
5
  const entries = {
6
- '': { usage: 'aptly <command> [options]', description: 'Aptly — subagent profile recommendations\n\nCommands:\n serve Start the stdio MCP server.\n capabilities Print catalog and local limits without an API call.\n catalog [refresh] Inspect the catalog or refresh official model descriptions.\n recommend Read task JSON from stdin and return advice.\n inspect CLIENT FILE Inspect an explicit settings inventory.\n config CLIENT Print an MCP registration fragment.\n set default Fill missing settings; select transmission scope interactively.\n set env ENV_KEY Set a supported environment value.\n set transmission Select or show Decisions API transmission scope.\n budget status Inspect local budget limits and usage.\n setup Register MCP and PreToolUse Hooks.\n remove Remove unchanged Aptly-owned registration.\n update Update a verified global npm installation.\n report Write redacted local diagnostic attachments.\n\nGlobal options:\n --help, -h Show help without executing a command.\n --version Print the package version.\n\nUse aptly COMMAND --help or aptly help COMMAND for details.', options: { '--version': true } },
6
+ '': { usage: 'aptly <command> [options]', description: 'Aptly — subagent profile recommendations\n\nCommands:\n serve Start the stdio MCP server.\n capabilities Print catalog and local limits without an API call.\n catalog [refresh] Inspect the catalog or refresh official model descriptions.\n recommend Read task JSON from stdin and return advice.\n inspect CLIENT FILE Inspect an explicit settings inventory.\n config CLIENT Print an MCP registration fragment.\n set default Fill missing settings; select transmission scope interactively.\n set env ENV_KEY Set a supported environment value.\n set transmission Select or show Decisions API transmission scope.\n budget status Inspect local budget limits and usage.\n stats [enable|disable] Inspect or control opt-in local execution statistics.\n setup Register MCP and PreToolUse Hooks.\n remove Remove unchanged Aptly-owned registration.\n update Update a verified global npm installation.\n report Write redacted local diagnostic attachments.\n\nGlobal options:\n --help, -h Show help without executing a command.\n --version Print the package version.\n\nUse aptly COMMAND --help or aptly help COMMAND for details.', options: { '--version': true } },
7
7
  serve: { usage: 'aptly serve', description: 'Start the stdio MCP server (default: fixture/shadow).\nDecisions mode requires ROUTER_PROVIDER=decisions, an absolute private ROUTER_LEDGER_PATH and a configured API key. Use aptly set env OPENAI_API_KEY for OS credential storage. Never put keys in request JSON or command arguments.' },
8
8
  capabilities: { usage: 'aptly capabilities', description: 'Print the active catalog, local limits and configuration metadata. No classification API call. Reads runtime configuration and credential availability; help does neither.' },
9
9
  catalog: { usage: 'aptly catalog\n aptly catalog refresh --output ABS_PATH', description: 'Print the active catalog without classification. Refresh is a separate explicit network operation; use aptly catalog refresh --help.' },
@@ -13,11 +13,14 @@ const entries = {
13
13
  config: { usage: 'aptly config codex|claude', description: 'Print a registration fragment only. Does not edit host configuration or classify. Preserve existing launchers and merge settings as described in the guide.', positional: ['client'] },
14
14
  set: { usage: 'aptly set default [--client codex|claude|all]\n aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]\n aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]', description: 'Set operator-controlled defaults, environment values or transmission scope. Use the subcommand help for input, preservation and restart details.' },
15
15
  'set default': { usage: 'aptly set default [--client codex|claude|all]', description: 'Fill missing MCP environment defaults for both clients by default. Preserve existing values, inherited budget bindings and launchers. Does not reset budget usage or caches. Interactive runs ask only for unselected transmission scope (Enter: none); noninteractive runs do not opt in. Restart MCP after changes.', options: { '--client': client } },
16
- 'set env': { usage: 'aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]', description: 'Set a supported value using hidden input; --stdin explicitly reads standard input. --client defaults to all. --check is only for OPENAI_API_KEY and checks registration without reading/storing a key.\nOPENAI_API_KEY uses OS credential storage; host files contain references only. Values are never accepted as command arguments. Existing launchers are preserved. Restart MCP after changes.\nBudget defaults: ' + Object.entries(budgetEnvironmentDefaults).map(([key, value]) => key + '=' + value).join(', ') + '. Only literal 0 disables a ceiling; the per-call rate stays positive.\nSupported environment keys: $ENV_KEYS', options: { '--client': client, '--stdin': true, '--check': true }, positional: ['environment'] },
16
+ 'set env': { usage: 'aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]', description: 'Set a supported value using hidden input; --stdin explicitly reads standard input. --client defaults to all. --check is only for OPENAI_API_KEY and checks registration and Linux store readiness without reading/storing a key.\nOPENAI_API_KEY uses OS credential storage; host files contain references only. Values are never accepted as command arguments. Existing launchers are preserved. Restart MCP after changes.\nBudget defaults: ' + Object.entries(budgetEnvironmentDefaults).map(([key, value]) => key + '=' + value).join(', ') + '. Only literal 0 disables a ceiling; the per-call rate stays positive.\nSupported environment keys: $ENV_KEYS', options: { '--client': client, '--stdin': true, '--check': true }, positional: ['environment'] },
17
17
  'set transmission': { usage: 'aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]', description: 'Control automatic task-data transmission to OpenAI Decisions, not developer telemetry. none disables automatic transmission; description permits caller-provided descriptions only; excerpt permits native excerpts. Direct recommendations remain separate explicit requests. --show reads redacted registration state. Restart MCP after changes.', options: { '--client': client, '--show': true }, positional: ['scope'] },
18
+ stats: { usage: 'aptly stats [--client codex|claude|all] [--today]\n aptly stats enable [--client codex|claude|all] [--codex-native-metadata]\n aptly stats disable [--client codex|claude|all]', description: 'Read retained local execution statistics without provider, credential or network access, state creation or update notification. Collection is disabled by default. --today uses UTC binding creation, not completion time. Model matches are host-reported model evidence, not user consent, quality, effective effort or billing. Aliases without canonical evidence remain unknown.', options: { '--client': client, '--today': true } },
19
+ 'stats enable': { usage: 'aptly stats enable [--client codex|claude|all] [--codex-native-metadata]', description: 'Explicitly register local statistics observers and enable collection after existing Aptly setup. Initial support is POSIX only. Preserve routing, credentials, budget ledger, custom launchers and Hooks. Restart MCP/host and review new Codex Hooks with /hooks; trust is never written automatically. --codex-native-metadata additionally permits exact-child native SQLite metadata reads; existing SHM read marks may change, no row/schema writes or new sidecar files are intended. Unsupported/ambiguous evidence remains unknown.', options: { '--client': client, '--codex-native-metadata': true } },
20
+ 'stats disable': { usage: 'aptly stats disable [--client codex|claude|all]', description: 'Disable Aptly collection and remove unchanged product-owned observer definitions. Preserve statistics/key/history, custom or modified observers and all routing settings. Retained modified definitions are reported for local review.', options: { '--client': client } },
18
21
  budget: { usage: 'aptly budget status [--client codex|claude|all]', description: 'Inspect local per-ledger budget limits and reserved usage. No reset/refill command is provided.' },
19
22
  'budget status': { usage: 'aptly budget status [--client codex|claude|all]', description: 'Read registered host budget settings and ledger metadata; defaults to both clients. No credentials, provider calls, configuration writes or ledger/gate initialization.\nLiteral 0 ceilings display Unlimited; reservations are not OpenAI billing. This is a registration/permitted-environment snapshot, not verification of running custom launchers. An existing gate is held briefly and can be busy.', options: { '--client': client } },
20
- setup: { usage: 'aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--transmission none|description|excerpt] [--automatic]\n aptly setup --client codex|claude --migrate-launcher [--include-existing] [--dry-run]', description: 'Register MCP and PreToolUse Hooks while preserving unrelated settings and existing launchers. Omitted --mode preserves an existing mode; a new policy defaults to defaults. New transmission remains unselected unless explicitly chosen.\n--automatic skips CI, APTLY_SKIP_SETUP=1 and absent host directories.\n--migrate-launcher reviews a single owned standard launcher; --include-existing explicitly includes an eligible preserved registration. --dry-run validates migration without writing. Do not combine migration with --automatic, --mode or --transmission. --include-existing and --dry-run require --migrate-launcher.\nNo keys are stored. Restart the host/MCP; Codex requires native /hooks trust review.', options: { '--client': client, '--mode': ['defaults', 'advisory'], '--transmission': scope, '--automatic': true, '--migrate-launcher': true, '--include-existing': true, '--dry-run': true } },
23
+ setup: { usage: 'aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--transmission none|description|excerpt] [--automatic]\n aptly setup --check [--client codex|claude|all]\n aptly setup --client codex|claude --migrate-launcher [--include-existing] [--dry-run]', description: 'Register MCP and PreToolUse Hooks while preserving unrelated settings and existing launchers. Omitted --mode preserves an existing mode; a new policy defaults to defaults. New transmission remains unselected unless explicitly chosen.\n--check snapshots the normal setup plan without writing; only --client may be combined with it. It does not verify a running host.\n--automatic skips CI, APTLY_SKIP_SETUP=1 and absent host directories.\n--migrate-launcher reviews a single owned standard launcher; --include-existing explicitly includes an eligible preserved registration. --dry-run validates migration without writing. Do not combine migration with --automatic, --mode or --transmission. --include-existing and --dry-run require --migrate-launcher.\nNo keys are stored. Restart the host/MCP; Codex requires native /hooks trust review.', options: { '--client': client, '--mode': ['defaults', 'advisory'], '--transmission': scope, '--automatic': true, '--check': true, '--migrate-launcher': true, '--include-existing': true, '--dry-run': true } },
21
24
  remove: { usage: 'aptly remove [--client codex|claude|all]', description: 'Remove only unchanged Aptly-owned registration for both clients by default. Preserve modified/user-owned entries, keys and ledger history. Restart host/MCP after removal.', options: { '--client': client } },
22
25
  update: { usage: 'aptly update', description: 'Update this verified global npm installation within the same prefix. Stop other hosts/MCP/CLI writers first. Local/source/unverified installations are rejected. Lifecycle setup is not run: run aptly setup and restart hosts afterward. Existing launchers and keys are preserved.' },
23
26
  report: { usage: 'aptly report [--format md|json|both] [--output-dir DIR]', description: 'Write redacted local diagnostic attachments. Default format: both; directory: reports. No uploads or classification API probes. Review attachments before sharing.', options: { '--format': ['md', 'json', 'both'], '--output-dir': 'path' } },
@@ -35,7 +38,7 @@ export function resolveCliHelp(argv, { environmentKeys = [] } = {}) {
35
38
  return { kind: 'error', code: 'invalid_help_options' };
36
39
  path = clean[0];
37
40
  count = 1;
38
- if (['set', 'catalog', 'budget'].includes(path) && clean[1] && Object.hasOwn(entries, path + ' ' + clean[1])) {
41
+ if (['set', 'catalog', 'budget', 'stats'].includes(path) && clean[1] && Object.hasOwn(entries, path + ' ' + clean[1])) {
39
42
  path += ' ' + clean[1];
40
43
  count = 2;
41
44
  }
@@ -88,8 +91,12 @@ export function resolveCliHelp(argv, { environmentKeys = [] } = {}) {
88
91
  return { kind: 'error', code: 'invalid_help_options' };
89
92
  if (path === 'set transmission' && seen.has('--show') && positionals.length)
90
93
  return { kind: 'error', code: 'invalid_help_options' };
94
+ if (path === 'stats enable' && seen.has('--codex-native-metadata') && values.get('--client') === 'claude')
95
+ return { kind: 'error', code: 'invalid_help_options' };
91
96
  if (path === 'setup') {
92
97
  const migrate = seen.has('--migrate-launcher');
98
+ if (seen.has('--check') && [...seen].some(flag => !['--check', '--client'].includes(flag)))
99
+ return { kind: 'error', code: 'invalid_help_options' };
93
100
  if ((seen.has('--dry-run') || seen.has('--include-existing')) && !migrate)
94
101
  return { kind: 'error', code: 'invalid_help_options' };
95
102
  if (migrate && (seen.has('--automatic') || seen.has('--mode') || seen.has('--transmission') || values.get('--client') === 'all'))
@@ -0,0 +1,12 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ export interface LinuxReadinessOptions {
3
+ platform?: NodeJS.Platform;
4
+ env?: NodeJS.ProcessEnv;
5
+ execute?: typeof spawnSync;
6
+ }
7
+ export interface StoreReadiness {
8
+ status: 'unavailable' | 'unverified';
9
+ code: string;
10
+ }
11
+ /** Passive metadata only: never query, activate, unlock, or write the Secret Service. */
12
+ export declare function linuxStoreReadiness(options?: LinuxReadinessOptions): StoreReadiness | undefined;
@@ -0,0 +1,67 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { accessSync, constants, statSync } from 'node:fs';
3
+ import { isAbsolute, resolve } from 'node:path';
4
+ // Locate programs without running them. Empty PATH entries have shell cwd semantics.
5
+ function executable(name, path, absoluteOnly = false) {
6
+ for (const dir of (path ?? '/usr/bin:/bin').split(':')) {
7
+ if (absoluteOnly && !isAbsolute(dir))
8
+ continue;
9
+ const candidate = resolve(dir || '.', name);
10
+ try {
11
+ if (statSync(candidate).isFile()) {
12
+ accessSync(candidate, constants.X_OK);
13
+ return candidate;
14
+ }
15
+ }
16
+ catch { /* try next PATH entry */ }
17
+ }
18
+ }
19
+ /** Passive metadata only: never query, activate, unlock, or write the Secret Service. */
20
+ export function linuxStoreReadiness(options = {}) {
21
+ if ((options.platform ?? process.platform) !== 'linux')
22
+ return undefined;
23
+ const env = options.env ?? process.env;
24
+ if (!executable('secret-tool', env.PATH))
25
+ return { status: 'unavailable', code: 'secure_store_secret_tool_missing' };
26
+ const address = env.DBUS_SESSION_BUS_ADDRESS;
27
+ if (!address || !/^unix:(?:path|abstract)=[^,;\s]+(?:,guid=[a-fA-F0-9]{32})?$/.test(address))
28
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
29
+ if (address.startsWith('unix:path=') && !isAbsolute(address.slice('unix:path='.length).split(',')[0]))
30
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
31
+ const socket = address.match(/^unix:path=([^,%]+)(?:,guid=[a-fA-F0-9]{32})?$/)?.[1];
32
+ if (socket && isAbsolute(socket)) {
33
+ try {
34
+ statSync(socket);
35
+ }
36
+ catch (error) {
37
+ if (error.code === 'ENOENT')
38
+ return { status: 'unavailable', code: 'secure_store_bus_missing' };
39
+ }
40
+ }
41
+ const gdbus = executable('gdbus', env.PATH, true);
42
+ if (!gdbus)
43
+ return { status: 'unverified', code: 'secure_store_probe_unavailable' };
44
+ const call = (method, extra = []) => {
45
+ try {
46
+ const result = (options.execute ?? spawnSync)(gdbus, ['call', '--address', address, '--dest', 'org.freedesktop.DBus', '--object-path', '/org/freedesktop/DBus', '--method', `org.freedesktop.DBus.${method}`, ...extra], { env: { PATH: env.PATH ?? '/usr/bin:/bin', LC_ALL: 'C' }, encoding: 'utf8', timeout: 2000, maxBuffer: 65536 });
47
+ return !result.error && result.status === 0 && typeof result.stdout === 'string' ? result.stdout.trim() : undefined;
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ };
53
+ const owner = call('NameHasOwner', ['org.freedesktop.secrets']);
54
+ if (owner === '(true,)')
55
+ return { status: 'unverified', code: 'secure_store_service_present_unverified' };
56
+ if (owner !== '(false,)')
57
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
58
+ const names = call('ListActivatableNames');
59
+ // gdbus prints a GVariant string array. Accept only its narrow standard shape.
60
+ if (names === '(@as [],)')
61
+ return { status: 'unavailable', code: 'secure_store_service_missing' };
62
+ if (names === undefined || !/^\(\[(?:\s*'[^'\\]*'\s*(?:,\s*'[^'\\]*'\s*)*)?\],\)$/.test(names))
63
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
64
+ if (names.includes("'org.freedesktop.secrets'"))
65
+ return { status: 'unverified', code: 'secure_store_service_activatable_unverified' };
66
+ return { status: 'unavailable', code: 'secure_store_service_missing' };
67
+ }
@@ -11,6 +11,7 @@ import { automaticHook, effectiveTransmission, loadAutomaticHookPolicy, initialH
11
11
  import { SpawnContexts } from './spawn-context.js';
12
12
  import { RoutingObservations } from './routing-observations.js';
13
13
  import { ContextRetries } from './context-retry.js';
14
+ import { statisticsState } from './statistics-policy.js';
14
15
  const taskSchema = z.object({ summary: z.string().min(1).max(4000), operation: z.enum(['read_only', 'write', 'review', 'analysis']), context_sufficient: z.boolean() }).strict();
15
16
  const constraintsSchema = z.object({ model_pinned: z.boolean().optional(), effort_pinned: z.boolean().optional(), role_pinned: z.boolean().optional(), fork_inherits: z.boolean().optional(), provenance_verified: z.boolean().optional() }).strict();
16
17
  const hookSchema = { client: z.enum(['codex', 'claude']), event: z.record(z.string(), z.unknown()) };
@@ -26,6 +27,32 @@ export function createServer({ env = process.env } = {}) {
26
27
  const contexts = new SpawnContexts();
27
28
  const retries = new ContextRetries(router, env.APTLY_HOOK_POLICY_PATH);
28
29
  const server = new McpServer({ name: 'aptly', version: VERSION });
30
+ // Durable statistics are a separate, opt-in best-effort projection after routing settles.
31
+ const trackStatistics = async (client, input) => {
32
+ if (process.platform === 'win32')
33
+ return;
34
+ try {
35
+ const stateDirectory = statisticsState(env.APTLY_HOOK_POLICY_PATH);
36
+ if (!stateDirectory)
37
+ return;
38
+ const stats = await import('./statistics.js'), options = { stateDirectory };
39
+ if (!stats.loadStatisticsConfig(options)?.enabled_clients.includes(client))
40
+ return;
41
+ const observation = input.observation, result = input.recommendation;
42
+ const profileId = typeof observation?.profile_id === 'string' ? observation.profile_id : typeof result?.profile_id === 'string' ? result.profile_id : undefined;
43
+ const profile = router.policy.profiles.find(p => p.id === profileId && p.client === client);
44
+ const expected = profile ? { profileId: profile.id, model: profile.model, ...(profile.reasoning_effort ? { effort: profile.reasoning_effort } : {}), catalogVersion: router.policy.catalog_version } : undefined;
45
+ if (input.event && observation) {
46
+ const disposition = observation.status === 'arguments_updated' ? 'auto' : observation.status === 'advisory' ? 'advisory' : ['blocked', 'awaiting_context'].includes(String(observation.status)) ? 'blocked' : String(observation.reason).startsWith('explicit_') ? 'explicit_preserved' : undefined;
47
+ if (!disposition)
48
+ return;
49
+ stats.recordStatisticsRecommendation(options, { client, sessionId: typeof input.event.session_id === 'string' ? input.event.session_id : undefined, toolUseId: typeof (input.event.tool_use_id ?? input.event.tool_call_id) === 'string' ? String(input.event.tool_use_id ?? input.event.tool_call_id) : undefined, requestId: typeof observation.request_id === 'string' ? observation.request_id : undefined, disposition, expected });
50
+ }
51
+ else if (expected && input.requestId && (result?.status === 'recommended' || result?.status === 'prepared'))
52
+ stats.recordStatisticsRecommendation(options, { client, requestId: input.requestId, disposition: 'unbound', expected });
53
+ }
54
+ catch { /* Statistics never alter provider, budget, Hook output or execution. */ }
55
+ };
29
56
  const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: mode === 'decisions' };
30
57
  const evidence = (client, event) => {
31
58
  const config = loadConfiguration(env);
@@ -41,6 +68,7 @@ export function createServer({ env = process.env } = {}) {
41
68
  recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
42
69
  model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
43
70
  credential_status: credentialStatus,
71
+ execution_statistics: { collection: 'explicit_operator_opt_in', view: 'aptly stats', semantics: 'host_reported_model_evidence_not_user_acceptance', effective_effort: 'not_measured', usage_rollups: 'not_collected' },
44
72
  automatic_hook: { status: automatic.reason, mode: automatic.policy?.mode ?? 'disabled', transmission: automatic.policy ? effectiveTransmission(automatic.policy) : null, transmission_provenance: automatic.policy ? (automatic.policy.schema_version === 1 ? 'legacy_v1_default' : 'operator_policy_v2') : 'unavailable', host_settings_verified: false, context_tool: 'prepare_spawn_context', context_scope: 'this_process_exact_event_5_minutes', context_retry_tool: 'retry_spawn_recommendation', context_retry_limit: 1, fresh_delegation_tool: 'prepare_fresh_delegation', fresh_delegation_intent: 'caller_declared_not_verified', observation_tool: 'get_spawn_routing_observation', observation_scope: 'this_process_recent_calls', execution_observation: 'not_supported',
45
73
  guarantee: { scope: 'enabled_trusted_connected_supported_hook_only', missing_hook_detectable: false, unavailable_host_hook: 'host_controls_fallback', eligible_defaults_failure: 'deny_when_transmission_enabled', inherited_application: 'defaults_deny_advisory_feedback', caller_recovery: 'model_driven_not_guaranteed' } },
46
74
  });
@@ -70,7 +98,7 @@ export function createServer({ env = process.env } = {}) {
70
98
  server.registerTool('recommend_agent', {
71
99
  description: 'Recommend an allowlisted profile for a supplied task only; never inspects host settings, spawns, or authorizes an agent. Optional constraints describe caller-declared choices to preserve; omitted flags are not claims about current host settings. Decisions mode may incur a bounded classification request.', annotations,
72
100
  inputSchema: { request_id: z.string().min(1).max(96), client: z.enum(['codex', 'claude']), task: taskSchema, eligible_profile_ids: z.array(z.string()).min(1).max(20).optional(), constraints: constraintsSchema.optional() }
73
- }, async (input) => content({ ...await router.advise(input), provider: mode }));
101
+ }, async (input) => { const result = await router.advise(input); await trackStatistics(input.client, { requestId: input.request_id, recommendation: result }); return content({ ...result, provider: mode }); });
74
102
  server.registerTool('retry_spawn_recommendation', {
75
103
  description: 'Supply one bounded task description after an Aptly Hook returns needs_context and a retry_id. Use the same MCP process within five minutes; no native call IDs are needed. May make one paid classification; duplicate input reuses its request identity, changed input conflicts. Never spawns or changes history. If still needs_context/unavailable, stop; do not create another ID. A blocked spawn_application remains advisory.',
76
104
  annotations, inputSchema: { retry_id: z.string().regex(/^[a-f0-9]{64}$/), description: z.string().max(4000) }
@@ -83,6 +111,9 @@ export function createServer({ env = process.env } = {}) {
83
111
  result = { status: 'unavailable', reason: 'context_retry_unavailable', application: 'advisory_only', retry_id, context_retry_allowed: false };
84
112
  }
85
113
  observations.recordRetry(retry_id, result);
114
+ const client = typeof result.profile === 'object' && result.profile && 'client' in result.profile ? result.profile.client : undefined;
115
+ if (client === 'codex' || client === 'claude')
116
+ await trackStatistics(client, { requestId: retry_id, recommendation: result });
86
117
  return content(result);
87
118
  });
88
119
  server.registerTool('prepare_fresh_delegation', {
@@ -92,6 +123,7 @@ export function createServer({ env = process.env } = {}) {
92
123
  }, async ({ retry_id, task_name, standalone_task, declaration }, extra) => {
93
124
  const result = retries.prepareFresh(retry_id, task_name, standalone_task, declaration, extra.signal);
94
125
  observations.recordFresh(retry_id, result);
126
+ await trackStatistics('codex', { requestId: retry_id, recommendation: result });
95
127
  return content(result);
96
128
  });
97
129
  server.registerTool('get_routing_precedence', {
@@ -108,6 +140,7 @@ export function createServer({ env = process.env } = {}) {
108
140
  if (env.APTLY_HOOK_POLICY_PATH !== undefined) {
109
141
  const result = await automaticHook({ client, event, router, policyPath: env.APTLY_HOOK_POLICY_PATH, signal: extra.signal, context: () => contexts.lookup(client, event), onObservation: value => observations.record(value), onNeedsContext: (seed, current) => retries.register(seed, current), onBlockedAdvice: (seed, current) => retries.registerAdvice(seed, current) });
110
142
  observations.record(result.observation);
143
+ await trackStatistics(client, { event, observation: result.observation });
111
144
  return { content: [{ type: 'text', text: JSON.stringify(result.output) }] };
112
145
  }
113
146
  const input = hookInput({ client, event, policy: router.policy });
@@ -16,6 +16,8 @@ export interface SetupClientResult {
16
16
  codes: string[];
17
17
  invalid_budget_keys?: string[];
18
18
  budget_error?: string;
19
+ policy_location?: 'default_home' | 'elsewhere';
20
+ selected_home_source?: 'default' | 'override';
19
21
  requires_hook_review?: boolean;
20
22
  recovery?: string[];
21
23
  transmission?: string;
@@ -35,6 +37,8 @@ export interface SetupResult {
35
37
  }
36
38
  export declare const configurableEnvironmentKeys: readonly string[];
37
39
  export declare function setupHosts(options?: SetupOptions): SetupResult;
40
+ /** Snapshot the normal setup plan without applying it; it does not verify a running host. */
41
+ export declare function checkSetup(options?: SetupOptions): SetupResult;
38
42
  export declare function removeSetup(options?: SetupOptions): SetupResult;
39
43
  export declare function setDefaults(options?: SetupOptions): SetupResult;
40
44
  export declare function setEnvironment(key: string, value: string, options?: SetupOptions): SetupResult;
@@ -111,4 +115,52 @@ export declare function showBudgetStatus(options?: SetupOptions): {
111
115
  codes: string[];
112
116
  })[];
113
117
  };
118
+ /** Explicit collection controls; legacy routing receipt and model/credential settings stay untouched. */
119
+ export declare function setStatisticsCollection(enabled: boolean, options?: SetupOptions & {
120
+ codexNativeMetadata?: boolean;
121
+ }): SetupResult;
122
+ /** Snapshot view; no runtime, credentials, provider, budget gate or state creation. */
123
+ export declare function showStatistics(options?: SetupOptions, today?: boolean): {
124
+ clients: ({
125
+ status: string;
126
+ scope: string;
127
+ semantics: string;
128
+ observation_completeness: string;
129
+ today_basis: string;
130
+ filter: {
131
+ client: "all" | import("./types.ts").Client;
132
+ today: boolean;
133
+ };
134
+ collection: {
135
+ codex: boolean;
136
+ claude: boolean;
137
+ };
138
+ capacity: {
139
+ delegations: number;
140
+ children: number;
141
+ reached: boolean;
142
+ };
143
+ delegations: number;
144
+ auto: Record<import("./statistics.ts").ModelState, number>;
145
+ advisory: Record<import("./statistics.ts").ModelState, number>;
146
+ blocked: number;
147
+ explicit_preserved: number;
148
+ unbound: number;
149
+ effort_actual_unknown: number;
150
+ application_confirmed: number;
151
+ unknown_alias_count: number;
152
+ model_observed: number;
153
+ model_comparable: number;
154
+ model_match_denominator: number;
155
+ observation_denominator: number;
156
+ usage_scope: string;
157
+ model_alias_scope: string;
158
+ counts_are_lifetime: boolean;
159
+ client: Client;
160
+ } | {
161
+ client: Client;
162
+ status: string;
163
+ collection: string;
164
+ })[];
165
+ };
114
166
  export {};