aptly 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -24,12 +24,12 @@ Requires Node.js **24 or later** and Claude Code or Codex. For first-time instal
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
- aptly setup --client all --mode defaults
27
+ aptly set default
28
28
  aptly set env OPENAI_API_KEY
29
29
  aptly --version
30
30
  ```
31
31
 
32
- Check the installed version with `aptly --version`. On supported npm versions, `--allow-scripts=aptly` allows Aptly’s installation script. If your npm does not support this option, follow the explicit installation and setup steps in the [installation guide](docs/guide/en.md#installation).
32
+ Check the installed version with `aptly --version`. On supported npm versions, `--allow-scripts=aptly` allows Aptly’s installation script. If your npm does not support this option, follow the explicit installation and setup steps in the [installation guide](docs/guide/en.md#installation). From Aptly 0.1.7, new registrations make no automatic transmission until you select an OpenAI Decisions API transmission scope with `aptly set default`.
33
33
 
34
34
  During installation, `postinstall` registers the MCP server and a `PreToolUse` Hook in existing host configuration directories. Run `setup` explicitly if automatic registration was skipped or a host has no configuration directory yet. Other settings and Hooks, and any existing Aptly launch command and environment, are preserved.
35
35
 
@@ -41,7 +41,7 @@ To update an existing global npm installation running Aptly 0.1.3 or later, stop
41
41
 
42
42
  ```sh
43
43
  aptly update
44
- aptly setup --client all --mode defaults
44
+ aptly setup --client all
45
45
  ```
46
46
 
47
47
  ## Usage modes
package/README.ja.md CHANGED
@@ -24,12 +24,12 @@ Node.js **24 以上**と Claude Code または Codex が必要です。初めて
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
- aptly setup --client all --mode defaults
27
+ aptly set default
28
28
  aptly set env OPENAI_API_KEY
29
29
  aptly --version
30
30
  ```
31
31
 
