aptly 0.1.6 → 0.1.8

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,100 @@
1
+ import { isAbsolute } from 'node:path';
2
+ import { budgetEnvironmentDefaults } from './budget.js';
3
+ const client = ['codex', 'claude', 'all'];
4
+ const scope = ['none', 'description', 'excerpt'];
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 } },
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
+ 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
+ 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.' },
10
+ 'catalog refresh': { usage: 'aptly catalog refresh --output ABS_PATH', description: 'Fetch official model descriptions into a private cache. --output must be an absolute path in a private directory. No model-account availability is certified. Set APTLY_MODEL_INFO_PATH and restart MCP to use the cache.', options: { '--output': 'path' } },
11
+ recommend: { usage: 'aptly recommend < request.json', description: 'Read request JSON from stdin. Required: request_id, client (codex|claude), task {summary, operation, context_sufficient}.\nOptional: eligible_profile_ids and caller-declared constraints. Results are advisory_only; no host settings are inspected or changed. Permissions and history remain with the host. Decisions mode may make a paid classification.\nExamples: examples/recommend.codex.json and examples/recommend.claude.json.' },
12
+ inspect: { usage: 'aptly inspect codex|claude FILE', description: 'Read an explicit JSON settings inventory and explain precedence. Does not discover the running host or call an API.', positional: ['client', 'file'] },
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
+ 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
+ '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'] },
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
+ 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
+ '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 } },
21
+ 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
+ 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
+ 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' } },
24
+ };
25
+ const helpFlag = (value) => value === '--help' || value === '-h';
26
+ /** Pure help dispatch. Required positional arguments may be omitted; supplied values/options are validated. */
27
+ export function resolveCliHelp(argv, { environmentKeys = [] } = {}) {
28
+ const prefixed = argv[0] === 'help';
29
+ if (!prefixed && !argv.some(helpFlag))
30
+ return undefined;
31
+ const tokens = prefixed ? argv.slice(1) : [...argv], clean = tokens.filter(token => !helpFlag(token));
32
+ let path = '', count = 0;
33
+ if (clean.length && clean[0] !== '--version') {
34
+ if (!clean[0] || clean[0].includes(' ') || !Object.hasOwn(entries, clean[0]))
35
+ return { kind: 'error', code: 'invalid_help_options' };
36
+ path = clean[0];
37
+ count = 1;
38
+ if (['set', 'catalog', 'budget'].includes(path) && clean[1] && Object.hasOwn(entries, path + ' ' + clean[1])) {
39
+ path += ' ' + clean[1];
40
+ count = 2;
41
+ }
42
+ }
43
+ const spec = entries[path], tail = [];
44
+ for (const token of tokens) {
45
+ if (count) {
46
+ if (!helpFlag(token))
47
+ count--;
48
+ continue;
49
+ }
50
+ tail.push(token);
51
+ }
52
+ const seen = new Set(), values = new Map(), positionals = [], options = spec.options ?? {};
53
+ for (let i = 0; i < tail.length; i++) {
54
+ const token = tail[i];
55
+ if (helpFlag(token))
56
+ continue;
57
+ const filePosition = spec.positional?.[positionals.length] === 'file';
58
+ if (token.startsWith('-') && !filePosition) {
59
+ if (!Object.hasOwn(options, token) || seen.has(token))
60
+ return { kind: 'error', code: 'invalid_help_options' };
61
+ if (path === 'set transmission' && token === '--show' && (seen.size || positionals.length))
62
+ return { kind: 'error', code: 'invalid_help_options' };
63
+ seen.add(token);
64
+ const type = options[token];
65
+ if (type === true)
66
+ continue;
67
+ const value = tail[++i];
68
+ if (!value || helpFlag(value) || (type === 'path' ? value.startsWith('--') : value.startsWith('-')) || (type !== 'path' && !type.includes(value)))
69
+ return { kind: 'error', code: 'invalid_help_options' };
70
+ values.set(token, value);
71
+ if (path === 'catalog refresh' && token === '--output' && !isAbsolute(value))
72
+ return { kind: 'error', code: 'invalid_help_options' };
73
+ }
74
+ else {
75
+ if (!token || seen.size)
76
+ return { kind: 'error', code: 'invalid_help_options' };
77
+ positionals.push(token);
78
+ }
79
+ }
80
+ if (positionals.length > (spec.positional?.length ?? 0))
81
+ return { kind: 'error', code: 'invalid_help_options' };
82
+ for (let i = 0; i < positionals.length; i++) {
83
+ const type = spec.positional[i], value = positionals[i];
84
+ if (type === 'client' && !['codex', 'claude'].includes(value) || type === 'scope' && !scope.includes(value) || type === 'environment' && !environmentKeys.includes(value))
85
+ return { kind: 'error', code: 'invalid_help_options' };
86
+ }
87
+ if (path === 'set env' && seen.has('--check') && (seen.has('--stdin') || (positionals[0] !== undefined && positionals[0] !== 'OPENAI_API_KEY')))
88
+ return { kind: 'error', code: 'invalid_help_options' };
89
+ if (path === 'set transmission' && seen.has('--show') && positionals.length)
90
+ return { kind: 'error', code: 'invalid_help_options' };
91
+ if (path === 'setup') {
92
+ const migrate = seen.has('--migrate-launcher');
93
+ if ((seen.has('--dry-run') || seen.has('--include-existing')) && !migrate)
94
+ return { kind: 'error', code: 'invalid_help_options' };
95
+ if (migrate && (seen.has('--automatic') || seen.has('--mode') || seen.has('--transmission') || values.get('--client') === 'all'))
96
+ return { kind: 'error', code: 'invalid_help_options' };
97
+ }
98
+ const text = 'Usage: ' + spec.usage + '\n\n' + spec.description.replace('$ENV_KEYS', environmentKeys.join(', ')) + '\n\nHelp: --help, -h, or aptly help' + (path ? ' ' + path : '') + '\n';
99
+ return { kind: 'help', text };
100
+ }
@@ -3,3 +3,5 @@ export declare function readEnvironmentValue({ key, fromStdin }: {
3
3
  key: string;
4
4
  fromStdin?: boolean;
5
5
  }): Promise<string>;
