aptly 0.1.22 → 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.
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
 
@@ -26,6 +26,8 @@ aptly set env OPENAI_API_KEY
26
26
 
27
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
+ For Antigravity CLI, see [workspace setup](docs/guide/en/advanced.md#guide-antigravity-advisory).
30
+
29
31
  ## Update
30
32
 
31
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)
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
 
@@ -26,6 +26,8 @@ aptly set env OPENAI_API_KEY
26
26
 
27
27
  `set default` で送信範囲を選び、API キーは非表示入力で登録します。ホストを再起動した後、**Codex では `/hooks` で新しい Hook を確認・承認**してください。登録状況の確認方法は[インストールと設定の確認](docs/guide/ja/installation.md#guide-verify-setup)を参照してください。
28
28
 
29
+ Antigravity CLI については、[ワークスペースの設定](docs/guide/ja/advanced.md#guide-antigravity-advisory)を参照してください。
30
+
29
31
  ## 更新
30
32
 
31
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)
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
 
@@ -26,6 +26,8 @@ aptly set env OPENAI_API_KEY
26
26
 
27
27
  `set default`에서 전송 범위를 선택하고 API 키는 숨김 입력으로 등록합니다. 호스트를 재시작한 뒤 **Codex는 `/hooks`에서 새 Hook을 검토·승인**하십시오. [설치·설정 확인](docs/guide/ko/installation.md#guide-verify-setup)에서 등록 상태를 점검할 수 있습니다.
28
28
 
29
+ Antigravity CLI는 [워크스페이스 설정 안내](docs/guide/ko/advanced.md#guide-antigravity-advisory)를 참고하십시오.
30
+
29
31
  ## 업데이트
30
32
 
31
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)
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
 
@@ -26,6 +26,8 @@ aptly set env OPENAI_API_KEY
26
26
 
27
27
  请在 `set default` 中选择传输范围,并通过隐藏输入注册 API 密钥。重启宿主后,**请在 Codex 的 `/hooks` 中审核并批准新 Hook**。如需检查注册状态,请参阅[安装与设置验证](docs/guide/zh-CN/installation.md#guide-verify-setup)。
28
28
 
29
+ 如需使用 Antigravity CLI,请参阅[工作区设置](docs/guide/zh-CN/advanced.md#guide-antigravity-advisory)。
30
+
29
31
  ## 更新
30
32
 
31
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)
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';
@@ -297,8 +298,23 @@ try {
297
298
  if (result.status === 'partial' && !automatic)
298
299
  process.exitCode = 1;
299
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
+ }
300
314
  else if (command === 'serve' && args.length === 0)
301
315
  await serve();
316
+ else if (command === 'serve' && args.length === 2 && args[0] === '--client' && args[1] === 'antigravity')
317
+ await serve({ advisoryClient: 'antigravity' });
302
318
  else if ((command === 'capabilities' || command === 'catalog') && args.length === 0) {
303
319
  const { router, mode, modelInfo, credentialStatus, disabledClients } = runtime();
304
320
  output({ ...router.capabilities(), provider: mode, credential_status: credentialStatus, model_information: { status: modelInfo.status, account_access_verified: false }, disabled_clients: disabledClients });
@@ -337,7 +353,7 @@ try {
337
353
  catch (error) {
338
354
  const codes = ['report_invalid_options', 'report_invalid_diagnostic', 'report_invalid_format', 'report_already_exists', 'report_output_unavailable'];
339
355
  const caughtCode = errorCode(error);
340
- 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'];
341
357
  const message = error instanceof Error ? error.message : undefined;
342
358
  const budgetCode = [caughtCode, message].find(value => typeof value === 'string' && ['invalid_budget_configuration', 'budget_invalid_options'].includes(value));
343
359
  const configCode = [caughtCode, message].find(value => typeof value === 'string' && safeConfigurationCodes.includes(value));
@@ -350,7 +366,7 @@ catch (error) {
350
366
  process.exitCode = 1;
351
367
  }
352
368
  finally {
353
- if (!process.exitCode && !helpHandled && !['stats', 'doctor'].includes(command)) {
369
+ if (!process.exitCode && !helpHandled && !['stats', 'doctor', 'antigravity-hook'].includes(command)) {
354
370
  try {
355
371
  const hint = await updateNotification({ command, args, env: process.env, stdinIsTTY: !!process.stdin.isTTY, stderrIsTTY: !!process.stderr.isTTY, stdoutIsTTY: !!process.stdout.isTTY, currentVersion: VERSION });
356
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
+ }
@@ -3,8 +3,9 @@ import { budgetEnvironmentDefaults } from './budget.js';
3
3
  const client = ['codex', 'claude', 'all'];
4
4
  const scope = ['none', 'description', 'excerpt'];
5
5
  const entries = {
6
- '': { usage: 'aptly <command> [options]', description: 'Aptly — subagent profile recommendations\n\nCommands:\n serve Start the stdio MCP server.\n capabilities Print catalog and local limits without an API call.\n catalog [refresh] Inspect the catalog or refresh official model descriptions.\n recommend Read task JSON from stdin and return advice.\n inspect CLIENT FILE Inspect an explicit settings inventory.\n config CLIENT Print an MCP registration fragment.\n set default Fill missing settings; review transmission scope interactively.\n set env ENV_KEY Set a supported environment value.\n set transmission Select, review or show Decisions API transmission scope.\n budget status Inspect local budget limits and usage.\n stats [enable|disable] Inspect or control opt-in local execution statistics.\n setup Register MCP and PreToolUse Hooks.\n remove Remove unchanged Aptly-owned registration.\n update Update a verified global npm installation.\n doctor Inspect local registration and bounded ledger metadata.\n report Write redacted local diagnostic attachments.\n\nGlobal options:\n --help, -h Show help without executing a command.\n --version Print the package version.\n\nUse aptly COMMAND --help or aptly help COMMAND for details.', options: { '--version': true } },
7
- serve: { usage: 'aptly serve', description: 'Start the stdio MCP server (default: fixture/shadow).\nDecisions mode requires ROUTER_PROVIDER=decisions, an absolute private ROUTER_LEDGER_PATH and a configured API key. Use aptly set env OPENAI_API_KEY for OS credential storage. Never put keys in request JSON or command arguments.' },
6
+ '': { usage: 'aptly <command> [options]', description: 'Aptly — subagent profile recommendations\n\nCommands:\n serve Start the stdio MCP server. See serve --help for Antigravity.\n antigravity-hook Apply an eligible Antigravity subagent tier.\n capabilities Print catalog and local limits without an API call.\n catalog [refresh] Inspect the catalog or refresh official model descriptions.\n recommend Read task JSON from stdin and return advice.\n inspect CLIENT FILE Inspect an explicit settings inventory.\n config CLIENT Print an MCP registration fragment.\n set default Fill missing settings; review transmission scope interactively.\n set env ENV_KEY Set a supported environment value.\n set transmission Select, review or show Decisions API transmission scope.\n budget status Inspect local budget limits and usage.\n stats [enable|disable] Inspect or control opt-in local execution statistics.\n setup Register MCP and PreToolUse Hooks.\n remove Remove unchanged Aptly-owned registration.\n update Update a verified global npm installation.\n doctor Inspect local registration and bounded ledger metadata.\n report Write redacted local diagnostic attachments.\n\nGlobal options:\n --help, -h Show help without executing a command.\n --version Print the package version.\n\nUse aptly COMMAND --help or aptly help COMMAND for details.', options: { '--version': true } },
7
+ serve: { usage: 'aptly serve [--client antigravity]', options: { '--client': ['antigravity'] }, description: 'Start the stdio MCP server (default: fixture/shadow).\nFor Codex and Claude Code, Decisions mode requires ROUTER_PROVIDER=decisions, an absolute private ROUTER_LEDGER_PATH and a configured API key. Use aptly set env OPENAI_API_KEY for OS credential storage.\nAntigravity supports direct recommendations through the workspace MCP server. See antigravity-hook --help for automatic tier selection. Set APTLY_ANTIGRAVITY_MODELS to a JSON array of eligible model IDs. Its Decisions mode requires APTLY_ANTIGRAVITY_STATE_DIR (an absolute, private directory) and OPENAI_API_KEY in the process environment. Never put keys in MCP configuration files, request JSON or command arguments.' },
8
+ 'antigravity-hook': { usage: 'aptly antigravity-hook', description: 'Read an Antigravity PreToolUse event from stdin and return a native tier decision. Enable it explicitly with APTLY_ANTIGRAVITY_AUTO_WORKSPACE and a provider. See the guide for workspace, permissions, and Decisions data settings.' },
8
9
  capabilities: { usage: 'aptly capabilities', description: 'Print the active catalog, local limits and configuration metadata. No classification API call. Reads runtime configuration and credential availability; help does neither.' },
9
10
  catalog: { usage: 'aptly catalog\n aptly catalog refresh --output ABS_PATH', description: 'Print the active catalog without classification. Refresh is a separate explicit network operation; use aptly catalog refresh --help.' },
10
11
  'catalog refresh': { usage: 'aptly catalog refresh --output ABS_PATH', description: 'Fetch official model descriptions into a private cache. --output must be an absolute path in a private directory. No model-account availability is certified. Set APTLY_MODEL_INFO_PATH and restart MCP to use the cache.', options: { '--output': 'path' } },
@@ -1,3 +1,4 @@
1
+ import type { AntigravityScope } from './antigravity-catalog.ts';
1
2
  import type { BudgetLimits } from './budget.ts';
2
3
  import type { BudgetLimit, Profile, RoutingPolicy, RoutingProvider, RoutingResult, RoutingStatus } from './types.ts';
3
4
  export declare const defaultPolicy: Readonly<RoutingPolicy>;
@@ -6,8 +7,10 @@ interface LedgerRecord {
6
7
  state: 'complete' | 'unknown';
7
8
  result?: RoutingResult;
8
9
  }
10
+ type AdvisoryScope = AntigravityScope;
9
11
  interface LedgerState {
10
12
  version: 1;
13
+ scope?: AdvisoryScope;
11
14
  calls: number;
12
15
  estimated_usd: number;
13
16
  days: Record<string, number>;
@@ -18,9 +21,10 @@ interface RouterOptions {
18
21
  provider?: RoutingProvider;
19
22
  ledgerPath?: string;
20
23
  budgetConfigurable?: boolean;
24
+ advisoryScope?: AdvisoryScope;
21
25
  }
22
- export declare function validateStoredOutcome(result: unknown): asserts result is RoutingResult;
23
- export declare function validateLedgerState(state: unknown): asserts state is LedgerState;
26
+ export declare function validateStoredOutcome(result: unknown, scope?: AdvisoryScope): asserts result is RoutingResult;
27
+ export declare function validateLedgerState(state: unknown, scope?: AdvisoryScope): asserts state is LedgerState;
24
28
  export declare class Router {
25
29
  policy: RoutingPolicy;
26
30
  provider: RoutingProvider;
@@ -29,7 +33,8 @@ export declare class Router {
29
33
  active: number;
30
34
  private budgetConfigurable;
31
35
  private heldLedgerLock;
32
- constructor({ policy, provider, ledgerPath, budgetConfigurable }?: RouterOptions);
36
+ private readonly advisoryScope;
37
+ constructor({ policy, provider, ledgerPath, budgetConfigurable, advisoryScope }?: RouterOptions);
33
38
  /** Stable legacy-default projection for runtime budget knobs only. Custom library policies retain their full identity. */
34
39
  semanticPolicy(): RoutingPolicy;
35
40
  private budgetSnapshot;
package/dist/src/core.js CHANGED
@@ -3,6 +3,7 @@ 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 { isAntigravityProfile } from './antigravity-catalog.js';
6
7
  import { defaultBudgetLimits } from './budget.js';
7
8
  const defaultCatalog = resolveCatalog({});
8
9
  export const defaultPolicy = Object.freeze({
@@ -20,7 +21,7 @@ const digest = (value) => {
20
21
  throw new Error('invalid_digest');
21
22
  return createHash('sha256').update(serialized).digest('hex');
22
23
  };
23
- const empty = () => ({ version: 1, calls: 0, estimated_usd: 0, days: {}, requests: {} });
24
+ const empty = (scope) => ({ version: 1, ...(scope ? { scope } : {}), calls: 0, estimated_usd: 0, days: {}, requests: {} });
24
25
  const own = (obj, key) => Object.hasOwn(obj, key);
25
26
  const keysOnly = (obj, allowed) => isRecord(obj) && Object.keys(obj).every(k => allowed.includes(k));
26
27
  const safeInt = (n, max = 1e9) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0 && n <= max;
@@ -33,8 +34,6 @@ const usageOf = (usage) => {
33
34
  throw new Error('invalid_usage');
34
35
  return { input_tokens, output_tokens, total_tokens };
35
36
  };
36
- // Runtime eligibility stays within the current finite catalog; archival compatibility below does not expand it.
37
- const supportedProfile = (p) => isSupportedProfile(p);
38
37
  // Storage compatibility only. These retired tuples may be read from an old
39
38
  // ledger, but do not enter the runtime catalog or grant Hook execution rights.
40
39
  const legacyStoredProfiles = [
@@ -44,7 +43,9 @@ const legacyStoredProfiles = [
44
43
  { id: 'claude-routine', client: 'claude', model: 'haiku' },
45
44
  { id: 'claude-deep', client: 'claude', model: 'sonnet' },
46
45
  ];
47
- function isStoredProfile(value) {
46
+ function isStoredProfile(value, scope) {
47
+ if (scope)
48
+ return isAntigravityProfile(value, scope);
48
49
  if (isSupportedProfile(value))
49
50
  return true;
50
51
  if (!isRecord(value) || Object.getOwnPropertySymbols(value).length)
@@ -61,9 +62,9 @@ const outcomeReasons = {
61
62
  needs_context: ['insufficient_context', 'provider_needs_context'],
62
63
  unavailable: ['budget_exhausted'],
63
64
  };
64
- const isClient = (value) => value === 'codex' || value === 'claude';
65
+ const isClient = (value, scope) => scope ? value === 'antigravity' : value === 'codex' || value === 'claude';
65
66
  const preservedFields = ['model_pinned', 'effort_pinned', 'role_pinned', 'fork_inherits'];
66
- export function validateStoredOutcome(result) {
67
+ export function validateStoredOutcome(result, scope) {
67
68
  if (!keysOnly(result, ['status', 'reason', 'application', 'policy_version', 'catalog_version', 'profile_id', 'profile', 'usage', 'latency_ms', 'confidence']) ||
68
69
  typeof result.status !== 'string' || !own(outcomeReasons, result.status) || typeof result.reason !== 'string' || !outcomeReasons[result.status].includes(result.reason) || result.application !== 'advisory_only' ||
69
70
  !safeVersion(result.policy_version) || !safeVersion(result.catalog_version) ||
@@ -75,14 +76,16 @@ export function validateStoredOutcome(result) {
75
76
  if (result.status === 'recommended') {
76
77
  // Validate archival shape/known provenance without requiring membership
77
78
  // in today's selected subset. Eligibility is checked again before reuse.
78
- if (!isStoredProfile(result.profile) || result.profile_id !== result.profile.id)
79
+ if (!isStoredProfile(result.profile, scope) || result.profile_id !== result.profile.id)
79
80
  throw new Error('invalid_outcome');
80
81
  }
81
82
  else if (own(result, 'profile') || own(result, 'profile_id'))
82
83
  throw new Error('invalid_outcome');
83
84
  }
84
- export function validateLedgerState(state) {
85
- 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 ||
85
+ export function validateLedgerState(state, scope) {
86
+ if (!keysOnly(state, ['version', 'scope', 'calls', 'estimated_usd', 'days', 'requests']) ||
87
+ (scope === undefined ? own(state, 'scope') : state.scope !== scope) ||
88
+ state.version !== 1 || !safeInt(state.calls) || typeof state.estimated_usd !== 'number' || !Number.isFinite(state.estimated_usd) || state.estimated_usd < 0 ||
86
89
  !isRecord(state.days) || !isRecord(state.requests))
87
90
  throw new Error('invalid_ledger');
88
91
  const days = state.days;
@@ -95,7 +98,7 @@ export function validateLedgerState(state) {
95
98
  if (!/^[A-Za-z0-9_-]{1,96}$/.test(id) || ['__proto__', 'constructor', 'prototype'].includes(id) || !keysOnly(record, ['digest', 'state', 'result']) || typeof record.digest !== 'string' || !/^[a-f0-9]{64}$/.test(record.digest) || (record.state !== 'complete' && record.state !== 'unknown'))
96
99
  throw new Error('invalid_ledger');
97
100
  if (record.state === 'complete')
98
- validateStoredOutcome(record.result);
101
+ validateStoredOutcome(record.result, scope);
99
102
  else if (own(record, 'result'))
100
103
  throw new Error('invalid_ledger');
101
104
  }
@@ -108,7 +111,9 @@ export class Router {
108
111
  active;
109
112
  budgetConfigurable;
110
113
  heldLedgerLock;
111
- constructor({ policy = defaultPolicy, provider, ledgerPath, budgetConfigurable = policy === defaultPolicy } = {}) {
114
+ advisoryScope;
115
+ constructor({ policy = defaultPolicy, provider, ledgerPath, budgetConfigurable = policy === defaultPolicy, advisoryScope } = {}) {
116
+ this.advisoryScope = advisoryScope;
112
117
  this.budgetConfigurable = budgetConfigurable;
113
118
  this.policy = clone(policy);
114
119
  const integerCaps = { max_summary_bytes: 64000, max_concurrency: 16, max_daily_calls: 100000, max_total_calls: 1000000, timeout_ms: 60000 };
@@ -126,14 +131,15 @@ export class Router {
126
131
  if (!Array.isArray(policy.profiles) || policy.profiles.length > 20 || policy.profiles.some(p => !p || typeof p !== 'object') || new Set(policy.profiles.map(p => p.id)).size !== policy.profiles.length)
127
132
  throw new Error('invalid_policy');
128
133
  for (const p of policy.profiles) {
129
- if (!keysOnly(p, ['id', 'client', 'model', 'reasoning_effort']) || typeof p.id !== 'string' || !/^[a-z0-9-]{1,64}$/.test(p.id) || !supportedProfile(p) || (p.client === 'claude' && own(p, 'reasoning_effort')))
134
+ if (!keysOnly(p, ['id', 'client', 'model', 'reasoning_effort']) || typeof p.id !== 'string' || !/^[a-z0-9-]{1,64}$/.test(p.id) ||
135
+ !(advisoryScope ? isAntigravityProfile(p, advisoryScope) : isSupportedProfile(p)) || (p.client === 'claude' && own(p, 'reasoning_effort')))
130
136
  throw new Error('invalid_policy');
131
137
  }
132
138
  if (policy.profile_descriptions !== undefined && (!isRecord(policy.profile_descriptions) || Object.entries(policy.profile_descriptions).some(([id, value]) => !/^[a-z0-9-]{1,64}$/.test(id) || typeof value !== 'string' || !value.trim() || Buffer.byteLength(value) > 2400)))
133
139
  throw new Error('invalid_policy');
134
140
  this.provider = provider;
135
141
  this.ledgerPath = ledgerPath;
136
- this.state = empty();
142
+ this.state = empty(advisoryScope);
137
143
  this.active = 0;
138
144
  }
139
145
  /** Stable legacy-default projection for runtime budget knobs only. Custom library policies retain their full identity. */
@@ -168,7 +174,7 @@ export class Router {
168
174
  }
169
175
  catch (error) {
170
176
  if (errorCode(error) === 'ENOENT') {
171
- this.state = empty();
177
+ this.state = empty(this.advisoryScope);
172
178
  return this.budgetSnapshot();
173
179
  }
174
180
  throw error;
@@ -193,7 +199,7 @@ export class Router {
193
199
  result(status, reason, extra = {}) {
194
200
  return { status, reason, application: 'advisory_only', policy_version: this.policy.version, catalog_version: this.policy.catalog_version, ...extra };
195
201
  }
196
- validateOutcome(result) { validateStoredOutcome(result); }
202
+ validateOutcome(result) { validateStoredOutcome(result, this.advisoryScope); }
197
203
  load({ readOnly = false } = {}) {
198
204
  if (!this.ledgerPath)
199
205
  return;
@@ -202,10 +208,10 @@ export class Router {
202
208
  const stat = lstatSync(this.ledgerPath);
203
209
  if (!stat.isFile() || stat.isSymbolicLink() || (readOnly && process.platform !== 'win32' && ((stat.mode & 0o077) !== 0 || (process.getuid && stat.uid !== process.getuid()))))
204
210
  throw new Error('unsafe_ledger');
211
+ const state = JSON.parse(readFileSync(this.ledgerPath, 'utf8'));
212
+ validateLedgerState(state, this.advisoryScope);
205
213
  if (!readOnly)
206
214
  chmodSync(this.ledgerPath, 0o600);
207
- const state = JSON.parse(readFileSync(this.ledgerPath, 'utf8'));
208
- validateLedgerState(state);
209
215
  // All records, counters and outcomes were validated above; no parsed
210
216
  // JSON shape is trusted at the file boundary before those checks.
211
217
  this.state = state;
@@ -243,13 +249,15 @@ export class Router {
243
249
  }
244
250
  /** Strict native-routing path: preserves existing host-evidence and digest semantics. */
245
251
  async recommend(input, signal) {
252
+ if (this.advisoryScope)
253
+ return this.result('unavailable', 'invalid_input');
246
254
  return this.route(input, 'hook', signal);
247
255
  }
248
256
  /** Independent task advice. Omitted constraints mean no caller-declared pins,
249
257
  * not verified host settings. A legacy provenance flag grants no authority. */
250
258
  async advise(input, signal) {
251
259
  const invalid = () => this.result('unavailable', 'invalid_input');
252
- if (!keysOnly(input, ['request_id', 'client', 'task', 'eligible_profile_ids', 'constraints']) || !isClient(input.client))
260
+ if (!keysOnly(input, ['request_id', 'client', 'task', 'eligible_profile_ids', 'constraints']) || !isClient(input.client, this.advisoryScope))
253
261
  return invalid();
254
262
  const constraints = own(input, 'constraints') ? input.constraints : {};
255
263
  if (!keysOnly(constraints, [...preservedFields, 'provenance_verified']) || Object.values(constraints).some(value => typeof value !== 'boolean'))
@@ -266,7 +274,7 @@ export class Router {
266
274
  return cancelled();
267
275
  const invalid = () => this.result('unavailable', 'invalid_input');
268
276
  if (!keysOnly(input, ['request_id', 'client', 'task', 'eligible_profile_ids', 'constraints']) ||
269
- typeof input.request_id !== 'string' || !/^[A-Za-z0-9_-]{1,96}$/.test(input.request_id) || !isClient(input.client) ||
277
+ typeof input.request_id !== 'string' || !/^[A-Za-z0-9_-]{1,96}$/.test(input.request_id) || !isClient(input.client, this.advisoryScope) ||
270
278
  ['__proto__', 'constructor', 'prototype'].includes(input.request_id) ||
271
279
  !keysOnly(input.task, ['summary', 'operation', 'context_sufficient']) || typeof input.task.summary !== 'string' ||
272
280
  !input.task.summary.trim() || Buffer.byteLength(input.task.summary) > this.policy.max_summary_bytes ||
@@ -276,9 +284,15 @@ export class Router {
276
284
  !keysOnly(input.constraints, ['model_pinned', 'effort_pinned', 'role_pinned', 'fork_inherits', 'provenance_verified']) ||
277
285
  Object.values(input.constraints).some(v => typeof v !== 'boolean'))
278
286
  return invalid();
279
- if (/\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(input.task.summary))
287
+ // Request IDs become ledger keys and provider headers. Recognize key
288
+ // prefixes at the start or after a separator without blocking task-* IDs.
289
+ if (/(?:^|[-_])sk-[A-Za-z0-9_-]{12,}/i.test(input.request_id) ||
290
+ /\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(input.task.summary)) {
280
291
  return this.result('keep_current', 'sensitive_input');
292
+ }
281
293
  const req = clone(input);
294
+ if (this.advisoryScope && !this.policy.profiles.length)
295
+ return this.result('keep_current', 'no_candidates');
282
296
  const profiles = this.policy.profiles.filter(p => p.client === req.client && req.eligible_profile_ids.includes(p.id));
283
297
  if (!profiles.length && !req.eligible_profile_ids.length)
284
298
  return this.result('keep_current', 'no_candidates');
@@ -1,7 +1,8 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- export declare function createServer({ env: inputEnv }?: {
2
+ interface ServerOptions {
3
3
  env?: NodeJS.ProcessEnv;
4
- }): McpServer;
5
- export declare function serve(options?: {
6
- env?: NodeJS.ProcessEnv;
7
- }): Promise<McpServer>;
4
+ advisoryClient?: 'antigravity';
5
+ }
6
+ export declare function createServer({ env: inputEnv, advisoryClient }?: ServerOptions): McpServer;
7
+ export declare function serve(options?: ServerOptions): Promise<McpServer>;
8
+ export {};
@@ -3,6 +3,7 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
3
3
  import { z } from 'zod';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { runtime } from './runtime.js';
6
+ import { antigravityRuntime } from './antigravity-runtime.js';
6
7
  import { VERSION } from './version.js';
7
8
  import { hookInput, hookOutput } from './hook.js';
8
9
  import { resolveProvenance } from './provenance.js';
@@ -22,7 +23,30 @@ const observationSchema = z.object({ client: hookSchema.client.optional(), event
22
23
  ctx.addIssue({ code: 'custom', message: 'Supply only {client,event} or only {retry_id}.' });
23
24
  });
24
25
  const content = (result) => ({ content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
25
- export function createServer({ env: inputEnv = process.env } = {}) {
26
+ function createAntigravityServer(env) {
27
+ const { router, mode, budget, candidateStatus, credentialStatus } = antigravityRuntime(env);
28
+ const server = new McpServer({ name: 'aptly', version: VERSION });
29
+ const annotations = { readOnlyHint: mode === 'fixture', destructiveHint: false, idempotentHint: true, openWorldHint: mode === 'decisions' };
30
+ server.registerTool('get_routing_capabilities', {
31
+ description: 'Antigravity advisory profiles and budget limits. No provider call.', annotations: { ...annotations, readOnlyHint: true, openWorldHint: false }, inputSchema: {},
32
+ }, async () => content({
33
+ ...router.capabilities(), provider: mode, client: 'antigravity', candidate_status: candidateStatus, credential_status: credentialStatus,
34
+ model_information: { selection: 'agy_cli_model_argument', account_access_verified: false, native_subagent_application: false },
35
+ budget_configuration: { ...budget, zero_ceiling_means_unlimited: true, settings_require_mcp_restart: true, cost_guard: 'local_estimate_not_billing_cap' },
36
+ runtime_diagnostics: { version: VERSION },
37
+ }));
38
+ server.registerTool('recommend_agent', {
39
+ description: 'Recommend an allowlisted model ID for manual agy --model selection using a bounded task description. Advisory only. ' +
40
+ (mode === 'decisions'
41
+ ? 'Sends request_id as X-Client-Request-Id and sends client, task.summary, task.operation, task.context_sufficient, and candidate profile IDs and descriptions in the body to the OpenAI Decisions API. Use an opaque ID free of sensitive information. Calls may incur a charge.'
42
+ : 'Uses local fixture rules.'),
43
+ annotations, inputSchema: { request_id: z.string().min(1).max(96), client: z.literal('antigravity'), task: taskSchema, eligible_profile_ids: z.array(z.string()).min(1).max(20).optional(), constraints: constraintsSchema.optional() },
44
+ }, async (input, extra) => content({ ...await router.advise(input, extra.signal), provider: mode }));
45
+ return server;
46
+ }
47
+ export function createServer({ env: inputEnv = process.env, advisoryClient } = {}) {
48
+ if (advisoryClient === 'antigravity')
49
+ return createAntigravityServer(inputEnv);
26
50
  const codexBound = inputEnv.APTLY_HOOK_POLICY_PATH === CODEX_HOME_POLICY_SOURCE;
27
51
  const policySourceKind = codexBound ? 'codex_home' : inputEnv.APTLY_HOOK_POLICY_PATH === undefined ? 'unconfigured' : 'fixed';
28
52
  const env = { ...inputEnv, APTLY_HOOK_POLICY_PATH: resolvePolicySource(inputEnv.APTLY_HOOK_POLICY_PATH, inputEnv) };
@@ -1,11 +1,12 @@
1
1
  export type Client = 'codex' | 'claude';
2
+ export type RecommendationClient = Client | 'antigravity';
2
3
  export type UnknownRecord = Record<string, unknown>;
3
4
  export type JsonValue = null | boolean | number | string | JsonValue[] | {
4
5
  [key: string]: JsonValue;
5
6
  };
6
7
  export interface Profile {
7
8
  id: string;
8
- client: Client;
9
+ client: RecommendationClient;
9
10
  model: string;
10
11
  reasoning_effort?: string;
11
12
  }
@@ -23,7 +24,7 @@ export interface RoutingTask {
23
24
  }
24
25
  export interface RoutingInput {
25
26
  request_id: string;
26
- client: Client;
27
+ client: RecommendationClient;
27
28
  task: RoutingTask;
28
29
  eligible_profile_ids: string[];
29
30
  constraints: RoutingConstraints;
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.22";
1
+ export declare const VERSION = "0.2.0";
@@ -1 +1 @@
1
- export const VERSION = '0.1.22';
1
+ export const VERSION = '0.2.0';
@@ -11,6 +11,7 @@
11
11
  - [Codex example](#guide-codex-configuration)
12
12
  - [Claude Code example](#guide-claude-configuration)
13
13
  - [Direct recommendations](#guide-direct-recommendations)
14
+ - [Antigravity CLI model recommendations](#guide-antigravity-advisory)
14
15
  - [Explicit description for opaque spawns (0.1.4+)](#guide-explicit-spawn-context)
15
16
  - [Retry with additional context (0.1.5+)](#guide-context-retry)
16
17
  - [Prepare a separate independent delegation (0.1.6+)](#guide-fresh-delegation)
@@ -123,6 +124,86 @@ If any of `model_pinned`, `effort_pinned`, `role_pinned`, or `fork_inherits` in
123
124
 
124
125
  The direct recommendation's `application: advisory_only` does not verify host settings or model access, or authorize execution. To retrieve a completed result again, keep the same ID, input, policy, and ledger. `unknown` means the outcome is uncertain; do not blindly retry with a new ID. A new request whose input has changed because context was added uses a different ID.
125
126
 
127
+ <a id="guide-antigravity-advisory"></a>
128
+
129
+ ## Antigravity CLI model recommendations
130
+
131
+ Add the entry below to `.agents/mcp_config.json` in a trusted workspace. Replace `command` with the absolute path to your installed `aptly` executable and retain only the candidates listed by `agy models`.
132
+
133
+ ```json
134
+ {
135
+ "mcpServers": {
136
+ "aptly-antigravity": {
137
+ "command": "/absolute/path/to/aptly",
138
+ "args": [
139
+ "serve",
140
+ "--client",
141
+ "antigravity"
142
+ ],
143
+ "env": {
144
+ "ROUTER_PROVIDER": "fixture",
145
+ "APTLY_ANTIGRAVITY_MODELS": "[\"gemini-4-hydrogen-medium\",\"gemini-4-carbon-medium\",\"gemini-4-neon-medium\"]"
146
+ }
147
+ }
148
+ }
149
+ }
150
+ ```
151
+
152
+ The suggested catalog uses Hydrogen Medium for simple work, Carbon Medium for routine work, and Neon Medium for deep work. Add `gemini-4-neon-high` to make it eligible for deep tasks that need more detailed reasoning. An omitted list or `[]` returns `no_candidates`. Aptly does not independently verify model access for your account.
153
+
154
+ Check the server in `/mcp` and call `recommend_agent` with the arguments below. Approve that tool when prompted. If you preapprove it for headless use, use the exact permission `mcp(aptly-antigravity/recommend_agent)`.
155
+
156
+ ```json
157
+ {
158
+ "request_id": "agy-sort-001",
159
+ "client": "antigravity",
160
+ "task": {
161
+ "summary": "Sort the supplied numbers [3, 1, 2] in ascending order.",
162
+ "operation": "analysis",
163
+ "context_sufficient": true
164
+ }
165
+ }
166
+ ```
167
+
168
+ The example uses local fixture rules. Pass the returned `profile.model` to `agy --model` when starting a new Antigravity CLI session. To use a native subagent, select its settings yourself. Aptly leaves the current session and native subagent settings untouched.
169
+
170
+ To use the Decisions API, set `ROUTER_PROVIDER` to `decisions` and set `APTLY_ANTIGRAVITY_STATE_DIR` to the absolute path to an existing private directory (mode `700` on POSIX). Aptly keeps this budget and request history separate from existing Codex and Claude Code state. Supply `OPENAI_API_KEY` to the MCP process through a trusted launch environment and keep it out of configuration files and command arguments.
171
+
172
+ A `recommend_agent` call may incur a charge when it sends a request to OpenAI Decisions. Aptly sends `request_id` to the OpenAI Decisions API in the `X-Client-Request-Id` header. The body contains `client`, `task.summary`, `task.operation`, `task.context_sufficient`, and candidate profile IDs and descriptions. Use a random ID free of sensitive information and reuse it only with the same request input. Installing or configuring the server does not trigger classification. See [what Aptly sends](transmission.md#guide-transmission-limits).
173
+
174
+ [Antigravity MCP](https://antigravity.google/docs/mcp?tab=cli) · [Permissions](https://antigravity.google/docs/cli-permissions)
175
+
176
+ <a id="guide-antigravity-hook"></a>
177
+
178
+ ### Automatic tier selection for Antigravity CLI
179
+
180
+ Enable automatic selection per workspace. Add the Hook below to `.agents/hooks.json` in a trusted workspace. If Antigravity CLI cannot find `aptly` on `PATH`, use the executable's absolute path.
181
+
182
+ ```json
183
+ {
184
+ "aptly-antigravity": {
185
+ "PreToolUse": [
186
+ {
187
+ "matcher": "^invoke_subagent$",
188
+ "hooks": [
189
+ {
190
+ "type": "command",
191
+ "command": "aptly antigravity-hook",
192
+ "timeout": 20
193
+ }
194
+ ]
195
+ }
196
+ ]
197
+ }
198
+ }
199
+ ```
200
+
201
+ When starting Antigravity CLI from the workspace root, set `APTLY_ANTIGRAVITY_AUTO_WORKSPACE` to that absolute directory. For Decisions, also set `ROUTER_PROVIDER=decisions`, a private `APTLY_ANTIGRAVITY_STATE_DIR`, and `OPENAI_API_KEY` in the same launch environment. Supply the key through the launch environment and keep it out of the Hook configuration and arguments. Use `ROUTER_PROVIDER=fixture` to check the Hook locally. Restart Antigravity CLI and check the registration in `/hooks`. The working directory and single workspace reported by the Hook event must match the configured root.
202
+
203
+ The Hook supports a single, flat invocation of the built-in `self` agent with model and effort unset. The Hook sets `Model` to one of `flash_lite`, `flash`, or `pro`. Antigravity resolves the model for that tier. The Hook preserves explicit choices and leaves the host to check permissions and proceed with the original arguments if it cannot verify the input or obtain a recommendation.
204
+
205
+ In Decisions mode, the Hook uses the child's `Prompt` as the task description when it meets the length limit. The request includes the client, operation, context sufficiency flag, tier candidates and descriptions, and a hashed request ID. Automatic and direct recommendations have separate request history and budgets. Enable the Hook only for approved workspaces and check whether child prompts may contain sensitive information. To turn off automatic selection, unset `APTLY_ANTIGRAVITY_AUTO_WORKSPACE` and restart Antigravity CLI.
206
+
126
207
  <a id="guide-explicit-spawn-context"></a>
127
208
 
128
209
  ## Explicit description for opaque spawns (0.1.4+)
@@ -11,6 +11,7 @@
11
11
  - [Codex の例](#guide-codex-configuration)
12
12
  - [Claude Code の例](#guide-claude-configuration)
13
13
  - [直接推薦](#guide-direct-recommendations)
14
+ - [Antigravity CLI のモデル推薦](#guide-antigravity-advisory)
14
15
  - [不透明な呼び出しへの明示的な説明(0.1.4 以降)](#guide-explicit-spawn-context)
15
16
  - [文脈を補って再推薦する(0.1.5 以降)](#guide-context-retry)
16
17
  - [別の独立した委任を準備する(0.1.6 以降)](#guide-fresh-delegation)
@@ -123,6 +124,86 @@ fixture は、キー・ネットワーク・子エージェントの実行なし
123
124
 
124
125
  直接推薦の `application: advisory_only` は、ホスト設定の確認・モデルへのアクセス権限・実行承認を意味しません。完了済みの結果を再照会する際は、同じ ID・入力・ポリシー・台帳を使用してください。`unknown` は結果が不明確であることを意味するため、新しい ID で無条件に再試行しないでください。コンテキストの補完で入力が変わった新規リクエストには、別の ID を使用してください。
125
126
 
127
+ <a id="guide-antigravity-advisory"></a>
128
+
129
+ ## Antigravity CLI のモデル推薦
130
+
131
+ 信頼できるワークスペースの `.agents/mcp_config.json` に、以下のサーバーを追加してください。`command` をインストール済みの `aptly` 実行ファイルの絶対パスに置き換え、`agy models` に表示される候補だけを残してください。
132
+
133
+ ```json
134
+ {
135
+ "mcpServers": {
136
+ "aptly-antigravity": {
137
+ "command": "/absolute/path/to/aptly",
138
+ "args": [
139
+ "serve",
140
+ "--client",
141
+ "antigravity"
142
+ ],
143
+ "env": {
144
+ "ROUTER_PROVIDER": "fixture",
145
+ "APTLY_ANTIGRAVITY_MODELS": "[\"gemini-4-hydrogen-medium\",\"gemini-4-carbon-medium\",\"gemini-4-neon-medium\"]"
146
+ }
147
+ }
148
+ }
149
+ }
150
+ ```
151
+
152
+ 単純な作業には Hydrogen Medium、通常の作業には Carbon Medium、複雑な作業には Neon Medium が候補です。詳細な推論が必要な複雑な作業に Neon High を使えるようにするには、`gemini-4-neon-high` をリストに追加してください。リストを省略するか `[]` を指定すると、推薦の結果は `no_candidates` になります。Aptly はアカウントでモデルを利用できるかどうかを個別に確認しません。
153
+
154
+ `/mcp` でサーバーを確認し、以下の引数で `recommend_agent` を呼び出してください。対話モードで確認が表示されたら、そのツールを承認してください。ヘッドレスモードで事前に許可する場合は、`mcp(aptly-antigravity/recommend_agent)` を指定してください。
155
+
156
+ ```json
157
+ {
158
+ "request_id": "agy-sort-001",
159
+ "client": "antigravity",
160
+ "task": {
161
+ "summary": "Sort the supplied numbers [3, 1, 2] in ascending order.",
162
+ "operation": "analysis",
163
+ "context_sufficient": true
164
+ }
165
+ }
166
+ ```
167
+
168
+ この例ではローカルのテスト用ルールを使います。新しい Antigravity CLI セッションを起動するときに、返された `profile.model` を `agy --model` に渡せます。ネイティブのサブエージェントを使う場合は、設定を自分で選んでください。Aptly は現在のセッションやネイティブのサブエージェントの設定を変更しません。
169
+
170
+ Decisions API を使うには、`ROUTER_PROVIDER` を `decisions` に変更し、`APTLY_ANTIGRAVITY_STATE_DIR` に既存の非公開ディレクトリの絶対パスを指定してください(POSIX の権限は `700`)。予算とリクエストの記録は、既存の Codex と Claude Code の状態とは別に保存されます。信頼できる起動環境から MCP プロセスに `OPENAI_API_KEY` を渡し、設定ファイルやコマンド引数にキーを書かないでください。
171
+
172
+ Aptly が推薦のために OpenAI Decisions API を呼び出すと、料金が発生することがあります。Aptly は `request_id` を `X-Client-Request-Id` ヘッダーに入れて OpenAI Decisions API に送信します。本文には `client`、`task.summary`、`task.operation`、`task.context_sufficient`、候補プロファイルの ID と説明が含まれます。機密情報を含まないランダムな ID を使い、同じ入力のリクエストにだけ再利用してください。サーバーをインストールまたは設定するだけでは、分類リクエストは送信されません。[送信する情報](transmission.md#guide-transmission-limits)を参照してください。
173
+
174
+ [Antigravity MCP](https://antigravity.google/docs/mcp?tab=cli) · [Permissions](https://antigravity.google/docs/cli-permissions)
175
+
176
+ <a id="guide-antigravity-hook"></a>
177
+
178
+ ### Antigravity CLI のティア自動適用
179
+
180
+ 自動適用はワークスペースごとに有効にします。信頼できるワークスペースの `.agents/hooks.json` に以下の Hook を追加してください。Antigravity CLI が `PATH` から `aptly` を見つけられない場合は、実行ファイルの絶対パスを指定してください。
181
+
182
+ ```json
183
+ {
184
+ "aptly-antigravity": {
185
+ "PreToolUse": [
186
+ {
187
+ "matcher": "^invoke_subagent$",
188
+ "hooks": [
189
+ {
190
+ "type": "command",
191
+ "command": "aptly antigravity-hook",
192
+ "timeout": 20
193
+ }
194
+ ]
195
+ }
196
+ ]
197
+ }
198
+ }
199
+ ```
200
+
201
+ ワークスペースのルートで Antigravity CLI を起動するときに、`APTLY_ANTIGRAVITY_AUTO_WORKSPACE` にその絶対パスを設定してください。Decisions を使う場合は、同じ起動環境に `ROUTER_PROVIDER=decisions`、非公開の `APTLY_ANTIGRAVITY_STATE_DIR`、`OPENAI_API_KEY` も設定してください。キーは起動環境から渡し、Hook の設定やコマンド引数には含めないでください。ローカルで Hook を確認するには `ROUTER_PROVIDER=fixture` を使えます。Antigravity CLI を再起動し、`/hooks` で登録を確認してください。Hook イベントの作業ディレクトリと単一のワークスペースは、設定したルートと一致する必要があります。
202
+
203
+ 対象は、モデルと推論強度が未指定の、組み込み `self` エージェントをネストされていない引数で単独呼び出しする場合です。Hook は `Model` に `flash_lite`、`flash`、`pro` のいずれかを設定します。実行するモデルは Antigravity が決めます。明示した指定を保持し、入力を確認できない場合や推薦を取得できない場合はホストが元の引数で権限を確認して続行します。
204
+
205
+ Decisions モードでは、長さの上限を満たす子の `Prompt` を作業の説明として使います。リクエストにはクライアント、作業の種類、文脈が十分かどうか、候補ティアと説明、ハッシュ化したリクエスト ID が含まれます。自動推薦と直接推薦のリクエスト履歴と予算は別々に管理されます。承認済みのワークスペースで有効にし、子のプロンプトに機密情報が含まれるか確認してください。自動適用を無効にするには、`APTLY_ANTIGRAVITY_AUTO_WORKSPACE` を解除し、Antigravity CLI を再起動してください。
206
+
126
207
  <a id="guide-explicit-spawn-context"></a>
127
208
 
128
209
  ## 不透明な呼び出しへの明示的な説明(0.1.4 以降)
@@ -11,6 +11,7 @@
11
11
  - [Codex 예제](#guide-codex-configuration)
12
12
  - [Claude Code 예제](#guide-claude-configuration)
13
13
  - [직접 추천](#guide-direct-recommendations)
14
+ - [Antigravity CLI 모델 추천](#guide-antigravity-advisory)
14
15
  - [불투명 호출에 명시적 설명 전달 (0.1.4부터)](#guide-explicit-spawn-context)
15
16
  - [맥락 보충 후 재추천 (0.1.5부터)](#guide-context-retry)
16
17
  - [상속 추천에서 별도 독립 위임 준비 (0.1.6부터)](#guide-fresh-delegation)
@@ -123,6 +124,86 @@ fixture는 키·네트워크·자식 실행 없이 로컬 규칙으로 생성한
123
124
 
124
125
  직접 추천의 `application: advisory_only`는 호스트 설정 확인·모델 접근 권한·실행 승인이 아닙니다. 완료 결과를 재조회할 때는 같은 ID·입력·정책·원장을 유지하십시오. `unknown`은 결과가 불명확하다는 뜻이므로 새 ID로 무조건 재시도하지 마십시오. 맥락을 보완해 입력이 달라진 새 요청에는 다른 ID를 사용하십시오.
125
126
 
127
+ <a id="guide-antigravity-advisory"></a>
128
+
129
+ ## Antigravity CLI 모델 추천
130
+
131
+ Antigravity CLI용 추천을 사용하려면 신뢰하는 워크스페이스의 `.agents/mcp_config.json`에 아래 서버를 추가하십시오. `command`는 설치된 `aptly` 실행 파일의 절대 경로로 바꾸고, `agy models`에 표시되는 후보만 남기십시오.
132
+
133
+ ```json
134
+ {
135
+ "mcpServers": {
136
+ "aptly-antigravity": {
137
+ "command": "/absolute/path/to/aptly",
138
+ "args": [
139
+ "serve",
140
+ "--client",
141
+ "antigravity"
142
+ ],
143
+ "env": {
144
+ "ROUTER_PROVIDER": "fixture",
145
+ "APTLY_ANTIGRAVITY_MODELS": "[\"gemini-4-hydrogen-medium\",\"gemini-4-carbon-medium\",\"gemini-4-neon-medium\"]"
146
+ }
147
+ }
148
+ }
149
+ }
150
+ ```
151
+
152
+ 기본 후보 목록은 단순 작업에 Hydrogen Medium, 일반 작업에 Carbon Medium, 심층 작업에 Neon Medium입니다. 세밀한 추론이 필요한 심층 작업에 Neon High를 후보로 허용하려면 `gemini-4-neon-high`를 목록에 추가하십시오. 후보를 설정하지 않거나 `[]`로 설정하면 추천을 요청해도 `no_candidates`를 반환합니다. Aptly는 계정에서 모델을 실행할 수 있는지 확인하지 않습니다.
153
+
154
+ `/mcp`에서 서버를 확인하고 `recommend_agent`에 아래 인자를 전달하십시오. 대화형 실행에서는 해당 도구를 승인하고, 비대화형 실행에서 미리 허용할 때는 `mcp(aptly-antigravity/recommend_agent)`를 지정하십시오.
155
+
156
+ ```json
157
+ {
158
+ "request_id": "agy-sort-001",
159
+ "client": "antigravity",
160
+ "task": {
161
+ "summary": "Sort the supplied numbers [3, 1, 2] in ascending order.",
162
+ "operation": "analysis",
163
+ "context_sufficient": true
164
+ }
165
+ }
166
+ ```
167
+
168
+ 예제는 로컬 테스트 규칙을 사용합니다. `profile.model`은 새 Antigravity CLI 세션에서 `agy --model`에 전달할 값입니다. Aptly는 현재 세션이나 네이티브 서브에이전트 설정을 변경하지 않습니다. 네이티브 서브에이전트를 쓸 때는 작업에 맞는 설정을 직접 선택하십시오.
169
+
170
+ Decisions API를 사용하려면 `ROUTER_PROVIDER`를 `decisions`로 바꾸고 `APTLY_ANTIGRAVITY_STATE_DIR`에 본인만 접근할 수 있는 기존 디렉터리의 절대 경로를 지정하십시오(POSIX 권한 `700`). 기존 Codex·Claude Code의 상태 파일과 별도로 예산 및 요청을 기록합니다. 신뢰하는 실행 환경에서 MCP 프로세스에 `OPENAI_API_KEY`를 주입하고 설정 파일이나 명령 인자에 키를 쓰지 마십시오.
171
+
172
+ Aptly가 추천을 위해 OpenAI Decisions API를 호출하면 비용이 발생할 수 있습니다. Aptly는 OpenAI Decisions API에 `request_id`를 `X-Client-Request-Id` 헤더로 보냅니다. 본문에는 `client`, `task.summary`, `task.operation`, `task.context_sufficient`와 후보 프로필의 ID 및 설명이 들어갑니다. 민감한 정보가 담기지 않은 무작위 ID를 사용하고, 입력이 같은 요청에만 ID를 재사용하십시오. 서버를 설치하거나 설정하는 것만으로는 분류 요청을 보내지 않습니다. [전송 항목](transmission.md#guide-transmission-limits)을 참고하십시오.
173
+
174
+ [Antigravity MCP](https://antigravity.google/docs/mcp?tab=cli) · [Permissions](https://antigravity.google/docs/cli-permissions)
175
+
176
+ <a id="guide-antigravity-hook"></a>
177
+
178
+ ### Antigravity CLI 자동 티어 적용
179
+
180
+ 자동 적용은 워크스페이스별로 켭니다. 신뢰하는 워크스페이스의 `.agents/hooks.json`에 아래 Hook을 추가하십시오. `aptly`가 Antigravity CLI의 `PATH`에 없으면 실행 파일의 절대 경로를 사용하십시오.
181
+
182
+ ```json
183
+ {
184
+ "aptly-antigravity": {
185
+ "PreToolUse": [
186
+ {
187
+ "matcher": "^invoke_subagent$",
188
+ "hooks": [
189
+ {
190
+ "type": "command",
191
+ "command": "aptly antigravity-hook",
192
+ "timeout": 20
193
+ }
194
+ ]
195
+ }
196
+ ]
197
+ }
198
+ }
199
+ ```
200
+
201
+ 워크스페이스 루트에서 Antigravity CLI를 시작할 때 `APTLY_ANTIGRAVITY_AUTO_WORKSPACE`에 해당 루트의 절대 경로를 지정하십시오. Decisions를 쓰려면 같은 실행 환경에서 `ROUTER_PROVIDER=decisions`, 비공개 `APTLY_ANTIGRAVITY_STATE_DIR`, `OPENAI_API_KEY`도 설정하십시오. 키는 실행 환경에서 전달하고 Hook 설정 파일과 명령 인자에서 제외하십시오. `ROUTER_PROVIDER=fixture`는 로컬에서 Hook을 점검할 때 사용할 수 있습니다. Antigravity CLI를 다시 시작하고 `/hooks`에서 등록을 확인하십시오. Hook 이벤트의 작업 디렉터리와 단일 워크스페이스가 설정한 루트와 일치해야 합니다.
202
+
203
+ 모델과 추론 강도가 지정되지 않은 내장 `self` 에이전트의 단일 호출을 지원합니다. 이 호출은 인자가 중첩되지 않는 형식입니다. Hook은 `Model`에 `flash_lite`, `flash`, `pro` 중 하나를 설정합니다. 실제 모델은 Antigravity가 결정합니다. 명시한 선택을 보존하며, 입력 형식을 확인할 수 없거나 추천을 받지 못하면 호스트가 기존 인자로 권한을 확인하고 계속 진행합니다.
204
+
205
+ Decisions 모드에서는 길이 제한을 충족하는 자식의 `Prompt`를 작업 설명으로 사용합니다. 요청에 클라이언트, 작업 종류, 문맥 충분성 표시, 티어 후보와 설명, 해시로 만든 요청 ID가 포함됩니다. 요청 기록과 예산은 직접 추천과 별도로 관리합니다. 승인된 워크스페이스에서만 활성화하고 민감한 내용이 자식 프롬프트에 포함되는지 확인하십시오. 자동 적용을 끄려면 `APTLY_ANTIGRAVITY_AUTO_WORKSPACE`를 해제한 뒤 Antigravity CLI를 다시 시작하십시오.
206
+
126
207
  <a id="guide-explicit-spawn-context"></a>
127
208
 
128
209
  ## 불투명 호출에 명시적 설명 전달 (0.1.4부터)
@@ -11,6 +11,7 @@
11
11
  - [Codex 示例](#guide-codex-configuration)
12
12
  - [Claude Code 示例](#guide-claude-configuration)
13
13
  - [直接推荐](#guide-direct-recommendations)
14
+ - [Antigravity CLI 模型推荐](#guide-antigravity-advisory)
14
15
  - [为不透明调用提供明确说明(0.1.4 起)](#guide-explicit-spawn-context)
15
16
  - [补充上下文后重新推荐(0.1.5 起)](#guide-context-retry)
16
17
  - [准备单独的独立委派(0.1.6 起)](#guide-fresh-delegation)
@@ -123,6 +124,86 @@ fixture 无需密钥、网络或执行子代理,即可返回本地模拟结果
123
124
 
124
125
  直接推荐的 `application: advisory_only` 不代表已确认宿主配置、模型访问权限或执行批准。重新查询已完成的结果时,请保持相同的 ID、输入、策略和账本。`unknown` 表示结果不明确,不要无条件使用新 ID 重试。因补充上下文而改变输入的新请求,应使用不同的 ID。
125
126
 
127
+ <a id="guide-antigravity-advisory"></a>
128
+
129
+ ## Antigravity CLI 模型推荐
130
+
131
+ 将下方条目添加到可信工作区的 `.agents/mcp_config.json` 中。把 `command` 替换为已安装的 `aptly` 可执行文件的绝对路径,并仅保留 `agy models` 列出的候选模型。
132
+
133
+ ```json
134
+ {
135
+ "mcpServers": {
136
+ "aptly-antigravity": {
137
+ "command": "/absolute/path/to/aptly",
138
+ "args": [
139
+ "serve",
140
+ "--client",
141
+ "antigravity"
142
+ ],
143
+ "env": {
144
+ "ROUTER_PROVIDER": "fixture",
145
+ "APTLY_ANTIGRAVITY_MODELS": "[\"gemini-4-hydrogen-medium\",\"gemini-4-carbon-medium\",\"gemini-4-neon-medium\"]"
146
+ }
147
+ }
148
+ }
149
+ }
150
+ ```
151
+
152
+ 推荐用 Hydrogen Medium 处理简单任务、Carbon Medium 处理常规任务、Neon Medium 处理复杂任务。如需为要求细致推理的复杂任务增加候选模型,请在列表中加入 `gemini-4-neon-high`。省略列表或设为 `[]` 时,推荐请求会返回 `no_candidates`。Aptly 不会单独验证当前账号能否运行这些模型。
153
+
154
+ 在 `/mcp` 中确认服务器,再使用下方参数调用 `recommend_agent`。交互模式下,请在出现提示时批准该工具。如需为非交互运行预先授权,请指定 `mcp(aptly-antigravity/recommend_agent)`。
155
+
156
+ ```json
157
+ {
158
+ "request_id": "agy-sort-001",
159
+ "client": "antigravity",
160
+ "task": {
161
+ "summary": "Sort the supplied numbers [3, 1, 2] in ascending order.",
162
+ "operation": "analysis",
163
+ "context_sufficient": true
164
+ }
165
+ }
166
+ ```
167
+
168
+ 示例使用本地测试规则。启动新的 Antigravity CLI 会话时,可将返回的 `profile.model` 传给 `agy --model`。如需调用原生子代理,请自行选择设置。Aptly 不会修改当前会话或原生子代理的设置。
169
+
170
+ 使用 Decisions API 时,请将 `ROUTER_PROVIDER` 设为 `decisions`,并将 `APTLY_ANTIGRAVITY_STATE_DIR` 设为已有私有目录的绝对路径(POSIX 权限为 `700`)。预算和请求记录与现有 Codex 和 Claude Code 的状态分开存放。请通过可信启动环境向 MCP 进程提供 `OPENAI_API_KEY`,不要将密钥写入配置文件或命令参数。
171
+
172
+ Aptly 调用 OpenAI Decisions API 获取推荐时可能产生费用。Aptly 通过 `X-Client-Request-Id` 请求头将 `request_id` 发送给 OpenAI Decisions API。请求正文包含 `client`、`task.summary`、`task.operation`、`task.context_sufficient` 以及候选模型配置的 ID 和说明。请使用不含敏感信息的随机 ID,并且仅对输入相同的请求复用该 ID。安装或配置服务器不会发起分类请求。请参阅[发送的内容](transmission.md#guide-transmission-limits)。
173
+
174
+ [Antigravity MCP](https://antigravity.google/docs/mcp?tab=cli) · [Permissions](https://antigravity.google/docs/cli-permissions)
175
+
176
+ <a id="guide-antigravity-hook"></a>
177
+
178
+ ### Antigravity CLI 自动应用档位
179
+
180
+ 自动应用按工作区启用。请将以下 Hook 添加到可信工作区的 `.agents/hooks.json`。如果 Antigravity CLI 无法通过 `PATH` 找到 `aptly`,请使用可执行文件的绝对路径。
181
+
182
+ ```json
183
+ {
184
+ "aptly-antigravity": {
185
+ "PreToolUse": [
186
+ {
187
+ "matcher": "^invoke_subagent$",
188
+ "hooks": [
189
+ {
190
+ "type": "command",
191
+ "command": "aptly antigravity-hook",
192
+ "timeout": 20
193
+ }
194
+ ]
195
+ }
196
+ ]
197
+ }
198
+ }
199
+ ```
200
+
201
+ 从工作区根目录启动 Antigravity CLI 时,请将该目录的绝对路径赋给 `APTLY_ANTIGRAVITY_AUTO_WORKSPACE`。使用 Decisions 时,请在同一启动环境中设置 `ROUTER_PROVIDER=decisions`、私有的 `APTLY_ANTIGRAVITY_STATE_DIR` 和 `OPENAI_API_KEY`。请通过启动环境提供密钥,不要将其写入 Hook 配置或命令参数。可用 `ROUTER_PROVIDER=fixture` 在本地检查 Hook。重启 Antigravity CLI 后,在 `/hooks` 中检查注册状态。Hook 事件中的工作目录和单个工作区都必须与所设置的根目录一致。
202
+
203
+ 支持以非嵌套参数单次调用内置 `self` 子代理,且调用未指定模型或推理强度。Hook 将 `Model` 设为 `flash_lite`、`flash` 或 `pro`。实际运行的模型由 Antigravity 决定。Hook 保留明确指定的选项,并在输入无法确认或推荐不可用时由宿主按原调用参数检查权限并继续。
204
+
205
+ 在 Decisions 模式下,Hook 将符合长度限制的子任务 `Prompt` 用作任务描述。请求还包含客户端、任务类型、上下文是否充分、候选档位及说明,以及经过哈希处理的请求 ID。自动推荐与直接推荐分别记录请求历史和预算。请在已获批准的工作区中启用,并检查子任务提示是否包含敏感信息。要停用自动应用,请取消设置 `APTLY_ANTIGRAVITY_AUTO_WORKSPACE`,然后重启 Antigravity CLI。
206
+
126
207
  <a id="guide-explicit-spawn-context"></a>
127
208
 
128
209
  ## 为不透明调用提供明确说明(0.1.4 起)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aptly",
3
- "version": "0.1.22",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {