aptly 0.1.9 → 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,7 +10,7 @@ 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 { checkSetup, 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
16
  import { linuxStoreReadiness } from '../src/linux-store-readiness.js';
@@ -40,6 +40,43 @@ try {
40
40
  if (result.status === 'error')
41
41
  process.exitCode = 1;
42
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
+ }
43
80
  else if (command === 'budget') {
44
81
  if (args[0] !== 'status')
45
82
  throw new Error('budget_invalid_options');
@@ -261,13 +298,13 @@ catch (error) {
261
298
  const budgetCode = [caughtCode, message].find(value => typeof value === 'string' && ['invalid_budget_configuration', 'budget_invalid_options'].includes(value));
262
299
  const configCode = [caughtCode, message].find(value => typeof value === 'string' && safeConfigurationCodes.includes(value));
263
300
  const setCodes = ['set_environment_key_unsupported', 'set_invalid_options', 'set_value_too_large', 'set_interactive_input_required', 'set_input_cancelled'];
264
- 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';
265
302
  const budgetDetails = budgetErrorDetails(error);
266
303
  process.stderr.write('aptly: ' + code + (budgetDetails.invalid_budget_keys?.length ? ' [' + budgetDetails.invalid_budget_keys.join(', ') + ']' : '') + (budgetDetails.budget_error ? ' (' + budgetDetails.budget_error + ')' : '') + '\n');
267
304
  process.exitCode = 1;
268
305
  }
269
306
  finally {
270
- if (!process.exitCode && !helpHandled) {
307
+ if (!process.exitCode && !helpHandled && command !== 'stats') {
271
308
  try {
272
309
  const hint = await updateNotification({ command, args, env: process.env, stdinIsTTY: !!process.stdin.isTTY, stderrIsTTY: !!process.stderr.isTTY, stdoutIsTTY: !!process.stdout.isTTY, currentVersion: VERSION });
273
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.' },
@@ -15,6 +15,9 @@ const entries = {
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
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
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 } },
@@ -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,6 +91,8 @@ 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');
93
98
  if (seen.has('--check') && [...seen].some(flag => !['--check', '--client'].includes(flag)))
@@ -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 });
@@ -115,4 +115,52 @@ export declare function showBudgetStatus(options?: SetupOptions): {
115
115
  codes: string[];
116
116
  })[];
117
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
+ };
118
166
  export {};