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/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);
@@ -0,0 +1,12 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ export interface LinuxReadinessOptions {
3
+ platform?: NodeJS.Platform;
4
+ env?: NodeJS.ProcessEnv;
5
+ execute?: typeof spawnSync;
6
+ }
7
+ export interface StoreReadiness {
8
+ status: 'unavailable' | 'unverified';
9
+ code: string;
10
+ }
11
+ /** Passive metadata only: never query, activate, unlock, or write the Secret Service. */
12
+ export declare function linuxStoreReadiness(options?: LinuxReadinessOptions): StoreReadiness | undefined;
@@ -0,0 +1,67 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { accessSync, constants, statSync } from 'node:fs';
3
+ import { isAbsolute, resolve } from 'node:path';
4
+ // Locate programs without running them. Empty PATH entries have shell cwd semantics.
5
+ function executable(name, path, absoluteOnly = false) {
6
+ for (const dir of (path ?? '/usr/bin:/bin').split(':')) {
7
+ if (absoluteOnly && !isAbsolute(dir))
8
+ continue;
9
+ const candidate = resolve(dir || '.', name);
10
+ try {
11
+ if (statSync(candidate).isFile()) {
12
+ accessSync(candidate, constants.X_OK);
13
+ return candidate;
14
+ }
15
+ }
16
+ catch { /* try next PATH entry */ }
17
+ }
18
+ }
19
+ /** Passive metadata only: never query, activate, unlock, or write the Secret Service. */
20
+ export function linuxStoreReadiness(options = {}) {
21
+ if ((options.platform ?? process.platform) !== 'linux')
22
+ return undefined;
23
+ const env = options.env ?? process.env;
24
+ if (!executable('secret-tool', env.PATH))
25
+ return { status: 'unavailable', code: 'secure_store_secret_tool_missing' };
26
+ const address = env.DBUS_SESSION_BUS_ADDRESS;
27
+ if (!address || !/^unix:(?:path|abstract)=[^,;\s]+(?:,guid=[a-fA-F0-9]{32})?$/.test(address))
28
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
29
+ if (address.startsWith('unix:path=') && !isAbsolute(address.slice('unix:path='.length).split(',')[0]))
30
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
31
+ const socket = address.match(/^unix:path=([^,%]+)(?:,guid=[a-fA-F0-9]{32})?$/)?.[1];
32
+ if (socket && isAbsolute(socket)) {
33
+ try {
34
+ statSync(socket);
35
+ }
36
+ catch (error) {
37
+ if (error.code === 'ENOENT')
38
+ return { status: 'unavailable', code: 'secure_store_bus_missing' };
39
+ }
40
+ }
41
+ const gdbus = executable('gdbus', env.PATH, true);
42
+ if (!gdbus)
43
+ return { status: 'unverified', code: 'secure_store_probe_unavailable' };
44
+ const call = (method, extra = []) => {
45
+ try {
46
+ const result = (options.execute ?? spawnSync)(gdbus, ['call', '--address', address, '--dest', 'org.freedesktop.DBus', '--object-path', '/org/freedesktop/DBus', '--method', `org.freedesktop.DBus.${method}`, ...extra], { env: { PATH: env.PATH ?? '/usr/bin:/bin', LC_ALL: 'C' }, encoding: 'utf8', timeout: 2000, maxBuffer: 65536 });
47
+ return !result.error && result.status === 0 && typeof result.stdout === 'string' ? result.stdout.trim() : undefined;
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ };
53
+ const owner = call('NameHasOwner', ['org.freedesktop.secrets']);
54
+ if (owner === '(true,)')
55
+ return { status: 'unverified', code: 'secure_store_service_present_unverified' };
56
+ if (owner !== '(false,)')
57
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
58
+ const names = call('ListActivatableNames');
59
+ // gdbus prints a GVariant string array. Accept only its narrow standard shape.
60
+ if (names === '(@as [],)')
61
+ return { status: 'unavailable', code: 'secure_store_service_missing' };
62
+ if (names === undefined || !/^\(\[(?:\s*'[^'\\]*'\s*(?:,\s*'[^'\\]*'\s*)*)?\],\)$/.test(names))
63
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
64
+ if (names.includes("'org.freedesktop.secrets'"))
65
+ return { status: 'unverified', code: 'secure_store_service_activatable_unverified' };
66
+ return { status: 'unavailable', code: 'secure_store_service_missing' };
67
+ }
@@ -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,22 @@ 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;
19
+ policy_location?: 'default_home' | 'elsewhere';
20
+ selected_home_source?: 'default' | 'override';
17
21
  requires_hook_review?: boolean;
18
22
  recovery?: string[];
19
23
  transmission?: string;
20
24
  transmission_source?: 'explicit' | 'legacy' | 'unselected';
25
+ budget?: {
26
+ limits: Record<string, number>;
27
+ added: string[];
28
+ updated: string[];
29
+ preserved: string[];
30
+ inherited: string[];
31
+ restart_required: boolean;
32
+ };
21
33
  }
22
34
  export interface SetupResult {
23
35
  status: 'complete' | 'partial' | 'skipped';
@@ -25,6 +37,8 @@ export interface SetupResult {
25
37
  }
26
38
  export declare const configurableEnvironmentKeys: readonly string[];
27
39
  export declare function setupHosts(options?: SetupOptions): SetupResult;
40
+ /** Snapshot the normal setup plan without applying it; it does not verify a running host. */
41
+ export declare function checkSetup(options?: SetupOptions): SetupResult;
28
42
  export declare function removeSetup(options?: SetupOptions): SetupResult;
29
43
  export declare function setDefaults(options?: SetupOptions): SetupResult;
30
44
  export declare function setEnvironment(key: string, value: string, options?: SetupOptions): SetupResult;
@@ -60,4 +74,45 @@ export declare function showTransmission(options?: SetupOptions): {
60
74
  transmission_source: string;
61
75
  })[];
62
76
  };
77
+ /** Registration snapshot only. Never loads credentials, starts a server or creates a ledger/gate. */
78
+ export declare function showBudgetStatus(options?: SetupOptions): {
79
+ status: string;
80
+ clients: ({
81
+ client: Client;
82
+ status: string;
83
+ budget: {
84
+ limits: import("./budget.ts").BudgetLimits;
85
+ usage: {
86
+ daily_calls: number;
87
+ total_calls: number;
88
+ estimated_usd: number;
89
+ };
90
+ remaining: {
91
+ daily_calls: number | null;
92
+ total_calls: number | null;
93
+ estimated_usd: number | null;
94
+ };
95
+ utc_day: string;
96
+ timezone: 'UTC';
97
+ local_estimate: true;
98
+ exhausted_by: import("./types.ts").BudgetLimit[];
99
+ provenance: Record<keyof import("./budget.ts").BudgetLimits, "default" | "environment">;
100
+ display_limits: {
101
+ [k: string]: any;
102
+ };
103
+ next_utc_day: string;
104
+ cost_guard: string;
105
+ snapshot_source: string;
106
+ running_host_verified: boolean;
107
+ settings_require_mcp_restart: boolean;
108
+ };
109
+ } | {
110
+ invalid_budget_keys?: string[];
111
+ budget_error?: import("./budget.ts").BudgetErrorReason;
112
+ budget?: undefined;
113
+ client: Client;
114
+ status: string;
115
+ codes: string[];
116
+ })[];
117
+ };
63
118
  export {};