aptly 0.1.4 → 0.1.5

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
@@ -20,22 +20,30 @@ Our own tests showed **about 52–58% lower API-equivalent costs**. See the [tes
20
20
 
21
21
  ## Quick start
22
22
 
23
- Requires Node.js **24 or later** and Claude Code or Codex. Install the latest stable version globally with these commands.
23
+ Requires Node.js **24 or later** and Claude Code or Codex. For first-time installation, install and configure the latest stable version globally with these commands.
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
27
  aptly setup --client all --mode defaults
28
+ aptly set env OPENAI_API_KEY
28
29
  aptly --version
29
30
  ```
30
31
 
31
32
  Check the installed version with `aptly --version`. On supported npm versions, `--allow-scripts=aptly` allows Aptly’s installation script. If your npm does not support this option, follow the explicit installation and setup steps in the [installation guide](docs/guide/en.md#installation).
32
33
 
33
- Before upgrading, stop all related host, MCP, and CLI processes and review the ledger transition in the [installation and upgrade guide](docs/guide/en.md#installation).
34
-
35
34
  During installation, `postinstall` registers the MCP server and a `PreToolUse` Hook in existing host configuration directories. Run `setup` explicitly if automatic registration was skipped or a host has no configuration directory yet. Other settings and Hooks, and any existing Aptly launch command and environment, are preserved.
36
35
 
37
36
  Store the classification key, `OPENAI_API_KEY`, in the OS credential store using the hidden prompt in `aptly set env OPENAI_API_KEY`, or pass it to the MCP process through a secure execution environment. Do not put it in command arguments, requests, configuration JSON, or the repository. Restart the host or MCP server, then **review and trust the new Hook through `/hooks` in Codex**. See [installation, keys, and registration](docs/guide/en.md#installation).
38
37
 
38
+ ## Update
39
+
40
+ To update an existing global npm installation running Aptly 0.1.3 or later, stop all related host, MCP, and CLI writers and review ledger migration and the manual fallback in the [installation and upgrade guide](docs/guide/en.md#installation). Existing key settings are preserved, so there is no need to re-enter the key. Restart afterward.
41
+
42
+ ```sh
43
+ aptly update
44
+ aptly setup --client all --mode defaults
45
+ ```
46
+
39
47
  ## Usage modes
40
48
 
41
49
  | Mode | Behavior |
@@ -48,9 +56,8 @@ From Aptly 0.1.4, inherited calls also reach recommendation. Application still r
48
56
 
49
57
  ## Documentation
50
58
 
51
- - [CLI configuration](docs/guide/en.md#configure-with-the-cli)
52
59
  - [User guide](docs/guide/en.md): installation and removal, keys, Hooks, direct recommendations, and error recovery
53
- - [Installation and removal](docs/guide/en.md#installation): global npm installation, host registration, restarting, and trust review
60
+ - [Installation and removal](docs/guide/en.md#installation) and [CLI configuration](docs/guide/en.md#configure-with-the-cli): global npm installation, host registration, restarting, and trust review
54
61
  - [Models and environment variables](docs/guide/en.md#models-and-environment-variables): six default profiles and candidate configuration
55
62
  - [Providing context](docs/guide/en.md#providing-context): encrypted messages and repository URL limitations
56
63
  - [Cost benchmark](docs/guide/en.md#cost-benchmark): tokens, converted costs, and measurement scope for a README translation review
package/README.ja.md CHANGED
@@ -20,22 +20,30 @@ Aptly は必要最小限のタスク要約を OpenAI Decisions API で分類し
20
20
 
21
21
  ## クイックスタート
22
22
 
23
- Node.js **24 以上**と Claude Code または Codex が必要です。以下のコマンドで最新の安定版をグローバルインストールしてください。
23
+ Node.js **24 以上**と Claude Code または Codex が必要です。初めてインストールする場合は、以下のコマンドで最新の安定版をグローバルにインストールして設定してください。
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
27
  aptly setup --client all --mode defaults
28
+ aptly set env OPENAI_API_KEY
28
29
  aptly --version
29
30
  ```
30
31
 
31
32
  `aptly --version` でインストール済みのバージョンを確認してください。対応する npm では、`--allow-scripts=aptly` で Aptly のインストールスクリプトを許可します。このオプションに対応していない npm では、[インストール案内](docs/guide/ja.md#インストール)の明示的なインストール・設定手順に従ってください。
32
33
 
33
- アップグレード前に、関連するホスト・MCP・CLI の全プロセスを停止し、[インストールとアップグレードの案内](docs/guide/ja.md#インストール)で台帳の移行手順を確認してください。
34
-
35
34
  インストール時の `postinstall` は、既存のホスト設定ディレクトリに MCP と `PreToolUse` Hook を登録します。自動登録をスキップした場合や、ホストに設定ディレクトリがまだない場合も、`setup` を明示的に実行して登録できます。他の既存設定・Hook と、既存の Aptly の実行コマンド・環境は保持します。
36
35
 
37
36
  分類用の `OPENAI_API_KEY` は、`aptly set env OPENAI_API_KEY` の非表示入力で OS の資格情報ストアに保存するか、安全な実行環境から MCP プロセスに渡してください。キーをコマンドライン・リクエスト・設定 JSON・リポジトリに記載しないでください。ホストまたは MCP を再起動した後、**Codex では `/hooks` で新しい Hook を確認し、信頼を承認**してください。[インストール・キー・登録の詳細](docs/guide/ja.md#インストール)を確認してください。
38
37
 
38
+ ## 更新
39
+
40
+ npm でグローバルインストール済みの Aptly 0.1.3 以降を更新するには、関連するホスト・MCP・CLI の書き込みプロセスをすべて停止し、[インストールとアップグレードの案内](docs/guide/ja.md#インストール)で台帳の移行と手動での代替手順を確認してください。既存のキー設定は保持されるため、キーの再入力は不要です。コマンド実行後に再起動してください。
41
+
42
+ ```sh
43
+ aptly update
44
+ aptly setup --client all --mode defaults
45
+ ```
46
+
39
47
  ## 使用方法
40
48
 
41
49
  | 方法 | 動作 |
@@ -48,9 +56,8 @@ Aptly 0.1.4 以降では継承呼び出しも推薦を評価します。適用
48
56
 
49
57
  ## ドキュメント
50
58
 
51
- - [CLI 設定](docs/guide/ja.md#cli-による設定)
52
59
  - [使用ガイド](docs/guide/ja.md): インストール・削除、キー、Hook、直接推薦、エラー復旧
53
- - [インストール・削除](docs/guide/ja.md#インストール): npm のグローバルインストール、ホスト登録、再起動と信頼の承認
60
+ - [インストール・削除](docs/guide/ja.md#インストール)と [CLI 設定](docs/guide/ja.md#cli-による設定): npm のグローバルインストール、ホスト登録、再起動と信頼の承認
54
61
  - [モデルと環境変数](docs/guide/ja.md#モデルと環境変数): 6 つのデフォルトプロファイルと候補の設定
55
62
  - [コンテキストの提供](docs/guide/ja.md#コンテキストの提供): 暗号化されたメッセージとリポジトリ URL の制約
56
63
  - [費用実測](docs/guide/ja.md#費用実測): README 翻訳レビューのトークン・換算費用と測定範囲
package/README.md CHANGED
@@ -20,22 +20,30 @@ Aptly는 최소한의 작업 요약을 OpenAI Decisions API로 분류하고 허
20
20
 
21
21
  ## 빠른 시작
22
22
 
23
- Node.js **24 이상**과 Claude Code 또는 Codex가 필요합니다. 다음 명령으로 최신 안정 버전을 전역 설치하십시오.
23
+ Node.js **24 이상**과 Claude Code 또는 Codex가 필요합니다. 처음 설치할 때는 다음 명령으로 최신 안정 버전을 전역 설치하고 설정하십시오.
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
27
  aptly setup --client all --mode defaults
28
+ aptly set env OPENAI_API_KEY
28
29
  aptly --version
29
30
  ```
30
31
 
31
32
  `aptly --version`으로 설치된 버전을 확인하십시오. `--allow-scripts=aptly`는 지원하는 npm에서 Aptly의 설치 스크립트를 허용합니다. 이 옵션을 지원하지 않는 npm은 [설치 안내](docs/guide/ko.md#설치)의 명시적 설치·설정 절차를 따르십시오.
32
33
 
33
- 업그레이드 전에는 관련 호스트·MCP·CLI 프로세스를 모두 중지하고 [설치·업그레이드 안내](docs/guide/ko.md#설치)의 원장 전환 절차를 확인하십시오.
34
-
35
34
  설치 시 `postinstall`은 기존 호스트 설정 디렉터리에 MCP와 `PreToolUse` Hook을 등록합니다. 명시적인 `setup`은 자동 등록을 건너뛰었거나 아직 설정 디렉터리가 없는 호스트에도 사용할 수 있습니다. 기존 다른 설정·Hook과 기존 Aptly 실행 명령·환경은 보존합니다.
36
35
 
37
36
  분류용 `OPENAI_API_KEY`는 `aptly set env OPENAI_API_KEY`의 숨김 입력으로 OS 자격 저장소에 보관하거나 안전한 실행 환경에서 MCP 프로세스에 전달하십시오. 키를 명령행·요청·설정 JSON·저장소에 기록하지 마십시오. 호스트 또는 MCP를 재시작한 뒤, **Codex에서는 `/hooks`에서 새 Hook을 검토하고 신뢰를 승인하십시오.** [설치·키·등록 상세](docs/guide/ko.md#설치)를 참고하십시오.
38
37
 
38
+ ## 업데이트
39
+
40
+ 기존 전역 npm 설치의 Aptly 0.1.3 이상을 업데이트하려면 관련 호스트·MCP·CLI 쓰기 프로세스를 모두 중지하고 [설치·업그레이드 안내](docs/guide/ko.md#설치)의 원장 전환 및 수동 대체 절차를 확인하십시오. 기존 키 설정은 유지하므로 다시 입력할 필요가 없습니다. 명령 실행 후 재시작하십시오.
41
+
42
+ ```sh
43
+ aptly update
44
+ aptly setup --client all --mode defaults
45
+ ```
46
+
39
47
  ## 사용 방식
40
48
 
41
49
  | 방식 | 동작 |
@@ -48,9 +56,8 @@ Aptly 0.1.4부터 상속 호출도 추천을 평가합니다. Codex의 적용은
48
56
 
49
57
  ## 문서
50
58
 
51
- - [CLI 설정](docs/guide/ko.md#cli로-설정하기)
52
59
  - [사용 가이드](docs/guide/ko.md): 설치·제거, 키, Hook, 직접 추천, 오류 복구
53
- - [설치·제거](docs/guide/ko.md#설치): npm 전역 설치, 호스트 등록, 재시작과 신뢰 승인
60
+ - [설치·제거](docs/guide/ko.md#설치) 및 [CLI 설정](docs/guide/ko.md#cli로-설정하기): npm 전역 설치, 호스트 등록, 재시작과 신뢰 승인
54
61
  - [모델과 환경변수](docs/guide/ko.md#모델과-환경변수): 여섯 기본 프로필과 후보 설정
55
62
  - [맥락 전달](docs/guide/ko.md#맥락-전달): 암호화된 메시지와 저장소 URL의 한계
56
63
  - [비용 실측](docs/guide/ko.md#비용-실측): README 번역 검토의 토큰·환산 비용과 측정 범위
package/README.zh-CN.md CHANGED
@@ -20,22 +20,30 @@ Aptly 使用 OpenAI Decisions API 对简要任务摘要进行分类,并推荐
20
20
 
21
21
  ## 快速开始
22
22
 
23
- 需要 Node.js **24 或更高版本**以及 Claude Code 或 Codex。请使用以下命令全局安装最新稳定版。
23
+ 需要 Node.js **24 或更高版本**以及 Claude Code 或 Codex。首次安装时,请使用以下命令全局安装并配置最新稳定版。
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
27
  aptly setup --client all --mode defaults
28
+ aptly set env OPENAI_API_KEY
28
29
  aptly --version
29
30
  ```
30
31
 
31
32
  请使用 `aptly --version` 确认已安装的版本。在支持此选项的 npm 中,`--allow-scripts=aptly` 允许执行 Aptly 的安装脚本。如果 npm 不支持此选项,请按照[安装指南](docs/guide/zh-CN.md#安装)中的显式安装与配置步骤操作。
32
33
 
33
- 升级前,请停止所有相关宿主、MCP 和 CLI 进程,并查看[安装与升级指南](docs/guide/zh-CN.md#安装)中的账本迁移步骤。
34
-
35
34
  安装时的 `postinstall` 会在现有宿主配置目录中注册 MCP 和 `PreToolUse` Hook。如果跳过了自动注册,或宿主尚无配置目录,也可以显式运行 `setup`。其他现有配置与 Hook,以及 Aptly 原有的启动命令和环境均会保留。
36
35
 
37
36
  请通过 `aptly set env OPENAI_API_KEY` 的隐藏输入,将分类用的 `OPENAI_API_KEY` 存入系统凭据存储,或通过安全的运行环境传递给 MCP 进程。不要将密钥写入命令行、请求、配置 JSON 或代码仓库。重启宿主或 MCP 后,**请在 Codex 的 `/hooks` 中审核新 Hook 并批准信任**。详见[安装、密钥与注册](docs/guide/zh-CN.md#安装)。
38
37
 
38
+ ## 更新
39
+
40
+ 如需更新通过 npm 全局安装的 Aptly 0.1.3 或更高版本,请先停止所有相关宿主、MCP 和 CLI 写入进程,并查阅[安装与升级指南](docs/guide/zh-CN.md#安装)中的账本迁移和手动备用步骤。现有密钥设置会保留,无需重新输入密钥。执行命令后请重启。
41
+
42
+ ```sh
43
+ aptly update
44
+ aptly setup --client all --mode defaults
45
+ ```
46
+
39
47
  ## 使用方式
40
48
 
41
49
  | 方式 | 行为 |
@@ -48,9 +56,8 @@ Aptly 0.1.4 起也会为继承调用评估推荐。应用仍要求 Codex 显式
48
56
 
49
57
  ## 文档
50
58
 
51
- - [CLI 配置](docs/guide/zh-CN.md#使用-cli-设置)
52
59
  - [使用指南](docs/guide/zh-CN.md):安装与移除、密钥、Hook、直接推荐、错误恢复
53
- - [安装与移除](docs/guide/zh-CN.md#安装):npm 全局安装、宿主注册、重启与信任批准
60
+ - [安装与移除](docs/guide/zh-CN.md#安装)及 [CLI 配置](docs/guide/zh-CN.md#使用-cli-设置):npm 全局安装、宿主注册、重启与信任批准
54
61
  - [模型与环境变量](docs/guide/zh-CN.md#模型与环境变量):六个默认配置与候选设置
55
62
  - [提供上下文](docs/guide/zh-CN.md#提供上下文):加密消息与仓库 URL 的限制
56
63
  - [成本实测](docs/guide/zh-CN.md#成本实测):README 翻译审阅的 token、换算成本与测量范围
@@ -1,5 +1,6 @@
1
1
  import { Router } from './core.ts';
2
2
  import type { HookOutput } from './hook.ts';
3
+ import type { Client } from './types.ts';
3
4
  export interface AutoPolicy {
4
5
  schema_version: 1;
5
6
  kind: 'aptly-auto-hook';
@@ -9,7 +10,7 @@ export interface AutoPolicy {
9
10
  state_directory: string;
10
11
  }
11
12
  export interface AutomaticHookObservation {
12
- status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending';
13
+ status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending' | 'awaiting_context' | 'blocked';
13
14
  preflight: 'observed';
14
15
  correlation_id?: string;
15
16
  classification: 'unknown' | 'evaluating' | 'not_requested' | 'provider_requested' | 'cache_hit' | 'local_outcome';
@@ -20,12 +21,39 @@ export interface AutomaticHookObservation {
20
21
  reason: string;
21
22
  profile_id?: string;
22
23
  request_id?: string;
24
+ retry_id?: string;
25
+ context_retry?: {
26
+ outcome?: {
27
+ status: string;
28
+ reason: string;
29
+ classification: string;
30
+ recommendation: 'produced' | 'not_produced';
31
+ application: 'blocked' | 'not_attempted';
32
+ request_id: string;
33
+ profile_id?: string;
34
+ };
35
+ last_attempt: {
36
+ status: string;
37
+ reason: string;
38
+ };
39
+ };
40
+ }
41
+ export interface ContextRetrySeed {
42
+ request_id: string;
43
+ client: Client;
44
+ eligible_profile_ids: string[];
45
+ policy_fingerprint: string;
46
+ application_blocked?: string;
47
+ fill_model?: boolean;
48
+ fill_effort?: boolean;
23
49
  }
24
50
  export interface AutomaticHookResult {
25
51
  output: HookOutput | {
26
52
  hookSpecificOutput: {
27
53
  hookEventName: 'PreToolUse';
28
54
  additionalContext: string;
55
+ permissionDecision?: 'deny';
56
+ permissionDecisionReason?: string;
29
57
  };
30
58
  };
31
59
  observation: AutomaticHookObservation;
@@ -45,6 +73,11 @@ export interface AutomaticHookOptions {
45
73
  signal?: AbortSignal;
46
74
  /** Internal diagnostics callback; never supplied through native tool arguments. */
47
75
  onObservation?: (observation: AutomaticHookObservation) => void;
76
+ /** Internal bounded recovery issuer; never supplied by native arguments. */
77
+ onNeedsContext?: (seed: ContextRetrySeed, current: () => string | undefined) => {
78
+ retry_id?: string;
79
+ reason?: string;
80
+ };
48
81
  /** A caller may revoke the pending event; absence does not certify native dispatch. */
49
82
  stillCurrent?: () => boolean | Promise<boolean>;
50
83
  }
@@ -60,4 +93,4 @@ export declare function automaticCallIdentity(client: unknown, event: unknown):
60
93
  export declare function automaticCallId(client: unknown, event: unknown): string | undefined;
61
94
  export declare function initialHookObservation(client: unknown, event: unknown): AutomaticHookObservation;
62
95
  /** Operator default selection only. No provenance_verified/evidence_verified host claim. */
63
- export declare function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation }: AutomaticHookOptions): Promise<AutomaticHookResult>;
96
+ export declare function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext }: AutomaticHookOptions): Promise<AutomaticHookResult>;
@@ -177,9 +177,23 @@ function bindCall(call, policy, policyFingerprint, catalog, contextDigest) {
177
177
  }
178
178
  }
179
179
  /** Operator default selection only. No provenance_verified/evidence_verified host claim. */
180
- export async function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation }) {
180
+ export async function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext }) {
181
181
  const observation = initialHookObservation(client, event);
182
- const preserve = (reason, request_id) => ({ output: {}, observation: { ...observation, status: 'preserved', reason, ...(request_id ? { request_id } : {}) } });
182
+ let activeMode;
183
+ const preserve = (reason, request_id) => {
184
+ const result = { output: {}, observation: { ...observation, status: 'preserved', reason, ...(request_id ? { request_id } : {}) } };
185
+ if (!activeMode || signal?.aborted || reason === 'call_cancelled')
186
+ return result;
187
+ // Respect an operator revocation rather than blocking under a disabled policy.
188
+ const currentPolicy = loadAutomaticHookPolicy(policyPath).policy;
189
+ if (!currentPolicy?.enabled)
190
+ return result;
191
+ const message = `Aptly could not select compatible subagent defaults (${reason}). Original arguments and execution constraints are preserved; no child execution is observed. Report this outcome. Do not repeat an uncertain paid request with a new ID or change history, explicit choices, roles or permissions to bypass this result.`;
192
+ result.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: message,
193
+ ...(currentPolicy.mode === 'defaults' ? { permissionDecision: 'deny', permissionDecisionReason: message } : {}) } };
194
+ result.observation.status = currentPolicy.mode === 'defaults' ? 'blocked' : 'preserved';
195
+ return result;
196
+ };
183
197
  try {
184
198
  const loaded = loadAutomaticHookPolicy(policyPath);
185
199
  if (!loaded.policy || !loaded.policy.enabled || !loaded.fingerprint)
@@ -199,14 +213,59 @@ export async function automaticHook({ client, event, router, policyPath, signal,
199
213
  // Synthetic fixture output must never select a native child's defaults.
200
214
  if (loaded.policy.mode === 'defaults' && router.policy.provider_id !== 'decisions')
201
215
  return preserve('synthetic_provider');
216
+ activeMode = loaded.policy.mode;
217
+ const needsContext = (reason, request_id) => {
218
+ if (!onNeedsContext)
219
+ return preserve(reason, request_id);
220
+ if (signal?.aborted)
221
+ return preserve('call_cancelled', request_id);
222
+ const currentPolicy = loadAutomaticHookPolicy(policyPath);
223
+ if (!currentPolicy.policy?.enabled || currentPolicy.fingerprint !== loaded.fingerprint)
224
+ return preserve('automatic_policy_changed', request_id);
225
+ const expectedContext = context?.();
226
+ const recovery = onNeedsContext({ request_id, client: call.client, eligible_profile_ids: profiles.map(profile => profile.id),
227
+ policy_fingerprint: loaded.fingerprint, application_blocked: applicationConstraint(call) ?? undefined,
228
+ fill_model: !hasModel, fill_effort: !hasEffort }, () => {
229
+ const latest = context?.();
230
+ if (latest?.reason)
231
+ return latest.reason;
232
+ if (latest?.fingerprint !== expectedContext?.fingerprint)
233
+ return 'context_changed';
234
+ const latestCall = readCall(client, event);
235
+ return latestCall?.payloadDigest === call.payloadDigest ? undefined : 'call_changed';
236
+ });
237
+ const instruction = recovery.retry_id
238
+ ? `Call Aptly retry_spawn_recommendation with retry_id "${recovery.retry_id}" and a short description of task purpose, scope, expected output and complexity. Use context you already have; ask the user only for genuinely missing information. One supplementation is allowed. Do not decode the opaque body or invent native call IDs. A recommendation is advice only: preserve explicit choices, roles, permissions and history; never change fork semantics to apply it. If application is blocked, report that limitation. Do not spawn while the retry still needs context or is unavailable.`
239
+ : `Context recovery is unavailable (${recovery.reason ?? 'context_retry_unavailable'}). Report the limitation; do not repeat the spawn unchanged.`;
240
+ const feedback = `Aptly needs additional task context (${reason}). ${instruction}`;
241
+ return { output: { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: feedback,
242
+ ...(loaded.policy.mode === 'defaults' ? { permissionDecision: 'deny', permissionDecisionReason: feedback } : {}) } },
243
+ observation: { ...observation, status: 'awaiting_context', reason, request_id, ...(recovery.retry_id ? { retry_id: recovery.retry_id } : {}) } };
244
+ };
202
245
  const supplied = context?.();
203
246
  if (supplied?.reason)
204
247
  return preserve(supplied.reason);
205
248
  const summary = supplied?.summary ? supplied : boundedSummary(call, router.policy.max_summary_bytes);
206
249
  if (Buffer.byteLength(summary.summary ?? '') > Math.min(4000, router.policy.max_summary_bytes))
207
250
  return preserve('insufficient_context');
208
- if (!summary.summary)
209
- return preserve(summary.reason ?? 'insufficient_context');
251
+ if (!summary.summary) {
252
+ if (summary.reason !== 'insufficient_context' || !onNeedsContext)
253
+ return preserve(summary.reason ?? 'insufficient_context');
254
+ if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
255
+ return preserve('call_cancelled');
256
+ const legacyId = hookInput({ client, event, policy: router.policy })?.request_id ?? hash([call.client, call.event.session_id, call.event.tool_use_id ?? call.event.tool_call_id]);
257
+ try {
258
+ router.load();
259
+ }
260
+ catch {
261
+ return preserve('ledger_error');
262
+ }
263
+ if (own(router.state.requests, legacyId))
264
+ return preserve('legacy_request_exists', legacyId);
265
+ // Reserve the same immutable native-call binding without making a paid request.
266
+ const bound = bindCall(call, loaded.policy, loaded.fingerprint, catalogFingerprint(router.policy), supplied?.fingerprint);
267
+ return bound.request_id ? needsContext('insufficient_context', bound.request_id) : preserve(bound.reason ?? 'automatic_state_unavailable');
268
+ }
210
269
  if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
211
270
  return preserve('call_cancelled');
212
271
  // Installing an operator policy must not bypass a historical strict-path
@@ -270,6 +329,8 @@ export async function automaticHook({ client, event, router, policyPath, signal,
270
329
  // The existing narrow catalog/tuple validator is reused. This local flag is an
271
330
  // operator-policy decision, never a claim about complete host-setting evidence.
272
331
  if (!profile || observation.recommendation !== 'produced') {
332
+ if (recommendation.status === 'needs_context')
333
+ return needsContext(recommendation.reason, request_id);
273
334
  const allowed = ['preserved_constraints', 'unsupported_profile', 'invalid_response', 'invalid_choice', 'provider_abstained', 'no_candidates', 'insufficient_context',
274
335
  'provider_needs_context', 'budget_exhausted', 'concurrency_limit', 'ledger_locked', 'request_conflict', 'outcome_unknown', 'ledger_error', 'timeout', 'refused',
275
336
  'truncated', 'invalid_json', 'unauthorized', 'rate_limited', 'network', 'provider_error', 'sensitive_input', 'invalid_input'];
@@ -279,7 +340,10 @@ export async function automaticHook({ client, event, router, policyPath, signal,
279
340
  if (blocked) {
280
341
  const kept = preserve(blocked, request_id);
281
342
  const next = blocked === 'effort_argument_unsupported' ? 'The caller must review the native reasoning_effort argument spelling; Aptly never rewrites an explicit choice.' : 'Inherited model/effort updates are not verified for this host. Verify the host version and native contract before enabling them; task arguments cannot certify support. Aptly never changes history automatically.';
282
- kept.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: `Aptly recommends ${profile.id}, but application is blocked (${blocked}). Original history and arguments are preserved; no child execution is observed. ${next}` } };
343
+ const message = `Aptly recommends ${profile.id}, but application is blocked (${blocked}). Original history and arguments are preserved; no child execution is observed. ${next} Report this constraint and stop this spawn; do not discard history or create a fresh child merely to apply the recommendation.`;
344
+ kept.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: message,
345
+ ...(activeMode === 'defaults' ? { permissionDecision: 'deny', permissionDecisionReason: message } : {}) } };
346
+ kept.observation.status = activeMode === 'defaults' ? 'blocked' : 'preserved';
283
347
  return kept;
284
348
  }
285
349
  const candidate = hookOutput({ client, event: snapshot, recommendation, mode: 'apply', compatibilityVerified: true, policy: router.policy, fillUnspecified: true });
@@ -0,0 +1,15 @@
1
+ import type { ContextRetrySeed } from './automatic-hook.ts';
2
+ import type { Router } from './core.ts';
3
+ /** One caller-supplied supplement, never an automatic native spawn or a retry chain. */
4
+ export declare class ContextRetries {
5
+ private entries;
6
+ private router;
7
+ private policyPath;
8
+ private now;
9
+ constructor(router: Router, policyPath: unknown, now?: () => number);
10
+ register(seed: ContextRetrySeed, current?: () => string | undefined): {
11
+ retry_id?: string;
12
+ reason?: string;
13
+ };
14
+ retry(retry_id: string, description: string, signal?: AbortSignal): Promise<Record<string, unknown>>;
15
+ }
@@ -0,0 +1,134 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, openSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { loadAutomaticHookPolicy } from './automatic-hook.js';
5
+ import { assertPrivateStatePath, readRegularFile } from './files.js';
6
+ const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
7
+ /** One caller-supplied supplement, never an automatic native spawn or a retry chain. */
8
+ export class ContextRetries {
9
+ entries = new Map();
10
+ router;
11
+ policyPath;
12
+ now;
13
+ constructor(router, policyPath, now = Date.now) { this.router = router; this.policyPath = policyPath; this.now = now; }
14
+ register(seed, current) {
15
+ try {
16
+ this.router.load();
17
+ const original = this.router.state.requests[seed.request_id];
18
+ if (original && (original.state !== 'complete' || original.result?.status !== 'needs_context'))
19
+ return { reason: original.state === 'unknown' ? 'outcome_unknown' : 'context_retry_not_eligible' };
20
+ }
21
+ catch {
22
+ return { reason: 'ledger_error' };
23
+ }
24
+ const retry_id = hash(['aptly-context-retry-v1', seed.request_id]);
25
+ const previous = this.entries.get(retry_id);
26
+ if (previous)
27
+ return { retry_id }; // No renewal or replacement of a ticket.
28
+ if (this.entries.size >= 128)
29
+ return { reason: 'context_retry_capacity' };
30
+ this.entries.set(retry_id, { seed: structuredClone(seed), at: this.now(), catalog: hash(this.router.policy), current });
31
+ return { retry_id };
32
+ }
33
+ async retry(retry_id, description, signal) {
34
+ const entry = this.entries.get(retry_id);
35
+ const unavailable = (reason) => ({ status: 'unavailable', reason, application: 'advisory_only', retry_id, context_retry_allowed: false });
36
+ if (!entry)
37
+ return unavailable('context_retry_not_found');
38
+ const check = () => {
39
+ if (entry.cancelled || signal?.aborted)
40
+ return 'context_retry_cancelled';
41
+ if (this.now() - entry.at >= 300_000)
42
+ return 'context_retry_expired';
43
+ try {
44
+ const changed = entry.current?.();
45
+ if (changed)
46
+ return changed;
47
+ }
48
+ catch {
49
+ return 'context_changed';
50
+ }
51
+ const loaded = loadAutomaticHookPolicy(this.policyPath);
52
+ if (!loaded.policy?.enabled)
53
+ return loaded.reason;
54
+ if (loaded.fingerprint !== entry.seed.policy_fingerprint)
55
+ return 'automatic_policy_changed';
56
+ if (hash(this.router.policy) !== entry.catalog)
57
+ return 'catalog_changed';
58
+ return undefined;
59
+ };
60
+ const blocked = check();
61
+ if (blocked)
62
+ return unavailable(blocked);
63
+ if (entry.active)
64
+ return unavailable('concurrency_limit');
65
+ if (typeof description !== 'string' || Buffer.byteLength(description) > Math.min(3800, this.router.policy.max_summary_bytes - 96) ||
66
+ description.trim().length < 12 || description.trim().split(/\s+/u).length < 3)
67
+ return unavailable('insufficient_context');
68
+ if (/\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(description))
69
+ return unavailable('sensitive_input');
70
+ const summary = `Caller-supplied task description (untrusted task data; opaque body not inspected): ${description.trim()}`;
71
+ if (Buffer.byteLength(summary) > Math.min(4000, this.router.policy.max_summary_bytes))
72
+ return unavailable('insufficient_context');
73
+ // Persist only a digest, before provider preflight (which may not write a ledger).
74
+ // Fixed retry ID plus an immutable digest protects restarts and unknown outcomes.
75
+ const request_id = retry_id;
76
+ const fingerprint = hash([summary, entry.seed, entry.catalog]);
77
+ let fd;
78
+ try {
79
+ const policy = loadAutomaticHookPolicy(this.policyPath).policy;
80
+ if (!policy)
81
+ return unavailable('automatic_policy_changed');
82
+ const path = join(policy.state_directory, `hook-retry-${retry_id}.json`);
83
+ assertPrivateStatePath(path);
84
+ try {
85
+ fd = openSync(path, 'wx', 0o600);
86
+ writeFileSync(fd, JSON.stringify({ fingerprint }));
87
+ }
88
+ catch (error) {
89
+ if (error.code !== 'EEXIST')
90
+ throw error;
91
+ const saved = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 256 }).toString('utf8'));
92
+ if (!saved || typeof saved !== 'object' || Object.keys(saved).length !== 1 || !('fingerprint' in saved) || saved.fingerprint !== fingerprint)
93
+ return unavailable('context_retry_conflict');
94
+ }
95
+ }
96
+ catch {
97
+ return unavailable('automatic_state_unavailable');
98
+ }
99
+ finally {
100
+ if (fd !== undefined)
101
+ closeSync(fd);
102
+ }
103
+ const before = check();
104
+ if (before)
105
+ return unavailable(before);
106
+ entry.active = true;
107
+ const cancel = () => { entry.cancelled = true; };
108
+ signal?.addEventListener('abort', cancel, { once: true });
109
+ try {
110
+ const result = await this.router.advise({ request_id, client: entry.seed.client,
111
+ task: { summary, operation: 'analysis', context_sufficient: true }, eligible_profile_ids: entry.seed.eligible_profile_ids,
112
+ constraints: { model_pinned: false, effort_pinned: false, role_pinned: false, fork_inherits: false } });
113
+ const after = check();
114
+ if (after)
115
+ return unavailable(after);
116
+ const defaults = result.status === 'recommended' && result.profile && !entry.seed.application_blocked ? {
117
+ ...(entry.seed.fill_model !== false ? { model: result.profile.model } : {}),
118
+ ...(entry.seed.client === 'codex' && entry.seed.fill_effort !== false && result.profile.reasoning_effort ? { reasoning_effort: result.profile.reasoning_effort } : {})
119
+ } : undefined;
120
+ return { ...result, retry_id, request_id, context_retry_allowed: false,
121
+ spawn_application: { status: entry.seed.application_blocked ? 'blocked' : 'caller_review_required',
122
+ reason: entry.seed.application_blocked ?? 'native_execution_not_observed' },
123
+ ...(defaults ? { next_call: { tool: entry.seed.client === 'claude' ? 'Agent' : 'spawn_agent', set_if_unspecified: defaults, preserve: 'all_other_arguments_and_history' } } : {}),
124
+ next_step: result.status === 'recommended'
125
+ ? entry.seed.application_blocked ? 'Report the application constraint and preserve original history and arguments. This profile is advice only.'
126
+ : `Context supplementation is complete; do not call retry_spawn_recommendation again. Caller review means the parent checks arguments, not a request for new user approval. To perform the already requested delegation, on the next native ${entry.seed.client === 'claude' ? 'Agent' : 'spawn_agent'} call, include these previously unspecified fields: ${JSON.stringify(defaults)}. Do not submit another model/effort-omitted call: it will be blocked again. Preserve all other arguments, explicit choices, history, roles and permissions. This response does not execute a child.`
127
+ : 'Stop this recovery attempt. Report the outcome; do not create another retry ID or spawn with an unresolved recommendation.' };
128
+ }
129
+ finally {
130
+ entry.active = false;
131
+ signal?.removeEventListener('abort', cancel);
132
+ }
133
+ }
134
+ }
@@ -7,8 +7,48 @@ export declare class RoutingObservations {
7
7
  private prune;
8
8
  record(value: AutomaticHookObservation): void;
9
9
  begin(client: unknown, event: unknown): void;
10
+ recordRetry(retry_id: string, result: Record<string, unknown>): void;
11
+ lookupRetry(retry_id: string): {
12
+ status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending' | 'awaiting_context' | 'blocked';
13
+ preflight: 'observed';
14
+ correlation_id?: string;
15
+ classification: 'unknown' | 'evaluating' | 'not_requested' | 'provider_requested' | 'cache_hit' | 'local_outcome';
16
+ recommendation: 'not_produced' | 'produced';
17
+ application: 'not_attempted' | 'blocked' | 'arguments_updated';
18
+ execution: 'not_observed';
19
+ constraint_provenance: 'unknown';
20
+ reason: string;
21
+ profile_id?: string;
22
+ request_id?: string;
23
+ retry_id?: string;
24
+ context_retry?: {
25
+ outcome?: {
26
+ status: string;
27
+ reason: string;
28
+ classification: string;
29
+ recommendation: 'produced' | 'not_produced';
30
+ application: 'blocked' | 'not_attempted';
31
+ request_id: string;
32
+ profile_id?: string;
33
+ };
34
+ last_attempt: {
35
+ status: string;
36
+ reason: string;
37
+ };
38
+ };
39
+ scope: string;
40
+ retention_seconds: number;
41
+ capacity: number;
42
+ } | {
43
+ scope: string;
44
+ retention_seconds: number;
45
+ capacity: number;
46
+ preflight: string;
47
+ reason: string;
48
+ execution: string;
49
+ };
10
50
  lookup(client: unknown, event: unknown): {
11
- status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending';
51
+ status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending' | 'awaiting_context' | 'blocked';
12
52
  preflight: 'observed';
13
53
  correlation_id?: string;
14
54
  classification: 'unknown' | 'evaluating' | 'not_requested' | 'provider_requested' | 'cache_hit' | 'local_outcome';
@@ -19,6 +59,22 @@ export declare class RoutingObservations {
19
59
  reason: string;
20
60
  profile_id?: string;
21
61
  request_id?: string;
62
+ retry_id?: string;
63
+ context_retry?: {
64
+ outcome?: {
65
+ status: string;
66
+ reason: string;
67
+ classification: string;
68
+ recommendation: 'produced' | 'not_produced';
69
+ application: 'blocked' | 'not_attempted';
70
+ request_id: string;
71
+ profile_id?: string;
72
+ };
73
+ last_attempt: {
74
+ status: string;
75
+ reason: string;
76
+ };
77
+ };
22
78
  scope: string;
23
79
  retention_seconds: number;
24
80
  capacity: number;
@@ -13,12 +13,43 @@ export class RoutingObservations {
13
13
  this.prune();
14
14
  if (!value.correlation_id)
15
15
  return;
16
+ const previous = this.entries.get(value.correlation_id);
17
+ const recovery = previous?.value.context_retry;
16
18
  this.entries.delete(value.correlation_id);
17
- this.entries.set(value.correlation_id, { at: this.now(), value: structuredClone(value) });
19
+ this.entries.set(value.correlation_id, { at: previous?.at ?? this.now(), value: structuredClone({ ...value,
20
+ ...(recovery ? { retry_id: previous.value.retry_id, context_retry: recovery } : {}) }) });
18
21
  while (this.entries.size > 128)
19
22
  this.entries.delete(this.entries.keys().next().value);
20
23
  }
21
24
  begin(client, event) { this.record(initialHookObservation(client, event)); }
25
+ recordRetry(retry_id, result) {
26
+ this.prune();
27
+ const entry = [...this.entries.values()].find(entry => entry.value.retry_id === retry_id);
28
+ if (!entry)
29
+ return;
30
+ const status = ['recommended', 'needs_context', 'unavailable', 'keep_current'].includes(String(result.status)) ? String(result.status) : 'unavailable';
31
+ const reason = typeof result.reason === 'string' && /^[a-z_]{1,64}$/.test(result.reason) ? result.reason : 'invalid_response';
32
+ const last_attempt = { status, reason };
33
+ const previous = entry.value.context_retry;
34
+ let outcome = previous?.outcome;
35
+ // Rejected duplicates/conflicts must not overwrite an earlier classification.
36
+ if (result.request_id === retry_id) {
37
+ const application = result.spawn_application;
38
+ outcome = { status, reason, request_id: retry_id,
39
+ classification: result.reason === 'outcome_unknown' ? 'unknown' : result.cached === true ? 'cache_hit' : typeof result.latency_ms === 'number' ? 'provider_requested' : 'local_outcome',
40
+ recommendation: status === 'recommended' ? 'produced' : 'not_produced',
41
+ application: application && typeof application === 'object' && 'status' in application && application.status === 'blocked' ? 'blocked' : 'not_attempted',
42
+ ...(typeof result.profile_id === 'string' && /^(codex|claude)-(simple|routine|deep)$/.test(result.profile_id) ? { profile_id: result.profile_id } : {}) };
43
+ }
44
+ // Keep the original timestamp and preflight stage; lookup never renews retention.
45
+ entry.value = { ...entry.value, context_retry: { ...(outcome ? { outcome } : {}), last_attempt } };
46
+ }
47
+ lookupRetry(retry_id) {
48
+ this.prune();
49
+ const entry = [...this.entries.values()].find(entry => entry.value.retry_id === retry_id);
50
+ return { scope: 'this_process_recent_calls', retention_seconds: 600, capacity: 128,
51
+ ...(entry ? structuredClone(entry.value) : { preflight: 'not_observed', reason: 'no_matching_observation', execution: 'not_observed' }) };
52
+ }
22
53
  lookup(client, event) {
23
54
  this.prune();
24
55
  const correlation_id = automaticCallId(client, event);
@@ -10,14 +10,21 @@ import { loadConfiguration, loadHostContext } from './config.js';
10
10
  import { automaticHook, loadAutomaticHookPolicy, initialHookObservation } from './automatic-hook.js';
11
11
  import { SpawnContexts } from './spawn-context.js';
12
12
  import { RoutingObservations } from './routing-observations.js';
13
+ import { ContextRetries } from './context-retry.js';
13
14
  const taskSchema = z.object({ summary: z.string().min(1).max(4000), operation: z.enum(['read_only', 'write', 'review', 'analysis']), context_sufficient: z.boolean() }).strict();
14
15
  const constraintsSchema = z.object({ model_pinned: z.boolean().optional(), effort_pinned: z.boolean().optional(), role_pinned: z.boolean().optional(), fork_inherits: z.boolean().optional(), provenance_verified: z.boolean().optional() }).strict();
15
16
  const hookSchema = { client: z.enum(['codex', 'claude']), event: z.record(z.string(), z.unknown()) };
17
+ const observationSchema = z.object({ client: hookSchema.client.optional(), event: hookSchema.event.optional(), retry_id: z.string().regex(/^[a-f0-9]{64}$/).optional() }).strict().superRefine((input, ctx) => {
18
+ const valid = input.retry_id !== undefined ? input.client === undefined && input.event === undefined : input.client !== undefined && input.event !== undefined;
19
+ if (!valid)
20
+ ctx.addIssue({ code: 'custom', message: 'Supply only {client,event} or only {retry_id}.' });
21
+ });
16
22
  const content = (result) => ({ content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
17
23
  export function createServer({ env = process.env } = {}) {
18
24
  const { router, mode, modelInfo, credentialStatus, disabledClients } = runtime(env);
19
25
  const observations = new RoutingObservations();
20
26
  const contexts = new SpawnContexts();
27
+ const retries = new ContextRetries(router, env.APTLY_HOOK_POLICY_PATH);
21
28
  const server = new McpServer({ name: 'aptly', version: VERSION });
22
29
  const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: mode === 'decisions' };
23
30
  const evidence = (client, event) => {
@@ -32,12 +39,13 @@ export function createServer({ env = process.env } = {}) {
32
39
  recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
33
40
  model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
34
41
  credential_status: credentialStatus,
35
- automatic_hook: { status: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).reason, mode: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).policy?.mode ?? 'disabled', host_settings_verified: false, context_tool: 'prepare_spawn_context', context_scope: 'this_process_exact_event_5_minutes', observation_tool: 'get_spawn_routing_observation', observation_scope: 'this_process_recent_calls', execution_observation: 'not_supported' },
42
+ automatic_hook: { status: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).reason, mode: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).policy?.mode ?? 'disabled', host_settings_verified: false, context_tool: 'prepare_spawn_context', context_scope: 'this_process_exact_event_5_minutes', context_retry_tool: 'retry_spawn_recommendation', context_retry_limit: 1, observation_tool: 'get_spawn_routing_observation', observation_scope: 'this_process_recent_calls', execution_observation: 'not_supported',
43
+ guarantee: { scope: 'enabled_trusted_connected_supported_hook_only', missing_hook_detectable: false, unavailable_host_hook: 'host_controls_fallback', eligible_defaults_failure: 'deny', inherited_application: 'defaults_deny_advisory_feedback', caller_recovery: 'model_driven_not_guaranteed' } },
36
44
  }));
37
45
  server.registerTool('get_spawn_routing_observation', {
38
- description: 'Look up one exact spawn event in this MCP process (128 calls, 10 minutes). No provider call. Missing records do not prove bypass; argument updates never prove native child execution.',
39
- annotations: { ...annotations, openWorldHint: false }, inputSchema: hookSchema
40
- }, async ({ client, event }) => content(observations.lookup(client, event)));
46
+ description: 'Look up an exact spawn event OR a Hook-issued retry_id in this MCP process (128 calls, 10 minutes). Supply only {client,event} or only {retry_id}. Original preflight and context_retry outcome are separate; no provider call. Missing records never prove bypass; execution remains not_observed.',
47
+ annotations: { ...annotations, openWorldHint: false }, inputSchema: observationSchema
48
+ }, async (input) => content(input.retry_id !== undefined ? observations.lookupRetry(input.retry_id) : observations.lookup(input.client, input.event)));
41
49
  server.registerTool('prepare_spawn_context', {
42
50
  description: 'Register a bounded untrusted description for an exact upcoming spawn event in this MCP process for five minutes. Requires enabled automatic policy. No provider call, file fetching, execution or permissions. The caller must know the real session/call IDs and exact original invocation; invented IDs do not connect to native Hooks.',
43
51
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
@@ -58,6 +66,20 @@ export function createServer({ env = process.env } = {}) {
58
66
  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,
59
67
  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() }
60
68
  }, async (input) => content({ ...await router.advise(input), provider: mode }));
69
+ server.registerTool('retry_spawn_recommendation', {
70
+ 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.',
71
+ annotations, inputSchema: { retry_id: z.string().regex(/^[a-f0-9]{64}$/), description: z.string().max(4000) }
72
+ }, async ({ retry_id, description }, extra) => {
73
+ let result;
74
+ try {
75
+ result = await retries.retry(retry_id, description, extra.signal);
76
+ }
77
+ catch {
78
+ result = { status: 'unavailable', reason: 'context_retry_unavailable', application: 'advisory_only', retry_id, context_retry_allowed: false };
79
+ }
80
+ observations.recordRetry(retry_id, result);
81
+ return content(result);
82
+ });
61
83
  server.registerTool('get_routing_precedence', {
62
84
  description: 'Explain preserved choices and unknown effective setting sources. Never classifies, reads a transcript, or changes permissions.', annotations: { ...annotations, openWorldHint: false }, inputSchema: hookSchema
63
85
  }, async ({ client, event }) => {
@@ -70,7 +92,7 @@ export function createServer({ env = process.env } = {}) {
70
92
  }, async ({ client, event, task }, extra) => {
71
93
  observations.begin(client, event);
72
94
  if (env.APTLY_HOOK_POLICY_PATH !== undefined) {
73
- const result = await automaticHook({ client, event, router, policyPath: env.APTLY_HOOK_POLICY_PATH, signal: extra.signal, context: () => contexts.lookup(client, event), onObservation: value => observations.record(value) });
95
+ const result = await automaticHook({ client, event, router, policyPath: env.APTLY_HOOK_POLICY_PATH, signal: extra.signal, context: () => contexts.lookup(client, event), onObservation: value => observations.record(value), onNeedsContext: (seed, current) => retries.register(seed, current) });
74
96
  observations.record(result.observation);
75
97
  return { content: [{ type: 'text', text: JSON.stringify(result.output) }] };
76
98
  }
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.4";
1
+ export declare const VERSION = "0.1.5";
@@ -1 +1 @@
1
- export const VERSION = '0.1.4';
1
+ export const VERSION = '0.1.5';
@@ -1,6 +1,8 @@
1
- # Explicit spawn context handoff (Aptly 0.1.4)
1
+ # Spawn context handoff and recovery
2
2
 
3
- Available from Aptly 0.1.4, following the pre-spawn routing changes in #60.
3
+ The original exact-event handoff is available from Aptly 0.1.4, following the
4
+ pre-spawn routing changes in #60. Context recovery and visible routing outcomes
5
+ are available from Aptly 0.1.5.
4
6
  It does not decode opaque messages, inspect conversations or modify host
5
7
  internals. It provides an explicit caller protocol, not an automatic description
6
8
  producer for the shipped Hook templates.
@@ -72,12 +74,12 @@ after the asynchronous provider call. Expiry/cancellation prevents output but
72
74
  cannot refund or erase a provider request already sent. Revocation does not
73
75
  cancel native execution; the host controls execution.
74
76
 
75
- There is no richer-summary retry mechanism in this change. Register before the
77
+ The original prepare_spawn_context handoff is immutable. Register before the
76
78
  first evaluation. If a label-only or description-bound evaluation already
77
79
  started, adding/changing the description fails closed (`call_conflict`);
78
80
  unknown paid outcomes remain unknown. Do not change IDs to bypass this guard.
79
- A future deliberate re-evaluation workflow needs its own explicit association
80
- and accounting design.
81
+ The 0.1.5 recovery protocol below provides a separate, bounded supplement;
82
+ it never rebinds this original association.
81
83
 
82
84
  ## Outcomes and evidence
83
85
 
@@ -123,4 +125,202 @@ This validates a caller that can capture the exact event before product
123
125
  preflight. The adapter does not ship an automatic description producer, and
124
126
  ordinary parent agents still cannot invent the required IDs. PR #60's separate
125
127
  history/model application acceptance and merge order must be resolved before
126
- merging this dependent change. No richer-summary retry workflow is enabled.
128
+ merging this dependent change. That historical test did not exercise the later recovery protocol below.
129
+
130
+
131
+ ## One context supplement after a Hook response
132
+
133
+ Available from Aptly 0.1.5.
134
+
135
+ When the enabled automatic Hook encounters local `insufficient_context` or a
136
+ completed provider `provider_needs_context`, it issues a `retry_id`. In
137
+ `defaults` mode it denies that pending spawn and includes model-visible recovery
138
+ instructions. In `advisory` mode it supplies those instructions without blocking.
139
+ This uses the documented [Codex PreToolUse deny feedback](https://learn.chatgpt.com/docs/hooks).
140
+ A missing, untrusted or failed Hook is outside this guarantee.
141
+
142
+ The parent agent can use its existing task knowledge to call:
143
+
144
+ ```json
145
+ {
146
+ "retry_id": "<copy the 64-character retry_id from the Hook response>",
147
+ "description": "Review a small synthetic refresh change for conflict markers and incorrect imports. Return findings only; do not edit files."
148
+ }
149
+ ```
150
+
151
+ Send this input to `retry_spawn_recommendation` on the same MCP process within
152
+ five minutes. No future native call ID is required. Describe purpose, scope,
153
+ expected output and complexity; ask the user only for information genuinely
154
+ missing from the task. The description uses the same size and known-secret
155
+ checks as the original handoff. Only the labelled description and normal
156
+ classification contract are sent, never the opaque body or original event.
157
+
158
+ One valid supplement is allowed per original immutable call binding. Its
159
+ classification request ID is fixed, and a description digest is persisted before
160
+ provider preflight; text is not persisted by Aptly. Duplicate input reuses the
161
+ ledger/cache. Changed input conflicts, including after process recreation.
162
+ Timeout/network/unknown outcomes never issue replacement identities. A second
163
+ `needs_context`, a budget failure or an unavailable result ends this recovery:
164
+ `context_retry_allowed` is false and no further recovery ticket is created. Each process
165
+ holds at most 128 tickets without eviction; duplicates do not extend expiry.
166
+ Restart loses ticket lookup, although persistent bindings and the ledger still
167
+ prevent a recreated original Hook event from creating another paid retry.
168
+
169
+ The retry tool returns advice, not a rewritten original Hook response or a native
170
+ spawn. For a recommendation, inspect `spawn_application`: `caller_review_required`
171
+ requires the parent to review and explicitly supply only unspecified model/effort
172
+ fields to a new compatible native call. Caller review means argument review,
173
+ not a request for new user approval. Existing delegation authorization and host
174
+ permission checks still apply; this advisory result grants neither.
175
+ The response supplies concrete fields in
176
+ `next_call.set_if_unspecified`, excluding original explicit choices. Claude
177
+ receives model only, never an effort field. Blocked results omit `next_call`. `blocked` requires reporting the original
178
+ history/application constraint. Never change `all` or omitted fork to `none`,
179
+ discard history, alter explicit choices or bypass permissions to apply advice.
180
+ If no recommendation is available, stop and report the result.
181
+
182
+ Cancellation during the retry, expiry, and changed/disabled policy or catalog
183
+ suppress its result. A sent request may still consume budget and complete in the
184
+ ledger. The original event observation remains `awaiting_context` with execution
185
+ `not_observed`; a retry recommendation does not prove child execution.
186
+
187
+ This is a caller-driven recovery protocol. Hook feedback does not itself run the
188
+ parent's next MCP call or spawn a child. It does not guarantee that every host or
189
+ parent model follows the instructions, and inherited application remains blocked.
190
+
191
+
192
+ ### Bounded native recovery verification — 2026-11-07
193
+
194
+ A local Codex CLI 0.167.0 trial exercised the pre-release recovery implementation with
195
+ its existing trusted Hook and ephemeral MCP command/environment overrides.
196
+ The parent was instructed to attempt one fresh child (`fork_turns: "none"`)
197
+ with no model/effort, a short synthetic task name and a message that the Hook
198
+ received as opaque. The Hook denied the call and returned recovery instructions.
199
+ The parent then called `retry_spawn_recommendation` through normal MCP tool
200
+ orchestration, supplying a bounded description of sorting `[3, 1, 2]` without
201
+ files, tools, network activity or changes.
202
+
203
+ The accepted retry ID matched the Hook feedback. Exactly one real Decisions
204
+ request contained the labelled description, without the opaque body or native
205
+ event metadata. It recommended `codex-simple` (`gpt-6-luna` / `max`). The parent
206
+ explicitly supplied that profile on its second native attempt, with the original
207
+ fresh-child semantics. The actual linked child recorded Luna/max and returned
208
+ `[1, 2, 3]`. Only one child was created. Neither Hook responses nor product
209
+ behavior were modified by the transparent observation adapter; persistent host
210
+ configuration and trust settings were unchanged, and temporary files were removed.
211
+
212
+ Three earlier attempts were retained as failures: each stopped before a paid
213
+ classification or child execution. Inspection of the nested MCP call established
214
+ that the recovery tool's initial write annotation required approval and was
215
+ rejected under `approvalPolicy: "never"`. The successful trial used the same
216
+ read-only advisory annotations as `recommend_agent`; local cache/budget metadata
217
+ is still recorded, and this is not a claim of stateless execution.
218
+
219
+ This is a prompt-guided caller recovery check, not proof that every parent model
220
+ will retry automatically. It does not validate inherited model application,
221
+ Claude Code native recovery, model quality or cost savings. Claude recovery,
222
+ provider abstention, duplicate/unknown outcomes and revocation are covered by
223
+ separate offline tests; they are not native execution evidence.
224
+
225
+
226
+ ## Visible routing outcomes and correlated recovery
227
+
228
+ Available from Aptly 0.1.5.
229
+
230
+ After establishing a valid enabled policy, a supported unpinned/default-selection
231
+ call and eligible profiles, `defaults` denies application incompatibilities and
232
+ classification failures instead of silently continuing with the original model.
233
+ The safe reason is model-visible. Budget exhaustion, unknown results and provider
234
+ errors do not authorize retrying with another identity. Cancellation of the host
235
+ request suppresses output; an operator-disabled policy stays disabled.
236
+
237
+ In particular, omitted or inherited Codex history still cannot apply a recommended
238
+ profile under the current verified contract. Defaults mode stops the spawn and
239
+ asks the parent to report that constraint. It does not silently rewrite history,
240
+ create a fresh child or execute the parent's defaults. Advisory mode remains
241
+ nonblocking feedback. Fully specified tuples, fixed roles and resumed agents
242
+ retain intentional local preservation without unnecessary paid classification.
243
+
244
+ The guarantee is limited to an enabled, trusted, connected and supported Hook.
245
+ The MCP server cannot intercept calls when the host does not invoke it. The
246
+ `automatic_hook.guarantee` capability describes this boundary and does not certify
247
+ installation, trust or dispatch. Missing/untrusted/unavailable Hooks remain a host
248
+ fallback condition, not a server-enforced block. See the official
249
+ [Codex Hook limitations](https://learn.chatgpt.com/docs/hooks) and
250
+ [Claude Code Hook reference](https://code.claude.com/docs/en/hooks).
251
+
252
+ A parent with a Hook-issued retry ID can query the existing observation tool:
253
+
254
+ ```text
255
+ get_spawn_routing_observation({retry_id})
256
+ ```
257
+
258
+ This is an alternative to `{client, event}`; the two forms are mutually exclusive
259
+ and partial forms are rejected. Both look up the same bounded process-local
260
+ record. Original preflight remains `awaiting_context`; `context_retry.outcome`
261
+ records the separately classified recovery and `context_retry.last_attempt`
262
+ records the latest retrieval/rejection. A conflicting or concurrent duplicate
263
+ does not erase an earlier classification. Only safe status/reason, classification,
264
+ recommendation/application state and allowlisted profile identity are retained in
265
+ this view, never the description, original event, policy or raw provider output.
266
+ Lookups make no paid calls or retention renewal. Missing/expired records do not
267
+ prove bypass, and execution remains `not_observed` throughout.
268
+
269
+
270
+ ### Ordinary Codex follow-through verification — 2026-11-07
271
+
272
+ A bounded native Codex CLI 0.167.0 trial used the existing trusted Hook with an
273
+ ephemeral product-server override and a transparent observer. The user prompt
274
+ requested a sorting delegation, a short synthetic task name and omitted model,
275
+ effort, fork and role fields. It did not describe the recovery tool, provide a
276
+ retry sequence or tell the parent how to supply a description after a denial.
277
+
278
+ The real opaque-body Hook invocation was denied for local context shortage.
279
+ The parent followed the Hook feedback and supplied a bounded description through
280
+ MCP. Exactly one real Decisions classification produced a recommendation, while
281
+ the original omitted-fork history constraint was returned as application blocked.
282
+ The parent reported the constraint without creating a child, switching to a
283
+ fresh fork or supplying a model to bypass it. The HTTP boundary recorder checked
284
+ that only the labelled description was shared as task text, without opaque body
285
+ or native event metadata. Persistent host configuration/trust stayed unchanged;
286
+ temporary files were removed.
287
+
288
+ This verifies one ordinary follow-through and a stopped inherited application,
289
+ not inherited-model compatibility, unconditional model compliance, a benchmark
290
+ or successful child execution. It does not recover evidence for the historical
291
+ reported session. The earlier fresh-child recovery verification is a separate
292
+ scenario and must not be substituted for this omitted-fork result.
293
+
294
+
295
+ ### Claude Code recovery and child verification — 2026-11-07
296
+
297
+ A native Claude Code 2.1.314 trial used an ephemeral copy of the installed Hook
298
+ settings, a temporary MCP server override and normal permission checks. The
299
+ parent received an ordinary sorting-delegation request with a short initial
300
+ Agent prompt and no initial model. The request explicitly distinguished that
301
+ initial unpinned omission from a user prohibition on later model selection. It
302
+ did not provide recovery tool names or an MCP retry sequence.
303
+
304
+ The first real Agent call was denied for insufficient context. The parent
305
+ supplied a description through MCP; exactly one real Decisions request selected
306
+ `claude-simple` / `haiku`. The retry returned concrete missing defaults under
307
+ `next_call.set_if_unspecified`. The parent submitted a second Agent call with
308
+ `model: "haiku"`. One actual child produced `[1, 2, 3]`; forwarded child messages
309
+ with parent-tool linkage recorded `claude-haiku-5-5`, also present in model usage.
310
+ The transparent observer did not modify Hook responses. Persistent settings and
311
+ MCP registration were unchanged, permission bypass was not used, and temporary
312
+ files were removed.
313
+
314
+ Earlier native attempts remain failures, not successes. Two stopped before any
315
+ Agent/classification under the previous login context. Four authenticated trials
316
+ reached recommendation but did not create a child: one resubmitted omitted
317
+ defaults, one answered inline, and two stopped without a second Agent call. The final retained assistant
318
+ report attributed its stop to interpreting the test's model-omission wording as
319
+ a user constraint. The contract was clarified with concrete missing
320
+ fields and `context_retry_allowed` (ending supplementation, not authorizing or
321
+ forbidding native execution), while the final prompt clarified only the initial
322
+ unpinned state. These trials are not a model-quality or cost comparison.
323
+
324
+ This verifies one caller-driven Claude recovery under explicit unpinned task
325
+ semantics. It does not guarantee every parent model follows feedback, change
326
+ host permission decisions, or establish inherited Codex application support.
package/docs/guide/en.md CHANGED
@@ -224,6 +224,7 @@ For genuinely independent work, the caller can intentionally choose a fresh chil
224
224
  | `get_spawn_routing_observation` | Looks up one exact Hook invocation; never proves native execution |
225
225
  | `prepare_spawn_context` | Registers a bounded description for one exact upcoming invocation |
226
226
  | `cancel_spawn_context` | Revokes the description association, not native execution or a request already sent |
227
+ | `retry_spawn_recommendation` | Accepts one task-description supplement using a Hook-issued retry_id |
227
228
 
228
229
  ### Outbound data and disabling automatic sharing
229
230
 
@@ -245,6 +246,24 @@ An integration that knows the real upcoming session/call IDs and exact original
245
246
 
246
247
  Associations last five minutes, are immutable, and are limited to 128 per process. Changed, expired or cancelled associations block routing; an already evaluated call cannot acquire a richer-summary retry or new paid identity. A caller unable to obtain the actual upcoming event cannot use this handoff; shipped Hooks do not create descriptions or call IDs. Local `insufficient_context`, provider `provider_needs_context`, and native `inherited_context_application_unverified` are distinct. The [handoff contract](../SPAWN_CONTEXT.md) records a bounded native description-handoff check. It does not establish automatic description production or execution of the recommended model.
247
248
 
249
+ ### Retry with additional context (0.1.5+)
250
+
251
+ When the automatic Hook returns `insufficient_context` or `provider_needs_context`, it provides a `retry_id` and recovery instructions. In `defaults` mode it denies that spawn; in `advisory` mode it only supplies feedback. The parent should describe purpose, scope, expected output and complexity using context it already has, then call `retry_spawn_recommendation({retry_id, description})` on the same MCP process within five minutes. No future native call ID is needed. Ask the user only for genuinely missing information.
252
+
253
+ One supplement is allowed per original call. Duplicate input reuses the cache; changed descriptions conflict. Stop if the retry still needs context or fails; never replace an uncertain paid request with a new ID. If `spawn_application` is `blocked`, report the constraint without applying the profile. Otherwise the parent must preserve explicit choices, history, roles and permissions when passing only unspecified model/effort to a new compatible native call. The Hook does not itself perform the parent's retry or native execution. The original `prepare_spawn_context` association stays immutable. See the [limits, costs and validation contract](../SPAWN_CONTEXT.md#one-context-supplement-after-a-hook-response).
254
+
255
+ The retry response includes `next_call.set_if_unspecified` with concrete fields for the next native call. It excludes already specified model/effort fields and never adds Claude effort. Blocked history/application results omit `next_call`. These fields are neither execution evidence nor permission approval.
256
+
257
+ `context_retry_allowed: false` ends further context supplementation. For a compatible recommendation, `caller_review_required` means the parent reviews arguments; it does not request new user approval. Existing delegation authorization and host permission checks still apply.
258
+
259
+ ### Automatic routing guarantees and blocked outcomes (0.1.5+)
260
+
261
+ The guarantee covers supported calls handled by an enabled, trusted Hook on a connected MCP process. Check `get_routing_capabilities.automatic_hook.guarantee` for this scope. The server cannot detect or enforce an absent, untrusted, disconnected or host-failed Hook; the host controls fallback. MCP connection status alone is not per-call routing evidence.
262
+
263
+ After a valid enabled policy and eligible call are established, `defaults` returns a deny decision and a safe reason for incompatible application, budget exhaustion, classification failure or unknown outcomes. Original arguments and constraints remain intact, but that spawn does not proceed. For unverified inherited history, report the constraint instead of silently running parent defaults or switching to `none`. `advisory` describes the limit without blocking. Missing/disabled policy, explicit tuples, fixed roles and resume remain intentional local preservation paths rather than blanket denials.
264
+
265
+ With a recovery ID, use `get_spawn_routing_observation({retry_id})` on the same MCP process, or use the existing `{client, event}` form. Mixed or partial forms are rejected. Original `awaiting_context` and `context_retry.outcome` are separate stages; rejected duplicates appear under `last_attempt` without replacing an earlier classification outcome. Lookups incur no paid request and do not renew retention. Execution always remains `not_observed`; neither advice nor argument updates establish actual child execution.
266
+
248
267
  ## Direct recommendations
249
268
 
250
269
  The `recommend_agent` MCP tool and CLI `recommend` accept a task summary and recommend a profile. They do not spawn subagents. Pass this JSON as MCP tool arguments, or save it to a file and provide it to the CLI through standard input.
package/docs/guide/ja.md CHANGED
@@ -224,6 +224,7 @@ Codex の本文が不透明な場合、`cleanup_merged_worktrees` のような
224
224
  | `get_spawn_routing_observation` | 一致する Hook 呼び出しを照会し、native 実行を証明しません |
225
225
  | `prepare_spawn_context` | 正確に一致する予定呼び出しに上限付きの説明を登録します |
226
226
  | `cancel_spawn_context` | 説明の対応付けを取り消します。native 実行や送信済みリクエストは取り消しません |
227
+ | `retry_spawn_recommendation` | Hook が返す retry_id を使い、タスク説明を一度補って再推薦します |
227
228
 
228
229
  ### 外部送信と自動共有の無効化
229
230
 
@@ -245,6 +246,24 @@ Decisions には `client`、`task.summary`、`task.operation`、`task.context_su
245
246
 
246
247
  対応付けは5分間有効で変更不可、プロセスごとに最大128件です。入力変更・期限切れ・取消時は分類を止め、評価済みの呼び出しを説明変更で有料再試行しません。実際の予定イベントを取得できない呼び出し元は利用できません。標準 Hook は説明や呼び出し ID を作成しません。ローカルの `insufficient_context`、プロバイダーの `provider_needs_context`、適用時の `inherited_context_application_unverified` は別の結果です。限定的な native 説明受け渡しの検証は[契約](../SPAWN_CONTEXT.md)に記録しています。この検証は、説明の自動生成や推薦モデルの実行を証明するものではありません。
247
248
 
249
+ ### 文脈を補って再推薦する(0.1.5 以降)
250
+
251
+ 自動 Hook が `insufficient_context` または `provider_needs_context` を返すと、`retry_id` と補足手順を提示します。`defaults` ではその生成呼び出しを拒否し、`advisory` では案内だけを返します。親エージェントは既知の情報から目的・範囲・期待する出力・複雑さを短く説明し、5分以内に同じ MCP プロセスで `retry_spawn_recommendation({retry_id, description})` を呼んでください。将来の native 呼び出し ID は不要です。本当に情報が不足する場合だけユーザーに質問してください。
252
+
253
+ 元の呼び出しごとに補足は一度だけです。同じ入力はキャッシュを再利用し、説明の変更は競合として拒否します。再推薦も文脈不足または失敗なら終了し、結果不明の有料要求を新しい ID で繰り返さないでください。`spawn_application` が `blocked` なら推薦を適用せず制約を報告してください。それ以外も親は明示的な選択・履歴・役割・権限を保ち、新しい互換 native 呼び出しに未指定のモデル・effort だけを渡す必要があります。Hook 自体が親の再要求や native 実行を行うわけではありません。元の `prepare_spawn_context` の対応付けは変更不可のままです。[制限・費用・検証契約](../SPAWN_CONTEXT.md#one-context-supplement-after-a-hook-response)を参照してください。
254
+
255
+ 再推薦の応答は `next_call.set_if_unspecified` に次の native 呼び出しで補う具体的な未指定フィールドを返します。明示済みのモデル・effort は含めず、Claude に effort を追加しません。履歴などで適用できない結果には `next_call` を返しません。実行証拠や権限承認ではありません。
256
+
257
+ `context_retry_allowed: false` は追加の文脈補足を終了する意味です。互換性のある推薦の `caller_review_required` は親が引数を確認する意味であり、新しいユーザー承認の要求ではありません。既存の委任権限とホストの権限確認は引き続き適用されます。
258
+
259
+ ### 自動ルーティングの保証範囲と拒否結果(0.1.5 以降)
260
+
261
+ 保証は、有効かつ信頼済みの Hook が接続中の MCP で処理する対応呼び出しに限ります。`get_routing_capabilities.automatic_hook.guarantee` で範囲を確認してください。サーバーは未登録・未信頼・切断・ホスト側で失敗した Hook を検出したり強制したりできず、その後の処理はホストが決めます。MCP の接続表示だけでは個別呼び出しの経由を証明できません。
262
+
263
+ 有効なポリシーと対象呼び出しを確認した後、`defaults` は適用不能・予算超過・分類失敗・結果不明を `deny` と安全な理由コードで返します。元の引数と制約は保持しますが、その生成は実行しません。継承履歴の互換性が未検証なら、親のデフォルトで黙って実行したり `none` に切り替えたりせず、制約を報告してください。`advisory` は拒否せず同じ制限を説明します。ポリシー未設定・無効、明示タプル・固定役割・resume は意図的なローカル保持経路であり、一律には拒否しません。
264
+
265
+ 復旧 ID があれば、同じ MCP プロセスで `get_spawn_routing_observation({retry_id})` を呼べます。従来の `{client, event}` 形式も使えますが、混在や不完全な入力は拒否します。元の `awaiting_context` と `context_retry.outcome` は別の段階です。拒否した重複要求は `last_attempt` に記録し、以前の分類結果を上書きしません。照会は有料要求を発行せず、保持期限も延長しません。実行は常に `not_observed` であり、推薦や引数更新は実際の子の実行証拠ではありません。
266
+
248
267
  ## 直接推薦
249
268
 
250
269
  `recommend_agent` MCP と CLI の `recommend` は、タスク要約を受け取ってプロファイルを推薦します。子エージェントを直接生成することはありません。以下の JSON を MCP ツールの引数として渡すか、ファイルに保存して CLI の標準入力に渡してください。
package/docs/guide/ko.md CHANGED
@@ -224,6 +224,7 @@ Codex 본문이 불투명할 때 `cleanup_merged_worktrees`처럼 구체적인
224
224
  | `get_spawn_routing_observation` | 정확히 일치하는 Hook 호출을 조회하며 native 실행을 증명하지 않습니다 |
225
225
  | `prepare_spawn_context` | 정확한 예정 호출에 제한된 설명을 등록합니다 |
226
226
  | `cancel_spawn_context` | 등록한 설명의 연결을 취소하며 native 실행이나 이미 전송된 요청을 취소하지 않습니다 |
227
+ | `retry_spawn_recommendation` | Hook의 `retry_id`로 작업 설명을 한 번 보충해 재추천합니다 |
227
228
 
228
229
  ### 외부 전송과 자동 공유 끄기
229
230
 
@@ -245,6 +246,24 @@ Decisions에는 `client`, `task.summary`, `task.operation`, `task.context_suffic
245
246
 
246
247
  연결은 5분간 유효하고 변경할 수 없으며 프로세스당 최대 128개입니다. 입력 변경·만료·취소 시 분류를 중단하고, 이미 평가한 호출에 설명을 바꿔 유료 재시도하지 않습니다. 실제 예정 이벤트를 알 수 없는 호출자는 사용할 수 없습니다. 기본 Hook은 설명이나 호출 ID를 만들지 않습니다. 로컬 `insufficient_context`, 공급자 `provider_needs_context`, 실제 적용의 `inherited_context_application_unverified`는 서로 다릅니다. 제한된 native 설명 전달 검증은 [전달 계약](../SPAWN_CONTEXT.md)에 기록했습니다. 이 검증은 기본 설명의 자동 생성이나 추천 모델의 실행을 증명하지 않습니다.
247
248
 
249
+ ### 맥락 보충 후 재추천 (0.1.5부터)
250
+
251
+ 자동 Hook이 `insufficient_context` 또는 `provider_needs_context`를 반환하면 `retry_id`와 보충 안내를 제공합니다. `defaults`에서는 해당 스폰을 차단하고, `advisory`에서는 안내만 전달합니다. 부모 에이전트는 이미 아는 작업 목적·범위·결과물·복잡도를 짧게 작성해 같은 MCP 프로세스에서 5분 안에 `retry_spawn_recommendation({retry_id, description})`를 호출하십시오. 미래 native 호출 ID는 필요하지 않습니다. 실제로 정보가 없을 때만 사용자에게 질문하십시오.
252
+
253
+ 보충은 원래 호출당 한 번이며 동일 입력은 캐시를 재사용하고 변경한 설명은 충돌로 거부합니다. 재추천도 `needs_context`이거나 실패하면 중단하십시오. 결과 불명인 요청을 새 ID로 반복하지 마십시오. `spawn_application`이 `blocked`이면 추천을 적용하지 말고 제약을 보고하십시오. 적용 가능한 추천도 부모가 명시 선택·이력·역할·권한을 보존하며 새 native 호출에 미지정 모델·effort만 전달해야 합니다. Hook이 부모의 재호출이나 실제 실행까지 자동 수행하지는 않습니다. 원래 `prepare_spawn_context` 연결은 여전히 변경할 수 없습니다. [한계·비용·검증 계약](../SPAWN_CONTEXT.md#one-context-supplement-after-a-hook-response)을 확인하십시오.
254
+
255
+ 재추천 응답의 `next_call.set_if_unspecified`는 다음 native 호출에 넣을 미지정 필드만 제공합니다. 명시한 모델·effort는 포함하지 않으며 Claude에는 effort를 추가하지 않습니다. 이력 등으로 적용이 막히면 `next_call`을 제공하지 않습니다. 이 값은 실행 결과나 권한 승인이 아닙니다.
256
+
257
+ `context_retry_allowed: false`는 추가 설명 보충을 더 허용하지 않는다는 뜻입니다. 호환 가능한 추천에서 `caller_review_required`는 부모가 인자를 검토한다는 의미이며 새 사용자 승인을 요구하지 않습니다. 기존 위임 권한과 호스트 권한 검사는 그대로 유지됩니다.
258
+
259
+ ### 자동 경유의 보장 범위와 차단 결과 (0.1.5부터)
260
+
261
+ 활성화되고 신뢰된 Hook이 연결된 MCP에서 지원 호출을 처리하는 범위만 보장합니다. `get_routing_capabilities.automatic_hook.guarantee`로 이 범위를 확인하십시오. Hook 미등록·미신뢰·연결 해제·호스트 오류는 서버가 탐지하거나 강제로 차단할 수 없으며 호스트가 후속 처리를 결정합니다. MCP 연결 표시만으로 개별 호출의 경유를 판단하지 마십시오.
262
+
263
+ 유효한 활성 정책과 지원 대상이 확인된 뒤, `defaults`는 추천 적용 불가·예산 초과·분류 실패·결과 불명 등을 `deny`와 안전한 사유 코드로 알립니다. 원래 인자와 제약은 유지하지만 해당 스폰은 진행하지 않습니다. 상속 이력이 미검증이면 부모 모델로 조용히 실행하거나 `none`으로 변경하지 말고 제약을 보고하십시오. `advisory`는 차단 없이 같은 한계를 설명합니다. 정책 미설정·비활성화, 명시 튜플·고정 역할·resume은 의도적인 로컬 보존 경로이며 일괄 차단하지 않습니다.
264
+
265
+ 복구 ID가 있으면 `get_spawn_routing_observation({retry_id})`로 같은 MCP 프로세스의 관측을 조회할 수 있습니다. 또는 기존 `{client, event}`를 사용하십시오. 두 형식을 섞거나 일부만 보내면 거부합니다. 원래 `awaiting_context`와 `context_retry.outcome`은 별개이며, 거부된 중복 요청은 `last_attempt`에 표시해 이전 분류 결과를 덮어쓰지 않습니다. 조회는 유료 요청을 만들지 않고 보관 시간을 연장하지 않습니다. 실행은 항상 `not_observed`이므로 추천이나 인자 갱신을 실제 자식 실행으로 표현하지 마십시오.
266
+
248
267
  ## 직접 추천
249
268
 
250
269
  `recommend_agent` MCP와 CLI `recommend`는 작업 요약을 받아 프로필을 추천합니다. 자식을 직접 생성하지 않습니다. 아래 JSON을 MCP 도구 인자로 전달하거나 파일에 저장해 CLI의 표준 입력으로 제공하십시오.
@@ -224,6 +224,7 @@ Codex 正文不透明时,`cleanup_merged_worktrees` 等具体的短任务名
224
224
  | `get_spawn_routing_observation` | 查询完全匹配的 Hook 调用,不证明原生执行 |
225
225
  | `prepare_spawn_context` | 为完全匹配的待执行调用注册受限说明 |
226
226
  | `cancel_spawn_context` | 撤销说明关联,不取消原生执行或已发送的请求 |
227
+ | `retry_spawn_recommendation` | 使用 Hook 返回的 retry_id 补充一次任务说明并重新推荐 |
227
228
 
228
229
  ### 对外传输与关闭自动共享
229
230
 
@@ -245,6 +246,24 @@ Decisions 会收到 `client`、`task.summary`、`task.operation`、`task.context
245
246
 
246
247
  关联有效期为五分钟,不可修改,每个进程最多128项。输入变化、过期或撤销会阻止分类;不能通过修改说明对已评估调用进行付费重试。无法获取真实待执行事件的调用方不能使用此路径;默认 Hook 不生成说明或调用 ID。本地 `insufficient_context`、提供方 `provider_needs_context` 和应用阶段 `inherited_context_application_unverified` 是不同结果。有限的原生说明交接验证记录于[交接契约](../SPAWN_CONTEXT.md)。此验证不表示会自动生成说明或执行推荐的模型。
247
248
 
249
+ ### 补充上下文后重新推荐(0.1.5 起)
250
+
251
+ 自动 Hook 返回 `insufficient_context` 或 `provider_needs_context` 时,会提供 `retry_id` 和补充指引。`defaults` 模式会阻止该次派生调用,`advisory` 模式仅提供反馈。父代理应根据已知信息简要说明任务目的、范围、预期输出和复杂度,并在五分钟内通过同一 MCP 进程调用 `retry_spawn_recommendation({retry_id, description})`。无需提前知道 native 调用 ID。仅在确实缺少信息时询问用户。
252
+
253
+ 每个原始调用仅允许补充一次;相同输入复用缓存,修改说明会因冲突而被拒绝。再次需要上下文或失败时,请停止,不要为结果不明的付费请求更换 ID 重试。若 `spawn_application` 为 `blocked`,请报告限制,不要应用推荐。否则,父代理仍须保留显式选择、历史、角色和权限,仅将未指定的模型和 effort 传给新的兼容 native 调用。Hook 不会自行执行父代理的重试或派生操作。原有 `prepare_spawn_context` 关联仍不可修改。请参阅[限制、费用与验证契约](../SPAWN_CONTEXT.md#one-context-supplement-after-a-hook-response)。
254
+
255
+ 重新推荐的响应通过 `next_call.set_if_unspecified` 提供下一次 native 调用所需的未指定字段;不包含已显式指定的模型或 effort,也不会为 Claude 添加 effort。因历史等约束无法应用时,不提供 `next_call`。这些字段不是执行结果或权限批准。
256
+
257
+ `context_retry_allowed: false` 仅表示不再接受上下文补充。对于兼容的推荐,`caller_review_required` 表示父代理检查参数,并非要求用户重新批准。现有委派授权和宿主权限检查仍然有效。
258
+
259
+ ### 自动路由的保证范围与阻止结果(0.1.5 起)
260
+
261
+ 保证仅适用于已启用、已信任且连接到 MCP 的 Hook 所处理的受支持调用。请通过 `get_routing_capabilities.automatic_hook.guarantee` 查看范围。服务器无法检测或强制阻止未注册、未信任、断连或宿主出错的 Hook,后续处理由宿主决定。MCP 连接状态本身不是单次调用经过路由的证据。
262
+
263
+ 确认有效的启用策略和适用调用后,`defaults` 对无法应用推荐、预算耗尽、分类失败或结果不明返回 `deny` 和安全原因码。原始参数与约束保持不变,但本次派生不会执行。若继承历史的兼容性未验证,请报告限制,不要静默使用父模型或改为 `none`。`advisory` 仅说明限制,不阻止执行。策略缺失或停用、显式配置组合、固定角色及 resume 仍属于有意保留的本地路径,不会一律阻止。
264
+
265
+ 获得恢复 ID 后,可在同一 MCP 进程调用 `get_spawn_routing_observation({retry_id})`,或使用原有 `{client, event}` 格式。混用或不完整的输入会被拒绝。原始 `awaiting_context` 与 `context_retry.outcome` 是独立阶段;被拒绝的重复请求记录在 `last_attempt`,不会覆盖已有分类结果。查询不产生付费请求,也不延长保留时间。执行始终为 `not_observed`,推荐或参数更新都不能证明子代理已实际执行。
266
+
248
267
  ## 直接推荐
249
268
 
250
269
  `recommend_agent` MCP 与 CLI 的 `recommend` 接收任务摘要并推荐执行配置,不会直接创建子代理。请将以下 JSON 作为 MCP 工具参数传递,或保存为文件并通过 CLI 的标准输入提供。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aptly",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {