aptly 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/aptly.js CHANGED
@@ -9,35 +9,53 @@ import { collectDiagnostics } from '../src/diagnostics.js';
9
9
  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
- import { setupHosts, removeSetup, setDefaults, setEnvironment, configurableEnvironmentKeys, migrateLauncher, setTransmission, showTransmission } from '../src/setup.js';
12
+ import { budgetErrorDetails } from '../src/budget.js';
13
+ import { checkSetup, setupHosts, removeSetup, setDefaults, setEnvironment, configurableEnvironmentKeys, migrateLauncher, setTransmission, showTransmission, showBudgetStatus } from '../src/setup.js';
13
14
  import { readEnvironmentValue, readTransmissionChoice } from '../src/cli-input.js';
14
15
  import { prepareApiKey } from '../src/credential-setup.js';
16
+ import { linuxStoreReadiness } from '../src/linux-store-readiness.js';
15
17
  import { updateGlobalInstallation } from '../src/update.js';
16
18
  import { updateNotification } from '../src/update-notifier.js';
19
+ import { resolveCliHelp } from '../src/cli-help.js';
17
20
  const [command = 'serve', ...args] = process.argv.slice(2);
18
21
  const output = (value) => process.stdout.write(JSON.stringify(value, null, 2) + '\n');
22
+ let helpHandled = false;
19
23
  try {
20
- if (['--help', '-h', 'help'].includes(command)) {
21
- process.stdout.write('Aptly (preview)\n\nCommands:\n serve Start the stdio MCP server (default: fixture/shadow).\n capabilities Print the active catalog; no API call.\n catalog Print the active catalog; no API call.\n catalog refresh --output ABS_PATH Fetch official model descriptions to a private cache.\n recommend Recommend for a task JSON on stdin; no host evidence required.\n inspect CLIENT FILE Inspect an explicit JSON settings inventory; no API call.\n config CLIENT Print an MCP registration fragment; does not edit settings.\n set default Add defaults; select API transmission scope interactively.\n set transmission Set/show OpenAI Decisions API transmission scope.\n set env ENV_KEY Prompt for an MCP environment value.\n setup Register MCP and automatic PreToolUse Hooks.\n remove Remove only unchanged Aptly-owned registration.\n update Update this verified global npm installation.\n report Write redacted local diagnostic attachments (default: md + json).\n --format md|json|both Select report formats.\n --output-dir DIR Private output directory (default: reports).\n --version Print the package version.\n\nUse aptly set env OPENAI_API_KEY for OS storage, or pass it through the MCP environment.\nPaid mode additionally requires\nROUTER_PROVIDER=decisions and an absolute ROUTER_LEDGER_PATH in a private directory.\nROUTER_CONFIG_PATH is an optional private operator configuration file.\n');
24
+ const help = resolveCliHelp(process.argv.slice(2), { environmentKeys: ['OPENAI_API_KEY', ...configurableEnvironmentKeys] });
25
+ if (help) {
26
+ helpHandled = true;
27
+ if (help.kind === 'error') {
28
+ process.stderr.write('aptly: ' + help.code + ' (use --help)\n');
29
+ process.exitCode = 2;
30
+ }
31
+ else
32
+ process.stdout.write(help.text);
22
33
  }
23
34
  else if (command === 'update') {
24
- if (args.length === 1 && args[0] === '--help')
25
- process.stdout.write('Usage: aptly update\nRequires a verified global npm installation. Stop other hosts/MCP/CLI writers first.\nUpdates the same npm prefix without lifecycle setup. Run aptly setup and restart hosts afterward; existing launchers are preserved.\n');
26
- else {
27
- if (args.length)
28
- throw new Error('update_invalid_options');
29
- const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
30
- const result = updateGlobalInstallation({ packageRoot });
31
- output(result);
32
- if (result.status === 'error')
33
- process.exitCode = 1;
35
+ if (args.length)
36
+ throw new Error('update_invalid_options');
37
+ const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
38
+ const result = updateGlobalInstallation({ packageRoot });
39
+ output(result);
40
+ if (result.status === 'error')
41
+ process.exitCode = 1;
42
+ }
43
+ else if (command === 'budget') {
44
+ if (args[0] !== 'status')
45
+ throw new Error('budget_invalid_options');
46
+ let clients = ['codex', 'claude'];
47
+ if (args.length !== 1) {
48
+ if (args.length !== 3 || args[1] !== '--client' || !['codex', 'claude', 'all'].includes(args[2]))
49
+ throw new Error('budget_invalid_options');
50
+ clients = args[2] === 'all' ? ['codex', 'claude'] : [args[2]];
34
51
  }
52
+ const result = showBudgetStatus({ clients });
53
+ output(result);
54
+ if (result.status === 'partial')
55
+ process.exitCode = 1;
35
56
  }
36
57
  else if (command === '--version')
37
58
  process.stdout.write(VERSION + '\n');
38
- else if (command === 'report' && args.length === 1 && args[0] === '--help') {
39
- process.stdout.write('Usage: aptly report [--format md|json|both] [--output-dir DIR]\nDefault: both formats in a private reports directory. No uploads or API probes.\n');
40
- }
41
59
  else if (command === 'report') {
42
60
  const options = { format: 'both', outputDir: 'reports' };
43
61
  const seen = new Set();
@@ -53,27 +71,21 @@ try {
53
71
  output(exportDiagnosticReport({ diagnostic: collectDiagnostics(), ...options }));
54
72
  }
55
73
  else if (command === 'set') {
56
- if (args.length === 1 && args[0] === '--help')
57
- process.stdout.write('Usage: aptly set default [--client codex|claude|all]\n aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]\n aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]\n--check diagnoses OPENAI_API_KEY registration without reading or storing a key.\nValues are entered interactively with hidden input; --stdin explicitly reads a value from standard input. Existing defaults and launchers are preserved. OPENAI_API_KEY is stored in the OS credential store; host files contain references only. Restart MCP after changes.\n');
58
- else if (args[0] === 'transmission') {
59
- if (args[1] === '--help' && args.length === 2)
60
- process.stdout.write('Usage: aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]\nControls automatic transmission to OpenAI Decisions, not developer telemetry. Direct recommendations are separate explicit requests. Restart MCP after changes.\n');
61
- else {
62
- const scope = args[1];
63
- if (!['none', 'description', 'excerpt', '--show'].includes(scope))
74
+ if (args[0] === 'transmission') {
75
+ const scope = args[1];
76
+ if (!['none', 'description', 'excerpt', '--show'].includes(scope))
77
+ throw new Error('set_invalid_options');
78
+ let clients = ['codex', 'claude'];
79
+ if (args.length !== 2) {
80
+ if (args.length !== 4 || args[2] !== '--client' || !['codex', 'claude', 'all'].includes(args[3]))
64
81
  throw new Error('set_invalid_options');
65
- let clients = ['codex', 'claude'];
66
- if (args.length !== 2) {
67
- if (args.length !== 4 || args[2] !== '--client' || !['codex', 'claude', 'all'].includes(args[3]))
68
- throw new Error('set_invalid_options');
69
- clients = args[3] === 'all' ? ['codex', 'claude'] : [args[3]];
70
- }
71
- const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
72
- const result = scope === '--show' ? showTransmission({ clients }) : setTransmission(scope, { clients, packageRoot });
73
- output(result);
74
- if ('status' in result && result.status === 'partial')
75
- process.exitCode = 1;
82
+ clients = args[3] === 'all' ? ['codex', 'claude'] : [args[3]];
76
83
  }
84
+ const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
85
+ const result = scope === '--show' ? showTransmission({ clients }) : setTransmission(scope, { clients, packageRoot });
86
+ output(result);
87
+ if ('status' in result && result.status === 'partial')
88
+ process.exitCode = 1;
77
89
  }
78
90
  else {
79
91
  const action = args[0];
@@ -115,6 +127,14 @@ try {
115
127
  if (checkOnly && fromStdin)
116
128
  throw new Error('set_invalid_options');
117
129
  const credential = key === 'OPENAI_API_KEY' ? prepareApiKey({ clients, packageRoot }) : undefined;
130
+ if (credential && credential.result.clients.some(client => client.status !== 'error')) {
131
+ const readiness = linuxStoreReadiness();
132
+ if (readiness) {
133
+ 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] }));
134
+ if (readiness.status === 'unavailable')
135
+ credential.result.status = 'partial';
136
+ }
137
+ }
118
138
  let value = '';
119
139
  if (credential && (checkOnly || credential.result.status === 'partial')) {
120
140
  output(credential.result);
@@ -144,56 +164,57 @@ try {
144
164
  }
145
165
  }
146
166
  else if (['setup', 'remove'].includes(command)) {
147
- if (args.length === 1 && args[0] === '--help')
148
- process.stdout.write('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]\n aptly remove [--client codex|claude|all]\nSetup merges MCP and PreToolUse registration. Codex requires native /hooks trust review.\nAutomatic setup skips CI, APTLY_SKIP_SETUP=1, and absent host directories. No keys are stored.\n');
149
- else {
150
- let clients = ['codex', 'claude'];
151
- let mode;
152
- let transmission;
153
- let automatic = false;
154
- let migrate = false;
155
- let dryRun = false;
156
- let includeExisting = false;
157
- const seen = new Set();
158
- for (let i = 0; i < args.length; i++) {
159
- const flag = args[i];
160
- if (seen.has(flag))
161
- throw new Error('setup_invalid_options');
162
- seen.add(flag);
163
- if (flag === '--migrate-launcher' && command === 'setup') {
164
- migrate = true;
165
- continue;
166
- }
167
- if (flag === '--include-existing' && command === 'setup') {
168
- includeExisting = true;
169
- continue;
170
- }
171
- if (flag === '--dry-run' && command === 'setup') {
172
- dryRun = true;
173
- continue;
174
- }
175
- if (flag === '--automatic' && command === 'setup') {
176
- automatic = true;
177
- continue;
178
- }
179
- const value = args[++i];
180
- if (flag === '--client' && ['codex', 'claude', 'all'].includes(value))
181
- clients = value === 'all' ? ['codex', 'claude'] : [value];
182
- else if (flag === '--transmission' && command === 'setup' && ['none', 'description', 'excerpt'].includes(value))
183
- transmission = value;
184
- else if (flag === '--mode' && command === 'setup' && ['defaults', 'advisory'].includes(value))
185
- mode = value;
186
- else
187
- throw new Error('setup_invalid_options');
167
+ let clients = ['codex', 'claude'];
168
+ let mode;
169
+ let transmission;
170
+ let automatic = false;
171
+ let check = false;
172
+ let migrate = false;
173
+ let dryRun = false;
174
+ let includeExisting = false;
175
+ const seen = new Set();
176
+ for (let i = 0; i < args.length; i++) {
177
+ const flag = args[i];
178
+ if (seen.has(flag))
179
+ throw new Error('setup_invalid_options');
180
+ seen.add(flag);
181
+ if (flag === '--check' && command === 'setup') {
182
+ check = true;
183
+ continue;
188
184
  }
189
- const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
190
- if ((migrate && (clients.length !== 1 || automatic || seen.has('--mode') || seen.has('--transmission'))) || ((dryRun || includeExisting) && !migrate))
185
+ if (flag === '--migrate-launcher' && command === 'setup') {
186
+ migrate = true;
187
+ continue;
188
+ }
189
+ if (flag === '--include-existing' && command === 'setup') {
190
+ includeExisting = true;
191
+ continue;
192
+ }
193
+ if (flag === '--dry-run' && command === 'setup') {
194
+ dryRun = true;
195
+ continue;
196
+ }
197
+ if (flag === '--automatic' && command === 'setup') {
198
+ automatic = true;
199
+ continue;
200
+ }
201
+ const value = args[++i];
202
+ if (flag === '--client' && ['codex', 'claude', 'all'].includes(value))
203
+ clients = value === 'all' ? ['codex', 'claude'] : [value];
204
+ else if (flag === '--transmission' && command === 'setup' && ['none', 'description', 'excerpt'].includes(value))
205
+ transmission = value;
206
+ else if (flag === '--mode' && command === 'setup' && ['defaults', 'advisory'].includes(value))
207
+ mode = value;
208
+ else
191
209
  throw new Error('setup_invalid_options');
192
- const result = migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot, transmission }) : removeSetup({ clients });
193
- output(result);
194
- if (result.status === 'partial' && !automatic)
195
- process.exitCode = 1;
196
210
  }
211
+ const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
212
+ if ((check && [...seen].some(flag => !['--check', '--client'].includes(flag))) || (migrate && (clients.length !== 1 || automatic || seen.has('--mode') || seen.has('--transmission'))) || ((dryRun || includeExisting) && !migrate))
213
+ throw new Error('setup_invalid_options');
214
+ const result = check ? checkSetup({ clients, packageRoot }) : migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot, transmission }) : removeSetup({ clients });
215
+ output(result);
216
+ if (result.status === 'partial' && !automatic)
217
+ process.exitCode = 1;
197
218
  }
198
219
  else if (command === 'serve' && args.length === 0)
199
220
  await serve();
@@ -206,12 +227,6 @@ try {
206
227
  saveModelInfo(args[2], snapshot);
207
228
  output({ status: 'refreshed', facts: snapshot.facts.length, sources: snapshot.sources, account_access_verified: false });
208
229
  }
209
- else if (command === 'catalog' && args.length === 1 && args[0] === '--help') {
210
- process.stdout.write('Usage: aptly catalog\n aptly catalog refresh --output /absolute/private/model-info.json\nSet APTLY_MODEL_INFO_PATH to load the cache at server startup. No account access is certified.\n');
211
- }
212
- else if (command === 'recommend' && args.length === 1 && args[0] === '--help') {
213
- process.stdout.write('Usage: aptly recommend < request.json\nRequired: request_id, client (codex|claude), task {summary, operation, context_sufficient}.\nOptional: eligible_profile_ids (defaults to client catalog), constraints (declared pins only).\nRecommendations are advisory_only; no host settings are inspected or changed.\nSee examples/recommend.codex.json and examples/recommend.claude.json.\n');
214
- }
215
230
  else if (command === 'recommend' && args.length === 0) {
216
231
  const raw = readFileSync(0, 'utf8');
217
232
  if (Buffer.byteLength(raw) > 16384)
@@ -231,7 +246,7 @@ try {
231
246
  if (args[0] === 'claude')
232
247
  output({ mcpServers: { 'aptly': { command: node, args: [server], env: { ROUTER_PROVIDER: 'fixture' } } } });
233
248
  else
234
- process.stdout.write('[mcp_servers.aptly]\ncommand = ' + JSON.stringify(node) + '\nargs = [' + JSON.stringify(server) + ']\nenv_vars = ["OPENAI_API_KEY", "ROUTER_PROVIDER", "ROUTER_LEDGER_PATH", "ROUTER_CONFIG_PATH", "APTLY_CLAUDE_MODELS", "APTLY_CODEX_MODELS", "CLAUDE_MODELS", "CODEX_MODELS", "APTLY_MODEL_INFO_PATH"]\n');
249
+ process.stdout.write('[mcp_servers.aptly]\ncommand = ' + JSON.stringify(node) + '\nargs = [' + JSON.stringify(server) + ']\nenv_vars = ["OPENAI_API_KEY", "ROUTER_PROVIDER", "ROUTER_LEDGER_PATH", "ROUTER_CONFIG_PATH", "APTLY_CLAUDE_MODELS", "APTLY_CODEX_MODELS", "CLAUDE_MODELS", "CODEX_MODELS", "APTLY_MODEL_INFO_PATH", "APTLY_MAX_DAILY_CALLS", "APTLY_MAX_TOTAL_CALLS", "APTLY_MAX_ESTIMATED_USD", "APTLY_ESTIMATED_CALL_USD"]\n');
235
250
  }
236
251
  else {
237
252
  process.stderr.write('aptly: invalid_command (use --help)\n');
@@ -243,14 +258,16 @@ catch (error) {
243
258
  const caughtCode = errorCode(error);
244
259
  const safeConfigurationCodes = ['catalog_configuration_invalid', 'catalog_configuration_conflict', 'catalog_environment_typo', 'catalog_facts_invalid', 'model_info_fetch_failed', 'model_info_unavailable', 'model_info_invalid', 'model_info_output_unavailable', 'model_info_path_invalid', 'model_info_refresh_failed', 'model_info_options_invalid', 'model_info_too_large', 'model_info_timeout', 'model_info_parse_failed', 'model_info_save_failed'];
245
260
  const message = error instanceof Error ? error.message : undefined;
261
+ const budgetCode = [caughtCode, message].find(value => typeof value === 'string' && ['invalid_budget_configuration', 'budget_invalid_options'].includes(value));
246
262
  const configCode = [caughtCode, message].find(value => typeof value === 'string' && safeConfigurationCodes.includes(value));
247
263
  const setCodes = ['set_environment_key_unsupported', 'set_invalid_options', 'set_value_too_large', 'set_interactive_input_required', 'set_input_cancelled'];
248
- 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') : configCode ?? 'operation_failed';
249
- process.stderr.write('aptly: ' + code + '\n');
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';
265
+ const budgetDetails = budgetErrorDetails(error);
266
+ process.stderr.write('aptly: ' + code + (budgetDetails.invalid_budget_keys?.length ? ' [' + budgetDetails.invalid_budget_keys.join(', ') + ']' : '') + (budgetDetails.budget_error ? ' (' + budgetDetails.budget_error + ')' : '') + '\n');
250
267
  process.exitCode = 1;
251
268
  }
252
269
  finally {
253
- if (!process.exitCode) {
270
+ if (!process.exitCode && !helpHandled) {
254
271
  try {
255
272
  const hint = await updateNotification({ command, args, env: process.env, stdinIsTTY: !!process.stdin.isTTY, stderrIsTTY: !!process.stderr.isTTY, stdoutIsTTY: !!process.stdout.isTTY, currentVersion: VERSION });
256
273
  if (hint)
@@ -187,6 +187,7 @@ function bindCall(call, policy, policyFingerprint, catalog, contextDigest) {
187
187
  export async function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext, onBlockedAdvice }) {
188
188
  const observation = initialHookObservation(client, event);
189
189
  let activeMode;
190
+ let budgetLimit;
190
191
  const preserve = (reason, request_id) => {
191
192
  const result = { output: {}, observation: { ...observation, status: 'preserved', reason, ...(request_id ? { request_id } : {}) } };
192
193
  if (!activeMode || signal?.aborted || reason === 'call_cancelled')
@@ -199,7 +200,7 @@ export async function automaticHook({ client, event, router, policyPath, signal,
199
200
  result.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: `Aptly automatic routing is inactive (${effectiveTransmission(currentPolicy)}). Original arguments are preserved.` } };
200
201
  return result;
201
202
  }
202
- const message = `Aptly could not select compatible subagent defaults (${reason}). Original arguments and execution constraints are preserved; no child execution is observed. Report this outcome. Do not repeat an uncertain paid request with a new ID or change history, explicit choices, roles or permissions to bypass this result.`;
203
+ const message = `Aptly could not select compatible subagent defaults (${reason}${reason === 'budget_exhausted' && budgetLimit ? '; ' + budgetLimit : ''}). Original arguments and execution constraints are preserved; no child execution is observed. Report this outcome. Do not repeat an uncertain paid request with a new ID or change history, explicit choices, roles or permissions to bypass this result.`;
203
204
  result.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: message,
204
205
  ...(currentPolicy.mode === 'defaults' ? { permissionDecision: 'deny', permissionDecisionReason: message } : {}) } };
205
206
  result.observation.status = currentPolicy.mode === 'defaults' ? 'blocked' : 'preserved';
@@ -335,6 +336,8 @@ export async function automaticHook({ client, event, router, policyPath, signal,
335
336
  eligible_profile_ids: profiles.map(profile => profile.id),
336
337
  constraints: { model_pinned: false, effort_pinned: false, role_pinned: false, fork_inherits: false },
337
338
  });
339
+ if (recommendation.reason === 'budget_exhausted' && ['max_daily_calls', 'max_total_calls', 'max_estimated_usd'].includes(recommendation.budget_limit ?? ''))
340
+ budgetLimit = recommendation.budget_limit;
338
341
  observation.classification = recommendation.cached ? 'cache_hit' : typeof recommendation.latency_ms === 'number' ? 'provider_requested' : 'local_outcome';
339
342
  const profile = validatedHookProfile(client, recommendation, router.policy);
340
343
  if (profile && profiles.some(candidate => candidate.id === profile.id)) {
@@ -0,0 +1,23 @@
1
+ /** Local reservation estimates only; none of these limits is a provider billing cap. */
2
+ export declare const budgetEnvironmentDefaults: Readonly<Record<string, string>>;
3
+ export declare const budgetEnvironmentKeys: readonly string[];
4
+ export interface BudgetLimits {
5
+ max_daily_calls: number;
6
+ max_total_calls: number;
7
+ max_estimated_usd: number;
8
+ estimated_call_usd: number;
9
+ }
10
+ export interface BudgetSettings {
11
+ limits: BudgetLimits;
12
+ provenance: Record<keyof BudgetLimits, 'environment' | 'default'>;
13
+ }
14
+ export type BudgetErrorReason = 'invalid_value' | 'rate_exceeds_ceiling' | 'unknown_budget_key';
15
+ export interface BudgetErrorDetails {
16
+ invalid_budget_keys?: string[];
17
+ budget_error?: BudgetErrorReason;
18
+ }
19
+ /** Return only static reasons and recognized field names, never input names or values. */
20
+ export declare function budgetErrorDetails(error: unknown): BudgetErrorDetails;
21
+ export declare function parseBudgetValue(key: string, value: string): number;
22
+ export declare function resolveBudgetSettings(env: NodeJS.ProcessEnv | Record<string, unknown>): BudgetSettings;
23
+ export declare const defaultBudgetLimits: Readonly<BudgetLimits>;
@@ -0,0 +1,54 @@
1
+ /** Local reservation estimates only; none of these limits is a provider billing cap. */
2
+ export const budgetEnvironmentDefaults = Object.freeze({
3
+ APTLY_MAX_DAILY_CALLS: '200',
4
+ APTLY_MAX_TOTAL_CALLS: '0',
5
+ APTLY_MAX_ESTIMATED_USD: '0',
6
+ APTLY_ESTIMATED_CALL_USD: '0.002',
7
+ });
8
+ export const budgetEnvironmentKeys = Object.freeze(Object.keys(budgetEnvironmentDefaults));
9
+ const fields = {
10
+ APTLY_MAX_DAILY_CALLS: 'max_daily_calls', APTLY_MAX_TOTAL_CALLS: 'max_total_calls',
11
+ APTLY_MAX_ESTIMATED_USD: 'max_estimated_usd', APTLY_ESTIMATED_CALL_USD: 'estimated_call_usd',
12
+ };
13
+ /** Return only static reasons and recognized field names, never input names or values. */
14
+ export function budgetErrorDetails(error) {
15
+ if (error === null || typeof error !== 'object')
16
+ return {};
17
+ const descriptors = Object.getOwnPropertyDescriptors(error);
18
+ const reason = descriptors.budget_error?.value;
19
+ if (!['invalid_value', 'rate_exceeds_ceiling', 'unknown_budget_key'].includes(reason))
20
+ return {};
21
+ const inputKeys = descriptors.invalid_budget_keys?.value;
22
+ const keys = Array.isArray(inputKeys) ? budgetEnvironmentKeys.filter(key => inputKeys.includes(key)) : [];
23
+ return { ...(keys.length ? { invalid_budget_keys: keys } : {}), budget_error: reason };
24
+ }
25
+ function invalidBudget(reason, keys = []) {
26
+ const details = { ...(keys.length ? { invalid_budget_keys: budgetEnvironmentKeys.filter(key => keys.includes(key)) } : {}), budget_error: reason };
27
+ throw Object.assign(new Error('invalid_budget_configuration'), details);
28
+ }
29
+ export function parseBudgetValue(key, value) {
30
+ if (!Object.hasOwn(fields, key))
31
+ invalidBudget('unknown_budget_key');
32
+ if (typeof value !== 'string' || !/^(?:0|[1-9]\d*)(?:\.\d{1,6})?$/.test(value))
33
+ invalidBudget('invalid_value', [key]);
34
+ const number = Number(value);
35
+ const calls = key === 'APTLY_MAX_DAILY_CALLS' || key === 'APTLY_MAX_TOTAL_CALLS';
36
+ const maximum = key === 'APTLY_MAX_DAILY_CALLS' ? 100000 : key === 'APTLY_MAX_TOTAL_CALLS' ? 1000000 : 100;
37
+ if (!Number.isFinite(number) || number > maximum || (calls && (!/^\d+$/.test(value) || !Number.isSafeInteger(number))) || (key === 'APTLY_ESTIMATED_CALL_USD' && number === 0) || (number === 0 && value !== '0'))
38
+ invalidBudget('invalid_value', [key]);
39
+ return number;
40
+ }
41
+ export function resolveBudgetSettings(env) {
42
+ if (Object.keys(env).some(key => /^(?:APTLY_MAX_|APTLY_ESTIMATED_)/.test(key) && !Object.hasOwn(fields, key)))
43
+ invalidBudget('unknown_budget_key');
44
+ const limits = {}, provenance = {};
45
+ for (const key of budgetEnvironmentKeys) {
46
+ const value = env[key], field = fields[key];
47
+ limits[field] = parseBudgetValue(key, value === undefined ? budgetEnvironmentDefaults[key] : value);
48
+ provenance[field] = value === undefined ? 'default' : 'environment';
49
+ }
50
+ if (limits.max_estimated_usd > 0 && limits.estimated_call_usd > limits.max_estimated_usd)
51
+ invalidBudget('rate_exceeds_ceiling', ['APTLY_MAX_ESTIMATED_USD', 'APTLY_ESTIMATED_CALL_USD']);
52
+ return { limits, provenance };
53
+ }
54
+ export const defaultBudgetLimits = Object.freeze(resolveBudgetSettings({}).limits);
@@ -0,0 +1,11 @@
1
+ export type HelpResult = {
2
+ kind: 'help';
3
+ text: string;
4
+ } | {
5
+ kind: 'error';
6
+ code: 'invalid_help_options';
7
+ };
8
+ /** Pure help dispatch. Required positional arguments may be omitted; supplied values/options are validated. */
9
+ export declare function resolveCliHelp(argv: readonly string[], { environmentKeys }?: {
10
+ environmentKeys?: readonly string[];
11
+ }): HelpResult | undefined;
@@ -0,0 +1,102 @@
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 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
+ '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 --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
+ 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('--check') && [...seen].some(flag => !['--check', '--client'].includes(flag)))
94
+ return { kind: 'error', code: 'invalid_help_options' };
95
+ if ((seen.has('--dry-run') || seen.has('--include-existing')) && !migrate)
96
+ return { kind: 'error', code: 'invalid_help_options' };
97
+ if (migrate && (seen.has('--automatic') || seen.has('--mode') || seen.has('--transmission') || values.get('--client') === 'all'))
98
+ return { kind: 'error', code: 'invalid_help_options' };
99
+ }
100
+ const text = 'Usage: ' + spec.usage + '\n\n' + spec.description.replace('$ENV_KEYS', environmentKeys.join(', ')) + '\n\nHelp: --help, -h, or aptly help' + (path ? ' ' + path : '') + '\n';
101
+ return { kind: 'help', text };
102
+ }
@@ -32,7 +32,7 @@ export class ContextRetries {
32
32
  return 'automatic_policy_changed';
33
33
  if (['none', 'unselected'].includes(effectiveTransmission(loaded.policy)))
34
34
  return 'automatic_transmission_disabled';
35
- if (hash(this.router.policy) !== entry.catalog)
35
+ if (hash(this.router.semanticPolicy()) !== entry.catalog)
36
36
  return 'catalog_changed';
37
37
  return undefined;
38
38
  }
@@ -55,7 +55,7 @@ export class ContextRetries {
55
55
  return { retry_id }; // No renewal or replacement of a ticket.
56
56
  if (this.entries.size >= 128)
57
57
  return { reason: 'context_retry_capacity' };
58
- 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 });
59
59
  return { retry_id };
60
60
  }
61
61
  registerAdvice(seed, current) {
@@ -78,7 +78,7 @@ export class ContextRetries {
78
78
  return { retry_id };
79
79
  if (this.entries.size >= 128)
80
80
  return { reason: 'context_retry_capacity' };
81
- 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 });
82
82
  return { retry_id };
83
83
  }
84
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>;