aptly 0.1.5 → 0.1.7

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
@@ -24,12 +24,12 @@ Requires Node.js **24 or later** and Claude Code or Codex. For first-time instal
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
- aptly setup --client all --mode defaults
27
+ aptly set default
28
28
  aptly set env OPENAI_API_KEY
29
29
  aptly --version
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
+ 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). From Aptly 0.1.7, new registrations make no automatic transmission until you select an OpenAI Decisions API transmission scope with `aptly set default`.
33
33
 
34
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.
35
35
 
@@ -41,7 +41,7 @@ To update an existing global npm installation running Aptly 0.1.3 or later, stop
41
41
 
42
42
  ```sh
43
43
  aptly update
44
- aptly setup --client all --mode defaults
44
+ aptly setup --client all
45
45
  ```
46
46
 
47
47
  ## Usage modes
package/README.ja.md CHANGED
@@ -24,12 +24,12 @@ Node.js **24 以上**と Claude Code または Codex が必要です。初めて
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
- aptly setup --client all --mode defaults
27
+ aptly set default
28
28
  aptly set env OPENAI_API_KEY
29
29
  aptly --version
30
30
  ```
31
31
 
32
- `aptly --version` でインストール済みのバージョンを確認してください。対応する npm では、`--allow-scripts=aptly` で Aptly のインストールスクリプトを許可します。このオプションに対応していない npm では、[インストール案内](docs/guide/ja.md#インストール)の明示的なインストール・設定手順に従ってください。
32
+ `aptly --version` でインストール済みのバージョンを確認してください。対応する npm では、`--allow-scripts=aptly` で Aptly のインストールスクリプトを許可します。このオプションに対応していない npm では、[インストール案内](docs/guide/ja.md#インストール)の明示的なインストール・設定手順に従ってください。 Aptly 0.1.7 以降、新規登録は自動送信せず、`aptly set default` で OpenAI Decisions API への送信範囲を選択します。
33
33
 
34
34
  インストール時の `postinstall` は、既存のホスト設定ディレクトリに MCP と `PreToolUse` Hook を登録します。自動登録をスキップした場合や、ホストに設定ディレクトリがまだない場合も、`setup` を明示的に実行して登録できます。他の既存設定・Hook と、既存の Aptly の実行コマンド・環境は保持します。
35
35
 
@@ -41,7 +41,7 @@ npm でグローバルインストール済みの Aptly 0.1.3 以降を更新す
41
41
 
42
42
  ```sh
43
43
  aptly update
44
- aptly setup --client all --mode defaults
44
+ aptly setup --client all
45
45
  ```
46
46
 
47
47
  ## 使用方法
package/README.md CHANGED
@@ -24,12 +24,12 @@ Node.js **24 이상**과 Claude Code 또는 Codex가 필요합니다. 처음 설
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
- aptly setup --client all --mode defaults
27
+ aptly set default
28
28
  aptly set env OPENAI_API_KEY
29
29
  aptly --version
30
30
  ```
31
31
 
32
- `aptly --version`으로 설치된 버전을 확인하십시오. `--allow-scripts=aptly`는 지원하는 npm에서 Aptly의 설치 스크립트를 허용합니다. 이 옵션을 지원하지 않는 npm은 [설치 안내](docs/guide/ko.md#설치)의 명시적 설치·설정 절차를 따르십시오.
32
+ `aptly --version`으로 설치된 버전을 확인하십시오. `--allow-scripts=aptly`는 지원하는 npm에서 Aptly의 설치 스크립트를 허용합니다. 이 옵션을 지원하지 않는 npm은 [설치 안내](docs/guide/ko.md#설치)의 명시적 설치·설정 절차를 따르십시오. Aptly 0.1.7부터 신규 등록의 자동 전송을 보류하며 `aptly set default`에서 OpenAI Decisions API 전송 범위를 선택합니다.
33
33
 
34
34
  설치 시 `postinstall`은 기존 호스트 설정 디렉터리에 MCP와 `PreToolUse` Hook을 등록합니다. 명시적인 `setup`은 자동 등록을 건너뛰었거나 아직 설정 디렉터리가 없는 호스트에도 사용할 수 있습니다. 기존 다른 설정·Hook과 기존 Aptly 실행 명령·환경은 보존합니다.
35
35
 
@@ -41,7 +41,7 @@ aptly --version
41
41
 
42
42
  ```sh
43
43
  aptly update
44
- aptly setup --client all --mode defaults
44
+ aptly setup --client all
45
45
  ```
46
46
 
47
47
  ## 사용 방식
package/README.zh-CN.md CHANGED
@@ -24,12 +24,12 @@ Aptly 使用 OpenAI Decisions API 对简要任务摘要进行分类,并推荐
24
24
 
25
25
  ```sh
26
26
  npm install -g aptly@latest --allow-scripts=aptly
27
- aptly setup --client all --mode defaults
27
+ aptly set default
28
28
  aptly set env OPENAI_API_KEY
29
29
  aptly --version
30
30
  ```
31
31
 
32
- 请使用 `aptly --version` 确认已安装的版本。在支持此选项的 npm 中,`--allow-scripts=aptly` 允许执行 Aptly 的安装脚本。如果 npm 不支持此选项,请按照[安装指南](docs/guide/zh-CN.md#安装)中的显式安装与配置步骤操作。
32
+ 请使用 `aptly --version` 确认已安装的版本。在支持此选项的 npm 中,`--allow-scripts=aptly` 允许执行 Aptly 的安装脚本。如果 npm 不支持此选项,请按照[安装指南](docs/guide/zh-CN.md#安装)中的显式安装与配置步骤操作。 从 Aptly 0.1.7 起,新注册不会自动传输;请通过 `aptly set default` 选择向 OpenAI Decisions API 传输的范围。
33
33
 
34
34
  安装时的 `postinstall` 会在现有宿主配置目录中注册 MCP 和 `PreToolUse` Hook。如果跳过了自动注册,或宿主尚无配置目录,也可以显式运行 `setup`。其他现有配置与 Hook,以及 Aptly 原有的启动命令和环境均会保留。
35
35
 
@@ -41,7 +41,7 @@ aptly --version
41
41
 
42
42
  ```sh
43
43
  aptly update
44
- aptly setup --client all --mode defaults
44
+ aptly setup --client all
45
45
  ```
46
46
 
47
47
  ## 使用方式
package/dist/bin/aptly.js CHANGED
@@ -9,8 +9,8 @@ import { collectDiagnostics } from '../src/diagnostics.js';
9
9
  import { exportDiagnosticReport } from '../src/report.js';
10
10
  import { fetchModelInfo, saveModelInfo } from '../src/model-info.js';
11
11
  import { errorCode } from '../src/types.js';
12
- import { setupHosts, removeSetup, setDefaults, setEnvironment, configurableEnvironmentKeys, migrateLauncher } from '../src/setup.js';
13
- import { readEnvironmentValue } from '../src/cli-input.js';
12
+ import { setupHosts, removeSetup, setDefaults, setEnvironment, configurableEnvironmentKeys, migrateLauncher, setTransmission, showTransmission } from '../src/setup.js';
13
+ import { readEnvironmentValue, readTransmissionChoice } from '../src/cli-input.js';
14
14
  import { prepareApiKey } from '../src/credential-setup.js';
15
15
  import { updateGlobalInstallation } from '../src/update.js';
16
16
  import { updateNotification } from '../src/update-notifier.js';
@@ -18,7 +18,7 @@ const [command = 'serve', ...args] = process.argv.slice(2);
18
18
  const output = (value) => process.stdout.write(JSON.stringify(value, null, 2) + '\n');
19
19
  try {
20
20
  if (['--help', '-h', 'help'].includes(command)) {
21
- process.stdout.write('Aptly (preview)\n\nCommands:\n serve Start the stdio MCP server (default: fixture/shadow).\n capabilities Print the active catalog; no API call.\n catalog Print the active catalog; no API call.\n catalog refresh --output ABS_PATH Fetch official model descriptions to a private cache.\n recommend Recommend for a task JSON on stdin; no host evidence required.\n inspect CLIENT FILE Inspect an explicit JSON settings inventory; no API call.\n config CLIENT Print an MCP registration fragment; does not edit settings.\n set default Add missing default MCP environment settings.\n set env ENV_KEY Prompt for an MCP environment value.\n setup Register MCP and automatic PreToolUse Hooks.\n remove Remove only unchanged Aptly-owned registration.\n update Update this verified global npm installation.\n report Write redacted local diagnostic attachments (default: md + json).\n --format md|json|both Select report formats.\n --output-dir DIR Private output directory (default: reports).\n --version Print the package version.\n\nUse aptly set env OPENAI_API_KEY for OS storage, or pass it through the MCP environment.\nPaid mode additionally requires\nROUTER_PROVIDER=decisions and an absolute ROUTER_LEDGER_PATH in a private directory.\nROUTER_CONFIG_PATH is an optional private operator configuration file.\n');
21
+ process.stdout.write('Aptly (preview)\n\nCommands:\n serve Start the stdio MCP server (default: fixture/shadow).\n capabilities Print the active catalog; no API call.\n catalog Print the active catalog; no API call.\n catalog refresh --output ABS_PATH Fetch official model descriptions to a private cache.\n recommend Recommend for a task JSON on stdin; no host evidence required.\n inspect CLIENT FILE Inspect an explicit JSON settings inventory; no API call.\n config CLIENT Print an MCP registration fragment; does not edit settings.\n set default Add defaults; select API transmission scope interactively.\n set transmission Set/show OpenAI Decisions API transmission scope.\n set env ENV_KEY Prompt for an MCP environment value.\n setup Register MCP and automatic PreToolUse Hooks.\n remove Remove only unchanged Aptly-owned registration.\n update Update this verified global npm installation.\n report Write redacted local diagnostic attachments (default: md + json).\n --format md|json|both Select report formats.\n --output-dir DIR Private output directory (default: reports).\n --version Print the package version.\n\nUse aptly set env OPENAI_API_KEY for OS storage, or pass it through the MCP environment.\nPaid mode additionally requires\nROUTER_PROVIDER=decisions and an absolute ROUTER_LEDGER_PATH in a private directory.\nROUTER_CONFIG_PATH is an optional private operator configuration file.\n');
22
22
  }
23
23
  else if (command === 'update') {
24
24
  if (args.length === 1 && args[0] === '--help')
@@ -54,7 +54,27 @@ try {
54
54
  }
55
55
  else if (command === 'set') {
56
56
  if (args.length === 1 && args[0] === '--help')
57
- process.stdout.write('Usage: aptly set default [--client codex|claude|all]\n aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]\n--check diagnoses OPENAI_API_KEY registration without reading or storing a key.\nValues are entered interactively with hidden input; --stdin explicitly reads a value from standard input. Existing defaults and launchers are preserved. OPENAI_API_KEY is stored in the OS credential store; host files contain references only. Restart MCP after changes.\n');
57
+ process.stdout.write('Usage: aptly set default [--client codex|claude|all]\n aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]\n aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]\n--check diagnoses OPENAI_API_KEY registration without reading or storing a key.\nValues are entered interactively with hidden input; --stdin explicitly reads a value from standard input. Existing defaults and launchers are preserved. OPENAI_API_KEY is stored in the OS credential store; host files contain references only. Restart MCP after changes.\n');
58
+ else if (args[0] === 'transmission') {
59
+ if (args[1] === '--help' && args.length === 2)
60
+ process.stdout.write('Usage: aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]\nControls automatic transmission to OpenAI Decisions, not developer telemetry. Direct recommendations are separate explicit requests. Restart MCP after changes.\n');
61
+ else {
62
+ const scope = args[1];
63
+ if (!['none', 'description', 'excerpt', '--show'].includes(scope))
64
+ throw new Error('set_invalid_options');
65
+ let clients = ['codex', 'claude'];
66
+ if (args.length !== 2) {
67
+ if (args.length !== 4 || args[2] !== '--client' || !['codex', 'claude', 'all'].includes(args[3]))
68
+ throw new Error('set_invalid_options');
69
+ clients = args[3] === 'all' ? ['codex', 'claude'] : [args[3]];
70
+ }
71
+ const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
72
+ const result = scope === '--show' ? showTransmission({ clients }) : setTransmission(scope, { clients, packageRoot });
73
+ output(result);
74
+ if ('status' in result && result.status === 'partial')
75
+ process.exitCode = 1;
76
+ }
77
+ }
58
78
  else {
59
79
  const action = args[0];
60
80
  let key;
@@ -105,7 +125,15 @@ try {
105
125
  try {
106
126
  if (action === 'env')
107
127
  value = await readEnvironmentValue({ key: key, fromStdin });
108
- const result = action === 'default' ? setDefaults({ clients, packageRoot }) : key === 'OPENAI_API_KEY' ? credential.apply(value) : setEnvironment(key, value, { clients, packageRoot });
128
+ let result = action === 'default' ? setDefaults({ clients, packageRoot }) : key === 'OPENAI_API_KEY' ? credential.apply(value) : setEnvironment(key, value, { clients, packageRoot });
129
+ if (action === 'default' && result.status === 'complete' && process.stdin.isTTY && process.stdout.isTTY) {
130
+ const pending = result.clients.filter(client => client.transmission === 'unselected').map(client => client.client);
131
+ if (pending.length) {
132
+ const scope = await readTransmissionChoice();
133
+ const selected = setTransmission(scope, { clients: pending, packageRoot, selectUnselectedOnly: true });
134
+ result = { status: selected.status, clients: result.clients.map(client => selected.clients.find(item => item.client === client.client) ?? client) };
135
+ }
136
+ }
109
137
  output(result);
110
138
  if (result.status === 'partial')
111
139
  process.exitCode = 1;
@@ -117,10 +145,11 @@ try {
117
145
  }
118
146
  else if (['setup', 'remove'].includes(command)) {
119
147
  if (args.length === 1 && args[0] === '--help')
120
- process.stdout.write('Usage: aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--automatic]\n aptly setup --client codex|claude --migrate-launcher [--include-existing] [--dry-run]\n aptly remove [--client codex|claude|all]\nSetup merges MCP and PreToolUse registration. Codex requires native /hooks trust review.\nAutomatic setup skips CI, APTLY_SKIP_SETUP=1, and absent host directories. No keys are stored.\n');
148
+ process.stdout.write('Usage: aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--transmission none|description|excerpt] [--automatic]\n aptly setup --client codex|claude --migrate-launcher [--include-existing] [--dry-run]\n aptly remove [--client codex|claude|all]\nSetup merges MCP and PreToolUse registration. Codex requires native /hooks trust review.\nAutomatic setup skips CI, APTLY_SKIP_SETUP=1, and absent host directories. No keys are stored.\n');
121
149
  else {
122
150
  let clients = ['codex', 'claude'];
123
- let mode = 'defaults';
151
+ let mode;
152
+ let transmission;
124
153
  let automatic = false;
125
154
  let migrate = false;
126
155
  let dryRun = false;
@@ -150,15 +179,17 @@ try {
150
179
  const value = args[++i];
151
180
  if (flag === '--client' && ['codex', 'claude', 'all'].includes(value))
152
181
  clients = value === 'all' ? ['codex', 'claude'] : [value];
182
+ else if (flag === '--transmission' && command === 'setup' && ['none', 'description', 'excerpt'].includes(value))
183
+ transmission = value;
153
184
  else if (flag === '--mode' && command === 'setup' && ['defaults', 'advisory'].includes(value))
154
185
  mode = value;
155
186
  else
156
187
  throw new Error('setup_invalid_options');
157
188
  }
158
189
  const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
159
- if ((migrate && (clients.length !== 1 || automatic || seen.has('--mode'))) || ((dryRun || includeExisting) && !migrate))
190
+ if ((migrate && (clients.length !== 1 || automatic || seen.has('--mode') || seen.has('--transmission'))) || ((dryRun || includeExisting) && !migrate))
160
191
  throw new Error('setup_invalid_options');
161
- const result = migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot }) : removeSetup({ clients });
192
+ const result = migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot, transmission }) : removeSetup({ clients });
162
193
  output(result);
163
194
  if (result.status === 'partial' && !automatic)
164
195
  process.exitCode = 1;
@@ -1,14 +1,21 @@
1
1
  import { Router } from './core.ts';
2
2
  import type { HookOutput } from './hook.ts';
3
3
  import type { Client } from './types.ts';
4
- export interface AutoPolicy {
5
- schema_version: 1;
4
+ interface AutoPolicyBase {
6
5
  kind: 'aptly-auto-hook';
7
6
  mode: 'defaults' | 'advisory';
8
7
  issuer: 'operator_installation';
9
8
  enabled: boolean;
10
9
  state_directory: string;
11
10
  }
11
+ export type Transmission = 'none' | 'description' | 'excerpt' | 'unselected';
12
+ export type AutoPolicy = AutoPolicyBase & ({
13
+ schema_version: 1;
14
+ } | {
15
+ schema_version: 2;
16
+ transmission: Transmission;
17
+ });
18
+ export declare function effectiveTransmission(policy: AutoPolicy): Transmission;
12
19
  export interface AutomaticHookObservation {
13
20
  status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending' | 'awaiting_context' | 'blocked';
14
21
  preflight: 'observed';
@@ -37,6 +44,17 @@ export interface AutomaticHookObservation {
37
44
  reason: string;
38
45
  };
39
46
  };
47
+ fresh_delegation?: {
48
+ outcome?: {
49
+ preparation_id: string;
50
+ profile_id: string;
51
+ };
52
+ last_attempt: {
53
+ status: string;
54
+ reason: string;
55
+ };
56
+ execution: 'not_observed';
57
+ };
40
58
  }
41
59
  export interface ContextRetrySeed {
42
60
  request_id: string;
@@ -46,6 +64,7 @@ export interface ContextRetrySeed {
46
64
  application_blocked?: string;
47
65
  fill_model?: boolean;
48
66
  fill_effort?: boolean;
67
+ fresh_eligible?: boolean;
49
68
  }
50
69
  export interface AutomaticHookResult {
51
70
  output: HookOutput | {
@@ -78,6 +97,10 @@ export interface AutomaticHookOptions {
78
97
  retry_id?: string;
79
98
  reason?: string;
80
99
  };
100
+ onBlockedAdvice?: (seed: ContextRetrySeed, current: () => string | undefined) => {
101
+ retry_id?: string;
102
+ reason?: string;
103
+ };
81
104
  /** A caller may revoke the pending event; absence does not certify native dispatch. */
82
105
  stillCurrent?: () => boolean | Promise<boolean>;
83
106
  }
@@ -93,4 +116,5 @@ export declare function automaticCallIdentity(client: unknown, event: unknown):
93
116
  export declare function automaticCallId(client: unknown, event: unknown): string | undefined;
94
117
  export declare function initialHookObservation(client: unknown, event: unknown): AutomaticHookObservation;
95
118
  /** Operator default selection only. No provenance_verified/evidence_verified host claim. */
96
- export declare function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext }: AutomaticHookOptions): Promise<AutomaticHookResult>;
119
+ export declare function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext, onBlockedAdvice }: AutomaticHookOptions): Promise<AutomaticHookResult>;
120
+ export {};
@@ -3,9 +3,13 @@ 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';
10
+ export function effectiveTransmission(policy) {
11
+ return policy.schema_version === 1 ? 'excerpt' : policy.transmission;
12
+ }
9
13
  const own = (object, key) => Object.hasOwn(object, key);
10
14
  const plain = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) &&
11
15
  [Object.prototype, null].includes(Object.getPrototypeOf(value));
@@ -19,14 +23,17 @@ export function loadAutomaticHookPolicy(path) {
19
23
  try {
20
24
  assertPrivateStatePath(path);
21
25
  const value = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 4096 }).toString('utf8'));
22
- if (!plain(value) || Object.keys(value).length !== policyKeys.length || Object.keys(value).some(key => !policyKeys.includes(key)) ||
23
- value.schema_version !== 1 || value.kind !== 'aptly-auto-hook' || (typeof value.mode !== 'string' || !['defaults', 'advisory'].includes(value.mode)) ||
26
+ if (!plain(value))
27
+ throw new Error('invalid_policy');
28
+ const keys = value.schema_version === 2 ? [...policyKeys, 'transmission'] : policyKeys;
29
+ if (Object.keys(value).length !== keys.length || Object.keys(value).some(key => !keys.includes(key)) ||
30
+ ![1, 2].includes(value.schema_version) || (value.schema_version === 2 && !['none', 'description', 'excerpt', 'unselected'].includes(value.transmission)) || value.kind !== 'aptly-auto-hook' || (typeof value.mode !== 'string' || !['defaults', 'advisory'].includes(value.mode)) ||
24
31
  value.issuer !== 'operator_installation' || typeof value.enabled !== 'boolean' ||
25
32
  typeof value.state_directory !== 'string' || !isAbsolute(value.state_directory))
26
33
  throw new Error('invalid_policy');
27
34
  // Validate an existing private state directory, without creating a path from untrusted event data.
28
35
  assertPrivateStatePath(join(value.state_directory, '.aptly-state-check'));
29
- const policy = Object.fromEntries(policyKeys.map(key => [key, value[key]]));
36
+ const policy = Object.fromEntries(keys.map(key => [key, value[key]]));
30
37
  return { policy, fingerprint: hash(policy), reason: policy.enabled ? 'automatic_policy_enabled' : 'automatic_policy_disabled' };
31
38
  }
32
39
  catch {
@@ -125,7 +132,7 @@ function boundedSummary(call, maxBytes) {
125
132
  return { summary };
126
133
  }
127
134
  const first = body.trim().split(/\r?\n\s*\r?\n/, 1)[0];
128
- if (first.length < 12 || first.trim().split(/\s+/u).length < 3 || (typeof label === 'string' && first.trim() === label.trim()))
135
+ if (!hasSufficientTaskText(first) || (typeof label === 'string' && first.trim() === label.trim()))
129
136
  return { reason: 'insufficient_context' };
130
137
  const prefix = safeText(label, 512) ? `Task: ${label.trim()}\n` : '';
131
138
  const budget = Math.min(4000, maxBytes) - Buffer.byteLength(prefix);
@@ -177,7 +184,7 @@ function bindCall(call, policy, policyFingerprint, catalog, contextDigest) {
177
184
  }
178
185
  }
179
186
  /** Operator default selection only. No provenance_verified/evidence_verified host claim. */
180
- export async function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext }) {
187
+ export async function automaticHook({ client, event, router, policyPath, signal, context, stillCurrent, onObservation, onNeedsContext, onBlockedAdvice }) {
181
188
  const observation = initialHookObservation(client, event);
182
189
  let activeMode;
183
190
  const preserve = (reason, request_id) => {
@@ -188,6 +195,10 @@ export async function automaticHook({ client, event, router, policyPath, signal,
188
195
  const currentPolicy = loadAutomaticHookPolicy(policyPath).policy;
189
196
  if (!currentPolicy?.enabled)
190
197
  return result;
198
+ if (['none', 'unselected'].includes(effectiveTransmission(currentPolicy))) {
199
+ result.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: `Aptly automatic routing is inactive (${effectiveTransmission(currentPolicy)}). Original arguments are preserved.` } };
200
+ return result;
201
+ }
191
202
  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
203
  result.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: message,
193
204
  ...(currentPolicy.mode === 'defaults' ? { permissionDecision: 'deny', permissionDecisionReason: message } : {}) } };
@@ -198,6 +209,10 @@ export async function automaticHook({ client, event, router, policyPath, signal,
198
209
  const loaded = loadAutomaticHookPolicy(policyPath);
199
210
  if (!loaded.policy || !loaded.policy.enabled || !loaded.fingerprint)
200
211
  return preserve(loaded.reason);
212
+ if (['none', 'unselected'].includes(effectiveTransmission(loaded.policy))) {
213
+ activeMode = loaded.policy.mode;
214
+ return preserve(`transmission_${effectiveTransmission(loaded.policy)}`);
215
+ }
201
216
  const call = readCall(client, event);
202
217
  if (!call)
203
218
  return preserve('invalid_event');
@@ -214,18 +229,13 @@ export async function automaticHook({ client, event, router, policyPath, signal,
214
229
  if (loaded.policy.mode === 'defaults' && router.policy.provider_id !== 'decisions')
215
230
  return preserve('synthetic_provider');
216
231
  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);
232
+ 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));
233
+ const reference = (request_id, issue) => {
225
234
  const expectedContext = context?.();
226
- const recovery = onNeedsContext({ request_id, client: call.client, eligible_profile_ids: profiles.map(profile => profile.id),
235
+ return issue({ request_id, client: call.client, eligible_profile_ids: profiles.map(profile => profile.id),
227
236
  policy_fingerprint: loaded.fingerprint, application_blocked: applicationConstraint(call) ?? undefined,
228
- fill_model: !hasModel, fill_effort: !hasEffort }, () => {
237
+ fill_model: !hasModel, fill_effort: !hasEffort,
238
+ ...(freshEligible ? { fresh_eligible: true } : {}) }, () => {
229
239
  const latest = context?.();
230
240
  if (latest?.reason)
231
241
  return latest.reason;
@@ -234,8 +244,18 @@ export async function automaticHook({ client, event, router, policyPath, signal,
234
244
  const latestCall = readCall(client, event);
235
245
  return latestCall?.payloadDigest === call.payloadDigest ? undefined : 'call_changed';
236
246
  });
247
+ };
248
+ const needsContext = (reason, request_id) => {
249
+ if (!onNeedsContext)
250
+ return preserve(reason, request_id);
251
+ if (signal?.aborted)
252
+ return preserve('call_cancelled', request_id);
253
+ const currentPolicy = loadAutomaticHookPolicy(policyPath);
254
+ if (!currentPolicy.policy?.enabled || currentPolicy.fingerprint !== loaded.fingerprint)
255
+ return preserve('automatic_policy_changed', request_id);
256
+ const recovery = reference(request_id, onNeedsContext);
237
257
  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.`
258
+ ? `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.`
239
259
  : `Context recovery is unavailable (${recovery.reason ?? 'context_retry_unavailable'}). Report the limitation; do not repeat the spawn unchanged.`;
240
260
  const feedback = `Aptly needs additional task context (${reason}). ${instruction}`;
241
261
  return { output: { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: feedback,
@@ -245,7 +265,8 @@ export async function automaticHook({ client, event, router, policyPath, signal,
245
265
  const supplied = context?.();
246
266
  if (supplied?.reason)
247
267
  return preserve(supplied.reason);
248
- const summary = supplied?.summary ? supplied : boundedSummary(call, router.policy.max_summary_bytes);
268
+ const summary = supplied?.summary ? supplied : effectiveTransmission(loaded.policy) === 'description'
269
+ ? { reason: 'insufficient_context' } : boundedSummary(call, router.policy.max_summary_bytes);
249
270
  if (Buffer.byteLength(summary.summary ?? '') > Math.min(4000, router.policy.max_summary_bytes))
250
271
  return preserve('insufficient_context');
251
272
  if (!summary.summary) {
@@ -253,6 +274,13 @@ export async function automaticHook({ client, event, router, policyPath, signal,
253
274
  return preserve(summary.reason ?? 'insufficient_context');
254
275
  if (signal?.aborted || (stillCurrent && await stillCurrent() !== true))
255
276
  return preserve('call_cancelled');
277
+ const currentPolicy = loadAutomaticHookPolicy(policyPath), currentCall = readCall(client, event), currentContext = context?.();
278
+ if (!currentPolicy.policy?.enabled || currentPolicy.fingerprint !== loaded.fingerprint)
279
+ return preserve('automatic_policy_changed');
280
+ if (!currentCall || currentCall.callKey !== call.callKey || currentCall.payloadDigest !== call.payloadDigest)
281
+ return preserve('call_changed');
282
+ if (currentContext?.reason || currentContext?.fingerprint !== supplied?.fingerprint)
283
+ return preserve(currentContext?.reason ?? 'context_changed');
256
284
  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
285
  try {
258
286
  router.load();
@@ -340,7 +368,11 @@ export async function automaticHook({ client, event, router, policyPath, signal,
340
368
  if (blocked) {
341
369
  const kept = preserve(blocked, request_id);
342
370
  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.';
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.`;
371
+ const fresh = blocked === 'inherited_context_application_unverified' && onBlockedAdvice ? reference(request_id, onBlockedAdvice) : undefined;
372
+ if (fresh?.retry_id)
373
+ kept.observation.retry_id = fresh.retry_id;
374
+ 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.';
375
+ 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}`;
344
376
  kept.output = { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: message,
345
377
  ...(activeMode === 'defaults' ? { permissionDecision: 'deny', permissionDecisionReason: message } : {}) } };
346
378
  kept.observation.status = activeMode === 'defaults' ? 'blocked' : 'preserved';
@@ -3,3 +3,5 @@ export declare function readEnvironmentValue({ key, fromStdin }: {
3
3
  key: string;
4
4
  fromStdin?: boolean;
5
5
  }): Promise<string>;
6
+ /** Operator choice of external transmission scope; Enter selects no automatic transmission. */
7
+ export declare function readTransmissionChoice(): Promise<'none' | 'description' | 'excerpt'>;
@@ -47,3 +47,36 @@ export async function readEnvironmentValue({ key, fromStdin = false }) {
47
47
  process.stdout.write('\n');
48
48
  }
49
49
  }
50
+ /** Operator choice of external transmission scope; Enter selects no automatic transmission. */
51
+ export async function readTransmissionChoice() {
52
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
53
+ throw fail('set_interactive_input_required');
54
+ process.stdout.write('Select task information sent to the OpenAI Decisions API (not Aptly developers).\nDescriptions and excerpts may contain sensitive information; this is not anonymization.\n 1. No automatic transmission (default)\n 2. Caller-provided descriptions only\n 3. Allow native task excerpts\n');
55
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
56
+ try {
57
+ return await new Promise((resolve, reject) => {
58
+ let settled = false;
59
+ const cancel = () => { if (!settled) {
60
+ settled = true;
61
+ reject(fail('set_input_cancelled'));
62
+ } };
63
+ rl.once('SIGINT', () => { cancel(); rl.close(); });
64
+ rl.once('close', cancel);
65
+ const ask = () => rl.question('Transmission scope [1]: ', value => {
66
+ const choices = { '': 'none', '1': 'none', '2': 'description', '3': 'excerpt', none: 'none', description: 'description', excerpt: 'excerpt' };
67
+ const scope = Object.hasOwn(choices, value.trim()) ? choices[value.trim()] : undefined;
68
+ if (!scope) {
69
+ process.stdout.write('Choose 1, 2 or 3.\n');
70
+ ask();
71
+ return;
72
+ }
73
+ settled = true;
74
+ resolve(scope);
75
+ });
76
+ ask();
77
+ });
78
+ }
79
+ finally {
80
+ rl.close();
81
+ }
82
+ }
@@ -1,5 +1,12 @@
1
1
  import type { ContextRetrySeed } from './automatic-hook.ts';
2
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
+ }
3
10
  /** One caller-supplied supplement, never an automatic native spawn or a retry chain. */
4
11
  export declare class ContextRetries {
5
12
  private entries;
@@ -7,9 +14,16 @@ export declare class ContextRetries {
7
14
  private policyPath;
8
15
  private now;
9
16
  constructor(router: Router, policyPath: unknown, now?: () => number);
17
+ private current;
10
18
  register(seed: ContextRetrySeed, current?: () => string | undefined): {
11
19
  retry_id?: string;
12
20
  reason?: string;
13
21
  };
22
+ registerAdvice(seed: ContextRetrySeed, current?: () => string | undefined): {
23
+ retry_id?: string;
24
+ reason?: string;
25
+ };
14
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>;
15
29
  }