aptly 0.1.7 → 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.
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
  }
@@ -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);
@@ -36,7 +36,7 @@ export function createServer({ env = process.env } = {}) {
36
36
  server.registerTool('get_routing_capabilities', { description: 'Advisory profile catalog, provider and local budget limits. No paid call.', annotations, inputSchema: {} }, async () => {
37
37
  const automatic = loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH);
38
38
  return content({
39
- ...router.capabilities(), provider: mode, hook_mode: loadConfiguration(env).mode,
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
40
  precedence: 'per_call_effective_host_evidence_required', automatic_settings_discovery: false,
41
41
  recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
42
42
  model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
@@ -14,10 +14,20 @@ export interface SetupClientResult {
14
14
  client: Client;
15
15
  status: 'configured' | 'unchanged' | 'removed' | 'skipped' | 'error';
16
16
  codes: string[];
17
+ invalid_budget_keys?: string[];
18
+ budget_error?: string;
17
19
  requires_hook_review?: boolean;
18
20
  recovery?: string[];
19
21
  transmission?: string;
20
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
+ };
21
31
  }
22
32
  export interface SetupResult {
23
33
  status: 'complete' | 'partial' | 'skipped';
@@ -60,4 +70,45 @@ export declare function showTransmission(options?: SetupOptions): {
60
70
  transmission_source: string;
61
71
  })[];
62
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
+ };
63
114
  export {};
package/dist/src/setup.js CHANGED
@@ -6,6 +6,8 @@ import { randomUUID } from 'node:crypto';
6
6
  import { isDeepStrictEqual } from 'node:util';
7
7
  import { parse } from 'smol-toml';
8
8
  import { resolveCatalog } from './catalog.js';
9
+ import { budgetEnvironmentDefaults, budgetEnvironmentKeys, parseBudgetValue, resolveBudgetSettings, budgetErrorDetails } from './budget.js';
10
+ import { Router, defaultPolicy } from './core.js';
9
11
  import { loadAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
10
12
  import { assertPrivateStatePath } from './files.js';
11
13
  import { assertWindowsPrivatePath, protectNewWindowsPrivateDirectory, copyWindowsFilePermissions } from './windows-private.js';
@@ -156,8 +158,8 @@ function removeTomlEnv(text, additions) {
156
158
  fail('managed_entry_changed');
157
159
  return text;
158
160
  }
159
- export const configurableEnvironmentKeys = Object.freeze(['ROUTER_PROVIDER', 'APTLY_CLAUDE_MODELS', 'APTLY_CODEX_MODELS', 'CLAUDE_MODELS', 'CODEX_MODELS', 'APTLY_MODEL_INFO_PATH']);
160
- const defaultEnvironment = { ROUTER_PROVIDER: 'decisions', APTLY_CLAUDE_MODELS: '["haiku","sonnet","opus"]', APTLY_CODEX_MODELS: '["gpt-6-luna","gpt-6.1-terra","gpt-6.1-sol"]' };
161
+ export const configurableEnvironmentKeys = Object.freeze([...budgetEnvironmentKeys, 'ROUTER_PROVIDER', 'APTLY_CLAUDE_MODELS', 'APTLY_CODEX_MODELS', 'CLAUDE_MODELS', 'CODEX_MODELS', 'APTLY_MODEL_INFO_PATH']);
162
+ const defaultEnvironment = { ...budgetEnvironmentDefaults, ROUTER_PROVIDER: 'decisions', APTLY_CLAUDE_MODELS: '["haiku","sonnet","opus"]', APTLY_CODEX_MODELS: '["gpt-6-luna","gpt-6.1-terra","gpt-6.1-sol"]' };
161
163
  function validateEnvironmentValue(key, value) {
162
164
  if (!configurableEnvironmentKeys.includes(key))
163
165
  fail(/KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL/i.test(key) ? 'environment_secret_key_unsupported' : 'environment_key_unsupported');
@@ -165,6 +167,14 @@ function validateEnvironmentValue(key, value) {
165
167
  fail('environment_invalid_value');
166
168
  if (/\bsk-[A-Za-z0-9_-]{8,}|\bBearer\s+\S+|https?:\/\/[^/\s]+:[^/\s]+@/i.test(value))
167
169
  fail('environment_sensitive_value');
170
+ if (budgetEnvironmentKeys.includes(key)) {
171
+ try {
172
+ parseBudgetValue(key, value);
173
+ }
174
+ catch (error) {
175
+ throw Object.assign(new Error('environment_invalid_value'), budgetErrorDetails(error));
176
+ }
177
+ }
168
178
  if (key === 'ROUTER_PROVIDER' && !['fixture', 'decisions'].includes(value))
169
179
  fail('environment_invalid_value');
170
180
  if (key === 'APTLY_MODEL_INFO_PATH') {
@@ -176,12 +186,28 @@ function validateEnvironmentValue(key, value) {
176
186
  }
177
187
  }
178
188
  }
179
- function editEnvironment(current, edit, client) {
189
+ function budgetInheritance(entry, environment, client) {
190
+ if (client === 'codex' && entry.env_vars !== undefined && (!Array.isArray(entry.env_vars) || entry.env_vars.some((key) => typeof key !== 'string')))
191
+ fail('configuration_shape_conflict');
192
+ const permitted = client === 'codex' ? (entry.env_vars ?? []) : [], keys = new Set(), values = {};
193
+ for (const key of budgetEnvironmentKeys) {
194
+ if (client === 'codex' ? permitted.includes(key) : environment[key] !== undefined) {
195
+ keys.add(key);
196
+ if (environment[key] !== undefined)
197
+ values[key] = environment[key];
198
+ }
199
+ }
200
+ for (const key of Object.keys(environment))
201
+ if ((key.startsWith('APTLY_MAX_') || key.startsWith('APTLY_ESTIMATED_')) && (client === 'claude' || permitted.includes(key)))
202
+ values[key] = environment[key];
203
+ return { keys, values };
204
+ }
205
+ function editEnvironment(current, edit, client, inherited) {
180
206
  const updates = {};
181
207
  if ('defaults' in edit) {
182
208
  for (const [key, value] of Object.entries(defaultEnvironment)) {
183
209
  const alias = key === 'APTLY_CLAUDE_MODELS' ? 'CLAUDE_MODELS' : key === 'APTLY_CODEX_MODELS' ? 'CODEX_MODELS' : null;
184
- if (current[key] === undefined && (!alias || current[alias] === undefined))
210
+ if (current[key] === undefined && (!alias || current[alias] === undefined) && !(budgetEnvironmentKeys.includes(key) && inherited.keys.has(key)))
185
211
  updates[key] = value;
186
212
  }
187
213
  }
@@ -193,14 +219,15 @@ function editEnvironment(current, edit, client) {
193
219
  validateEnvironmentValue(edit.key, edit.value);
194
220
  updates[edit.key] = edit.value;
195
221
  }
196
- const effective = { ...current, ...updates };
222
+ const effective = { ...inherited.values, ...current, ...updates };
197
223
  if (effective.ROUTER_PROVIDER !== undefined && !['fixture', 'decisions'].includes(effective.ROUTER_PROVIDER))
198
224
  fail('environment_invalid_value');
199
225
  try {
200
226
  resolveCatalog(effective);
227
+ resolveBudgetSettings(effective);
201
228
  }
202
- catch {
203
- fail('environment_invalid_value');
229
+ catch (error) {
230
+ throw Object.assign(new Error('environment_invalid_value'), budgetErrorDetails(error));
204
231
  }
205
232
  return Object.fromEntries(Object.entries(updates).filter(([key, value]) => current[key] !== value));
206
233
  }
@@ -422,7 +449,8 @@ function prepare(options, client, removing, edit) {
422
449
  if (edit && ('credential' in edit || 'migrate' in edit))
423
450
  requireCredentialRuntime(servers.aptly, root);
424
451
  const currentEnv = map(servers.aptly, 'env');
425
- const updates = edit ? editEnvironment(currentEnv, edit, client) : {};
452
+ const originalEnvKeys = new Set(Object.keys(currentEnv)), inheritedBudget = budgetInheritance(servers.aptly, env, client);
453
+ const updates = edit ? editEnvironment(currentEnv, edit, client, inheritedBudget) : {};
426
454
  Object.assign(currentEnv, updates);
427
455
  if (created) {
428
456
  if (client === 'codex') {
@@ -514,12 +542,19 @@ function prepare(options, client, removing, edit) {
514
542
  }
515
543
  if (requestedScope !== undefined)
516
544
  owner.policy = structuredClone(policyValue);
545
+ if (edit && ('defaults' in edit || ('key' in edit && budgetEnvironmentKeys.includes(edit.key)))) {
546
+ const budget = resolveBudgetSettings({ ...inheritedBudget.values, ...currentEnv });
547
+ result.budget = { limits: { ...budget.limits }, added: budgetEnvironmentKeys.filter(key => Object.hasOwn(updates, key) && !originalEnvKeys.has(key)),
548
+ updated: budgetEnvironmentKeys.filter(key => Object.hasOwn(updates, key) && originalEnvKeys.has(key)),
549
+ preserved: budgetEnvironmentKeys.filter(key => !Object.hasOwn(updates, key) && currentEnv[key] !== undefined),
550
+ inherited: budgetEnvironmentKeys.filter(key => currentEnv[key] === undefined && inheritedBudget.keys.has(key)), restart_required: budgetEnvironmentKeys.some(key => Object.hasOwn(updates, key)) };
551
+ }
517
552
  result.transmission = effectiveTransmission(policyValue);
518
553
  result.transmission_source = policyValue.schema_version === 1 ? 'legacy' : policyValue.transmission === 'unselected' ? 'unselected' : 'explicit';
519
554
  manifest.after = stringify(owner);
520
555
  if (client === 'codex')
521
556
  result.requires_hook_review = true;
522
- result.codes = [...(client === 'codex' ? ['requires_hook_review'] : []), ...(result.transmission === 'unselected' ? ['transmission_selection_required'] : result.transmission_source === 'legacy' ? ['legacy_transmission_excerpt'] : []), ...(requestedScope !== undefined ? ['mcp_restart_required'] : [])];
557
+ result.codes = [...(client === 'codex' ? ['requires_hook_review'] : []), ...(result.transmission === 'unselected' ? ['transmission_selection_required'] : result.transmission_source === 'legacy' ? ['legacy_transmission_excerpt'] : []), ...(requestedScope !== undefined || result.budget?.restart_required ? ['mcp_restart_required'] : [])];
523
558
  dirs.push(dir, privateDir, stateDir);
524
559
  }
525
560
  // Validate complete desired data before any host file is changed.
@@ -595,7 +630,7 @@ function execute(options, removing, edit, captured) {
595
630
  return prepare(options, client, removing, edit);
596
631
  }
597
632
  catch (e) {
598
- return { changes: [], observations: [], dirs: [], result: { client, status: 'error', codes: [safeCode(e)] } };
633
+ return { changes: [], observations: [], dirs: [], result: { client, status: 'error', codes: [safeCode(e)], ...budgetErrorDetails(e) } };
599
634
  }
600
635
  });
601
636
  const results = prepared.map(plan => plan.result);
@@ -662,7 +697,7 @@ function execute(options, removing, edit, captured) {
662
697
  }
663
698
  return { status: results.some(result => result.status === 'error') ? 'partial' : results.every(result => result.status === 'skipped') ? 'skipped' : 'complete', clients: results };
664
699
  }
665
- const codes = new Set(['transmission_selection_changed', 'transmission_invalid_scope', 'launcher_migration_not_owned', 'launcher_migration_not_standard', 'credential_launcher_unverified', 'environment_invalid_value', 'environment_sensitive_value', 'environment_key_unsupported', 'environment_secret_key_unsupported', 'unsafe_directory', 'unsafe_symlink', 'unsafe_configuration_file', 'invalid_json', 'invalid_json_object', 'configuration_shape_conflict', 'hook_shape_conflict', 'invalid_toml', 'unsupported_toml_layout', 'relative_configuration_directory', 'invalid_ownership', 'managed_hook_changed', 'managed_mcp_changed', 'managed_entry_changed', 'managed_policy_changed', 'mcp_entry_conflict', 'mcp_environment_conflict', 'existing_routing_hook_conflict', 'policy_conflict', 'existing_hook_not_owned', 'concurrent_configuration_change', 'private_directory_permissions', 'private_file_permissions']);
700
+ const codes = new Set(['unsafe_ledger', 'invalid_ledger', 'budget_ledger_unconfigured', 'invalid_budget_configuration', 'ledger_locked', 'ledger_error', 'transmission_selection_changed', 'transmission_invalid_scope', 'launcher_migration_not_owned', 'launcher_migration_not_standard', 'credential_launcher_unverified', 'environment_invalid_value', 'environment_sensitive_value', 'environment_key_unsupported', 'environment_secret_key_unsupported', 'unsafe_directory', 'unsafe_symlink', 'unsafe_configuration_file', 'invalid_json', 'invalid_json_object', 'configuration_shape_conflict', 'hook_shape_conflict', 'invalid_toml', 'unsupported_toml_layout', 'relative_configuration_directory', 'invalid_ownership', 'managed_hook_changed', 'managed_mcp_changed', 'managed_entry_changed', 'managed_policy_changed', 'mcp_entry_conflict', 'mcp_environment_conflict', 'existing_routing_hook_conflict', 'policy_conflict', 'existing_hook_not_owned', 'concurrent_configuration_change', 'private_directory_permissions', 'private_file_permissions']);
666
701
  function safeCode(error) { return error instanceof Error && codes.has(error.message) ? error.message : 'configuration_io_error'; }
667
702
  export function setupHosts(options = {}) { return execute(options, false); }
668
703
  export function removeSetup(options = {}) { return execute(options, true); }
@@ -672,7 +707,7 @@ export function setEnvironment(key, value, options = {}) {
672
707
  validateEnvironmentValue(key, value);
673
708
  }
674
709
  catch (error) {
675
- return { status: 'partial', clients: (options.clients ?? ['codex', 'claude']).map(client => ({ client, status: 'error', codes: [safeCode(error)] })) };
710
+ return { status: 'partial', clients: (options.clients ?? ['codex', 'claude']).map(client => ({ client, status: 'error', codes: [safeCode(error)], ...budgetErrorDetails(error) })) };
676
711
  }
677
712
  return execute(options, false, { key, value });
678
713
  }
@@ -771,3 +806,46 @@ export function showTransmission(options = {}) {
771
806
  }
772
807
  }) };
773
808
  }
