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
@@ -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' } },
@@ -20,9 +21,9 @@ const entries = {
20
21
  'stats disable': { usage: 'aptly stats disable [--client codex|claude|all]', description: 'Disable Aptly collection and remove unchanged product-owned observer definitions. Preserve statistics/key/history, custom or modified observers and all routing settings. Retained modified definitions are reported for local review.', options: { '--client': client } },
21
22
  budget: { usage: 'aptly budget status [--client codex|claude|all]', description: 'Inspect local per-ledger budget limits and reserved usage. No reset/refill command is provided.' },
22
23
  'budget status': { usage: 'aptly budget status [--client codex|claude|all]', description: 'Read registered host budget settings and ledger metadata; defaults to both clients. No credentials, provider calls, configuration writes or ledger/gate initialization.\nLiteral 0 ceilings display Unlimited; reservations are not OpenAI billing. This is a registration/permitted-environment snapshot, not verification of running custom launchers. An existing gate is held briefly and can be busy.', options: { '--client': client } },
23
- setup: { usage: 'aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--transmission none|description|excerpt] [--launcher stable] [--automatic]\n aptly setup --check [--client codex|claude|all]\n aptly setup --client codex|claude --migrate-launcher [--launcher stable] [--include-existing] [--dry-run]\n aptly setup --client codex --policy-source codex-home [--dry-run]', description: 'Register MCP and PreToolUse Hooks while preserving unrelated settings and existing launchers. --launcher stable explicitly selects a POSIX-only private immutable runtime outside versioned Node installs; for existing direct registrations combine it with --migrate-launcher. The snapshot includes the package and production dependencies, not Node itself. A supported installed Node is still required. Existing stable registrations stay stable, including later migrations without the flag. Default/automatic installations keep direct Node registrations. Modified/custom launchers remain unchanged. Stable migration updates owned statistics observers in the same host transaction; direct-to-direct legacy migration retains its separate observer refresh contract and may report statistics_observer_migration_required; keys, history and collection/native-metadata choices remain unchanged. Old/shared snapshots are retained after remove. Windows stable mode is unsupported; the existing direct mode remains available. Omitted --mode preserves an existing mode; a new policy defaults to defaults. New transmission remains unselected unless explicitly chosen.\n--check snapshots the normal setup plan without writing; only --client may be combined with it. It does not verify a running host.\n--automatic skips CI, APTLY_SKIP_SETUP=1 and absent host directories.\n--migrate-launcher reviews a single owned standard launcher; --include-existing explicitly includes an eligible preserved registration. --dry-run validates migration without writing. Do not combine migration with --automatic, --mode or --transmission. --include-existing requires --migrate-launcher. --policy-source codex-home explicitly binds an existing owned Codex setup to the runtime CODEX_HOME using a reserved selector and forwarded CODEX_HOME; it preserves policy, ledger and statistics state. CLI commands and MCP startup select ~/.codex under the OS user home when CODEX_HOME is absent; an explicit absolute override takes precedence. Explicitly empty, relative or control-character-containing overrides are rejected. A custom host that omits CODEX_HOME uses the default home policy and transmission scope. Custom account homes are not discovered automatically; account managers must forward the intended CODEX_HOME. This default-home MCP fallback is available starting with 0.1.15; published 0.1.14 requires explicit forwarding even for the default home. Use it in the canonical registration and intended account homes when a manager mirrors MCP tables. --dry-run validates either migration without writing. Policy-source migration requires --client codex and cannot combine with other setup actions. Upgrade all MCP backends first; restart MCP afterward.\nOrdinary interactive setup reviews unreviewed transmission choices, including existing registrations; Enter keeps configured scopes or selects none for unselected clients. --automatic, --check and launcher migration never prompt. Explicit --transmission records that choice without asking. No keys are stored. Restart the host/MCP; Codex requires native /hooks trust review.', options: { '--client': client, '--launcher': ['stable'], '--mode': ['defaults', 'advisory'], '--transmission': scope, '--automatic': true, '--check': true, '--migrate-launcher': true, '--policy-source': ['codex-home'], '--include-existing': true, '--dry-run': true } },
24
+ setup: { usage: 'aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--transmission none|description|excerpt] [--launcher stable|npx] [--automatic]\n aptly setup --check [--client codex|claude|all]\n aptly setup --client codex|claude --migrate-launcher [--launcher stable|npx] [--include-existing] [--dry-run]\n aptly setup --client codex --policy-source codex-home [--dry-run]', description: 'Register MCP and PreToolUse Hooks while preserving unrelated settings and existing launchers. --launcher stable or npx explicitly selects a private immutable runtime on macOS and Linux outside versioned Node installs; for existing direct registrations combine it with --migrate-launcher. The snapshot includes the package and production dependencies, not Node itself. A supported installed Node is still required. Existing managed registrations keep their selected launcher. Managed npx requires a trusted Node.js 24+ installation with npm and is unavailable with --automatic. Default/automatic installations keep direct Node registrations. Modified/custom launchers remain unchanged. Stable migration updates owned statistics observers in the same host transaction; direct-to-direct legacy migration retains its separate observer refresh contract and may report statistics_observer_migration_required; keys, history and collection/native-metadata choices remain unchanged. Old/shared snapshots are retained after remove. Windows managed mode is unsupported; the existing direct mode remains available. Omitted --mode preserves an existing mode; a new policy defaults to defaults. New transmission remains unselected unless explicitly chosen.\n--check snapshots the normal setup plan without writing; only --client may be combined with it. It does not verify a running host.\n--automatic skips CI, APTLY_SKIP_SETUP=1 and absent host directories.\n--migrate-launcher reviews a single owned standard launcher; --include-existing explicitly includes an eligible preserved registration. --dry-run validates migration without writing. Do not combine migration with --automatic, --mode or --transmission. --include-existing requires --migrate-launcher. --policy-source codex-home explicitly binds an existing owned Codex setup to the runtime CODEX_HOME using a reserved selector and forwarded CODEX_HOME; it preserves policy, ledger and statistics state. CLI commands and MCP startup select ~/.codex under the OS user home when CODEX_HOME is absent; an explicit absolute override takes precedence. Explicitly empty, relative or control-character-containing overrides are rejected. A custom host that omits CODEX_HOME uses the default home policy and transmission scope. Custom account homes are not discovered automatically; account managers must forward the intended CODEX_HOME. This default-home MCP fallback is available starting with 0.1.15; published 0.1.14 requires explicit forwarding even for the default home. Use it in the canonical registration and intended account homes when a manager mirrors MCP tables. --dry-run validates either migration without writing. Policy-source migration requires --client codex and cannot combine with other setup actions. Upgrade all MCP backends first; restart MCP afterward.\nOrdinary interactive setup reviews unreviewed transmission choices, including existing registrations; Enter keeps configured scopes or selects none for unselected clients. --automatic, --check and launcher migration never prompt. Explicit --transmission records that choice without asking. No keys are stored. Restart the host/MCP; Codex requires native /hooks trust review.', options: { '--client': client, '--launcher': ['stable', 'npx'], '--mode': ['defaults', 'advisory'], '--transmission': scope, '--automatic': true, '--check': true, '--migrate-launcher': true, '--policy-source': ['codex-home'], '--include-existing': true, '--dry-run': true } },
24
25
  remove: { usage: 'aptly remove [--client codex|claude|all]', description: 'Remove only unchanged Aptly-owned registration for both clients by default. Preserve modified/user-owned entries, keys and ledger history. Restart host/MCP after removal.', options: { '--client': client } },
25
- update: { usage: 'aptly update', description: 'Update this verified global npm installation within the same prefix. Stop other hosts/MCP/CLI writers first. Local/source/unverified installations are rejected. Lifecycle setup is not run: run aptly setup and restart hosts afterward. Existing stable registrations retain their selected snapshot until explicit per-client --migrate-launcher --launcher stable; plain setup reports stable_snapshot_outdated when versions differ. Existing launchers and keys are preserved. Update does not run setup or a new CLI process: next interactive setup/set default reviews pending transmission choices; use aptly set transmission --review for an explicit review. The first upgrade from older code requires a subsequent setup/default command to load this behavior.' },
26
+ update: { usage: 'aptly update [--client codex|claude --launcher npx]', options: { '--client': ['codex', 'claude'], '--launcher': ['npx'] }, description: 'Update this verified global npm installation within the same prefix. Stop other hosts/MCP/CLI writers first. On macOS and Linux, the fresh CLI migrates existing Aptly-owned Codex and Claude Code registrations to managed npx. Absent or unowned registrations are skipped, and each host reports its migration result. The explicit --client and --launcher npx pair selects only one host. The package update is retained if a later migration fails. Windows updates the package only. Lifecycle scripts are disabled. Older releases first need an ordinary update to install the new CLI. Then run aptly update again to migrate existing hosts. Recheck changed Codex Hooks in /hooks and restart the host. Review transmission choices with aptly set transmission --review.' },
26
27
  doctor: { usage: 'aptly doctor [--client codex|claude|all]', description: 'Read local registration, policy, package version and bounded ledger metadata as JSON. No launcher execution, credential-store query, provider/network call, state creation or update notification. Complete (exit 0) means the query completed, not host readiness; partial (exit 1) means an observation failed. Runtime version, Hook trust/execution, restart need and retry ticket usage remain unknown. Ledgers above 4 MiB are not scanned. A missing first-use ledger has unknown history. Scan time includes validation/rechecks; write timing is not measured. Existing report exports are separate and unchanged.', options: { '--client': client } },
27
28
  report: { usage: 'aptly report [--format md|json|both] [--output-dir DIR]', description: 'Write redacted local diagnostic attachments. Default format: both; directory: reports. No uploads or classification API probes. Review attachments before sharing.', options: { '--format': ['md', 'json', 'both'], '--output-dir': 'path' } },
28
29
  };
