aptly 0.1.21 → 0.2.0

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.
Files changed (43) hide show
  1. package/README.en.md +6 -11
  2. package/README.ja.md +6 -11
  3. package/README.md +6 -11
  4. package/README.zh-CN.md +6 -11
  5. package/dist/bin/aptly.js +50 -10
  6. package/dist/src/antigravity-catalog.d.ts +38 -0
  7. package/dist/src/antigravity-catalog.js +64 -0
  8. package/dist/src/antigravity-hook.d.ts +14 -0
  9. package/dist/src/antigravity-hook.js +84 -0
  10. package/dist/src/antigravity-runtime.d.ts +9 -0
  11. package/dist/src/antigravity-runtime.js +46 -0
  12. package/dist/src/automatic-hook.js +4 -4
  13. package/dist/src/cli-help.js +7 -4
  14. package/dist/src/context-retry.js +1 -1
  15. package/dist/src/core.d.ts +10 -5
  16. package/dist/src/core.js +73 -29
  17. package/dist/src/doctor.d.ts +1 -0
  18. package/dist/src/doctor.js +1 -1
  19. package/dist/src/provider.js +9 -3
  20. package/dist/src/server.d.ts +6 -5
  21. package/dist/src/server.js +41 -3
  22. package/dist/src/setup.d.ts +2 -1
  23. package/dist/src/setup.js +15 -13
  24. package/dist/src/stable-runtime.d.ts +4 -0
  25. package/dist/src/stable-runtime.js +119 -18
  26. package/dist/src/types.d.ts +3 -2
  27. package/dist/src/update.d.ts +19 -0
  28. package/dist/src/update.js +84 -0
  29. package/dist/src/version.d.ts +1 -1
  30. package/dist/src/version.js +1 -1
  31. package/docs/guide/en/advanced.md +81 -0
  32. package/docs/guide/en/configuration.md +16 -1
  33. package/docs/guide/en/installation.md +20 -3
  34. package/docs/guide/ja/advanced.md +81 -0
  35. package/docs/guide/ja/configuration.md +16 -1
  36. package/docs/guide/ja/installation.md +20 -3
  37. package/docs/guide/ko/advanced.md +81 -0
  38. package/docs/guide/ko/configuration.md +16 -1
  39. package/docs/guide/ko/installation.md +20 -3
  40. package/docs/guide/zh-CN/advanced.md +81 -0
  41. package/docs/guide/zh-CN/configuration.md +16 -1
  42. package/docs/guide/zh-CN/installation.md +20 -3
  43. package/package.json +1 -1
package/README.en.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  </div>
14
14
 
15
- Aptly recommends models and reasoning effort for Claude Code and Codex subagents. It sends a task summary to the OpenAI Decisions API and preserves explicitly selected models, reasoning effort, and execution permissions.
15
+ Aptly recommends subagent models and reasoning effort for Claude Code and Codex, and models and execution tiers for Antigravity CLI. It sends a task summary to the OpenAI Decisions API and preserves explicitly selected models, reasoning effort, and execution permissions.
16
16
 
17
17
  ## Quick start
18
18
 
@@ -24,22 +24,17 @@ aptly set default
24
24
  aptly set env OPENAI_API_KEY
25
25
  ```
26
26
 
27
- Choose the transmission scope in `set default` and enter your API key through the hidden prompt. Restart the host, then **review and approve the new Hook in `/hooks` for Codex**. See [installation and key setup](docs/guide/en/installation.md) for npm compatibility and account-specific configuration.
27
+ Choose the transmission scope in `set default` and enter your API key through the hidden prompt. Restart the host, then **review and approve the new Hook in `/hooks` for Codex**. See [installation and setup verification](docs/guide/en/installation.md#guide-verify-setup) to check the registration.
28
28
 
29
- ## Update
30
-
31
- Stop the relevant hosts, MCP servers, and CLI processes before running these commands.
29
+ For Antigravity CLI, see [workspace setup](docs/guide/en/advanced.md#guide-antigravity-advisory).
32
30
 
33
- ```sh
34
- aptly update
35
- aptly setup --client all
36
- ```
31
+ ## Update
37
32
 
38
- Restart the host. You do not need to re-enter the key. If migrating a stable launcher or an older version, see [updates](docs/guide/en/installation.md#guide-package-updates).
33
+ Stop the related hosts, MCP servers, and CLI processes, then run `aptly update`. On macOS and Linux, the update migrates existing Aptly-owned registrations to managed npx. On Windows, it updates the package. When upgrading from 0.1.21, run `aptly update` again with the new CLI. Approve changed Codex Hooks in `/hooks` and restart the host. [Update guide](docs/guide/en/installation.md#guide-package-updates)
39
34
 
40
35
  ## Documentation
41
36
 
42
37
  - [User guide](docs/guide/en.md): configuration, automatic recommendations, budgets, statistics, and troubleshooting
43
38
  - [Model candidates](docs/guide/en/configuration.md#guide-models-and-environment)
44
39
  - [Transmission scope](docs/guide/en/transmission.md): information sent to the Decisions API
45
- - [Measured costs](docs/guide/en/benchmarks.md) — In a small README review test, the API-equivalent cost of subagent review and Decisions classification fell by about 52–58%. The estimate covers only those two costs.
40
+ - [Measured costs](docs/guide/en/benchmarks.md) — For one README review task with three runs per condition, subagent review and Decisions classification costs at Standard API rates were about 52–58% lower with explicit MCP recommendations.
package/README.ja.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  </div>
14
14
 
15
- Claude Code・Codex のサブエージェントにモデルと推論強度を推薦します。タスクの要約を OpenAI Decisions API に送信し、明示されたモデル・推論強度・実行権限は保持します。
15
+ Claude Code と Codex のサブエージェントにモデルと推論強度を、Antigravity CLI にはモデルと実行ティアを推薦します。タスクの要約を OpenAI Decisions API に送信し、明示されたモデル・推論強度・実行権限は保持します。
16
16
 
17
17
  ## クイックスタート
18
18
 
@@ -24,22 +24,17 @@ aptly set default
24
24
  aptly set env OPENAI_API_KEY
25
25
  ```
