aptly 0.1.4 → 0.1.6
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 +12 -5
- package/README.ja.md +12 -5
- package/README.md +12 -5
- package/README.zh-CN.md +12 -5
- package/dist/src/automatic-hook.d.ts +51 -2
- package/dist/src/automatic-hook.js +80 -6
- package/dist/src/context-retry.d.ts +29 -0
- package/dist/src/context-retry.js +236 -0
- package/dist/src/context-sufficiency.d.ts +1 -0
- package/dist/src/context-sufficiency.js +24 -0
- package/dist/src/routing-observations.d.ts +80 -1
- package/dist/src/routing-observations.js +43 -1
- package/dist/src/server.js +36 -5
- package/dist/src/setup.js +26 -17
- package/dist/src/spawn-context.js +2 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/windows-private.d.ts +2 -1
- package/dist/src/windows-private.js +37 -20
- package/docs/SPAWN_CONTEXT.md +305 -6
- package/docs/guide/en.md +28 -0
- package/docs/guide/ja.md +28 -0
- package/docs/guide/ko.md +28 -0
- package/docs/guide/zh-CN.md +28 -0
- package/package.json +1 -1
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.
|
|
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,51 @@ 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
|
+
fresh_delegation?: {
|
|
41
|
+
outcome?: {
|
|
42
|
+
preparation_id: string;
|
|
43
|
+
profile_id: string;
|
|
44
|
+
};
|
|
45
|
+
last_attempt: {
|
|
46
|
+
status: string;
|
|
47
|
+
reason: string;
|
|
48
|
+
};
|
|
49
|
+
execution: 'not_observed';
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export interface ContextRetrySeed {
|
|
53
|
+
request_id: string;
|
|
54
|
+
client: Client;
|
|
55
|
+
eligible_profile_ids: string[];
|
|
56
|
+
policy_fingerprint: string;
|
|
57
|
+
application_blocked?: string;
|
|
58
|
+
fill_model?: boolean;
|
|
59
|
+
fill_effort?: boolean;
|
|
60
|
+
fresh_eligible?: boolean;
|
|
23
61
|
}
|
|
24
62
|
export interface AutomaticHookResult {
|
|
25
63
|
output: HookOutput | {
|
|
26
64
|
hookSpecificOutput: {
|
|
27
65
|
hookEventName: 'PreToolUse';
|
|
28
66
|
additionalContext: string;
|
|
67
|
+
permissionDecision?: 'deny';
|
|
68
|
+
permissionDecisionReason?: string;
|
|
29
69
|
};
|
|
30
70
|
};
|
|
31
71
|
observation: AutomaticHookObservation;
|
|
@@ -45,6 +85,15 @@ export interface AutomaticHookOptions {
|
|
|
45
85
|
signal?: AbortSignal;
|
|
46
86
|
/** Internal diagnostics callback; never supplied through native tool arguments. */
|
|
47
87
|
onObservation?: (observation: AutomaticHookObservation) => void;
|
|
88
|
+
/** Internal bounded recovery issuer; never supplied by native arguments. */
|
|
89
|
+
onNeedsContext?: (seed: ContextRetrySeed, current: () => string | undefined) => {
|
|
90
|
+
retry_id?: string;
|
|
91
|
+
reason?: string;
|
|
92
|
+
};
|
|
93
|
+
onBlockedAdvice?: (seed: ContextRetrySeed, current: () => string | undefined) => {
|
|
94
|
+
retry_id?: string;
|
|
95
|
+
reason?: string;
|
|
96
|
+
};
|
|
48
97
|
/** A caller may revoke the pending event; absence does not certify native dispatch. */
|
|
49
98
|
stillCurrent?: () => boolean | Promise<boolean>;
|
|
50
99
|
}
|
|
@@ -60,4 +109,4 @@ export declare function automaticCallIdentity(client: unknown, event: unknown):
|
|
|
60
109
|
export declare function automaticCallId(client: unknown, event: unknown): string | undefined;
|
|
61
110
|
export declare function initialHookObservation(client: unknown, event: unknown): AutomaticHookObservation;
|
|
62
111
|
/** 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>;
|
|
112
|
+
export declare function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext, onBlockedAdvice }: AutomaticHookOptions): Promise<AutomaticHookResult>;
|
|
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
|
|
|
3
3
|
import { closeSync, openSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { isAbsolute, join } from 'node:path';
|
|
5
5
|
import { Router } from './core.js';
|
|
6
|
+
import { hasSufficientTaskText } from './context-sufficiency.js';
|
|
6
7
|
import { assertPrivateStatePath, readRegularFile } from './files.js';
|
|
7
8
|
import { hookInput, hookOutput, validatedHookProfile, profilePreservesChoices, effortKeys } from './hook.js';
|
|
8
9
|
import { digestToolInput } from './provenance.js';
|
|
@@ -125,7 +126,7 @@ function boundedSummary(call, maxBytes) {
|
|
|
125
126
|
return { summary };
|
|
126
127
|
}
|
|
127
128
|
const first = body.trim().split(/\r?\n\s*\r?\n/, 1)[0];
|
|
128
|
-
if (first
|
|
129
|
+
if (!hasSufficientTaskText(first) || (typeof label === 'string' && first.trim() === label.trim()))
|
|
129
130
|
return { reason: 'insufficient_context' };
|
|
130
131
|
const prefix = safeText(label, 512) ? `Task: ${label.trim()}\n` : '';
|
|
131
132
|
const budget = Math.min(4000, maxBytes) - Buffer.byteLength(prefix);
|
|
@@ -177,9 +178,23 @@ function bindCall(call, policy, policyFingerprint, catalog, contextDigest) {
|
|
|
177
178
|
}
|
|
178
179
|
}
|
|
179
180
|
/** Operator default selection only. No provenance_verified/evidence_verified host claim. */
|
|
180
|
-
export async function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation }) {
|
|
181
|
+
export async function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext, onBlockedAdvice }) {
|
|
181
182
|
const observation = initialHookObservation(client, event);
|
|
182
|
-
|
|
183
|
+
let activeMode;
|
|
184
|
+
const preserve = (reason, request_id) => {
|
|
185
|
+
const result = { output: {}, observation: { ...observation, status: 'preserved', reason, ...(request_id ? { request_id } : {}) } };
|
|
186
|
+
if (!activeMode || signal?.aborted || reason === 'call_cancelled')
|
|
187
|
+
return result;
|
|
188
|
+
// Respect an operator revocation rather than blocking under a disabled policy.
|
|
189
|
+
const currentPolicy = loadAutomaticHookPolicy(policyPath).policy;
|
|
190
|
+
if (!currentPolicy?.enabled)
|
|
191
|
+
return result;
|
|
192
|
+
const message = `Aptly could not select compatible subagent defaults (${reason}). Original arguments and execution constraints are preserved; no child execution is observed. Report this outcome. Do not repeat an uncertain paid request with a new ID or change history, explicit choices, roles or permissions to bypass this result.`;
|
|
193
|
+
result.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: message,
|
|
194
|
+
...(currentPolicy.mode === 'defaults' ? { permissionDecision: 'deny', permissionDecisionReason: message } : {}) } };
|
|
195
|
+
result.observation.status = currentPolicy.mode === 'defaults' ? 'blocked' : 'preserved';
|
|
196
|
+
return result;
|
|
197
|
+
};
|
|
183
198
|
try {
|
|
184
199
|
const loaded = loadAutomaticHookPolicy(policyPath);
|
|
185
200
|
if (!loaded.policy || !loaded.policy.enabled || !loaded.fingerprint)
|
|
@@ -199,14 +214,64 @@ export async function automaticHook({ client, event, router, policyPath, signal,
|
|
|
199
214
|
// Synthetic fixture output must never select a native child's defaults.
|
|
200
215
|
if (loaded.policy.mode === 'defaults' && router.policy.provider_id !== 'decisions')
|
|
201
216
|
return preserve('synthetic_provider');
|
|
217
|
+
activeMode = loaded.policy.mode;
|
|
218
|
+
const freshEligible = loaded.policy.mode === 'defaults' && call.client === 'codex' && (call.input.fork_turns === undefined || call.input.fork_turns === 'all') && Object.keys(call.input).every(key => ['task_name', 'message', 'fork_turns', 'model', 'reasoning_effort'].includes(key));
|
|
219
|
+
const reference = (request_id, issue) => {
|
|
220
|
+
const expectedContext = context?.();
|
|
221
|
+
return issue({ request_id, client: call.client, eligible_profile_ids: profiles.map(profile => profile.id),
|
|
222
|
+
policy_fingerprint: loaded.fingerprint, application_blocked: applicationConstraint(call) ?? undefined,
|
|
223
|
+
fill_model: !hasModel, fill_effort: !hasEffort,
|
|
224
|
+
...(freshEligible ? { fresh_eligible: true } : {}) }, () => {
|
|
225
|
+
const latest = context?.();
|
|
226
|
+
if (latest?.reason)
|
|
227
|
+
return latest.reason;
|
|
228
|
+
if (latest?.fingerprint !== expectedContext?.fingerprint)
|
|
229
|
+
return 'context_changed';
|
|
230
|
+
const latestCall = readCall(client, event);
|
|
231
|
+
return latestCall?.payloadDigest === call.payloadDigest ? undefined : 'call_changed';
|
|
232
|
+
});
|
|
233
|
+
};
|
|
234
|
+
const needsContext = (reason, request_id) => {
|
|
235
|
+
if (!onNeedsContext)
|
|
236
|
+
return preserve(reason, request_id);
|
|
237
|
+
if (signal?.aborted)
|
|
238
|
+
return preserve('call_cancelled', request_id);
|
|
239
|
+
const currentPolicy = loadAutomaticHookPolicy(policyPath);
|
|
240
|
+
if (!currentPolicy.policy?.enabled || currentPolicy.fingerprint !== loaded.fingerprint)
|
|
241
|
+
return preserve('automatic_policy_changed', request_id);
|
|
242
|
+
const recovery = reference(request_id, onNeedsContext);
|
|
243
|
+
const instruction = recovery.retry_id
|
|
244
|
+
? `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 all explicit user choices, roles, permissions and required history. Never rewrite the ORIGINAL invocation in place or resubmit it with changed history semantics to apply advice. If application is blocked, report that limitation. ${freshEligible ? 'A separate NEW invocation for the SAME independent task is supported ONLY through prepare_fresh_delegation if a later response offers it, under all of that response\'s conditions; do not invent a direct fresh call. This protocol does not change the original invocation or grant permissions.' : 'Do not create a fresh child to bypass this constraint.'} Do not spawn while the retry still needs context or is unavailable.`
|
|
245
|
+
: `Context recovery is unavailable (${recovery.reason ?? 'context_retry_unavailable'}). Report the limitation; do not repeat the spawn unchanged.`;
|
|
246
|
+
const feedback = `Aptly needs additional task context (${reason}). ${instruction}`;
|
|
247
|
+
return { output: { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: feedback,
|
|
248
|
+
...(loaded.policy.mode === 'defaults' ? { permissionDecision: 'deny', permissionDecisionReason: feedback } : {}) } },
|
|
249
|
+
observation: { ...observation, status: 'awaiting_context', reason, request_id, ...(recovery.retry_id ? { retry_id: recovery.retry_id } : {}) } };
|
|
250
|
+
};
|
|
202
251
|
const supplied = context?.();
|
|
203
252
|
if (supplied?.reason)
|
|
204
253
|
return preserve(supplied.reason);
|
|
205
254
|
const summary = supplied?.summary ? supplied : boundedSummary(call, router.policy.max_summary_bytes);
|
|
206
255
|
if (Buffer.byteLength(summary.summary ?? '') > Math.min(4000, router.policy.max_summary_bytes))
|
|
207
256
|
return preserve('insufficient_context');
|
|
208
|
-
if (!summary.summary)
|
|
209
|
-
|
|
257
|
+
if (!summary.summary) {
|
|
258
|
+
if (summary.reason !== 'insufficient_context' || !onNeedsContext)
|
|
259
|
+
return preserve(summary.reason ?? 'insufficient_context');
|
|
260
|
+
if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
|
|
261
|
+
return preserve('call_cancelled');
|
|
262
|
+
const legacyId = hookInput({ client, event, policy: router.policy })?.request_id ?? hash([call.client, call.event.session_id, call.event.tool_use_id ?? call.event.tool_call_id]);
|
|
263
|
+
try {
|
|
264
|
+
router.load();
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return preserve('ledger_error');
|
|
268
|
+
}
|
|
269
|
+
if (own(router.state.requests, legacyId))
|
|
270
|
+
return preserve('legacy_request_exists', legacyId);
|
|
271
|
+
// Reserve the same immutable native-call binding without making a paid request.
|
|
272
|
+
const bound = bindCall(call, loaded.policy, loaded.fingerprint, catalogFingerprint(router.policy), supplied?.fingerprint);
|
|
273
|
+
return bound.request_id ? needsContext('insufficient_context', bound.request_id) : preserve(bound.reason ?? 'automatic_state_unavailable');
|
|
274
|
+
}
|
|
210
275
|
if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
|
|
211
276
|
return preserve('call_cancelled');
|
|
212
277
|
// Installing an operator policy must not bypass a historical strict-path
|
|
@@ -270,6 +335,8 @@ export async function automaticHook({ client, event, router, policyPath, signal,
|
|
|
270
335
|
// The existing narrow catalog/tuple validator is reused. This local flag is an
|
|
271
336
|
// operator-policy decision, never a claim about complete host-setting evidence.
|
|
272
337
|
if (!profile || observation.recommendation !== 'produced') {
|
|
338
|
+
if (recommendation.status === 'needs_context')
|
|
339
|
+
return needsContext(recommendation.reason, request_id);
|
|
273
340
|
const allowed = ['preserved_constraints', 'unsupported_profile', 'invalid_response', 'invalid_choice', 'provider_abstained', 'no_candidates', 'insufficient_context',
|
|
274
341
|
'provider_needs_context', 'budget_exhausted', 'concurrency_limit', 'ledger_locked', 'request_conflict', 'outcome_unknown', 'ledger_error', 'timeout', 'refused',
|
|
275
342
|
'truncated', 'invalid_json', 'unauthorized', 'rate_limited', 'network', 'provider_error', 'sensitive_input', 'invalid_input'];
|
|
@@ -279,7 +346,14 @@ export async function automaticHook({ client, event, router, policyPath, signal,
|
|
|
279
346
|
if (blocked) {
|
|
280
347
|
const kept = preserve(blocked, request_id);
|
|
281
348
|
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
|
-
|
|
349
|
+
const fresh = blocked === 'inherited_context_application_unverified' && onBlockedAdvice ? reference(request_id, onBlockedAdvice) : undefined;
|
|
350
|
+
if (fresh?.retry_id)
|
|
351
|
+
kept.observation.retry_id = fresh.retry_id;
|
|
352
|
+
const continuation = fresh?.retry_id ? ` Only after the host reports this tool call blocked, if the task is independently declared, inherited history is not required by the user, and complete standalone instructions are available, prepare a SEPARATE fresh delegation with prepare_fresh_delegation using retry_id \"${fresh.retry_id}\". Never do this for required or unknown history, or unknown original execution.` : ' Do not create a fresh child merely to apply the recommendation.';
|
|
353
|
+
const message = `Aptly recommends ${profile.id}, but application is blocked (${blocked}). Original history and arguments are preserved; no child execution is observed. ${next} ${activeMode === 'defaults' ? 'Report this constraint and stop this ORIGINAL spawn.' : 'The host may still execute this original call under advisory policy; do not submit an additional call solely to apply the recommendation.'} Do not discard required history merely to apply the recommendation.${continuation}`;
|
|
354
|
+
kept.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: message,
|
|
355
|
+
...(activeMode === 'defaults' ? { permissionDecision: 'deny', permissionDecisionReason: message } : {}) } };
|
|
356
|
+
kept.observation.status = activeMode === 'defaults' ? 'blocked' : 'preserved';
|
|
283
357
|
return kept;
|
|
284
358
|
}
|
|
285
359
|
const candidate = hookOutput({ client, event: snapshot, recommendation, mode: 'apply', compatibilityVerified: true, policy: router.policy, fillUnspecified: true });
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ContextRetrySeed } from './automatic-hook.ts';
|
|
2
|
+
import type { Router } from './core.ts';
|
|
3
|
+
export interface FreshDeclaration {
|
|
4
|
+
independent_task: boolean;
|
|
5
|
+
same_task: boolean;
|
|
6
|
+
original_call_outcome: 'blocked' | 'executed' | 'unknown';
|
|
7
|
+
history_requirement: 'not_required' | 'required' | 'unknown';
|
|
8
|
+
standalone_context_complete: boolean;
|
|
9
|
+
}
|
|
10
|
+
/** One caller-supplied supplement, never an automatic native spawn or a retry chain. */
|
|
11
|
+
export declare class ContextRetries {
|
|
12
|
+
private entries;
|
|
13
|
+
private router;
|
|
14
|
+
private policyPath;
|
|
15
|
+
private now;
|
|
16
|
+
constructor(router: Router, policyPath: unknown, now?: () => number);
|
|
17
|
+
private current;
|
|
18
|
+
register(seed: ContextRetrySeed, current?: () => string | undefined): {
|
|
19
|
+
retry_id?: string;
|
|
20
|
+
reason?: string;
|
|
21
|
+
};
|
|
22
|
+
registerAdvice(seed: ContextRetrySeed, current?: () => string | undefined): {
|
|
23
|
+
retry_id?: string;
|
|
24
|
+
reason?: string;
|
|
25
|
+
};
|
|
26
|
+
retry(retry_id: string, description: string, signal?: AbortSignal): Promise<Record<string, unknown>>;
|
|
27
|
+
/** Caller-declared independent work only; never rewrites or executes the blocked call. */
|
|
28
|
+
prepareFresh(retry_id: string, task_name: string, standalone_task: string, declaration: FreshDeclaration, signal?: AbortSignal): Record<string, unknown>;
|
|
29
|
+
}
|