@@ -94,6 +95,8 @@ export function resolveCliHelp(argv, { environmentKeys = [] } = {}) {
94
95
  return { kind: 'error', code: 'invalid_help_options' };
95
96
  if (path === 'stats enable' && seen.has('--codex-native-metadata') && values.get('--client') === 'claude')
96
97
  return { kind: 'error', code: 'invalid_help_options' };
98
+ if (path === 'update' && (seen.has('--client') !== seen.has('--launcher')))
99
+ return { kind: 'error', code: 'invalid_help_options' };
97
100
  if (path === 'setup') {
98
101
  const migrate = seen.has('--migrate-launcher'), policySource = seen.has('--policy-source');
99
102
  if (seen.has('--check') && [...seen].some(flag => !['--check', '--client'].includes(flag)))
@@ -155,7 +155,7 @@ export class ContextRetries {
155
155
  try {
156
156
  const result = await this.router.advise({ request_id, client: entry.seed.client,
157
157
  task: { summary, operation: 'analysis', context_sufficient: true }, eligible_profile_ids: entry.seed.eligible_profile_ids,
158
- constraints: { model_pinned: false, effort_pinned: false, role_pinned: false, fork_inherits: false } });
158
+ constraints: { model_pinned: false, effort_pinned: false, role_pinned: false, fork_inherits: false } }, signal);
159
159
  const after = check();
160
160
  if (after)
161
161
  return unavailable(after);
@@ -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;
@@ -70,10 +75,10 @@ export declare class Router {
70
75
  }): void;
71
76
  save(): void;
72
77
  /** Strict native-routing path: preserves existing host-evidence and digest semantics. */
73
- recommend(input: unknown): Promise<RoutingResult>;
78
+ recommend(input: unknown, signal?: AbortSignal): Promise<RoutingResult>;
74
79
  /** Independent task advice. Omitted constraints mean no caller-declared pins,
75
80
  * not verified host settings. A legacy provenance flag grants no authority. */
76
- advise(input: unknown): Promise<RoutingResult>;
81
+ advise(input: unknown, signal?: AbortSignal): Promise<RoutingResult>;
77
82
  private route;
78
83
  }
79
84
  export {};
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;
@@ -242,14 +248,16 @@ export class Router {
242
248
  }
243
249
  }
244
250
  /** Strict native-routing path: preserves existing host-evidence and digest semantics. */
245
- async recommend(input) {
246
- return this.route(input, 'hook');
251
+ async recommend(input, signal) {
252
+ if (this.advisoryScope)
253
+ return this.result('unavailable', 'invalid_input');
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
- async advise(input) {
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'))
@@ -258,12 +266,15 @@ export class Router {
258
266
  return this.route({ ...input,
259
267
  eligible_profile_ids: own(input, 'eligible_profile_ids') ? input.eligible_profile_ids : this.policy.profiles.filter(profile => profile.client === input.client).map(profile => profile.id),
260
268
  constraints: declared,
261
- }, 'advisory');
269
+ }, 'advisory', signal);
262
270
  }
263
- async route(input, kind) {
271
+ async route(input, kind, signal) {
272
+ const cancelled = () => this.result('unavailable', 'call_cancelled');
273
+ if (signal?.aborted)
274
+ return cancelled();
264
275
  const invalid = () => this.result('unavailable', 'invalid_input');
265
276
  if (!keysOnly(input, ['request_id', 'client', 'task', 'eligible_profile_ids', 'constraints']) ||
266
- 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) ||
267
278
  ['__proto__', 'constructor', 'prototype'].includes(input.request_id) ||
268
279
  !keysOnly(input.task, ['summary', 'operation', 'context_sufficient']) || typeof input.task.summary !== 'string' ||
269
280
  !input.task.summary.trim() || Buffer.byteLength(input.task.summary) > this.policy.max_summary_bytes ||
@@ -273,9 +284,15 @@ export class Router {
273
284
  !keysOnly(input.constraints, ['model_pinned', 'effort_pinned', 'role_pinned', 'fork_inherits', 'provenance_verified']) ||
274
285
  Object.values(input.constraints).some(v => typeof v !== 'boolean'))
275
286
  return invalid();
276
- 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)) {
277
291
  return this.result('keep_current', 'sensitive_input');
292
+ }
278
293
  const req = clone(input);
294
+ if (this.advisoryScope && !this.policy.profiles.length)
295
+ return this.result('keep_current', 'no_candidates');
279
296
  const profiles = this.policy.profiles.filter(p => p.client === req.client && req.eligible_profile_ids.includes(p.id));
280
297
  if (!profiles.length && !req.eligible_profile_ids.length)
281
298
  return this.result('keep_current', 'no_candidates');
@@ -316,6 +333,8 @@ export class Router {
316
333
  // Only this known completion can proceed again under the same ID.
317
334
  }
318
335
  const complete = (result) => {
336
+ if (signal?.aborted)
337
+ return this.result('unavailable', 'call_cancelled', { latency_ms: result.latency_ms });
319
338
  this.state.requests[req.request_id] = { digest: hash, state: 'complete', result };
320
339
  this.save();
321
340
  return clone(result);
@@ -331,8 +350,12 @@ export class Router {
331
350
  this.provider.preflight?.();
332
351
  }
333
352
  catch (e) {
353
+ if (signal?.aborted)
354
+ return cancelled();
334
355
  return this.result('unavailable', errorCode(e) === 'unauthorized' ? 'unauthorized' : 'provider_error');
335
356
  }
357
+ if (signal?.aborted)
358
+ return cancelled();
336
359
  const day = new Date().toISOString().slice(0, 10);
337
360
  const exhausted = this.budgetSnapshot(day).exhausted_by;
338
361
  if (exhausted.length)
@@ -343,14 +366,32 @@ export class Router {
343
366
  this.state.requests[req.request_id] = { digest: hash, state: 'unknown' };
344
367
  this.save();
345
368
  const controller = new AbortController();
346
- let timer;
369
+ const { promise: interrupted, reject } = Promise.withResolvers();
370
+ let stopped;
371
+ const stop = (code) => {
372
+ if (stopped)
373
+ return;
374
+ stopped = code;
375
+ const error = Object.assign(new Error(code), { code });
376
+ reject(error);
377
+ controller.abort(error);
378
+ };
379
+ const onAbort = () => stop('call_cancelled');
380
+ signal?.addEventListener('abort', onAbort, { once: true });
381
+ if (signal?.aborted)
382
+ onAbort();
383
+ const timer = setTimeout(() => stop('timeout'), this.policy.timeout_ms);
347
384
  const started = performance.now();
348
385
  const latency = () => Math.round((performance.now() - started) * 1000) / 1000;
349
386
  try {
350
387
  const response = await Promise.race([
351
- Promise.resolve().then(() => this.provider({ input: clone(req), profiles: clone(profiles), signal: controller.signal })),
352
- new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(Object.assign(new Error('timeout'), { code: 'timeout' })); }, this.policy.timeout_ms); }),
388
+ interrupted,
389
+ Promise.resolve().then(() => {
390
+ controller.signal.throwIfAborted();
391
+ return this.provider({ input: clone(req), profiles: clone(profiles), signal: controller.signal });
392
+ }),
353
393
  ]);
394
+ controller.signal.throwIfAborted();
354
395
  if (!isRecord(response) || typeof response.choice !== 'string' || (own(response, 'confidence') && (typeof response.confidence !== 'number' || !Number.isFinite(response.confidence) || response.confidence < 0 || response.confidence > 1)))
355
396
  return complete(this.result('keep_current', 'invalid_response', { latency_ms: latency() }));
356
397
  const metadata = { latency_ms: latency() };
@@ -374,13 +415,16 @@ export class Router {
374
415
  return complete(this.result('recommended', 'allowed_profile', { profile_id: profile.id, profile: clone(profile), ...metadata }));
375
416
  }
376
417
  catch (e) {
377
- // A failed transport can have consumed a paid call. Preserve its unknown marker.
418
+ // The slot and gate protect local work. A remote request may outlive cancellation.
419
+ if (stopped)
420
+ return this.result('unavailable', stopped, { latency_ms: latency() });
378
421
  const allowed = ['timeout', 'refused', 'truncated', 'invalid_json', 'unauthorized', 'rate_limited', 'network', 'ledger_error'];
379
422
  const code = errorCode(e);
380
423
  return this.result('unavailable', code !== undefined && allowed.includes(code) ? code : 'provider_error', { latency_ms: latency() });
381
424
  }