809
+ /** Registration snapshot only. Never loads credentials, starts a server or creates a ledger/gate. */
810
+ export function showBudgetStatus(options = {}) {
811
+ const environment = options.env ?? process.env;
812
+ const clients = (options.clients ?? ['codex', 'claude']).map(client => {
813
+ try {
814
+ const { mcpPath } = resolved(options, client), source = read(mcpPath);
815
+ if (source.text === null)
816
+ return { client, status: 'skipped', codes: ['host_not_configured'] };
817
+ const config = client === 'codex' ? toml(source.text) : json(source.text);
818
+ const entry = config[client === 'codex' ? 'mcp_servers' : 'mcpServers']?.aptly;
819
+ if (entry === undefined)
820
+ return { client, status: 'skipped', codes: ['host_not_configured'] };
821
+ if (!object(entry) || entry.env !== undefined && !object(entry.env))
822
+ fail('configuration_shape_conflict');
823
+ if (client === 'codex' && entry.env_vars !== undefined && (!Array.isArray(entry.env_vars) || entry.env_vars.some((key) => typeof key !== 'string')))
824
+ fail('configuration_shape_conflict');
825
+ const permitted = client === 'codex' ? (entry.env_vars ?? []) : [];
826
+ const settings = {};
827
+ const budgetKeys = [...new Set([...budgetEnvironmentKeys, ...Object.keys(entry.env ?? {}).filter(key => key.startsWith('APTLY_MAX_') || key.startsWith('APTLY_ESTIMATED_')), ...Object.keys(environment).filter(key => (key.startsWith('APTLY_MAX_') || key.startsWith('APTLY_ESTIMATED_')) && (client === 'claude' || permitted.includes(key)))])];
828
+ for (const key of [...budgetKeys, 'ROUTER_LEDGER_PATH']) {
829
+ const value = Object.hasOwn(entry.env ?? {}, key) ? entry.env[key] : (client === 'claude' || permitted.includes(key) ? environment[key] : undefined);
830
+ if (value !== undefined)
831
+ settings[key] = value;
832
+ }
833
+ const budget = resolveBudgetSettings(settings), ledgerPath = settings.ROUTER_LEDGER_PATH;
834
+ if (typeof ledgerPath !== 'string')
835
+ fail('budget_ledger_unconfigured');
836
+ assertPrivateStatePath(ledgerPath);
837
+ const router = new Router({ policy: { ...defaultPolicy, ...budget.limits }, budgetConfigurable: true, ledgerPath,
838
+ provider: async () => { throw new Error('status_provider_forbidden'); } });
839
+ const snapshot = router.budgetStatus();
840
+ return { client, status: 'ok', budget: { ...snapshot, provenance: budget.provenance,
841
+ display_limits: Object.fromEntries(Object.entries(snapshot.limits).map(([key, value]) => [key, key !== 'estimated_call_usd' && value === 0 ? 'Unlimited' : value])),
842
+ next_utc_day: new Date(Date.parse(snapshot.utc_day + 'T00:00:00Z') + 86_400_000).toISOString(),
843
+ cost_guard: 'local_estimate_not_billing_cap', snapshot_source: 'host_registration_and_allowed_process_environment',
844
+ running_host_verified: false, settings_require_mcp_restart: true } };
845
+ }
846
+ catch (error) {
847
+ return { client, status: 'error', codes: [safeCode(error)], ...budgetErrorDetails(error) };
848
+ }
849
+ });
850
+ return { status: clients.some(client => client.status === 'error') ? 'partial' : 'complete', clients };
851
+ }
@@ -34,7 +34,9 @@ export interface Usage {
34
34
  total_tokens: number;
35
35
  }