6
+ /** Operator choice of external transmission scope; Enter selects no automatic transmission. */
7
+ export declare function readTransmissionChoice(): Promise<'none' | 'description' | 'excerpt'>;
@@ -47,3 +47,36 @@ export async function readEnvironmentValue({ key, fromStdin = false }) {
47
47
  process.stdout.write('\n');
48
48
  }
49
49
  }
50
+ /** Operator choice of external transmission scope; Enter selects no automatic transmission. */
51
+ export async function readTransmissionChoice() {
52
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
53
+ throw fail('set_interactive_input_required');
54
+ process.stdout.write('Select task information sent to the OpenAI Decisions API (not Aptly developers).\nDescriptions and excerpts may contain sensitive information; this is not anonymization.\n 1. No automatic transmission (default)\n 2. Caller-provided descriptions only\n 3. Allow native task excerpts\n');
55
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
56
+ try {
57
+ return await new Promise((resolve, reject) => {
58
+ let settled = false;
59
+ const cancel = () => { if (!settled) {
60
+ settled = true;
61
+ reject(fail('set_input_cancelled'));
62
+ } };
63
+ rl.once('SIGINT', () => { cancel(); rl.close(); });
64
+ rl.once('close', cancel);
65
+ const ask = () => rl.question('Transmission scope [1]: ', value => {
66
+ const choices = { '': 'none', '1': 'none', '2': 'description', '3': 'excerpt', none: 'none', description: 'description', excerpt: 'excerpt' };
67
+ const scope = Object.hasOwn(choices, value.trim()) ? choices[value.trim()] : undefined;
68
+ if (!scope) {
69
+ process.stdout.write('Choose 1, 2 or 3.\n');
70
+ ask();
71
+ return;
72
+ }
73
+ settled = true;
74
+ resolve(scope);
75
+ });
76
+ ask();
77
+ });
78
+ }
79
+ finally {
80
+ rl.close();
81
+ }
82
+ }
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { closeSync, openSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
- import { loadAutomaticHookPolicy } from './automatic-hook.js';
4
+ import { effectiveTransmission, loadAutomaticHookPolicy } from './automatic-hook.js';
5
5
  import { assertPrivateStatePath, readRegularFile } from './files.js';
6
6
  import { hasSufficientTaskText } from './context-sufficiency.js';
7
7
  const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
@@ -30,11 +30,16 @@ export class ContextRetries {
30
30
  return loaded.reason;
31
31
  if (loaded.fingerprint !== entry.seed.policy_fingerprint)
32
32
  return 'automatic_policy_changed';
33
- if (hash(this.router.policy) !== entry.catalog)
33
+ if (['none', 'unselected'].includes(effectiveTransmission(loaded.policy)))
34
+ return 'automatic_transmission_disabled';
35
+ if (hash(this.router.semanticPolicy()) !== entry.catalog)
34
36
  return 'catalog_changed';
35
37
  return undefined;
36
38
  }
37
39
  register(seed, current) {
40
+ const policy = loadAutomaticHookPolicy(this.policyPath);
41
+ if (!policy.policy?.enabled || policy.fingerprint !== seed.policy_fingerprint || ['none', 'unselected'].includes(effectiveTransmission(policy.policy)))
42
+ return { reason: 'automatic_policy_changed' };
38
43
  try {
39
44
  this.router.load();
40
45
  const original = this.router.state.requests[seed.request_id];
@@ -50,10 +55,13 @@ export class ContextRetries {
50
55
  return { retry_id }; // No renewal or replacement of a ticket.
51
56
  if (this.entries.size >= 128)
52
57
  return { reason: 'context_retry_capacity' };
53
- this.entries.set(retry_id, { seed: structuredClone(seed), at: this.now(), catalog: hash(this.router.policy), current });
58
+ this.entries.set(retry_id, { seed: structuredClone(seed), at: this.now(), catalog: hash(this.router.semanticPolicy()), current });
54
59
  return { retry_id };
55
60
  }
56
61
  registerAdvice(seed, current) {
62
+ const policy = loadAutomaticHookPolicy(this.policyPath);
63
+ if (!policy.policy?.enabled || policy.fingerprint !== seed.policy_fingerprint || ['none', 'unselected'].includes(effectiveTransmission(policy.policy)))
64
+ return { reason: 'automatic_policy_changed' };
57
65
  if (!seed.fresh_eligible || seed.application_blocked !== 'inherited_context_application_unverified')
58
66
  return { reason: 'fresh_delegation_unsupported' };
59
67
  try {
@@ -70,7 +78,7 @@ export class ContextRetries {
70
78
  return { retry_id };
71
79
  if (this.entries.size >= 128)
72
80
  return { reason: 'context_retry_capacity' };
73
- this.entries.set(retry_id, { seed: structuredClone(seed), at: this.now(), catalog: hash(this.router.policy), current, recommendation_id: seed.request_id });
81
+ this.entries.set(retry_id, { seed: structuredClone(seed), at: this.now(), catalog: hash(this.router.semanticPolicy()), current, recommendation_id: seed.request_id });
74
82
  return { retry_id };
75
83
  }
76
84
  async retry(retry_id, description, signal) {
@@ -1,4 +1,5 @@
1
- import type { Profile, RoutingPolicy, RoutingProvider, RoutingResult, RoutingStatus } from './types.ts';
1
+ import type { BudgetLimits } from './budget.ts';
2
+ import type { BudgetLimit, Profile, RoutingPolicy, RoutingProvider, RoutingResult, RoutingStatus } from './types.ts';
2
3
  export declare const defaultPolicy: Readonly<RoutingPolicy>;
3
4
  interface LedgerRecord {
4
5
  digest: string;
@@ -16,6 +17,7 @@ interface RouterOptions {
16
17
  policy?: RoutingPolicy;
17
18
  provider?: RoutingProvider;
18
19
  ledgerPath?: string;
20
+ budgetConfigurable?: boolean;
19
21
  }
20
22
  export declare class Router {
21
23
  policy: RoutingPolicy;
@@ -23,8 +25,30 @@ export declare class Router {
23
25
  ledgerPath: string | undefined;
24
26
  state: LedgerState;
25
27
  active: number;
28
+ private budgetConfigurable;
26
29
  private heldLedgerLock;
27
- constructor({ policy, provider, ledgerPath }?: RouterOptions);
30
+ constructor({ policy, provider, ledgerPath, budgetConfigurable }?: RouterOptions);
31
+ /** Stable legacy-default projection for runtime budget knobs only. Custom library policies retain their full identity. */
32
+ semanticPolicy(): RoutingPolicy;
33
+ private budgetSnapshot;
34
+ /** No provider, secret lookup, reservation or file creation. Existing ledgers use their existing gate. */
35
+ budgetStatus(): {
36
+ limits: BudgetLimits;
37
+ usage: {
38
+ daily_calls: number;
39
+ total_calls: number;
40
+ estimated_usd: number;
41
+ };
42
+ remaining: {
43
+ daily_calls: number | null;
44
+ total_calls: number | null;
45
+ estimated_usd: number | null;
46
+ };
47
+ utc_day: string;
48
+ timezone: 'UTC';
49
+ local_estimate: true;
50
+ exhausted_by: BudgetLimit[];
51
+ };
28
52
  capabilities(): {
29
53
  policy_version: string;
30
54
  catalog_version: string;
@@ -39,7 +63,9 @@ export declare class Router {
39
63
  };
40
64
  result(status: RoutingStatus, reason: string, extra?: Partial<RoutingResult>): RoutingResult;
41
65
  validateOutcome(result: unknown): asserts result is RoutingResult;
42
- load(): void;
66
+ load({ readOnly }?: {
67
+ readOnly?: boolean;
68
+ }): void;
43
69
  save(): void;
44
70
  /** Strict native-routing path: preserves existing host-evidence and digest semantics. */
45
71
  recommend(input: unknown): Promise<RoutingResult>;
package/dist/src/core.js CHANGED
@@ -3,11 +3,12 @@ import { openSync, closeSync, readFileSync, writeFileSync, renameSync, unlinkSyn
3
3
  import { isRecord, errorCode } from './types.js';
4
4
  import { builtInProfiles, resolveCatalog, isSupportedProfile } from './catalog.js';
5
5
  import { acquireLedgerLock } from './ledger-lock.js';
6
+ import { defaultBudgetLimits } from './budget.js';
6
7
  const defaultCatalog = resolveCatalog({});
7
8
  export const defaultPolicy = Object.freeze({
8
9
  version: 'aptly-v010', catalog_version: defaultCatalog.version, max_summary_bytes: 4000,
9
- max_concurrency: 1, max_daily_calls: 20, max_total_calls: 50,
10
- estimated_call_usd: 0.01, max_estimated_usd: 0.5, timeout_ms: 10000,
10
+ max_concurrency: 1, max_daily_calls: defaultBudgetLimits.max_daily_calls, max_total_calls: defaultBudgetLimits.max_total_calls,
11
+ estimated_call_usd: defaultBudgetLimits.estimated_call_usd, max_estimated_usd: defaultBudgetLimits.max_estimated_usd, timeout_ms: 10000,
11
12
  profiles: Object.freeze(builtInProfiles().map(profile => Object.freeze(profile))),
12
13
  profile_descriptions: Object.freeze(defaultCatalog.descriptions),
13
14
  });
@@ -67,18 +68,20 @@ export class Router {
67
68
  ledgerPath;
68
69
  state;
69
70
  active;
71
+ budgetConfigurable;
70
72
  heldLedgerLock;
71
- constructor({ policy = defaultPolicy, provider, ledgerPath } = {}) {
73
+ constructor({ policy = defaultPolicy, provider, ledgerPath, budgetConfigurable = policy === defaultPolicy } = {}) {
74
+ this.budgetConfigurable = budgetConfigurable;
72
75
  this.policy = clone(policy);
73
76
  const integerCaps = { max_summary_bytes: 64000, max_concurrency: 16, max_daily_calls: 100000, max_total_calls: 1000000, timeout_ms: 60000 };
74
77
  if (!safeVersion(policy.version) || !safeVersion(policy.catalog_version))
75
78
  throw new Error('invalid_policy');
76
79
  for (const k of Object.keys(integerCaps)) {
77
- if (!safeInt(this.policy[k], integerCaps[k]) || this.policy[k] === 0)
80
+ if (!safeInt(this.policy[k], integerCaps[k]) || (this.policy[k] === 0 && k !== 'max_daily_calls' && k !== 'max_total_calls'))
78
81
  throw new Error('invalid_policy');
79
82
  }
80
83
  for (const k of ['estimated_call_usd', 'max_estimated_usd'])
81
- if (!Number.isFinite(policy[k]) || policy[k] <= 0 || policy[k] > 100)
84
+ if (!Number.isFinite(policy[k]) || (policy[k] < 0 || (k === 'estimated_call_usd' && policy[k] === 0)) || policy[k] > 100)
82
85
  throw new Error('invalid_policy');
83
86
  if (typeof provider !== 'function')
84
87
  throw new Error('invalid_provider');
@@ -95,6 +98,54 @@ export class Router {
95
98
  this.state = empty();
96
99
  this.active = 0;
97
100
  }
101
+ /** Stable legacy-default projection for runtime budget knobs only. Custom library policies retain their full identity. */
102
+ semanticPolicy() {
103
+ return this.budgetConfigurable ? { ...clone(this.policy), max_daily_calls: 20, max_total_calls: 50, estimated_call_usd: 0.01, max_estimated_usd: 0.5 } : clone(this.policy);
104
+ }
105
+ budgetSnapshot(utc_day = new Date().toISOString().slice(0, 10)) {
106
+ const limits = { max_daily_calls: this.policy.max_daily_calls, max_total_calls: this.policy.max_total_calls, max_estimated_usd: this.policy.max_estimated_usd, estimated_call_usd: this.policy.estimated_call_usd };
107
+ const daily_calls = this.state.days[utc_day] ?? 0;
108
+ const exhausted_by = [];
109
+ if (limits.max_daily_calls > 0 && daily_calls >= limits.max_daily_calls)
110
+ exhausted_by.push('max_daily_calls');
111
+ if (limits.max_total_calls > 0 && this.state.calls >= limits.max_total_calls)
112
+ exhausted_by.push('max_total_calls');
113
+ if (limits.max_estimated_usd > 0 && this.state.estimated_usd + limits.estimated_call_usd > limits.max_estimated_usd + 1e-12)
114
+ exhausted_by.push('max_estimated_usd');
115
+ return { limits, usage: { daily_calls, total_calls: this.state.calls, estimated_usd: this.state.estimated_usd },
116
+ remaining: { daily_calls: limits.max_daily_calls === 0 ? null : Math.max(0, limits.max_daily_calls - daily_calls),
117
+ total_calls: limits.max_total_calls === 0 ? null : Math.max(0, limits.max_total_calls - this.state.calls),
118
+ estimated_usd: limits.max_estimated_usd === 0 ? null : Math.max(0, limits.max_estimated_usd - this.state.estimated_usd) },
119
+ utc_day, timezone: 'UTC', local_estimate: true,
120
+ exhausted_by };
121
+ }
122
+ /** No provider, secret lookup, reservation or file creation. Existing ledgers use their existing gate. */
123
+ budgetStatus() {
124
+ if (this.active)
125
+ throw Object.assign(new Error('ledger_locked'), { code: 'ledger_locked' });
126
+ if (!this.ledgerPath)
127
+ return this.budgetSnapshot();
128
+ try {
129
+ lstatSync(this.ledgerPath);
130
+ }
131
+ catch (error) {
132
+ if (errorCode(error) === 'ENOENT') {
133
+ this.state = empty();
134
+ return this.budgetSnapshot();
135
+ }
136
+ throw error;
137
+ }
138
+ const lock = acquireLedgerLock(this.ledgerPath, { initialize: false });
139
+ this.heldLedgerLock = lock;
140
+ try {
141
+ this.load({ readOnly: true });
142
+ return this.budgetSnapshot();
143
+ }
144
+ finally {
145
+ this.heldLedgerLock = undefined;
146
+ lock.release();
147
+ }
148
+ }
98
149
  capabilities() {
99
150
  return { policy_version: this.policy.version, catalog_version: this.policy.catalog_version,
100
151
  profiles: clone(this.policy.profiles), profile_descriptions: clone(this.policy.profile_descriptions ?? {}), application: 'advisory_only',
@@ -122,15 +173,16 @@ export class Router {
122
173
  else if (own(result, 'profile') || own(result, 'profile_id'))
123
174
  throw new Error('invalid_outcome');
124
175
  }
125
- load() {
176
+ load({ readOnly = false } = {}) {
126
177
  if (!this.ledgerPath)
127
178
  return;
128
179
  this.heldLedgerLock?.assertHeld();
129
180
  try {
130
181
  const stat = lstatSync(this.ledgerPath);
131
- if (!stat.isFile() || stat.isSymbolicLink())
182
+ if (!stat.isFile() || stat.isSymbolicLink() || (readOnly && process.platform !== 'win32' && ((stat.mode & 0o077) !== 0 || (process.getuid && stat.uid !== process.getuid()))))
132
183
  throw new Error('unsafe_ledger');
133
- chmodSync(this.ledgerPath, 0o600);
184
+ if (!readOnly)
185
+ chmodSync(this.ledgerPath, 0o600);
134
186
  const state = JSON.parse(readFileSync(this.ledgerPath, 'utf8'));
135
187
  if (!keysOnly(state, ['version', 'calls', 'estimated_usd', 'days', 'requests']) || state.version !== 1 || !safeInt(state.calls) || typeof state.estimated_usd !== 'number' || !Number.isFinite(state.estimated_usd) || state.estimated_usd < 0 ||
136
188
  !isRecord(state.days) || !isRecord(state.requests))
@@ -227,7 +279,7 @@ export class Router {
227
279
  // Keep historical strict-path hashes unchanged. Advice has a separate digest
228
280
  // namespace within the SAME request ledger, so cross-purpose ID reuse cannot
229
281
  // reuse results or automatically retry a previously uncertain paid request.
230
- const hash = kind === 'hook' ? digest({ input: req, policy: this.policy }) : digest({ kind: 'advisory-v1', input: req, policy: this.policy });
282
+ const hash = kind === 'hook' ? digest({ input: req, policy: this.semanticPolicy() }) : digest({ kind: 'advisory-v1', input: req, policy: this.semanticPolicy() });
231
283
  if (this.active >= this.policy.max_concurrency)
232
284
  return this.result('unavailable', 'concurrency_limit');
233
285
  let lock;
@@ -253,7 +305,10 @@ export class Router {
253
305
  if (previous.result.policy_version !== this.policy.version || previous.result.catalog_version !== this.policy.catalog_version ||
254
306
  (previous.result.status === 'recommended' && !profiles.some(p => p.id === previous.result?.profile_id && digest(p) === digest(previous.result?.profile))))
255
307
  return this.result('unavailable', 'ledger_error');
256
- return { ...clone(previous.result), cached: true };
308
+ if (!(previous.result.status === 'unavailable' && previous.result.reason === 'budget_exhausted'))
309
+ return { ...clone(previous.result), cached: true };
310
+ // A verified historical local denial did not reserve or dispatch a call.
311
+ // Only this known completion can proceed again under the same ID.
257
312
  }
258
313
  const complete = (result) => {
259
314
  this.state.requests[req.request_id] = { digest: hash, state: 'complete', result };
@@ -274,8 +329,9 @@ export class Router {
274
329
  return this.result('unavailable', errorCode(e) === 'unauthorized' ? 'unauthorized' : 'provider_error');
275
330
  }
276
331
  const day = new Date().toISOString().slice(0, 10);
277
- if (this.state.calls >= this.policy.max_total_calls || (this.state.days[day] ?? 0) >= this.policy.max_daily_calls || this.state.estimated_usd + this.policy.estimated_call_usd > this.policy.max_estimated_usd + 1e-12)
278
- return complete(this.result('unavailable', 'budget_exhausted'));
332
+ const exhausted = this.budgetSnapshot(day).exhausted_by;
333
+ if (exhausted.length)
334
+ return this.result('unavailable', 'budget_exhausted', { budget_limit: exhausted[0] });
279
335
  this.state.calls++;
280
336
  this.state.days[day] = (this.state.days[day] ?? 0) + 1;
281
337
  this.state.estimated_usd += this.policy.estimated_call_usd;
@@ -5,4 +5,6 @@ export interface LedgerLock {
5
5
  release(): void;
6
6
  }
7
7
  /** Local, hard-link-capable filesystems only; no PID or stale-age recovery. */
8
- export declare function acquireLedgerLock(ledgerPath: string): LedgerLock;
8
+ export declare function acquireLedgerLock(ledgerPath: string, options?: {
9
+ initialize?: boolean;
10
+ }): LedgerLock;
@@ -82,7 +82,7 @@ function initialize(path, Database) {
82
82
  }
83
83
  }
84
84
  /** Local, hard-link-capable filesystems only; no PID or stale-age recovery. */
85
- export function acquireLedgerLock(ledgerPath) {
85
+ export function acquireLedgerLock(ledgerPath, options = {}) {
86
86
  let connection, transaction = false;
87
87
  try {
88
88
  const path = `${ledgerPath}.lock`;
@@ -97,6 +97,8 @@ export function acquireLedgerLock(ledgerPath) {
97
97
  catch (error) {
98
98
  if (codeOf(error) !== 'ENOENT')
99
99
  throw error;
100
+ if (options.initialize === false)
101
+ fail('ledger_error');
100
102
  initialize(path, DatabaseSync);
101
103
  }
102
104
  assertPrivateStatePath(path);
@@ -4,6 +4,7 @@ export declare function runtime(env?: NodeJS.ProcessEnv, options?: {
4
4
  secretLoader?: typeof loadSecret;
5
5
  }): {
6
6
  router: Router;
7
+ budget: import("./budget.ts").BudgetSettings;
7
8
  mode: "decisions" | "fixture";
8
9
  modelInfo: import("./model-info.ts").LoadedModelInfo;
9
10
  credentialStatus: string;
@@ -1,3 +1,4 @@
1
+ import { resolveBudgetSettings } from './budget.js';
1
2
  import { Router, defaultPolicy } from './core.js';
2
3
  import { decisionsProvider, fixtureProvider } from './provider.js';
3
4
  import { loadConfiguration } from './config.js';
@@ -6,6 +7,7 @@ import { loadModelInfo } from './model-info.js';
6
7
  import { assertPrivateStatePath } from './files.js';
7
8
  import { loadSecret } from './secret-store.js';
8
9
  export function runtime(env = process.env, options = {}) {
10
+ const budget = resolveBudgetSettings(env);
9
11
  const value = env.ROUTER_PROVIDER ?? 'fixture';
10
12
  if (value !== 'fixture' && value !== 'decisions')
11
13
  throw new Error('invalid_provider_mode');
@@ -17,7 +19,7 @@ export function runtime(env = process.env, options = {}) {
17
19
  }
18
20
  const modelInfo = loadModelInfo(env.APTLY_MODEL_INFO_PATH);
19
21
  const catalog = resolveCatalog(env, modelInfo.facts);
20
- const policy = { ...defaultPolicy, provider_id: mode, profiles: catalog.profiles, profile_descriptions: catalog.descriptions, catalog_version: catalog.version };
22
+ const policy = { ...defaultPolicy, ...budget.limits, provider_id: mode, profiles: catalog.profiles, profile_descriptions: catalog.descriptions, catalog_version: catalog.version };
21
23
  let key = env.OPENAI_API_KEY, credentialStatus = mode === 'fixture' ? 'unused_in_fixture' : key ? 'environment' : 'not_configured';
22
24
  if (mode === 'decisions' && env.APTLY_SECRET_BACKEND !== undefined) {
23
25
  key = undefined;
@@ -32,7 +34,7 @@ export function runtime(env = process.env, options = {}) {
32
34
  credentialStatus = 'os_store_unavailable';
33
35
  }
34
36
  }
35
- const router = new Router({ policy, provider: mode === 'fixture' ? fixtureProvider : decisionsProvider({ key, descriptions: catalog.descriptions }), ledgerPath: env.ROUTER_LEDGER_PATH });
37
+ const router = new Router({ policy, budgetConfigurable: true, provider: mode === 'fixture' ? fixtureProvider : decisionsProvider({ key, descriptions: catalog.descriptions }), ledgerPath: env.ROUTER_LEDGER_PATH });
36
38
  key = undefined;
37
- return { router, mode, modelInfo, credentialStatus, disabledClients: catalog.disabled_clients, configuration: loadConfiguration(env) };
39
+ return { router, budget, mode, modelInfo, credentialStatus, disabledClients: catalog.disabled_clients, configuration: loadConfiguration(env) };
38
40
  }
@@ -7,7 +7,7 @@ import { VERSION } from './version.js';
7
7
  import { hookInput, hookOutput } from './hook.js';
8
8
  import { resolveProvenance } from './provenance.js';
9
9
  import { loadConfiguration, loadHostContext } from './config.js';
10
- import { automaticHook, loadAutomaticHookPolicy, initialHookObservation } from './automatic-hook.js';
10
+ import { automaticHook, effectiveTransmission, loadAutomaticHookPolicy, initialHookObservation } from './automatic-hook.js';
11
11
  import { SpawnContexts } from './spawn-context.js';
12
12
  import { RoutingObservations } from './routing-observations.js';
13
13
  import { ContextRetries } from './context-retry.js';
@@ -21,7 +21,7 @@ const observationSchema = z.object({ client: hookSchema.client.optional(), event
21
21
  });
22
22
  const content = (result) => ({ content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
23
23
  export function createServer({ env = process.env } = {}) {
24
- const { router, mode, modelInfo, credentialStatus, disabledClients } = runtime(env);
24
+ const { router, budget, mode, modelInfo, credentialStatus, disabledClients } = runtime(env);
25
25
  const observations = new RoutingObservations();
26
26
  const contexts = new SpawnContexts();
27
27
  const retries = new ContextRetries(router, env.APTLY_HOOK_POLICY_PATH);
@@ -33,15 +33,18 @@ export function createServer({ env = process.env } = {}) {
33
33
  const precedence = resolveProvenance({ client, event, context: loaded.context });
34
34
  return { config, loaded, precedence };
35
35
  };
36
- server.registerTool('get_routing_capabilities', { description: 'Advisory profile catalog, provider and local budget limits. No paid call.', annotations, inputSchema: {} }, async () => content({
37
- ...router.capabilities(), provider: mode, hook_mode: loadConfiguration(env).mode,
38
- precedence: 'per_call_effective_host_evidence_required', automatic_settings_discovery: false,
39
- recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
40
- model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
41
- credential_status: credentialStatus,
42
- automatic_hook: { status: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).reason, mode: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).policy?.mode ?? 'disabled', 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',
43
- guarantee: { scope: 'enabled_trusted_connected_supported_hook_only', missing_hook_detectable: false, unavailable_host_hook: 'host_controls_fallback', eligible_defaults_failure: 'deny', inherited_application: 'defaults_deny_advisory_feedback', caller_recovery: 'model_driven_not_guaranteed' } },
44
- }));
36
+ server.registerTool('get_routing_capabilities', { description: 'Advisory profile catalog, provider and local budget limits. No paid call.', annotations, inputSchema: {} }, async () => {
37
+ const automatic = loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH);
38
+ return content({
39
+ ...router.capabilities(), budget_configuration: { ...budget, zero_ceiling_means_unlimited: true, settings_require_mcp_restart: true, cost_guard: 'local_estimate_not_billing_cap' }, provider: mode, hook_mode: loadConfiguration(env).mode,
40
+ precedence: 'per_call_effective_host_evidence_required', automatic_settings_discovery: false,
41
+ recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
42
+ model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
43
+ credential_status: credentialStatus,
44
+ 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
+ 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
+ });
47
+ });
45
48
  server.registerTool('get_spawn_routing_observation', {
46
49
  description: 'Look up an exact spawn event OR a Hook-issued retry_id in this MCP process (128 calls, 10 minutes). Supply only {client,event} or only {retry_id}. Original preflight and context_retry outcome are separate; no provider call. Missing records never prove bypass; execution remains not_observed.',
47
50
  annotations: { ...annotations, openWorldHint: false }, inputSchema: observationSchema
@@ -54,6 +57,8 @@ export function createServer({ env = process.env } = {}) {
54
57
  const policy = loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH);
55
58
  if (!policy.policy?.enabled)
56
59
  return content({ status: 'rejected', reason: policy.reason });
60
+ if (['none', 'unselected'].includes(effectiveTransmission(policy.policy)))
61
+ return content({ status: 'rejected', reason: 'automatic_transmission_disabled' });
57
62
  if (extra.signal.aborted)
58
63
  return content({ status: 'rejected', reason: 'context_cancelled' });
59
64
  return content(contexts.register(client, event, description, router.policy.max_summary_bytes));
@@ -6,13 +6,28 @@ export interface SetupOptions {
6
6
  automatic?: boolean;
7
7
  clients?: Client[];
8
8
  mode?: 'defaults' | 'advisory';
9
+ transmission?: TransmissionScope;
10
+ selectUnselectedOnly?: boolean;
9
11
  }
12
+ export type TransmissionScope = 'none' | 'description' | 'excerpt';
10
13
  export interface SetupClientResult {
11
14
  client: Client;
12
15
  status: 'configured' | 'unchanged' | 'removed' | 'skipped' | 'error';
13
16
  codes: string[];
17
+ invalid_budget_keys?: string[];
18
+ budget_error?: string;
14
19
  requires_hook_review?: boolean;
15
20
  recovery?: string[];
21
+ transmission?: string;
22
+ transmission_source?: 'explicit' | 'legacy' | 'unselected';
23
+ budget?: {
24
+ limits: Record<string, number>;
25
+ added: string[];
26
+ updated: string[];
27
+ preserved: string[];
28
+ inherited: string[];
29
+ restart_required: boolean;
30
+ };
16
31
  }
17
32
  export interface SetupResult {
18
33
  status: 'complete' | 'partial' | 'skipped';
@@ -33,4 +48,67 @@ export declare function prepareCredentialReference(options: SetupOptions, client
33
48
  };
34
49
  /** Preserved standard registrations require a separate explicit opt-in; ownership stays unchanged. */
35
50
  export declare function migrateLauncher(options: SetupOptions, dryRun?: boolean, includeExisting?: boolean): SetupResult;
51
+ /** Explicit operator change; updates policy and its receipt through normal guarded staging. */
52
+ export declare function setTransmission(scope: TransmissionScope, options?: SetupOptions): SetupResult;
53
+ /** Read-only redacted policy state. Does not create host directories or contact a provider. */
54
+ export declare function showTransmission(options?: SetupOptions): {
55
+ clients: ({
56
+ client: Client;
57
+ status: string;
58
+ code: string;
59
+ application_mode?: undefined;
60
+ enabled?: undefined;
61
+ transmission?: undefined;
62
+ transmission_source?: undefined;
63
+ } | {
64
+ code?: undefined;
65
+ client: Client;
66
+ status: string;
67
+ application_mode: "advisory" | "defaults";
68
+ enabled: boolean;
69
+ transmission: import("./automatic-hook.ts").Transmission;
70
+ transmission_source: string;
71
+ })[];
72
+ };
73
+ /** Registration snapshot only. Never loads credentials, starts a server or creates a ledger/gate. */
74
+ export declare function showBudgetStatus(options?: SetupOptions): {
75
+ status: string;
76
+ clients: ({
77
+ client: Client;
78
+ status: string;
79
+ budget: {
80
+ limits: import("./budget.ts").BudgetLimits;
81
+ usage: {
82
+ daily_calls: number;
83
+ total_calls: number;
84
+ estimated_usd: number;
85
+ };
86
+ remaining: {
87
+ daily_calls: number | null;
88
+ total_calls: number | null;
89
+ estimated_usd: number | null;
90
+ };
91
+ utc_day: string;
92
+ timezone: 'UTC';
93
+ local_estimate: true;
94
+ exhausted_by: import("./types.ts").BudgetLimit[];
95
+ provenance: Record<keyof import("./budget.ts").BudgetLimits, "default" | "environment">;
96
+ display_limits: {
97
+ [k: string]: any;
98
+ };
99
+ next_utc_day: string;
100
+ cost_guard: string;
101
+ snapshot_source: string;
102
+ running_host_verified: boolean;
103
+ settings_require_mcp_restart: boolean;
104
+ };
105
+ } | {
106
+ invalid_budget_keys?: string[];
107
+ budget_error?: import("./budget.ts").BudgetErrorReason;
108
+ budget?: undefined;
109
+ client: Client;
110
+ status: string;
111
+ codes: string[];
112
+ })[];
113
+ };
36
114
  export {};