26
26
 
27
- `set default` で送信範囲を選び、API キーは非表示入力で登録します。ホストを再起動した後、**Codex では `/hooks` で新しい Hook を確認・承認**してください。[インストール・キー設定](docs/guide/ja/installation.md)で npm の互換オプションとアカウント別の設定を確認できます。
27
+ `set default` で送信範囲を選び、API キーは非表示入力で登録します。ホストを再起動した後、**Codex では `/hooks` で新しい Hook を確認・承認**してください。登録状況の確認方法は[インストールと設定の確認](docs/guide/ja/installation.md#guide-verify-setup)を参照してください。
28
28
 
29
- ## 更新
30
-
31
- 実行前に、関連するホスト・MCP サーバー・CLI プロセスを停止してください。
29
+ Antigravity CLI については、[ワークスペースの設定](docs/guide/ja/advanced.md#guide-antigravity-advisory)を参照してください。
32
30
 
33
- ```sh
34
- aptly update
35
- aptly setup --client all
36
- ```
31
+ ## 更新
37
32
 
38
- ホストを再起動してください。キーの再入力は不要です。stable ランチャーや以前のバージョンから移行する場合は、[更新案内](docs/guide/ja/installation.md#guide-package-updates)を確認してください。
33
+ 関連するホスト・MCP サーバー・CLI を停止してから `aptly update` を実行してください。macOS と Linux では Aptly が所有する既存登録を管理型 npx に移行し、Windows ではパッケージを更新します。0.1.21 から更新する場合は、新しい CLI で `aptly update` をもう一度実行してください。変更された Codex Hook を `/hooks` で承認し、ホストを再起動してください。[更新ガイド](docs/guide/ja/installation.md#guide-package-updates)
39
34
 
40
35
  ## ドキュメント
41
36
 
42
37
  - [使用ガイド](docs/guide/ja.md): 設定・自動推薦・予算・統計・トラブルシューティング
43
38
  - [候補モデルの設定](docs/guide/ja/configuration.md#guide-models-and-environment)
44
39
  - [送信範囲](docs/guide/ja/transmission.md): Decisions API に送る情報
45
- - [費用実測](docs/guide/ja/benchmarks.md) — 小規模な README レビュー試験では、サブエージェントのレビューと Decisions の分類にかかる API 換算費用が、合計で約 52~58% 減りました。集計の対象はこの二つの費用です。
40
+ - [費用実測](docs/guide/ja/benchmarks.md) — 1 つの README レビュー課題を各条件で 3 回ずつ実行しました。明示的な MCP 推薦を使った場合、サブエージェントのレビューと Decisions の分類にかかる費用は、Standard API の単価で換算すると約 52~58% 低くなりました。
package/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  </div>
14
14
 
15
- Claude Code·Codex 서브에이전트의 모델과 추론 강도를 추천합니다. 작업 요약을 OpenAI Decisions API로 보내며, 명시한 모델·추론 강도·실행 권한은 보존합니다.
15
+ Claude Code·Codex에는 서브에이전트 모델과 추론 강도를, Antigravity CLI에는 모델과 실행 티어를 추천합니다. 작업 요약을 OpenAI Decisions API로 보내며, 명시한 모델·추론 강도·실행 권한은 보존합니다.
16
16
 
17
17
  ## 빠른 시작
18
18
 
@@ -24,22 +24,17 @@ aptly set default
24
24
  aptly set env OPENAI_API_KEY
25
25
  ```
26
26
 
27
- `set default`에서 전송 범위를 선택하고 API 키는 숨김 입력으로 등록합니다. 호스트를 재시작한 뒤 **Codex는 `/hooks`에서 새 Hook을 검토·승인**하십시오. [설치·키 설정](docs/guide/ko/installation.md)에서 npm 호환 옵션과 계정별 설정을 확인할 수 있습니다.
27
+ `set default`에서 전송 범위를 선택하고 API 키는 숨김 입력으로 등록합니다. 호스트를 재시작한 뒤 **Codex는 `/hooks`에서 새 Hook을 검토·승인**하십시오. [설치·설정 확인](docs/guide/ko/installation.md#guide-verify-setup)에서 등록 상태를 점검할 수 있습니다.
28
28
 
29
- ## 업데이트
30
-
31
- 관련 호스트·MCP 서버·CLI 프로세스를 중지한 뒤 실행하십시오.
29
+ Antigravity CLI는 [워크스페이스 설정 안내](docs/guide/ko/advanced.md#guide-antigravity-advisory)를 참고하십시오.
32
30
 
33
- ```sh
34
- aptly update
35
- aptly setup --client all
36
- ```
31
+ ## 업데이트
37
32
 
38
- 호스트를 재시작하십시오. 키를 다시 입력할 필요는 없습니다. stable 실행기나 이전 버전에서 전환하는 경우 [업데이트 안내](docs/guide/ko/installation.md#guide-package-updates)를 확인하십시오.
33
+ 관련 호스트·MCP·CLI를 중지한 뒤 `aptly update`를 실행하십시오. macOS·Linux에서는 기존 Aptly 소유 등록을 관리형 npx로 전환하고, Windows에서는 패키지를 갱신합니다. 0.1.21에서 올리는 경우 새 CLI로 `aptly update`를 한 번 더 실행하십시오. 변경된 Codex Hook을 `/hooks`에서 승인하고 호스트를 재시작하십시오. [업데이트 안내](docs/guide/ko/installation.md#guide-package-updates)
39
34
 
40
35
  ## 문서
41
36
 
42
37
  - [사용 가이드](docs/guide/ko.md): 설정·자동 추천·예산·통계·문제 해결
43
38
  - [모델 후보 설정](docs/guide/ko/configuration.md#guide-models-and-environment)
44
39
  - [전송 범위](docs/guide/ko/transmission.md): Decisions API에 보내는 정보
45
- - [비용 실측](docs/guide/ko/benchmarks.md) — 소규모 README 검토 시험에서 서브에이전트의 검토 비용과 Decisions 분류 비용을 합산한 API 환산액이 약 52~58% 줄었습니다. 측정 범위는 이 두 비용입니다.
40
+ - [비용 실측](docs/guide/ko/benchmarks.md) — README 검토 과제 하나를 조건별로 3회씩 실행했습니다. 명시적 MCP 추천을 사용했을 때 서브에이전트 검토와 Decisions 분류의 Standard API 환산 비용이 약 52~58% 낮았습니다.
package/README.zh-CN.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  </div>
14
14
 
15
- 为 Claude Code 和 Codex 子代理推荐模型与推理强度。Aptly 将任务摘要发送给 OpenAI Decisions API,并保留明确指定的模型、推理强度和执行权限。
15
+ 为 Claude Code 和 Codex 子代理推荐模型与推理强度,为 Antigravity CLI 推荐模型和运行档位。Aptly 将任务摘要发送给 OpenAI Decisions API,并保留明确指定的模型、推理强度和执行权限。
16
16
 
17
17
  ## 快速开始
18
18
 
@@ -24,22 +24,17 @@ aptly set default
24
24
  aptly set env OPENAI_API_KEY
25
25
  ```
26
26
 
27
- 请在 `set default` 中选择传输范围,并通过隐藏输入注册 API 密钥。重启宿主后,**请在 Codex 的 `/hooks` 中审核并批准新 Hook**。有关 npm 兼容选项和各账户设置,请参阅[安装与密钥设置](docs/guide/zh-CN/installation.md)。
27
+ 请在 `set default` 中选择传输范围,并通过隐藏输入注册 API 密钥。重启宿主后,**请在 Codex 的 `/hooks` 中审核并批准新 Hook**。如需检查注册状态,请参阅[安装与设置验证](docs/guide/zh-CN/installation.md#guide-verify-setup)。
28
28
 
29
- ## 更新
30
-
31
- 执行前,请停止相关宿主、MCP 服务器和 CLI 进程。
29
+ 如需使用 Antigravity CLI,请参阅[工作区设置](docs/guide/zh-CN/advanced.md#guide-antigravity-advisory)。
32
30
 
33
- ```sh
34
- aptly update
35
- aptly setup --client all
36
- ```
31
+ ## 更新
37
32
 
38
- 请重启宿主,无需重新输入密钥。如果从 stable 启动器或旧版本迁移,请参阅[更新指南](docs/guide/zh-CN/installation.md#guide-package-updates)。
33
+ 关闭相关宿主、MCP 服务器和 CLI 后,运行 `aptly update`。在 macOS 和 Linux 上,更新会将 Aptly 管理的现有注册迁移到托管 npx。在 Windows 上,更新会升级软件包。从 0.1.21 升级时,请使用新的 CLI 再运行一次 `aptly update`。请在 Codex 的 `/hooks` 中批准变更后的 Hook,然后重启宿主。[更新指南](docs/guide/zh-CN/installation.md#guide-package-updates)
39
34
 
40
35
  ## 文档
41
36
 
42
37
  - [使用指南](docs/guide/zh-CN.md):设置、自动推荐、预算、统计与问题排查
43
38
  - [候选模型设置](docs/guide/zh-CN/configuration.md#guide-models-and-environment)
44
39
  - [传输范围](docs/guide/zh-CN/transmission.md):发送给 Decisions API 的信息
45
- - [成本实测](docs/guide/zh-CN/benchmarks.md):在一次小规模 README 审阅测试中,子代理审阅和 Decisions 分类的 API 折算费用合计下降了约 52%~58%。统计范围仅包括这两项费用。
40
+ - [成本实测](docs/guide/zh-CN/benchmarks.md):对同一个 README 审阅任务,每种条件各运行 3 次。使用显式 MCP 推荐时,按 Standard API 单价折算的子代理审阅和 Decisions 分类费用低了约 52%~58%。
package/dist/bin/aptly.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { serve } from '../src/server.js';
5
+ import { runAntigravityHook } from '../src/antigravity-hook.js';
5
6
  import { runtime } from '../src/runtime.js';
6
7
  import { explainSettings } from '../src/inspect.js';
7
8
  import { VERSION } from '../src/version.js';
@@ -15,7 +16,7 @@ import { checkSetup, setupHosts, removeSetup, setDefaults, setEnvironment, confi
15
16
  import { readEnvironmentValue } from '../src/cli-input.js';
16
17
  import { prepareApiKey } from '../src/credential-setup.js';
17
18
  import { linuxStoreReadiness } from '../src/linux-store-readiness.js';
18
- import { updateGlobalInstallation } from '../src/update.js';
19
+ import { updateGlobalAndMigrate } from '../src/update.js';
19
20
  import { updateNotification } from '../src/update-notifier.js';
20
21
  import { resolveCliHelp } from '../src/cli-help.js';
21
22
  import { runTransmissionReview, reviewAfterSetup } from '../src/transmission-review-cli.js';
@@ -34,15 +35,39 @@ try {
34
35
  process.stdout.write(help.text);
35
36
  }
36
37
  else if (command === 'update') {
37
- if (args.length)
38
+ let updateClient;
39
+ let updateLauncher = false;
40
+ const seen = new Set();
41
+ for (let i = 0; i < args.length; i++) {
42
+ const flag = args[i];
43
+ if (seen.has(flag))
44
+ throw new Error('update_invalid_options');
45
+ seen.add(flag);
46
+ const value = args[++i];
47
+ if (flag === '--client' && (value === 'codex' || value === 'claude'))
48
+ updateClient = value;
49
+ else if (flag === '--launcher' && value === 'npx')
50
+ updateLauncher = true;
51
+ else
52
+ throw new Error('update_invalid_options');
53
+ }
54
+ if (!!updateClient !== updateLauncher)
38
55
  throw new Error('update_invalid_options');
39
56
  const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
40
- const result = updateGlobalInstallation({ packageRoot });
41
- output(result.status === 'complete' ? { ...result, next_steps: ['aptly setup', 'aptly set transmission --review'], ...(process.platform !== 'win32' ? { stable_launcher_update_note: 'Existing stable registrations retain their snapshot until an explicit per-client migration; run aptly setup --help for --migrate-launcher --launcher stable.' } : {}) } : result);
57
+ const result = updateGlobalAndMigrate({ packageRoot, client: updateClient });
58
+ const setupRequired = result.status === 'complete' && result.codes.includes('setup_required');
59
+ output(setupRequired ? { ...result, next_steps: ['aptly setup', 'aptly set transmission --review'] } : result);
42
60
  if (result.status === 'error')
43
61
  process.exitCode = 1;
44
- else if (process.stderr.isTTY && !process.env.CI)
45
- process.stderr.write('Run aptly setup after updating; its first interactive run reviews transmission scope. Use aptly set transmission --review for an explicit review, then restart MCP.\n');
62
+ if (process.stderr.isTTY && !process.env.CI) {
63
+ if (setupRequired)
64
+ process.stderr.write('Run aptly setup to register a new host. Use aptly set transmission --review to review the transmission scope, then restart MCP.\n');
65
+ const configured = (result.migrations ?? (result.migration ? [result.migration] : [])).filter(host => host.status === 'configured');
66
+ if (configured.some(host => host.requires_hook_review))
67
+ process.stderr.write('Approve changed Codex Hooks in /hooks.\n');
68
+ if (configured.length)
69
+ process.stderr.write('Restart the migrated hosts to load the new launcher.\n');
70
+ }
46
71
  }
47
72
  else if (command === 'doctor') {
48
73
  let clients = ['codex', 'claude'];
@@ -250,8 +275,8 @@ try {
250
275
  const value = args[++i];
251
276
  if (flag === '--client' && ['codex', 'claude', 'all'].includes(value))
252
277
  clients = value === 'all' ? ['codex', 'claude'] : [value];
253
- else if (flag === '--launcher' && command === 'setup' && value === 'stable')
254
- launcher = 'stable';
278
+ else if (flag === '--launcher' && command === 'setup' && (value === 'stable' || value === 'npx'))
279
+ launcher = value;
255
280
  else if (flag === '--policy-source' && command === 'setup' && value === 'codex-home')
256
281
  policySource = true;
257
282
  else if (flag === '--transmission' && command === 'setup' && ['none', 'description', 'excerpt'].includes(value))
@@ -273,8 +298,23 @@ try {
273
298
  if (result.status === 'partial' && !automatic)
274
299
  process.exitCode = 1;
275
300
  }
301
+ else if (command === 'antigravity-hook' && args.length === 0) {
302
+ const controller = new AbortController();
303
+ const abort = () => controller.abort();
304
+ process.once('SIGINT', abort);
305
+ process.once('SIGTERM', abort);
306
+ try {
307
+ process.stdout.write(JSON.stringify(await runAntigravityHook(controller.signal)) + '\n');
308
+ }
309
+ finally {
310
+ process.removeListener('SIGINT', abort);
311
+ process.removeListener('SIGTERM', abort);
312
+ }
313
+ }
276
314
  else if (command === 'serve' && args.length === 0)
277
315
  await serve();
316
+ else if (command === 'serve' && args.length === 2 && args[0] === '--client' && args[1] === 'antigravity')
317
+ await serve({ advisoryClient: 'antigravity' });
278
318
  else if ((command === 'capabilities' || command === 'catalog') && args.length === 0) {
279
319
  const { router, mode, modelInfo, credentialStatus, disabledClients } = runtime();
280
320
  output({ ...router.capabilities(), provider: mode, credential_status: credentialStatus, model_information: { status: modelInfo.status, account_access_verified: false }, disabled_clients: disabledClients });
@@ -313,7 +353,7 @@ try {
313
353
  catch (error) {
314
354
  const codes = ['report_invalid_options', 'report_invalid_diagnostic', 'report_invalid_format', 'report_already_exists', 'report_output_unavailable'];
315
355
  const caughtCode = errorCode(error);
316
- 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'];
356
+ const safeConfigurationCodes = ['antigravity_provider_invalid', 'antigravity_models_invalid', 'antigravity_state_directory_required', 'antigravity_state_directory_invalid', 'antigravity_credential_reference_unsupported', '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'];
317
357
  const message = error instanceof Error ? error.message : undefined;
318
358
  const budgetCode = [caughtCode, message].find(value => typeof value === 'string' && ['invalid_budget_configuration', 'budget_invalid_options'].includes(value));
319
359
  const configCode = [caughtCode, message].find(value => typeof value === 'string' && safeConfigurationCodes.includes(value));
@@ -326,7 +366,7 @@ catch (error) {
326
366
  process.exitCode = 1;
327
367
  }
328
368
  finally {
329
- if (!process.exitCode && !helpHandled && !['stats', 'doctor'].includes(command)) {
369
+ if (!process.exitCode && !helpHandled && !['stats', 'doctor', 'antigravity-hook'].includes(command)) {
330
370
  try {
331
371
  const hint = await updateNotification({ command, args, env: process.env, stdinIsTTY: !!process.stdin.isTTY, stderrIsTTY: !!process.stderr.isTTY, stdoutIsTTY: !!process.stdout.isTTY, currentVersion: VERSION });
332
372
  if (hint)
@@ -0,0 +1,38 @@
1
+ import type { Profile } from './types.ts';
2
+ type AntigravityProfile = Profile & {
3
+ client: 'antigravity';
4
+ };
5
+ export type AntigravityScope = 'antigravity' | 'antigravity-automatic';
6
+ declare const tierCandidates: readonly [{
7
+ readonly id: 'antigravity-tier-simple';
8
+ readonly model: 'flash_lite';
9
+ readonly description: 'Native Antigravity tier for focused extraction and small mechanical tasks.';
10
+ }, {
11
+ readonly id: 'antigravity-tier-routine';
12
+ readonly model: 'flash';
13
+ readonly description: 'Native Antigravity tier for bounded implementation, translation or ordinary review.';
14
+ }, {
15
+ readonly id: 'antigravity-tier-deep';
16
+ readonly model: 'pro';
17
+ readonly description: 'Native Antigravity tier for architecture, dependency analysis or complex debugging and review.';
18
+ }];
19
+ export type AntigravityTier = typeof tierCandidates[number]['model'];
20
+ export declare function isAntigravityTier(value: unknown): value is AntigravityTier;
21
+ export declare function isAntigravityProfile(value: unknown, scope?: AntigravityScope): value is AntigravityProfile;
22
+ export declare function resolveAntigravityCatalog(raw: string | undefined): {
23
+ profiles: AntigravityProfile[];
24
+ descriptions: {
25
+ [k: string]: string;
26
+ };
27
+ version: string;
28
+ status: string;
29
+ };
30
+ export declare function resolveAntigravityTierCatalog(): {
31
+ profiles: AntigravityProfile[];
32
+ descriptions: {
33
+ [k: string]: "Native Antigravity tier for architecture, dependency analysis or complex debugging and review." | "Native Antigravity tier for bounded implementation, translation or ordinary review." | "Native Antigravity tier for focused extraction and small mechanical tasks.";
34
+ };
35
+ version: string;
36
+ status: 'configured';
37
+ };
38
+ export {};
@@ -0,0 +1,64 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isRecord } from './types.js';
3
+ // These are CLI model IDs, including their thinking levels. Antigravity
4
+ // subagent tiers use a separate catalog and ledger.
5
+ const candidates = [
6
+ { id: 'antigravity-simple', model: 'gemini-4-hydrogen-medium',
7
+ description: 'For focused extraction, light edits, formatting, or bounded mechanical changes.' },
8
+ { id: 'antigravity-routine', model: 'gemini-4-carbon-medium',
9
+ description: 'For context-aware writing, bounded implementation, or ordinary code review.' },
10
+ { id: 'antigravity-deep', model: 'gemini-4-neon-medium',
11
+ description: 'For complex debugging, dependency analysis, or architecture and deep review.' },
12
+ { id: 'antigravity-deep-high', model: 'gemini-4-neon-high',
13
+ description: 'Use instead of Neon Medium only when the task explicitly requires detailed reasoning across interacting constraints or subtle failure modes.' },
14
+ ];
15
+ const tierCandidates = [
16
+ { id: 'antigravity-tier-simple', model: 'flash_lite',
17
+ description: 'Native Antigravity tier for focused extraction and small mechanical tasks.' },
18
+ { id: 'antigravity-tier-routine', model: 'flash',
19
+ description: 'Native Antigravity tier for bounded implementation, translation or ordinary review.' },
20
+ { id: 'antigravity-tier-deep', model: 'pro',
21
+ description: 'Native Antigravity tier for architecture, dependency analysis or complex debugging and review.' },
22
+ ];
23
+ export function isAntigravityTier(value) {
24
+ return tierCandidates.some(({ model }) => model === value);
25
+ }
26
+ export function isAntigravityProfile(value, scope = 'antigravity') {
27
+ if (!isRecord(value) || Object.getOwnPropertySymbols(value).length)
28
+ return false;
29
+ const fields = Object.getOwnPropertyDescriptors(value);
30
+ return Object.keys(fields).length === 3 &&
31
+ ['id', 'client', 'model'].every(key => fields[key]?.enumerable && Object.hasOwn(fields[key], 'value')) &&
32
+ fields.client.value === 'antigravity' &&
33
+ (scope === 'antigravity-automatic' ? tierCandidates : candidates)
34
+ .some(({ id, model }) => fields.id.value === id && fields.model.value === model);
35
+ }
36
+ export function resolveAntigravityCatalog(raw) {
37
+ let models = [];
38
+ if (raw !== undefined) {
39
+ try {
40
+ if (raw.length > 256)
41
+ throw new Error();
42
+ models = JSON.parse(raw);
43
+ }
44
+ catch {
45
+ throw new Error('antigravity_models_invalid');
46
+ }
47
+ }
48
+ if (!Array.isArray(models) || models.length > candidates.length || new Set(models).size !== models.length ||
49
+ models.some(model => !candidates.some(candidate => candidate.model === model))) {
50
+ throw new Error('antigravity_models_invalid');
51
+ }
52
+ const selected = candidates.filter(({ model }) => models.includes(model));
53
+ const profiles = selected.map(({ id, model }) => ({ id, client: 'antigravity', model }));
54
+ const descriptions = Object.fromEntries(selected.map(({ id, model, description }) => [id, model + '. ' + description]));
55
+ const version = 'antigravity-' + createHash('sha256').update(JSON.stringify({ profiles, descriptions })).digest('hex').slice(0, 32);
56
+ const status = raw === undefined ? 'unconfigured' : profiles.length ? 'configured' : 'empty';
57
+ return { profiles, descriptions, version, status };
58
+ }
59
+ export function resolveAntigravityTierCatalog() {
60
+ const profiles = tierCandidates.map(({ id, model }) => ({ id, client: 'antigravity', model }));
61
+ const descriptions = Object.fromEntries(tierCandidates.map(({ id, description }) => [id, description]));
62
+ const version = 'antigravity-tiers-' + createHash('sha256').update(JSON.stringify({ profiles, descriptions })).digest('hex').slice(0, 32);
63
+ return { profiles, descriptions, version, status: 'configured' };
64
+ }
@@ -0,0 +1,14 @@
1
+ import type { AntigravityTier } from './antigravity-catalog.ts';
2
+ type HookDecision = {
3
+ decision: 'allow';
4
+ overwrite?: {
5
+ Model: AntigravityTier;
6
+ };
7
+ };
8
+ /** Strictly scoped to the observed flat, single-child invocation. */
9
+ export declare function routeAntigravityHook(value: unknown, { env, signal, }?: {
10
+ env?: NodeJS.ProcessEnv;
11
+ signal?: AbortSignal;
12
+ }): Promise<HookDecision>;
13
+ export declare function runAntigravityHook(signal: AbortSignal): Promise<HookDecision>;
14
+ export {};
@@ -0,0 +1,84 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { realpathSync, statSync, readSync } from 'node:fs';
3
+ import { isAbsolute } from 'node:path';
4
+ import { antigravityRuntime } from './antigravity-runtime.js';
5
+ import { isAntigravityProfile, isAntigravityTier } from './antigravity-catalog.js';
6
+ import { isRecord } from './types.js';
7
+ const preserve = Object.freeze({ decision: 'allow' });
8
+ const eventLimit = 64 * 1024;
9
+ function workspaceIdentity(event, enabledPath) {
10
+ if (!isAbsolute(enabledPath) || !Array.isArray(event.workspacePaths) || event.workspacePaths.length !== 1)
11
+ return;
12
+ const workspace = realpathSync(enabledPath);
13
+ // agy can execute command hooks outside the working directory of the
14
+ // invocation. Check its event's cwd and workspace against the operator opt-in.
15
+ const observed = [event.cwd, event.workspacePaths[0]];
16
+ if (!observed.every(path => typeof path === 'string' && isAbsolute(path) && realpathSync(path) === workspace))
17
+ return;
18
+ const stat = statSync(workspace, { bigint: true });
19
+ if (stat.isDirectory())
20
+ return { workspace, dev: stat.dev, ino: stat.ino };
21
+ }
22
+ /** Strictly scoped to the observed flat, single-child invocation. */
23
+ export async function routeAntigravityHook(value, { env = process.env, signal, } = {}) {
24
+ const enabledPath = env.APTLY_ANTIGRAVITY_AUTO_WORKSPACE;
25
+ if (!enabledPath || (env.ROUTER_PROVIDER !== 'decisions' && env.ROUTER_PROVIDER !== 'fixture') || signal?.aborted)
26
+ return preserve;
27
+ if (!isRecord(value) || value.hookEventName !== 'PreToolUse' ||
28
+ !isRecord(value.toolCall) || value.toolCall.name !== 'invoke_subagent' || !isRecord(value.toolCall.args))
29
+ return preserve;
30
+ const args = value.toolCall.args;
31
+ if (args.TypeName !== 'self' || typeof args.Role !== 'string' || typeof args.Prompt !== 'string' ||
32
+ Object.keys(args).some(key => !['TypeName', 'Role', 'Prompt'].includes(key)))
33
+ return preserve;
34
+ const { conversationId, stepIdx } = value;
35
+ if (typeof conversationId !== 'string' || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(conversationId) ||
36
+ typeof stepIdx !== 'number' || !Number.isSafeInteger(stepIdx) || stepIdx < 0)
37
+ return preserve;
38
+ try {
39
+ const identity = workspaceIdentity(value, enabledPath);
40
+ if (!identity)
41
+ return preserve;
42
+ const { router } = antigravityRuntime(env, 'antigravity-automatic');
43
+ // One opaque ID per host step. A changed task on the same step conflicts
44
+ // in the shared routing contract instead of spending on a fresh request.
45
+ const request_id = createHash('sha256').update(JSON.stringify([
46
+ 'antigravity-automatic-v1', identity.workspace, conversationId, stepIdx,
47
+ ])).digest('hex');
48
+ const result = await router.advise({
49
+ request_id, client: 'antigravity',
50
+ task: { summary: args.Prompt, operation: 'analysis', context_sufficient: Boolean(args.Prompt.trim()) },
51
+ }, signal);
52
+ if (signal?.aborted || result.status !== 'recommended' ||
53
+ !isAntigravityProfile(result.profile, 'antigravity-automatic') || !isAntigravityTier(result.profile.model))
54
+ return preserve;
55
+ const current = workspaceIdentity(value, enabledPath);
56
+ if (!current || current.workspace !== identity.workspace || current.dev !== identity.dev || current.ino !== identity.ino)
57
+ return preserve;
58
+ return { decision: 'allow', overwrite: { Model: result.profile.model } };
59
+ }
60
+ catch {
61
+ return preserve;
62
+ }
63
+ }
64
+ export async function runAntigravityHook(signal) {
65
+ if (!process.env.APTLY_ANTIGRAVITY_AUTO_WORKSPACE)
66
+ return preserve;
67
+ try {
68
+ const buffer = Buffer.alloc(eventLimit + 1);
69
+ let size = 0;
70
+ while (size < buffer.length) {
71
+ const count = readSync(0, buffer, size, buffer.length - size, null);
72
+ if (!count)
73
+ break;
74
+ size += count;
75
+ }
76
+ if (size > eventLimit)
77
+ return preserve;
78
+ const body = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, size));
79
+ return await routeAntigravityHook(JSON.parse(body), { signal });
80
+ }
81
+ catch {
82
+ return preserve;
83
+ }
84
+ }
@@ -0,0 +1,9 @@
1
+ import type { AntigravityScope } from './antigravity-catalog.ts';
2
+ import { Router } from './core.ts';
3
+ export declare function antigravityRuntime(env: NodeJS.ProcessEnv, scope?: AntigravityScope): {
4
+ router: Router;
5
+ mode: string;
6
+ budget: import("./budget.ts").BudgetSettings;
7
+ candidateStatus: string;
8
+ credentialStatus: string;
9
+ };
@@ -0,0 +1,46 @@
1
+ import { isAbsolute, join } from 'node:path';
2
+ import { resolveAntigravityCatalog, resolveAntigravityTierCatalog } from './antigravity-catalog.js';
3
+ import { resolveBudgetSettings } from './budget.js';
4
+ import { Router, defaultPolicy } from './core.js';
5
+ import { assertPrivateStatePath } from './files.js';
6
+ import { decisionsProvider, fixtureProvider } from './provider.js';
7
+ export function antigravityRuntime(env, scope = 'antigravity') {
8
+ const mode = env.ROUTER_PROVIDER ?? 'fixture';
9
+ if (mode !== 'fixture' && mode !== 'decisions')
10
+ throw new Error('antigravity_provider_invalid');
11
+ const automatic = scope === 'antigravity-automatic';
12
+ const catalog = automatic ? resolveAntigravityTierCatalog() : resolveAntigravityCatalog(env.APTLY_ANTIGRAVITY_MODELS);
13
+ const budget = resolveBudgetSettings(env);
14
+ let ledgerPath;
15
+ let key;
16
+ if (mode === 'decisions') {
17
+ if (env.APTLY_SECRET_BACKEND !== undefined)
18
+ throw new Error('antigravity_credential_reference_unsupported');
19
+ const stateDir = env.APTLY_ANTIGRAVITY_STATE_DIR;
20
+ if (!stateDir || !isAbsolute(stateDir))
21
+ throw new Error('antigravity_state_directory_required');
22
+ ledgerPath = join(stateDir, automatic ? 'antigravity-automatic-ledger.json' : 'antigravity-advisory-ledger.json');
23
+ try {
24
+ assertPrivateStatePath(ledgerPath);
25
+ }
26
+ catch {
27
+ throw new Error('antigravity_state_directory_invalid');
28
+ }
29
+ key = env.OPENAI_API_KEY?.trim();
30
+ }
31
+ const router = new Router({
32
+ advisoryScope: scope,
33
+ policy: {
34
+ ...defaultPolicy, ...budget.limits,
35
+ provider_id: mode, catalog_version: catalog.version,
36
+ profiles: catalog.profiles, profile_descriptions: catalog.descriptions,
37
+ },
38
+ budgetConfigurable: true,
39
+ ledgerPath,
40
+ provider: mode === 'fixture' ? fixtureProvider : decisionsProvider({ key, descriptions: catalog.descriptions }),
41
+ });
42
+ return {
43
+ router, mode, budget, candidateStatus: catalog.status,
44
+ credentialStatus: mode === 'fixture' ? 'unused_in_fixture' : key ? 'environment' : 'not_configured',
45
+ };
46
+ }
@@ -298,7 +298,7 @@ export async function automaticHook({ client, event, router, policyPath, signal,
298
298
  const reason = summary.reason ?? 'insufficient_context';
299
299
  if (reason !== 'insufficient_context' || !onNeedsContext)
300
300
  return preserve(reason);
301
- if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
301
+ if (signal?.aborted || (stillCurrent && (await stillCurrent() !== true || signal?.aborted)))
302
302
  return preserve('call_cancelled');
303
303
  const currentPolicy = loadAutomaticHookPolicy(policyPath), currentCall = readCall(client, event), currentContext = context?.();
304
304
  if (!currentPolicy.policy?.enabled || currentPolicy.fingerprint !== loaded.fingerprint)
@@ -320,7 +320,7 @@ export async function automaticHook({ client, event, router, policyPath, signal,
320
320
  const bound = bindCall(call, loaded.policy, loaded.fingerprint, catalogFingerprint(router.policy), supplied?.fingerprint);
321
321
  return bound.request_id ? needsContext('insufficient_context', bound.request_id) : preserve(bound.reason ?? 'automatic_state_unavailable');
322
322
  }
323
- if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
323
+ if (signal?.aborted || (stillCurrent && (await stillCurrent() !== true || signal?.aborted)))
324
324
  return preserve('call_cancelled');
325
325
  // Installing an operator policy must not bypass a historical strict-path
326
326
  // unknown/complete record for this same native call with a new paid ID.
@@ -360,7 +360,7 @@ export async function automaticHook({ client, event, router, policyPath, signal,
360
360
  task: { summary: summary.summary, operation: 'analysis', context_sufficient: true },
361
361
  eligible_profile_ids: classifyProfiles.map(profile => profile.id),
362
362
  constraints: { model_pinned: false, effort_pinned: false, role_pinned: false, fork_inherits: false },
363
- });
363
+ }, signal);
364
364
  if (recommendation.reason === 'budget_exhausted' && ['max_daily_calls', 'max_total_calls', 'max_estimated_usd'].includes(recommendation.budget_limit ?? ''))
365
365
  budgetLimit = recommendation.budget_limit;
366
366
  observation.classification = recommendation.cached ? 'cache_hit' : typeof recommendation.latency_ms === 'number' ? 'provider_requested' : 'local_outcome';
@@ -370,7 +370,7 @@ export async function automaticHook({ client, event, router, policyPath, signal,
370
370
  observation.profile_id = profile.id;
371
371
  observation.application = 'blocked';
372
372
  }
373
- if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
373
+ if (signal?.aborted || (stillCurrent && (await stillCurrent() !== true || signal?.aborted)))
374
374
  return preserve('call_cancelled', request_id);
375
375
  const currentContext = context?.();
376
376
  if (currentContext?.reason || currentContext?.fingerprint !== supplied?.fingerprint)