36
36
  export type RoutingStatus = 'recommended' | 'keep_current' | 'needs_context' | 'unavailable';
37
+ export type BudgetLimit = 'max_daily_calls' | 'max_total_calls' | 'max_estimated_usd';
37
38
  export interface RoutingResult {
39
+ budget_limit?: BudgetLimit;
38
40
  status: RoutingStatus;
39
41
  reason: string;
40
42
  application: 'advisory_only';
@@ -23,7 +23,7 @@ function newer(candidate, current) {
23
23
  }
24
24
  function eligible(o) {
25
25
  return o.stdinIsTTY && o.stderrIsTTY && o.stdoutIsTTY !== false && !o.env.CI && o.env.APTLY_NO_UPDATE_NOTIFIER !== '1' && !!version(o.currentVersion) &&
26
- ['help', '--help', '-h', '--version', 'config', 'setup', 'remove', 'set', 'report'].includes(o.command) && !o.args.includes('--automatic') && !(o.command === 'set' && o.args[0] === 'transmission' && o.args.includes('--show'));
26
+ ['--version', 'config', 'setup', 'remove', 'set', 'report'].includes(o.command) && !o.args.some(arg => arg === '--help' || arg === '-h') && !o.args.includes('--automatic') && !(o.command === 'set' && o.args[0] === 'transmission' && o.args.includes('--show'));
27
27
  }
28
28
  function directory(path) {
29
29
  if (!isAbsolute(path))
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.7";
1
+ export declare const VERSION = "0.1.8";
@@ -1 +1 @@
1
- export const VERSION = '0.1.7';
1
+ export const VERSION = '0.1.8';
package/docs/guide/en.md CHANGED
@@ -59,6 +59,23 @@ Existing MCP launchers and user wrappers are not automatically migrated. Follow
59
59
 
60
60
  Only public Aptly version metadata is requested from the npm registry; no key, task summary, or host configuration is sent. Network and body reads are limited to 800ms and 16KiB. Results are cached at `~/.cache/aptly/update-check.json` for 24 hours, with a one-hour cooldown after failure. Network/cache errors cannot fail the requested command. Set `APTLY_NO_UPDATE_NOTIFIER=1` in the CLI environment to disable checks; it is not a supported key for `aptly set env`. Notifications never install updates.
61
61
 
62
+ <a id="command-help"></a>
63
+
64
+ ### Command help (0.1.8+)
65
+
66
+ Consistent per-command and nested help is supported from Aptly 0.1.8. Use these forms:
67
+
68
+ ```sh
69
+ aptly --help
70
+ aptly setup -h
71
+ aptly set default --help
72
+ aptly set env OPENAI_API_KEY --help
73
+ aptly budget status --help
74
+ aptly help catalog refresh
75
+ ```
76
+
77
+ `--help`, `-h` and `aptly help <command path>` only show usage. They do not read settings, supplied files, stdin or credential stores; prompt; change settings; call APIs or model metadata endpoints; install/update; or run update notifications. Help can follow valid options, but unknown paths/options, invalid supplied values and contradictory option combinations remain errors. Required positional arguments may be omitted to discover usage. A form such as `--output --help` is a missing option value, not a help request that supplies an output path.
78
+
62
79
  ### Configure with the CLI
63
80
 
64
81
  The `set` commands require 0.1.1 or later. Commands do not automatically switch existing launch paths. API-key setup accepts only the current package’s standard Node/server registration with a verified OS-source-compatible runtime. Custom wrappers, older versions, and other installation prefixes are rejected with `credential_launcher_unverified`; explicitly switch the registration or upgrade it before trying again.
@@ -231,6 +248,36 @@ For genuinely independent work, the caller can intentionally choose a fresh chil
231
248
 
232
249
  `confidence` is metadata and has not been validated here as a calibrated probability of correctness. It is not currently used as an automatic-application threshold. Zero and low values are currently allowed when other application conditions hold. A missing value in a live Decisions response is rejected as an error; it remains optional in generic Router and stored results. `keep_current` and `needs_context` are separate outcomes with existing abstention and context-recovery rules. Explicit model, effort, history and permissions are preserved. A small classification pilot does not establish improved child-task quality or total cost.
233
250
 
251
+ <a id="budget-limits"></a>
252
+
253
+ ### Budget limits and usage (0.1.8+)
254
+
255
+ Budget environment settings and usage status are supported from Aptly 0.1.8. `aptly set default` also fills missing budget environment settings for selected hosts. It adds no budget questionnaire, preserves existing values including explicit `0`, and does not reset usage, ledgers or caches. The existing transmission-scope question is separate. Existing registrations without budget variables also use the new runtime defaults after upgrade. The old implicit 20-call/50-call/$0.50 ceilings are not retained; configure any limits you require explicitly.
256
+
257
+ | Environment variable | Default | Meaning |
258
+ |---|---:|---|
259
+ | `APTLY_MAX_DAILY_CALLS` | `200` | Per-ledger UTC daily classification-attempt ceiling |
260
+ | `APTLY_MAX_TOTAL_CALLS` | `0` | Per-ledger cumulative attempt ceiling |
261
+ | `APTLY_MAX_ESTIMATED_USD` | `0` | Cumulative local reservation ceiling |
262
+ | `APTLY_ESTIMATED_CALL_USD` | `0.002` | Estimated dollars reserved for each new classification attempt |
263
+
264
+ Zero means unlimited for the three ceilings. The per-attempt reservation is a rate and must stay positive. Only literal `0` means unlimited; forms such as `0.0` and `0.00` are rejected. Unset uses defaults; empty, negative, malformed or exponent notation values are rejected. Calls use whole integers; money uses fixed decimal notation with at most six fractional digits. Maximum finite settings are 100,000 daily calls, 1,000,000 cumulative calls and 100 for monetary values. A finite cost ceiling must cover one reservation. Existing invalid settings are not silently overwritten.
265
+
266
+ ```sh
267
+ aptly set env APTLY_MAX_DAILY_CALLS
268
+ aptly set env APTLY_MAX_TOTAL_CALLS
269
+ aptly set env APTLY_MAX_ESTIMATED_USD
270
+ aptly set env APTLY_ESTIMATED_CALL_USD
271
+ aptly budget status --client codex
272
+ aptly budget status --client claude
273
+ ```
274
+
275
+ Setting commands support `--client codex|claude|all`, hidden input and explicit `--stdin`. Restart MCP after changes. Defaults also preserve existing Codex budget passthrough bindings in `env_vars` and Claude budget values observed in this CLI process environment, listed as `inherited`. Direct `recommend`/`capabilities` use the CLI process environment and do not automatically read host settings files. Status briefly holds the existing gate, so a concurrent request can receive temporary `ledger_locked`. Status is a snapshot of registration and permitted current environment settings, not verification of custom wrappers or the running host. It reads no keys, API or task text and creates no ledger or gate. Unlimited ceilings display `Unlimited` with `null` remaining. Sessions sharing a ledger share its budget; other ledgers and account-wide OpenAI usage are not aggregated.
276
+
277
+ `budget_exhausted` is local, not an OpenAI authentication or account-credit error. Direct/retry responses identify `budget_limit`; status lists `exhausted_by`. Reservations are not an actual billing cap and do not reset monthly. Changing the rate does not reprice past reservations; replacing a key or applying defaults does not refund them.
278
+
279
+ New pre-HTTP budget denials are not cached. Only verifiable known-unpaid legacy default-policy denials can be reevaluated with the same ID; completed recommendations, abstentions, context outcomes and `unknown` remain protected. Budget recovery does not extend the original five-minute retry reference or process lifetime and does not remove history or permission constraints. Arbitrary historical custom-policy digests are not guessed; do not bypass conflicts/unknowns with new IDs or ledger deletion.
280
+
234
281
  <a id="outbound-data-and-disabling-automatic-sharing"></a>
235
282
 
236
283
  ### Decisions API transmission scope