32
- `aptly --version` でインストール済みのバージョンを確認してください。対応する npm では、`--allow-scripts=aptly` で Aptly のインストールスクリプトを許可します。このオプションに対応していない npm では、[インストール案内](docs/guide/ja.md#インストール)の明示的なインストール・設定手順に従ってください。
32
+ `aptly --version` でインストール済みのバージョンを確認してください。対応する npm では、`--allow-scripts=aptly` で Aptly のインストールスクリプトを許可します。このオプションに対応していない npm では、[インストール案内](docs/guide/ja.md#インストール)の明示的なインストール・設定手順に従ってください。 Aptly 0.1.7 以降、新規登録は自動送信せず、`aptly set default` で OpenAI Decisions API への送信範囲を選択します。
33
33
 
34
34
  インストール時の `postinstall` は、既存のホスト設定ディレクトリに MCP と `PreToolUse` Hook を登録します。自動登録をスキップした場合や、ホストに設定ディレクトリがまだない場合も、`setup` を明示的に実行して登録できます。他の既存設定・Hook と、既存の Aptly の実行コマンド・環境は保持します。
35
35
 
@@ -41,7 +41,7 @@ npm でグローバルインストール済みの Aptly 0.1.3 以降を更新す
41
41
 
42
42
  ```sh
43
43
  aptly update
44
- aptly setup --client all --mode defaults
44
+ aptly setup --client all
45
45
  ```
46
46
 
47
47
  ## 使用方法
package/README.md CHANGED
@@ -24,12 +24,12 @@ Node.js **24 이상**과 Claude Code 또는 Codex가 필요합니다. 처음 설
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
- aptly setup --client all --mode defaults
27
+ aptly set default
28
28
  aptly set env OPENAI_API_KEY
29
29
  aptly --version
30
30
  ```
31
31
 
32
- `aptly --version`으로 설치된 버전을 확인하십시오. `--allow-scripts=aptly`는 지원하는 npm에서 Aptly의 설치 스크립트를 허용합니다. 이 옵션을 지원하지 않는 npm은 [설치 안내](docs/guide/ko.md#설치)의 명시적 설치·설정 절차를 따르십시오.
32
+ `aptly --version`으로 설치된 버전을 확인하십시오. `--allow-scripts=aptly`는 지원하는 npm에서 Aptly의 설치 스크립트를 허용합니다. 이 옵션을 지원하지 않는 npm은 [설치 안내](docs/guide/ko.md#설치)의 명시적 설치·설정 절차를 따르십시오. Aptly 0.1.7부터 신규 등록의 자동 전송을 보류하며 `aptly set default`에서 OpenAI Decisions API 전송 범위를 선택합니다.
33
33
 
34
34
  설치 시 `postinstall`은 기존 호스트 설정 디렉터리에 MCP와 `PreToolUse` Hook을 등록합니다. 명시적인 `setup`은 자동 등록을 건너뛰었거나 아직 설정 디렉터리가 없는 호스트에도 사용할 수 있습니다. 기존 다른 설정·Hook과 기존 Aptly 실행 명령·환경은 보존합니다.
35
35
 
@@ -41,7 +41,7 @@ aptly --version
41
41
 
42
42
  ```sh
43
43
  aptly update
44
- aptly setup --client all --mode defaults
44
+ aptly setup --client all
45
45
  ```
46
46
 
47
47
  ## 사용 방식
package/README.zh-CN.md CHANGED
@@ -24,12 +24,12 @@ Aptly 使用 OpenAI Decisions API 对简要任务摘要进行分类,并推荐
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
- aptly setup --client all --mode defaults
27
+ aptly set default
28
28
  aptly set env OPENAI_API_KEY
29
29
  aptly --version
30
30
  ```
31
31
 
32
- 请使用 `aptly --version` 确认已安装的版本。在支持此选项的 npm 中,`--allow-scripts=aptly` 允许执行 Aptly 的安装脚本。如果 npm 不支持此选项,请按照[安装指南](docs/guide/zh-CN.md#安装)中的显式安装与配置步骤操作。
32
+ 请使用 `aptly --version` 确认已安装的版本。在支持此选项的 npm 中,`--allow-scripts=aptly` 允许执行 Aptly 的安装脚本。如果 npm 不支持此选项,请按照[安装指南](docs/guide/zh-CN.md#安装)中的显式安装与配置步骤操作。 从 Aptly 0.1.7 起,新注册不会自动传输;请通过 `aptly set default` 选择向 OpenAI Decisions API 传输的范围。
33
33
 
34
34
  安装时的 `postinstall` 会在现有宿主配置目录中注册 MCP 和 `PreToolUse` Hook。如果跳过了自动注册,或宿主尚无配置目录,也可以显式运行 `setup`。其他现有配置与 Hook,以及 Aptly 原有的启动命令和环境均会保留。
35
35
 
@@ -41,7 +41,7 @@ aptly --version
41
41
 
42
42
  ```sh
43
43
  aptly update
44
- aptly setup --client all --mode defaults
44
+ aptly setup --client all
45
45
  ```
46
46
 
47
47
  ## 使用方式
package/dist/bin/aptly.js CHANGED
@@ -9,35 +9,52 @@ 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 } from '../src/setup.js';
13
- import { readEnvironmentValue } from '../src/cli-input.js';
12
+ import { budgetErrorDetails } from '../src/budget.js';
13
+ import { setupHosts, removeSetup, setDefaults, setEnvironment, configurableEnvironmentKeys, migrateLauncher, setTransmission, showTransmission, showBudgetStatus } from '../src/setup.js';
14
+ import { readEnvironmentValue, readTransmissionChoice } from '../src/cli-input.js';
14
15
  import { prepareApiKey } from '../src/credential-setup.js';
15
16
  import { updateGlobalInstallation } from '../src/update.js';
16
17
  import { updateNotification } from '../src/update-notifier.js';
18
+ import { resolveCliHelp } from '../src/cli-help.js';
17
19
  const [command = 'serve', ...args] = process.argv.slice(2);
18
20
  const output = (value) => process.stdout.write(JSON.stringify(value, null, 2) + '\n');
21
+ let helpHandled = false;
19
22
  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 missing default MCP environment settings.\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');
23
+ const help = resolveCliHelp(process.argv.slice(2), { environmentKeys: ['OPENAI_API_KEY', ...configurableEnvironmentKeys] });
24
+ if (help) {
25
+ helpHandled = true;
26
+ if (help.kind === 'error') {
27
+ process.stderr.write('aptly: ' + help.code + ' (use --help)\n');
28
+ process.exitCode = 2;
29
+ }
30
+ else
31
+ process.stdout.write(help.text);
22
32
  }
23
33
  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;
34
+ if (args.length)
35
+ throw new Error('update_invalid_options');
36
+ const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
37
+ const result = updateGlobalInstallation({ packageRoot });
38
+ output(result);
39
+ if (result.status === 'error')
40
+ process.exitCode = 1;
41
+ }
42
+ else if (command === 'budget') {
43
+ if (args[0] !== 'status')
44
+ throw new Error('budget_invalid_options');
45
+ let clients = ['codex', 'claude'];
46
+ if (args.length !== 1) {
47
+ if (args.length !== 3 || args[1] !== '--client' || !['codex', 'claude', 'all'].includes(args[2]))
48
+ throw new Error('budget_invalid_options');
49
+ clients = args[2] === 'all' ? ['codex', 'claude'] : [args[2]];
34
50
  }
51
+ const result = showBudgetStatus({ clients });
52
+ output(result);
53
+ if (result.status === 'partial')
54
+ process.exitCode = 1;
35
55
  }
36
56
  else if (command === '--version')
37
57
  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
58
  else if (command === 'report') {
42
59
  const options = { format: 'both', outputDir: 'reports' };
43
60
  const seen = new Set();
@@ -53,8 +70,22 @@ try {
53
70
  output(exportDiagnosticReport({ diagnostic: collectDiagnostics(), ...options }));
54
71
  }
55
72
  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 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');
73
+ if (args[0] === 'transmission') {
74
+ const scope = args[1];
75
+ if (!['none', 'description', 'excerpt', '--show'].includes(scope))
76
+ throw new Error('set_invalid_options');
77
+ let clients = ['codex', 'claude'];
78
+ if (args.length !== 2) {
79
+ if (args.length !== 4 || args[2] !== '--client' || !['codex', 'claude', 'all'].includes(args[3]))
80
+ throw new Error('set_invalid_options');
81
+ clients = args[3] === 'all' ? ['codex', 'claude'] : [args[3]];
82
+ }
83
+ const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
84
+ const result = scope === '--show' ? showTransmission({ clients }) : setTransmission(scope, { clients, packageRoot });
85
+ output(result);
86
+ if ('status' in result && result.status === 'partial')
87
+ process.exitCode = 1;
88
+ }
58
89
  else {
59
90
  const action = args[0];
60
91
  let key;
@@ -105,7 +136,15 @@ try {
105
136
  try {
106
137
  if (action === 'env')
107
138
  value = await readEnvironmentValue({ key: key, fromStdin });
108
- const result = action === 'default' ? setDefaults({ clients, packageRoot }) : key === 'OPENAI_API_KEY' ? credential.apply(value) : setEnvironment(key, value, { clients, packageRoot });
139
+ let result = action === 'default' ? setDefaults({ clients, packageRoot }) : key === 'OPENAI_API_KEY' ? credential.apply(value) : setEnvironment(key, value, { clients, packageRoot });
140
+ if (action === 'default' && result.status === 'complete' && process.stdin.isTTY && process.stdout.isTTY) {
141
+ const pending = result.clients.filter(client => client.transmission === 'unselected').map(client => client.client);
142
+ if (pending.length) {
143
+ const scope = await readTransmissionChoice();
144
+ const selected = setTransmission(scope, { clients: pending, packageRoot, selectUnselectedOnly: true });
145
+ result = { status: selected.status, clients: result.clients.map(client => selected.clients.find(item => item.client === client.client) ?? client) };
146
+ }
147
+ }
109
148
  output(result);
110
149
  if (result.status === 'partial')
111
150
  process.exitCode = 1;
@@ -116,53 +155,52 @@ try {
116
155
  }
117
156
  }
118
157
  else if (['setup', 'remove'].includes(command)) {
119
- if (args.length === 1 && args[0] === '--help')
120
- process.stdout.write('Usage: aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--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');
121
- else {
122
- let clients = ['codex', 'claude'];
123
- let mode = 'defaults';
124
- let automatic = false;
125
- let migrate = false;
126
- let dryRun = false;
127
- let includeExisting = false;
128
- const seen = new Set();
129
- for (let i = 0; i < args.length; i++) {
130
- const flag = args[i];
131
- if (seen.has(flag))
132
- throw new Error('setup_invalid_options');
133
- seen.add(flag);
134
- if (flag === '--migrate-launcher' && command === 'setup') {
135
- migrate = true;
136
- continue;
137
- }
138
- if (flag === '--include-existing' && command === 'setup') {
139
- includeExisting = true;
140
- continue;
141
- }
142
- if (flag === '--dry-run' && command === 'setup') {
143
- dryRun = true;
144
- continue;
145
- }
146
- if (flag === '--automatic' && command === 'setup') {
147
- automatic = true;
148
- continue;
149
- }
150
- const value = args[++i];
151
- if (flag === '--client' && ['codex', 'claude', 'all'].includes(value))
152
- clients = value === 'all' ? ['codex', 'claude'] : [value];
153
- else if (flag === '--mode' && command === 'setup' && ['defaults', 'advisory'].includes(value))
154
- mode = value;
155
- else
156
- throw new Error('setup_invalid_options');
158
+ let clients = ['codex', 'claude'];
159
+ let mode;
160
+ let transmission;
161
+ let automatic = false;
162
+ let migrate = false;
163
+ let dryRun = false;
164
+ let includeExisting = false;
165
+ const seen = new Set();
166
+ for (let i = 0; i < args.length; i++) {
167
+ const flag = args[i];
168
+ if (seen.has(flag))
169
+ throw new Error('setup_invalid_options');
170
+ seen.add(flag);
171
+ if (flag === '--migrate-launcher' && command === 'setup') {
172
+ migrate = true;
173
+ continue;
157
174
  }
158
- const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
159
- if ((migrate && (clients.length !== 1 || automatic || seen.has('--mode'))) || ((dryRun || includeExisting) && !migrate))
175
+ if (flag === '--include-existing' && command === 'setup') {
176
+ includeExisting = true;
177
+ continue;
178
+ }
179
+ if (flag === '--dry-run' && command === 'setup') {
180
+ dryRun = true;
181
+ continue;
182
+ }
183
+ if (flag === '--automatic' && command === 'setup') {
184
+ automatic = true;
185
+ continue;
186
+ }
187
+ const value = args[++i];
188
+ if (flag === '--client' && ['codex', 'claude', 'all'].includes(value))
189
+ clients = value === 'all' ? ['codex', 'claude'] : [value];
190
+ else if (flag === '--transmission' && command === 'setup' && ['none', 'description', 'excerpt'].includes(value))
191
+ transmission = value;
192
+ else if (flag === '--mode' && command === 'setup' && ['defaults', 'advisory'].includes(value))
193
+ mode = value;
194
+ else
160
195
  throw new Error('setup_invalid_options');
161
- const result = migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot }) : removeSetup({ clients });
162
- output(result);
163
- if (result.status === 'partial' && !automatic)
164
- process.exitCode = 1;
165
196
  }
197
+ const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
198
+ if ((migrate && (clients.length !== 1 || automatic || seen.has('--mode') || seen.has('--transmission'))) || ((dryRun || includeExisting) && !migrate))
199
+ throw new Error('setup_invalid_options');
200
+ const result = migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot, transmission }) : removeSetup({ clients });
201
+ output(result);
202
+ if (result.status === 'partial' && !automatic)
203
+ process.exitCode = 1;
166
204
  }
167
205
  else if (command === 'serve' && args.length === 0)
168
206
  await serve();
@@ -175,12 +213,6 @@ try {
175
213
  saveModelInfo(args[2], snapshot);
176
214
  output({ status: 'refreshed', facts: snapshot.facts.length, sources: snapshot.sources, account_access_verified: false });
177
215
  }
178
- else if (command === 'catalog' && args.length === 1 && args[0] === '--help') {
179
- 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');
180
- }
181
- else if (command === 'recommend' && args.length === 1 && args[0] === '--help') {
182
- 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');
183
- }
184
216
  else if (command === 'recommend' && args.length === 0) {
185
217
  const raw = readFileSync(0, 'utf8');
186
218
  if (Buffer.byteLength(raw) > 16384)
@@ -200,7 +232,7 @@ try {
200
232
  if (args[0] === 'claude')
201
233
  output({ mcpServers: { 'aptly': { command: node, args: [server], env: { ROUTER_PROVIDER: 'fixture' } } } });
202
234
  else
203
- 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');
235
+ 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');
204
236
  }
205
237
  else {
206
238
  process.stderr.write('aptly: invalid_command (use --help)\n');
@@ -212,14 +244,16 @@ catch (error) {
212
244
  const caughtCode = errorCode(error);
213
245
  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'];
214
246
  const message = error instanceof Error ? error.message : undefined;
247
+ const budgetCode = [caughtCode, message].find(value => typeof value === 'string' && ['invalid_budget_configuration', 'budget_invalid_options'].includes(value));
215
248
  const configCode = [caughtCode, message].find(value => typeof value === 'string' && safeConfigurationCodes.includes(value));
216
249
  const setCodes = ['set_environment_key_unsupported', 'set_invalid_options', 'set_value_too_large', 'set_interactive_input_required', 'set_input_cancelled'];
217
- 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';
218
- process.stderr.write('aptly: ' + code + '\n');
250
+ 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';
251
+ const budgetDetails = budgetErrorDetails(error);
252
+ process.stderr.write('aptly: ' + code + (budgetDetails.invalid_budget_keys?.length ? ' [' + budgetDetails.invalid_budget_keys.join(', ') + ']' : '') + (budgetDetails.budget_error ? ' (' + budgetDetails.budget_error + ')' : '') + '\n');
219
253
  process.exitCode = 1;
220
254
  }
221
255
  finally {
222
- if (!process.exitCode) {
256
+ if (!process.exitCode && !helpHandled) {
223
257
  try {
224
258
  const hint = await updateNotification({ command, args, env: process.env, stdinIsTTY: !!process.stdin.isTTY, stderrIsTTY: !!process.stderr.isTTY, stdoutIsTTY: !!process.stdout.isTTY, currentVersion: VERSION });
225
259
  if (hint)
@@ -1,14 +1,21 @@
1
1
  import { Router } from './core.ts';
2
2
  import type { HookOutput } from './hook.ts';
3
3
  import type { Client } from './types.ts';
4
- export interface AutoPolicy {
5
- schema_version: 1;
4
+ interface AutoPolicyBase {
6
5
  kind: 'aptly-auto-hook';
7
6
  mode: 'defaults' | 'advisory';
8
7
  issuer: 'operator_installation';
9
8
  enabled: boolean;
10
9
  state_directory: string;
11
10
  }
11
+ export type Transmission = 'none' | 'description' | 'excerpt' | 'unselected';
12
+ export type AutoPolicy = AutoPolicyBase & ({
13
+ schema_version: 1;
14
+ } | {
15
+ schema_version: 2;
16
+ transmission: Transmission;
17
+ });
18
+ export declare function effectiveTransmission(policy: AutoPolicy): Transmission;
12
19
  export interface AutomaticHookObservation {
13
20
  status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending' | 'awaiting_context' | 'blocked';
14
21
  preflight: 'observed';
@@ -110,3 +117,4 @@ export declare function automaticCallId(client: unknown, event: unknown): string
110
117
  export declare function initialHookObservation(client: unknown, event: unknown): AutomaticHookObservation;
111
118
  /** Operator default selection only. No provenance_verified/evidence_verified host claim. */
112
119
  export declare function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext, onBlockedAdvice }: AutomaticHookOptions): Promise<AutomaticHookResult>;
120
+ export {};
@@ -7,6 +7,9 @@ import { hasSufficientTaskText } from './context-sufficiency.js';
7
7
  import { assertPrivateStatePath, readRegularFile } from './files.js';
8
8
  import { hookInput, hookOutput, validatedHookProfile, profilePreservesChoices, effortKeys } from './hook.js';
9
9
  import { digestToolInput } from './provenance.js';
10
+ export function effectiveTransmission(policy) {
11
+ return policy.schema_version === 1 ? 'excerpt' : policy.transmission;
12
+ }
10
13
  const own = (object, key) => Object.hasOwn(object, key);
11
14
  const plain = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) &&
12
15
  [Object.prototype, null].includes(Object.getPrototypeOf(value));
@@ -20,14 +23,17 @@ export function loadAutomaticHookPolicy(path) {
20
23
  try {
21
24
  assertPrivateStatePath(path);
22
25
  const value = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 4096 }).toString('utf8'));
23
- if (!plain(value) || Object.keys(value).length !== policyKeys.length || Object.keys(value).some(key => !policyKeys.includes(key)) ||
24
- value.schema_version !== 1 || value.kind !== 'aptly-auto-hook' || (typeof value.mode !== 'string' || !['defaults', 'advisory'].includes(value.mode)) ||
26
+ if (!plain(value))
27
+ throw new Error('invalid_policy');
28
+ const keys = value.schema_version === 2 ? [...policyKeys, 'transmission'] : policyKeys;
29
+ if (Object.keys(value).length !== keys.length || Object.keys(value).some(key => !keys.includes(key)) ||
30
+ ![1, 2].includes(value.schema_version) || (value.schema_version === 2 && !['none', 'description', 'excerpt', 'unselected'].includes(value.transmission)) || value.kind !== 'aptly-auto-hook' || (typeof value.mode !== 'string' || !['defaults', 'advisory'].includes(value.mode)) ||
25
31
  value.issuer !== 'operator_installation' || typeof value.enabled !== 'boolean' ||
26
32
  typeof value.state_directory !== 'string' || !isAbsolute(value.state_directory))
27
33
  throw new Error('invalid_policy');
28
34
  // Validate an existing private state directory, without creating a path from untrusted event data.
29
35
  assertPrivateStatePath(join(value.state_directory, '.aptly-state-check'));
30
- const policy = Object.fromEntries(policyKeys.map(key => [key, value[key]]));
36
+ const policy = Object.fromEntries(keys.map(key => [key, value[key]]));
31
37
  return { policy, fingerprint: hash(policy), reason: policy.enabled ? 'automatic_policy_enabled' : 'automatic_policy_disabled' };
32
38
  }
33
39
  catch {
@@ -181,6 +187,7 @@ function bindCall(call, policy, policyFingerprint, catalog, contextDigest) {
181
187
  export async function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext, onBlockedAdvice }) {
182
188
  const observation = initialHookObservation(client, event);
183
189
  let activeMode;
190
+ let budgetLimit;
184
191
  const preserve = (reason, request_id) => {
185
192
  const result = { output: {}, observation: { ...observation, status: 'preserved', reason, ...(request_id ? { request_id } : {}) } };
186
193
  if (!activeMode || signal?.aborted || reason === 'call_cancelled')
@@ -189,7 +196,11 @@ export async function automaticHook({ client, event, router, policyPath, signal,
189
196
  const currentPolicy = loadAutomaticHookPolicy(policyPath).policy;
190
197
  if (!currentPolicy?.enabled)
191
198
  return result;
192
- 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.`;
199
+ if (['none', 'unselected'].includes(effectiveTransmission(currentPolicy))) {
200
+ result.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: `Aptly automatic routing is inactive (${effectiveTransmission(currentPolicy)}). Original arguments are preserved.` } };
201
+ return result;
202
+ }
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.`;
193
204
  result.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: message,
194
205
  ...(currentPolicy.mode === 'defaults' ? { permissionDecision: 'deny', permissionDecisionReason: message } : {}) } };
195
206
  result.observation.status = currentPolicy.mode === 'defaults' ? 'blocked' : 'preserved';
@@ -199,6 +210,10 @@ export async function automaticHook({ client, event, router, policyPath, signal,
199
210
  const loaded = loadAutomaticHookPolicy(policyPath);
200
211
  if (!loaded.policy || !loaded.policy.enabled || !loaded.fingerprint)
201
212
  return preserve(loaded.reason);
213
+ if (['none', 'unselected'].includes(effectiveTransmission(loaded.policy))) {
214
+ activeMode = loaded.policy.mode;
215
+ return preserve(`transmission_${effectiveTransmission(loaded.policy)}`);
216
+ }
202
217
  const call = readCall(client, event);
203
218
  if (!call)
204
219
  return preserve('invalid_event');
@@ -251,7 +266,8 @@ export async function automaticHook({ client, event, router, policyPath, signal,
251
266
  const supplied = context?.();
252
267
  if (supplied?.reason)
253
268
  return preserve(supplied.reason);
254
- const summary = supplied?.summary ? supplied : boundedSummary(call, router.policy.max_summary_bytes);
269
+ const summary = supplied?.summary ? supplied : effectiveTransmission(loaded.policy) === 'description'
270
+ ? { reason: 'insufficient_context' } : boundedSummary(call, router.policy.max_summary_bytes);
255
271
  if (Buffer.byteLength(summary.summary ?? '') > Math.min(4000, router.policy.max_summary_bytes))
256
272
  return preserve('insufficient_context');
257
273
  if (!summary.summary) {
@@ -259,6 +275,13 @@ export async function automaticHook({ client, event, router, policyPath, signal,
259
275
  return preserve(summary.reason ?? 'insufficient_context');
260
276
  if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
261
277
  return preserve('call_cancelled');
278
+ const currentPolicy = loadAutomaticHookPolicy(policyPath), currentCall = readCall(client, event), currentContext = context?.();
279
+ if (!currentPolicy.policy?.enabled || currentPolicy.fingerprint !== loaded.fingerprint)
280
+ return preserve('automatic_policy_changed');
281
+ if (!currentCall || currentCall.callKey !== call.callKey || currentCall.payloadDigest !== call.payloadDigest)
282
+ return preserve('call_changed');
283
+ if (currentContext?.reason || currentContext?.fingerprint !== supplied?.fingerprint)
284
+ return preserve(currentContext?.reason ?? 'context_changed');
262
285
  const legacyId = hookInput({ client, event, policy: router.policy })?.request_id ?? hash([call.client, call.event.session_id, call.event.tool_use_id ?? call.event.tool_call_id]);
263
286
  try {
264
287
  router.load();
@@ -313,6 +336,8 @@ export async function automaticHook({ client, event, router, policyPath, signal,
313
336
  eligible_profile_ids: profiles.map(profile => profile.id),
314
337
  constraints: { model_pinned: false, effort_pinned: false, role_pinned: false, fork_inherits: false },
315
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;
316
341
  observation.classification = recommendation.cached ? 'cache_hit' : typeof recommendation.latency_ms === 'number' ? 'provider_requested' : 'local_outcome';
317
342
  const profile = validatedHookProfile(client, recommendation, router.policy);
318
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;