382
425
  finally {
383
426
  clearTimeout(timer);
427
+ signal?.removeEventListener('abort', onAbort);
384
428
  }
385
429
  }
386
430
  catch {
@@ -56,6 +56,7 @@ export declare function collectDoctor(options?: DoctorOptions): {
56
56
  stable_snapshot_outdated?: boolean | undefined;
57
57
  recovery?: string[] | undefined;
58
58
  registration: string;
59
+ runtime_launcher?: import("./stable-runtime.ts").ManagedLauncher | undefined;
59
60
  registered_package: {
60
61
  status: string;
61
62
  version: string | null;
@@ -164,7 +164,7 @@ export function collectDoctor(options = {}) {
164
164
  ledger = { status: 'not_declared', counts: null, write_timing: 'not_measured' };
165
165
  }
166
166
  snapshot.verify();
167
- return { ...base, status: 'complete', ...(stable && stable.version !== VERSION ? { stable_snapshot_outdated: true, recovery: [`aptly setup --client ${client} --migrate-launcher${process.platform === 'win32' ? '' : ' --launcher stable'} --dry-run`] } : {}), registration: stable ? 'stable_runtime_registration' : standard ? 'standard_node_registration' : 'custom_or_remote_launcher', registered_package: target, policy: { source_kind: source, status: policyStatus, transmission }, hook_registration: hook, credential_reference: settings.APTLY_SECRET_BACKEND === 'os' ? 'os_reference' : Object.hasOwn(settings, 'OPENAI_API_KEY') ? 'inline_environment_present' : permitted('OPENAI_API_KEY') ? 'runtime_environment_permitted' : 'not_declared', ledger: { ...ledger, diagnostic_scan_ms: Math.max(0, performance.now() - started), timing_scope: 'full_client_observation_and_rechecks' } };
167
+ return { ...base, status: 'complete', ...(stable && stable.version !== VERSION ? { stable_snapshot_outdated: true, recovery: [`aptly setup --client ${client} --migrate-launcher --launcher ${stable.launcher} --dry-run`] } : {}), registration: stable ? 'stable_runtime_registration' : standard ? 'standard_node_registration' : 'custom_or_remote_launcher', ...(stable ? { runtime_launcher: stable.launcher } : {}), registered_package: target, policy: { source_kind: source, status: policyStatus, transmission }, hook_registration: hook, credential_reference: settings.APTLY_SECRET_BACKEND === 'os' ? 'os_reference' : Object.hasOwn(settings, 'OPENAI_API_KEY') ? 'inline_environment_present' : permitted('OPENAI_API_KEY') ? 'runtime_environment_permitted' : 'not_declared', ledger: { ...ledger, diagnostic_scan_ms: Math.max(0, performance.now() - started), timing_scope: 'full_client_observation_and_rechecks' } };
168
168
  }
169
169
  catch (error) {
170
170
  // A changed observation takes precedence over a parse/validation failure.
@@ -38,19 +38,25 @@ export function decisionsProvider({ key, fetchImpl = fetch, descriptions = {} }
38
38
  throw fail(response.status === 401 || response.status === 403 ? 'unauthorized' : response.status === 429 ? 'rate_limited' : 'provider_error');
39
39
  }
40
40
  // Bounded response, never expose raw provider text or headers in diagnostics.
41
- let body = '';
41
+ const chunks = [];
42
+ let bytes = 0;
42
43
  try {
43
44
  if (!response.body)
44
45
  throw fail('network');
45
46
  for await (const chunk of response.body) {
46
- body += Buffer.from(chunk).toString('utf8');
47
- if (Buffer.byteLength(body) > 65536)
47
+ if (!(chunk instanceof Uint8Array))
48
+ throw fail('network');
49
+ bytes += chunk.byteLength;
50
+ if (bytes > 65_536)
48
51
  throw fail('truncated');
52
+ if (chunk.byteLength)
53
+ chunks.push(chunk);
49
54
  }
50
55
  }
51
56
  catch (e) {
52
57
  throw fail(errorCode(e) === 'truncated' ? 'truncated' : signal?.aborted ? 'timeout' : 'network');
53
58
  }
59
+ const body = Buffer.concat(chunks, bytes).toString('utf8');
54
60
  let data;
55
61
  try {
56
62
  data = JSON.parse(body);
@@ -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) };
@@ -105,7 +129,12 @@ export function createServer({ env: inputEnv = process.env } = {}) {
105
129
  server.registerTool('recommend_agent', {
106
130
  description: 'Recommend an allowlisted profile for a supplied task only; never inspects host settings, spawns, or authorizes an agent. Optional constraints describe caller-declared choices to preserve; omitted flags are not claims about current host settings. Decisions mode may incur a bounded classification request.', annotations,
107
131
  inputSchema: { request_id: z.string().min(1).max(96), client: z.enum(['codex', 'claude']), task: taskSchema, eligible_profile_ids: z.array(z.string()).min(1).max(20).optional(), constraints: constraintsSchema.optional() }
108
- }, async (input) => { const result = await router.advise(input); await trackStatistics(input.client, { requestId: input.request_id, recommendation: result }); return content({ ...result, provider: mode }); });
132
+ }, async (input, extra) => {
133
+ const result = await router.advise(input, extra.signal);
134
+ if (!extra.signal.aborted)
135
+ await trackStatistics(input.client, { requestId: input.request_id, recommendation: result });
136
+ return content({ ...result, provider: mode });
137
+ });
109
138
  server.registerTool('retry_spawn_recommendation', {
110
139
  description: 'Supply one bounded task description after an Aptly Hook returns needs_context and a retry_id. Use the same MCP process within five minutes; no native call IDs are needed. May make one paid classification; duplicate input reuses its request identity, changed input conflicts. Never spawns or changes history. If still needs_context/unavailable, stop; do not create another ID. A blocked spawn_application remains advisory. When next_call is supplied, required_fields and next_action describe only missing profile arguments. Apply them only under existing user/host permissions; if forbidden or unclear, stop and report. Existing-agent reuse is an alternative, not proof of applying this recommendation.',
111
140
  annotations, inputSchema: { retry_id: z.string().regex(/^[a-f0-9]{64}$/), description: z.string().max(4000) }
@@ -163,7 +192,16 @@ export function createServer({ env: inputEnv = process.env } = {}) {
163
192
  input.constraints = before.precedence.constraints;
164
193
  if (task)
165
194
  input.task = task;
166
- const recommendation = await router.recommend(input);
195
+ const recommendation = await router.recommend(input, extra.signal);
196
+ if (extra.signal.aborted) {
197
+ // Keep any already committed recommendation distinct from native application.
198
+ const produced = recommendation.status === 'recommended';
199
+ observations.record({ ...initialHookObservation(client, event), status: 'preserved', reason: 'call_cancelled', request_id: input.request_id,
200
+ classification: recommendation.cached ? 'cache_hit' : typeof recommendation.latency_ms === 'number' ? 'provider_requested' : 'local_outcome',
201
+ recommendation: produced ? 'produced' : 'not_produced', application: produced ? 'blocked' : 'not_attempted',
202
+ ...(recommendation.profile_id ? { profile_id: recommendation.profile_id } : {}) });
203
+ return { content: [{ type: 'text', text: '{}' }] };
204
+ }
167
205
  // Revalidate binding, expiry, source fingerprints and operator configuration
168
206
  // after an asynchronous provider call. A changed source cannot enable apply.
169
207
  const after = evidence(client, event);
@@ -1,9 +1,10 @@
1
+ import { type ManagedLauncher } from './stable-runtime.ts';
1
2
  type Client = 'codex' | 'claude';
2
3
  export interface SetupOptions {
3
4
  home?: string;
4
5
  env?: NodeJS.ProcessEnv;
5
6
  packageRoot?: string;
6
- launcher?: 'stable';
7
+ launcher?: ManagedLauncher;
7
8
  automatic?: boolean;
8
9
  clients?: Client[];
9
10
  mode?: 'defaults' | 'advisory';