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.
@@ -1,8 +1,9 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { closeSync, openSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
- import { loadAutomaticHookPolicy } from './automatic-hook.js';
4
+ import { effectiveTransmission, loadAutomaticHookPolicy } from './automatic-hook.js';
5
5
  import { assertPrivateStatePath, readRegularFile } from './files.js';
6
+ import { hasSufficientTaskText } from './context-sufficiency.js';
6
7
  const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
7
8
  /** One caller-supplied supplement, never an automatic native spawn or a retry chain. */
8
9
  export class ContextRetries {
@@ -11,7 +12,34 @@ export class ContextRetries {
11
12
  policyPath;
12
13
  now;
13
14
  constructor(router, policyPath, now = Date.now) { this.router = router; this.policyPath = policyPath; this.now = now; }
15
+ current(entry, signal) {
16
+ if (entry.cancelled || signal?.aborted)
17
+ return 'context_retry_cancelled';
18
+ if (this.now() - entry.at >= 300_000)
19
+ return 'context_retry_expired';
20
+ try {
21
+ const changed = entry.current?.();
22
+ if (changed)
23
+ return changed;
24
+ }
25
+ catch {
26
+ return 'context_changed';
27
+ }
28
+ const loaded = loadAutomaticHookPolicy(this.policyPath);
29
+ if (!loaded.policy?.enabled)
30
+ return loaded.reason;
31
+ if (loaded.fingerprint !== entry.seed.policy_fingerprint)
32
+ return 'automatic_policy_changed';
33
+ if (['none', 'unselected'].includes(effectiveTransmission(loaded.policy)))
34
+ return 'automatic_transmission_disabled';
35
+ if (hash(this.router.policy) !== entry.catalog)
36
+ return 'catalog_changed';
37
+ return undefined;
38
+ }
14
39
  register(seed, current) {
40
+ const policy = loadAutomaticHookPolicy(this.policyPath);
41
+ if (!policy.policy?.enabled || policy.fingerprint !== seed.policy_fingerprint || ['none', 'unselected'].includes(effectiveTransmission(policy.policy)))
42
+ return { reason: 'automatic_policy_changed' };
15
43
  try {
16
44
  this.router.load();
17
45
  const original = this.router.state.requests[seed.request_id];
@@ -30,40 +58,44 @@ export class ContextRetries {
30
58
  this.entries.set(retry_id, { seed: structuredClone(seed), at: this.now(), catalog: hash(this.router.policy), current });
31
59
  return { retry_id };
32
60
  }
61
+ registerAdvice(seed, current) {
62
+ const policy = loadAutomaticHookPolicy(this.policyPath);
63
+ if (!policy.policy?.enabled || policy.fingerprint !== seed.policy_fingerprint || ['none', 'unselected'].includes(effectiveTransmission(policy.policy)))
64
+ return { reason: 'automatic_policy_changed' };
65
+ if (!seed.fresh_eligible || seed.application_blocked !== 'inherited_context_application_unverified')
66
+ return { reason: 'fresh_delegation_unsupported' };
67
+ try {
68
+ this.router.load();
69
+ const record = this.router.state.requests[seed.request_id];
70
+ if (!record || record.state !== 'complete' || record.result?.status !== 'recommended')
71
+ return { reason: 'recommendation_not_available' };
72
+ }
73
+ catch {
74
+ return { reason: 'ledger_error' };
75
+ }
76
+ const retry_id = hash(['aptly-blocked-advice-v1', seed.request_id]);
77
+ if (this.entries.has(retry_id))
78
+ return { retry_id };
79
+ if (this.entries.size >= 128)
80
+ return { reason: 'context_retry_capacity' };
81
+ this.entries.set(retry_id, { seed: structuredClone(seed), at: this.now(), catalog: hash(this.router.policy), current, recommendation_id: seed.request_id });
82
+ return { retry_id };
83
+ }
33
84
  async retry(retry_id, description, signal) {
34
85
  const entry = this.entries.get(retry_id);
35
86
  const unavailable = (reason) => ({ status: 'unavailable', reason, application: 'advisory_only', retry_id, context_retry_allowed: false });
36
87
  if (!entry)
37
88
  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
- };
89
+ if (entry.recommendation_id)
90
+ return unavailable('context_retry_not_eligible');
91
+ const check = () => this.current(entry, signal);
60
92
  const blocked = check();
61
93
  if (blocked)
62
94
  return unavailable(blocked);
63
95
  if (entry.active)
64
96
  return unavailable('concurrency_limit');
65
97
  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)
98
+ !hasSufficientTaskText(description))
67
99
  return unavailable('insufficient_context');
68
100
  if (/\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(description))
69
101
  return unavailable('sensitive_input');
@@ -122,7 +154,7 @@ export class ContextRetries {
122
154
  reason: entry.seed.application_blocked ?? 'native_execution_not_observed' },
123
155
  ...(defaults ? { next_call: { tool: entry.seed.client === 'claude' ? 'Agent' : 'spawn_agent', set_if_unspecified: defaults, preserve: 'all_other_arguments_and_history' } } : {}),
124
156
  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.'
157
+ ? entry.seed.application_blocked ? `Report the application constraint and preserve original history and arguments for the ORIGINAL invocation. This profile is advice only. ${entry.seed.fresh_eligible ? 'This is the SAME task but a NEW invocation, not a retry of the original call. Use only the separate caller-declared preparation protocol offered below. Only after the host reports the original tool call blocked, if you can declare that this is the same independent task, the user does not require inherited history, and you can supply complete standalone instructions, call prepare_fresh_delegation with this retry_id, task_name, standalone_task and declaration {independent_task:true,same_task:true,original_call_outcome:"blocked",history_requirement:"not_required",standalone_context_complete:true}. It prepares a separate fresh invocation without a new classification. Never use it when history is required or unknown, or when original execution is unknown.' : ''}`
126
158
  : `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
159
  : 'Stop this recovery attempt. Report the outcome; do not create another retry ID or spawn with an unresolved recommendation.' };
128
160
  }
@@ -131,4 +163,82 @@ export class ContextRetries {
131
163
  signal?.removeEventListener('abort', cancel);
132
164
  }
133
165
  }
166
+ /** Caller-declared independent work only; never rewrites or executes the blocked call. */
167
+ prepareFresh(retry_id, task_name, standalone_task, declaration, signal) {
168
+ const reject = (reason) => ({ status: 'rejected', reason, application: 'advisory_only', source_retry_id: retry_id, execution: 'not_observed' });
169
+ const entry = this.entries.get(retry_id);
170
+ if (!entry)
171
+ return reject('context_retry_not_found');
172
+ const blocked = this.current(entry, signal);
173
+ if (blocked)
174
+ return reject(blocked);
175
+ if (entry.seed.client !== 'codex' || entry.seed.application_blocked !== 'inherited_context_application_unverified' || entry.seed.fresh_eligible !== true)
176
+ return reject('fresh_delegation_unsupported');
177
+ if (!declaration || declaration.history_requirement !== 'not_required')
178
+ return reject('history_requirement_preserved');
179
+ if (declaration.independent_task !== true)
180
+ return reject('independent_task_not_declared');
181
+ if (declaration.same_task !== true)
182
+ return reject('task_scope_changed');
183
+ if (declaration.original_call_outcome !== 'blocked')
184
+ return reject('original_execution_not_confirmed_blocked');
185
+ if (declaration.standalone_context_complete !== true)
186
+ return reject('standalone_context_incomplete');
187
+ if (typeof task_name !== 'string' || !task_name.trim() || Buffer.byteLength(task_name) > 128 || typeof standalone_task !== 'string' || Buffer.byteLength(standalone_task) > 12000 || !hasSufficientTaskText(standalone_task))
188
+ return reject('insufficient_context');
189
+ if (/\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(task_name + '\n' + standalone_task))
190
+ return reject('sensitive_input');
191
+ if (entry.active || this.router.active)
192
+ return reject('concurrency_limit');
193
+ try {
194
+ this.router.load();
195
+ const record = this.router.state.requests[entry.recommendation_id ?? retry_id];
196
+ if (!record)
197
+ return reject('recommendation_not_found');
198
+ if (record.state !== 'complete')
199
+ return reject('outcome_unknown');
200
+ const result = record.result;
201
+ this.router.validateOutcome(result);
202
+ if (result.status !== 'recommended' || !result.profile)
203
+ return reject('recommendation_not_available');
204
+ const profile = this.router.policy.profiles.find(p => p.id === result.profile_id);
205
+ if (!profile || !entry.seed.eligible_profile_ids.includes(profile.id) || hash(profile) !== hash(result.profile) || result.policy_version !== this.router.policy.version || result.catalog_version !== this.router.policy.catalog_version)
206
+ return reject('profile_changed');
207
+ const preparation_id = hash(['aptly-fresh-delegation-v1', retry_id]);
208
+ const fingerprint = hash([entry.seed, entry.catalog, profile, declaration, task_name, standalone_task]);
209
+ const policy = loadAutomaticHookPolicy(this.policyPath).policy;
210
+ if (!policy)
211
+ return reject('automatic_policy_changed');
212
+ const path = join(policy.state_directory, `hook-fresh-${preparation_id}.json`);
213
+ assertPrivateStatePath(path);
214
+ let fd;
215
+ try {
216
+ try {
217
+ fd = openSync(path, 'wx', 0o600);
218
+ writeFileSync(fd, JSON.stringify({ fingerprint }));
219
+ }
220
+ catch (error) {
221
+ if (error.code !== 'EEXIST')
222
+ throw error;
223
+ const previous = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 256 }).toString('utf8'));
224
+ if (!previous || typeof previous !== 'object' || Object.keys(previous).length !== 1 || !('fingerprint' in previous) || previous.fingerprint !== fingerprint)
225
+ return reject('fresh_delegation_conflict');
226
+ }
227
+ }
228
+ finally {
229
+ if (fd !== undefined)
230
+ closeSync(fd);
231
+ }
232
+ const changed = this.current(entry, signal);
233
+ if (changed)
234
+ return reject(changed);
235
+ return { status: 'prepared', reason: 'caller_declared_independent', application: 'advisory_only', source_retry_id: retry_id, preparation_id,
236
+ profile_id: profile.id, profile: structuredClone(profile), intent_provenance: 'caller_declared_not_verified', original_invocation: 'deny_returned_execution_not_observed', execution: 'not_observed',
237
+ next_call: { tool: 'spawn_agent', arguments: { task_name, message: standalone_task, fork_turns: 'none', model: profile.model, reasoning_effort: profile.reasoning_effort } },
238
+ next_step: 'Review and submit this separate native invocation only after a host-reported blocked outcome, under existing delegation authorization and unchanged host permissions. Original arguments were not rewritten; host execution is not observed by this server. Do not add history/role/resume overrides or reuse this preparation for another task. Preparation does not prove interception, permission approval, single execution or child execution.' };
239
+ }
240
+ catch {
241
+ return reject('fresh_delegation_unavailable');
242
+ }
243
+ }
134
244
  }
@@ -0,0 +1 @@
1
+ export declare function hasSufficientTaskText(text: string): boolean;
@@ -0,0 +1,24 @@
1
+ // A local screen for task text, not a guarantee of provider sufficiency.
2
+ const segmenter = new Intl.Segmenter('en', { granularity: 'word' });
3
+ export function hasSufficientTaskText(text) {
4
+ const trimmed = text.trim();
5
+ if ([...trimmed].length < 12)
6
+ return false;
7
+ // Numbers and repeated characters alone should not turn a vague request into
8
+ // a descriptive one. Identifiers still contribute their letter content.
9
+ const normalized = trimmed.normalize('NFKC').toLowerCase().replace(/(\p{L})\1{2,}/gu, '$1');
10
+ const content = [...normalized].filter(char => /\p{L}/u.test(char));
11
+ if (content.length < 8 || new Set(content).size < 6)
12
+ return false;
13
+ const compact = content.join('');
14
+ if (/^(.{1,20})\1+$/u.test(compact))
15
+ return false;
16
+ const words = [...segmenter.segment(normalized)].filter(part => part.isWordLike && /\p{L}/u.test(part.segment))
17
+ .map(part => part.segment);
18
+ if (new Set(words).size < 3)
19
+ return false;
20
+ // CJK prose and mixed CJK/identifier text do not require whitespace, but
21
+ // need more letter content and distinct word segments.
22
+ const cjk = content.filter(char => /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(char));
23
+ return cjk.length >= 2 ? content.length >= 12 : trimmed.split(/\s+/u).length >= 3;
24
+ }
@@ -7,6 +7,7 @@ export declare class RoutingObservations {
7
7
  private prune;
8
8
  record(value: AutomaticHookObservation): void;
9
9
  begin(client: unknown, event: unknown): void;
10
+ recordFresh(retry_id: string, result: Record<string, unknown>): void;
10
11
  recordRetry(retry_id: string, result: Record<string, unknown>): void;
11
12
  lookupRetry(retry_id: string): {
12
13
  status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending' | 'awaiting_context' | 'blocked';
@@ -36,6 +37,17 @@ export declare class RoutingObservations {
36
37
  reason: string;
37
38
  };
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
+ };
39
51
  scope: string;
40
52
  retention_seconds: number;
41
53
  capacity: number;
@@ -75,6 +87,17 @@ export declare class RoutingObservations {
75
87
  reason: string;
76
88
  };
77
89
  };
90
+ fresh_delegation?: {
91
+ outcome?: {
92
+ preparation_id: string;
93
+ profile_id: string;
94
+ };
95
+ last_attempt: {
96
+ status: string;
97
+ reason: string;
98
+ };
99
+ execution: 'not_observed';
100
+ };
78
101
  scope: string;
79
102
  retention_seconds: number;
80
103
  capacity: number;
@@ -15,13 +15,24 @@ export class RoutingObservations {
15
15
  return;
16
16
  const previous = this.entries.get(value.correlation_id);
17
17
  const recovery = previous?.value.context_retry;
18
+ const fresh = previous?.value.fresh_delegation;
18
19
  this.entries.delete(value.correlation_id);
19
20
  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 } : {}) }) });
21
+ ...(recovery ? { retry_id: previous.value.retry_id, context_retry: recovery } : {}), ...(fresh ? { retry_id: previous.value.retry_id, fresh_delegation: fresh } : {}) }) });
21
22
  while (this.entries.size > 128)
22
23
  this.entries.delete(this.entries.keys().next().value);
23
24
  }
24
25
  begin(client, event) { this.record(initialHookObservation(client, event)); }
26
+ recordFresh(retry_id, result) {
27
+ this.prune();
28
+ const entry = [...this.entries.values()].find(entry => entry.value.retry_id === retry_id);
29
+ if (!entry)
30
+ return;
31
+ const status = result.status === 'prepared' ? 'prepared' : 'rejected';
32
+ const reason = typeof result.reason === 'string' && /^[a-z_]{1,64}$/.test(result.reason) ? result.reason : 'invalid_response';
33
+ const outcome = status === 'prepared' && typeof result.preparation_id === 'string' && /^[a-f0-9]{64}$/.test(result.preparation_id) && typeof result.profile_id === 'string' && /^codex-(simple|routine|deep)$/.test(result.profile_id) ? { preparation_id: result.preparation_id, profile_id: result.profile_id } : entry.value.fresh_delegation?.outcome;
34
+ entry.value = { ...entry.value, fresh_delegation: { ...(outcome ? { outcome } : {}), last_attempt: { status, reason }, execution: 'not_observed' } };
35
+ }
25
36
  recordRetry(retry_id, result) {
26
37
  this.prune();
27
38
  const entry = [...this.entries.values()].find(entry => entry.value.retry_id === retry_id);
@@ -7,7 +7,7 @@ import { VERSION } from './version.js';
7
7
  import { hookInput, hookOutput } from './hook.js';
8
8
  import { resolveProvenance } from './provenance.js';
9
9
  import { loadConfiguration, loadHostContext } from './config.js';
10
- import { automaticHook, loadAutomaticHookPolicy, initialHookObservation } from './automatic-hook.js';
10
+ import { automaticHook, effectiveTransmission, loadAutomaticHookPolicy, initialHookObservation } from './automatic-hook.js';
11
11
  import { SpawnContexts } from './spawn-context.js';
12
12
  import { RoutingObservations } from './routing-observations.js';
13
13
  import { ContextRetries } from './context-retry.js';
@@ -33,15 +33,18 @@ export function createServer({ env = process.env } = {}) {
33
33
  const precedence = resolveProvenance({ client, event, context: loaded.context });
34
34
  return { config, loaded, precedence };
35
35
  };
36
- server.registerTool('get_routing_capabilities', { description: 'Advisory profile catalog, provider and local budget limits. No paid call.', annotations, inputSchema: {} }, async () => content({
37
- ...router.capabilities(), provider: mode, hook_mode: loadConfiguration(env).mode,
38
- precedence: 'per_call_effective_host_evidence_required', automatic_settings_discovery: false,
39
- recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
40
- model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
41
- credential_status: credentialStatus,
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' } },
44
- }));
36
+ server.registerTool('get_routing_capabilities', { description: 'Advisory profile catalog, provider and local budget limits. No paid call.', annotations, inputSchema: {} }, async () => {
37
+ const automatic = loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH);
38
+ return content({
39
+ ...router.capabilities(), provider: mode, hook_mode: loadConfiguration(env).mode,
40
+ precedence: 'per_call_effective_host_evidence_required', automatic_settings_discovery: false,
41
+ recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
42
+ model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
43
+ credential_status: credentialStatus,
44
+ automatic_hook: { status: automatic.reason, mode: automatic.policy?.mode ?? 'disabled', transmission: automatic.policy ? effectiveTransmission(automatic.policy) : null, transmission_provenance: automatic.policy ? (automatic.policy.schema_version === 1 ? 'legacy_v1_default' : 'operator_policy_v2') : 'unavailable', 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, fresh_delegation_tool: 'prepare_fresh_delegation', fresh_delegation_intent: 'caller_declared_not_verified', observation_tool: 'get_spawn_routing_observation', observation_scope: 'this_process_recent_calls', execution_observation: 'not_supported',
45
+ guarantee: { scope: 'enabled_trusted_connected_supported_hook_only', missing_hook_detectable: false, unavailable_host_hook: 'host_controls_fallback', eligible_defaults_failure: 'deny_when_transmission_enabled', inherited_application: 'defaults_deny_advisory_feedback', caller_recovery: 'model_driven_not_guaranteed' } },
46
+ });
47
+ });
45
48
  server.registerTool('get_spawn_routing_observation', {
46
49
  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
50
  annotations: { ...annotations, openWorldHint: false }, inputSchema: observationSchema
@@ -54,6 +57,8 @@ export function createServer({ env = process.env } = {}) {
54
57
  const policy = loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH);
55
58
  if (!policy.policy?.enabled)
56
59
  return content({ status: 'rejected', reason: policy.reason });
60
+ if (['none', 'unselected'].includes(effectiveTransmission(policy.policy)))
61
+ return content({ status: 'rejected', reason: 'automatic_transmission_disabled' });
57
62
  if (extra.signal.aborted)
58
63
  return content({ status: 'rejected', reason: 'context_cancelled' });
59
64
  return content(contexts.register(client, event, description, router.policy.max_summary_bytes));
@@ -80,6 +85,15 @@ export function createServer({ env = process.env } = {}) {
80
85
  observations.recordRetry(retry_id, result);
81
86
  return content(result);
82
87
  });
88
+ server.registerTool('prepare_fresh_delegation', {
89
+ description: 'Prepare a SEPARATE intentional Codex fresh-child call from a completed inherited recommendation. No classification or spawn. Use the original Hook retry_id on this process within five minutes. Only when the caller can declare independent work, no user-required inherited history, and complete standalone instructions. Never use for required/unknown history or to bypass permissions. Explicit choices and the original blocked invocation remain intact. Same task is idempotent; changed task conflicts.',
90
+ annotations: { ...annotations, openWorldHint: false }, inputSchema: { retry_id: z.string().regex(/^[a-f0-9]{64}$/), task_name: z.string().min(1).max(128), standalone_task: z.string().min(1).max(12000),
91
+ declaration: z.object({ independent_task: z.boolean(), same_task: z.boolean(), original_call_outcome: z.enum(['blocked', 'executed', 'unknown']), history_requirement: z.enum(['not_required', 'required', 'unknown']), standalone_context_complete: z.boolean() }).strict() }
92
+ }, async ({ retry_id, task_name, standalone_task, declaration }, extra) => {
93
+ const result = retries.prepareFresh(retry_id, task_name, standalone_task, declaration, extra.signal);
94
+ observations.recordFresh(retry_id, result);
95
+ return content(result);
96
+ });
83
97
  server.registerTool('get_routing_precedence', {
84
98
  description: 'Explain preserved choices and unknown effective setting sources. Never classifies, reads a transcript, or changes permissions.', annotations: { ...annotations, openWorldHint: false }, inputSchema: hookSchema
85
99
  }, async ({ client, event }) => {
@@ -92,7 +106,7 @@ export function createServer({ env = process.env } = {}) {
92
106
  }, async ({ client, event, task }, extra) => {
93
107
  observations.begin(client, event);
94
108
  if (env.APTLY_HOOK_POLICY_PATH !== undefined) {
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) });
109
+ 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), onBlockedAdvice: (seed, current) => retries.registerAdvice(seed, current) });
96
110
  observations.record(result.observation);
97
111
  return { content: [{ type: 'text', text: JSON.stringify(result.output) }] };
98
112
  }
@@ -6,13 +6,18 @@ export interface SetupOptions {
6
6
  automatic?: boolean;
7
7
  clients?: Client[];
8
8
  mode?: 'defaults' | 'advisory';
9
+ transmission?: TransmissionScope;
10
+ selectUnselectedOnly?: boolean;
9
11
  }
12
+ export type TransmissionScope = 'none' | 'description' | 'excerpt';
10
13
  export interface SetupClientResult {
11
14
  client: Client;
12
15
  status: 'configured' | 'unchanged' | 'removed' | 'skipped' | 'error';
13
16
  codes: string[];
14
17
  requires_hook_review?: boolean;
15
18
  recovery?: string[];
19
+ transmission?: string;
20
+ transmission_source?: 'explicit' | 'legacy' | 'unselected';
16
21
  }
17
22
  export interface SetupResult {
18
23
  status: 'complete' | 'partial' | 'skipped';
@@ -33,4 +38,26 @@ export declare function prepareCredentialReference(options: SetupOptions, client
33
38
  };
34
39
  /** Preserved standard registrations require a separate explicit opt-in; ownership stays unchanged. */
35
40
  export declare function migrateLauncher(options: SetupOptions, dryRun?: boolean, includeExisting?: boolean): SetupResult;
41
+ /** Explicit operator change; updates policy and its receipt through normal guarded staging. */
42
+ export declare function setTransmission(scope: TransmissionScope, options?: SetupOptions): SetupResult;
43
+ /** Read-only redacted policy state. Does not create host directories or contact a provider. */
44
+ export declare function showTransmission(options?: SetupOptions): {
45
+ clients: ({
46
+ client: Client;
47
+ status: string;
48
+ code: string;
49
+ application_mode?: undefined;
50
+ enabled?: undefined;
51
+ transmission?: undefined;
52
+ transmission_source?: undefined;
53
+ } | {
54
+ code?: undefined;
55
+ client: Client;
56
+ status: string;
57
+ application_mode: "advisory" | "defaults";
58
+ enabled: boolean;
59
+ transmission: import("./automatic-hook.ts").Transmission;
60
+ transmission_source: string;
61
+ })[];
62
+ };
36
63
  export {};
package/dist/src/setup.js CHANGED
@@ -6,6 +6,7 @@ import { randomUUID } from 'node:crypto';
6
6
  import { isDeepStrictEqual } from 'node:util';
7
7
  import { parse } from 'smol-toml';
8
8
  import { resolveCatalog } from './catalog.js';
9
+ import { loadAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
9
10
  import { assertPrivateStatePath } from './files.js';
10
11
  import { assertWindowsPrivatePath, protectNewWindowsPrivateDirectory, copyWindowsFilePermissions } from './windows-private.js';
11
12
  const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
@@ -188,7 +189,7 @@ function editEnvironment(current, edit, client) {
188
189
  updates.APTLY_SECRET_BACKEND = 'os';
189
190
  updates.APTLY_SECRET_CLIENT = client;
190
191
  }
191
- else if (!('migrate' in edit)) {
192
+ else if (!('migrate' in edit) && !('transmission' in edit)) {
192
193
  validateEnvironmentValue(edit.key, edit.value);
193
194
  updates[edit.key] = edit.value;
194
195
  }
@@ -442,12 +443,35 @@ function prepare(options, client, removing, edit) {
442
443
  if (existingRoute.length === 0)
443
444
  entries.push(hookValue);
444
445
  hooks.after = edit && 'migrate' in edit ? hooks.before : stringify(hooksObject);
445
- const preservedMode = edit && policy.before !== null ? json(policy.before).mode : undefined;
446
- const policyValue = { schema_version: 1, kind: 'aptly-auto-hook', mode: options.mode ?? (['defaults', 'advisory'].includes(preservedMode) ? preservedMode : 'defaults'), issuer: 'operator_installation', enabled: true, state_directory: stateDir };
446
+ const currentPolicy = policy.before === null ? undefined : loadAutomaticHookPolicy(policyPath).policy;
447
+ if (policy.before !== null && !currentPolicy)
448
+ fail('policy_conflict');
449
+ const requestedScope = options.transmission ?? (edit && 'transmission' in edit ? edit.transmission : undefined);
450
+ if (requestedScope !== undefined && !['none', 'description', 'excerpt'].includes(requestedScope))
451
+ fail('transmission_invalid_scope');
452
+ const preservedMode = edit && currentPolicy ? currentPolicy.mode : undefined;
453
+ const desiredMode = options.mode ?? preservedMode ?? currentPolicy?.mode ?? 'defaults';
454
+ // Existing v1 settings retain their original scope and byte representation.
455
+ // Only an explicit operator scope selection migrates them to v2.
456
+ let policyValue = currentPolicy ? { ...currentPolicy, mode: desiredMode } : {
457
+ schema_version: 2, kind: 'aptly-auto-hook', mode: desiredMode,
458
+ issuer: 'operator_installation', enabled: true, state_directory: stateDir, transmission: 'unselected',
459
+ };
460
+ if (requestedScope !== undefined) {
461
+ if (options.selectUnselectedOnly && (!currentPolicy || effectiveTransmission(currentPolicy) !== 'unselected'))
462
+ fail('transmission_selection_changed');
463
+ if (currentPolicy && (!oldOwner || !isDeepStrictEqual(currentPolicy, oldOwner.policy)))
464
+ fail('managed_policy_changed');
465
+ policyValue = { ...policyValue, schema_version: 2, transmission: requestedScope };
466
+ }
447
467
  if (policy.before !== null) {
448
- const p = json(policy.before);
449
- if (!isDeepStrictEqual(p, policyValue))
468
+ if (requestedScope === undefined && !isDeepStrictEqual(currentPolicy, policyValue))
469
+ fail('policy_conflict');
470
+ // An unrelated setup/env operation must never adopt externally modified policy.
471
+ if (oldOwner && !isDeepStrictEqual(currentPolicy, oldOwner.policy))
450
472
  fail('policy_conflict');
473
+ if (requestedScope !== undefined)
474
+ policy.after = stringify(policyValue);
451
475
  }
452
476
  else
453
477
  policy.after = stringify(policyValue);
@@ -488,10 +512,14 @@ function prepare(options, client, removing, edit) {
488
512
  if (priorEnv[key] === undefined)
489
513
  owner.env_added[key] = value;
490
514
  }
515
+ if (requestedScope !== undefined)
516
+ owner.policy = structuredClone(policyValue);
517
+ result.transmission = effectiveTransmission(policyValue);
518
+ result.transmission_source = policyValue.schema_version === 1 ? 'legacy' : policyValue.transmission === 'unselected' ? 'unselected' : 'explicit';
491
519
  manifest.after = stringify(owner);
492
520
  if (client === 'codex')
493
521
  result.requires_hook_review = true;
494
- result.codes = client === 'codex' ? ['requires_hook_review'] : [];
522
+ result.codes = [...(client === 'codex' ? ['requires_hook_review'] : []), ...(result.transmission === 'unselected' ? ['transmission_selection_required'] : result.transmission_source === 'legacy' ? ['legacy_transmission_excerpt'] : []), ...(requestedScope !== undefined ? ['mcp_restart_required'] : [])];
495
523
  dirs.push(dir, privateDir, stateDir);
496
524
  }
497
525
  // Validate complete desired data before any host file is changed.
@@ -507,15 +535,19 @@ function prepare(options, client, removing, edit) {
507
535
  /** Secure sibling staging is short-lived and never a backup; original settings stay in memory. */
508
536
  function replace(snapshot, forward) {
509
537
  const expected = forward ? snapshot.before : snapshot.after, next = forward ? snapshot.after : snapshot.before;
510
- if (read(snapshot.path).text !== expected)
511
- fail('concurrent_configuration_change');
538
+ const check = () => {
539
+ const current = read(snapshot.path);
540
+ if (current.text !== expected || (process.platform !== 'win32' && expected !== null && current.mode !== snapshot.mode))
541
+ fail('concurrent_configuration_change');
542
+ };
543
+ check();
512
544
  if (next === null) {
513
545
  if (expected !== null)
514
546
  unlinkSync(snapshot.path);
515
547
  return;
516
548
  }
517
549
  const stage = join(dirname(snapshot.path), `.aptly-stage-${randomUUID()}`);
518
- let fd;
550
+ let fd, staged = true;
519
551
  try {
520
552
  fd = openSync(stage, 'wx', 0o600);
521
553
  if (process.platform === 'win32' && expected !== null) {
@@ -529,21 +561,23 @@ function replace(snapshot, forward) {
529
561
  writeFileSync(fd, next);
530
562
  closeSync(fd);
531
563
  fd = undefined;
532
- if (read(snapshot.path).text !== expected)
533
- fail('concurrent_configuration_change');
564
+ if (process.platform !== 'win32')
565
+ chmodSync(stage, snapshot.mode);
566
+ check();
534
567
  renameSync(stage, snapshot.path);
535
- if (process.platform !== 'win32' && snapshot.mode !== 0o600)
536
- chmodSync(snapshot.path, snapshot.mode);
568
+ staged = false;
537
569
  }
538
570
  finally {
539
571
  if (fd !== undefined)
540
572
  closeSync(fd);
541
- try {
542
- unlinkSync(stage);
543
- }
544
- catch (e) {
545
- if (e.code !== 'ENOENT')
546
- throw e;
573
+ if (staged) {
574
+ try {
575
+ unlinkSync(stage);
576
+ }
577
+ catch (e) {
578
+ if (e.code !== 'ENOENT')
579
+ throw e;
580
+ }
547
581
  }
548
582
  }
549
583
  }
@@ -552,6 +586,8 @@ function execute(options, removing, edit, captured) {
552
586
  if (clients.some(client => client !== 'codex' && client !== 'claude'))
553
587
  return { status: 'partial', clients: [] };
554
588
  const env = options.env ?? process.env;
589
+ if (options.transmission !== undefined && !['none', 'description', 'excerpt'].includes(options.transmission))
590
+ return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['transmission_invalid_scope'] })) };
555
591
  if (!removing && options.automatic && (env.APTLY_SKIP_SETUP === '1' || !!env.CI))
556
592
  return { status: 'skipped', clients: clients.map(client => ({ client, status: 'skipped', codes: [env.APTLY_SKIP_SETUP === '1' ? 'setup_disabled' : 'ci_environment'] })) };
557
593
  const prepared = captured ?? clients.map(client => {
@@ -602,13 +638,16 @@ function execute(options, removing, edit, captured) {
602
638
  validateObservations(plan, written);
603
639
  }
604
640
  catch (e) {
605
- let rollbackConflict = false;
641
+ let rollbackConflict = false, rollbackFailure = false;
606
642
  for (const snapshot of written.reverse()) {
607
643
  try {
608
644
  replace(snapshot, false);
609
645
  }
610
- catch {
611
- rollbackConflict = true;
646
+ catch (error) {
647
+ if (safeCode(error) === 'concurrent_configuration_change')
648
+ rollbackConflict = true;
649
+ else
650
+ rollbackFailure = true;
612
651
  }
613
652
  }
614
653
  for (const path of madeDirs.reverse()) {
@@ -618,12 +657,12 @@ function execute(options, removing, edit, captured) {
618
657
  catch { /* Never remove another writer's files. */ }
619
658
  }
620
659
  plan.result.status = 'error';
621
- plan.result.codes = [safeCode(e), ...(rollbackConflict ? ['rollback_concurrent_change'] : [])];
660
+ plan.result.codes = [safeCode(e), ...(rollbackConflict ? ['rollback_concurrent_change'] : []), ...(rollbackFailure ? ['rollback_failed'] : [])];
622
661
  }
623
662
  }
624
663
  return { status: results.some(result => result.status === 'error') ? 'partial' : results.every(result => result.status === 'skipped') ? 'skipped' : 'complete', clients: results };
625
664
  }
626
- const codes = new Set(['launcher_migration_not_owned', 'launcher_migration_not_standard', 'credential_launcher_unverified', 'environment_invalid_value', 'environment_sensitive_value', 'environment_key_unsupported', 'environment_secret_key_unsupported', 'unsafe_directory', 'unsafe_symlink', 'unsafe_configuration_file', 'invalid_json', 'invalid_json_object', 'configuration_shape_conflict', 'hook_shape_conflict', 'invalid_toml', 'unsupported_toml_layout', 'relative_configuration_directory', 'invalid_ownership', 'managed_hook_changed', 'managed_mcp_changed', 'managed_entry_changed', 'managed_policy_changed', 'mcp_entry_conflict', 'mcp_environment_conflict', 'existing_routing_hook_conflict', 'policy_conflict', 'existing_hook_not_owned', 'concurrent_configuration_change', 'private_directory_permissions', 'private_file_permissions']);
665
+ const codes = new Set(['transmission_selection_changed', 'transmission_invalid_scope', 'launcher_migration_not_owned', 'launcher_migration_not_standard', 'credential_launcher_unverified', 'environment_invalid_value', 'environment_sensitive_value', 'environment_key_unsupported', 'environment_secret_key_unsupported', 'unsafe_directory', 'unsafe_symlink', 'unsafe_configuration_file', 'invalid_json', 'invalid_json_object', 'configuration_shape_conflict', 'hook_shape_conflict', 'invalid_toml', 'unsupported_toml_layout', 'relative_configuration_directory', 'invalid_ownership', 'managed_hook_changed', 'managed_mcp_changed', 'managed_entry_changed', 'managed_policy_changed', 'mcp_entry_conflict', 'mcp_environment_conflict', 'existing_routing_hook_conflict', 'policy_conflict', 'existing_hook_not_owned', 'concurrent_configuration_change', 'private_directory_permissions', 'private_file_permissions']);
627
666
  function safeCode(error) { return error instanceof Error && codes.has(error.message) ? error.message : 'configuration_io_error'; }
628
667
  export function setupHosts(options = {}) { return execute(options, false); }
629
668
  export function removeSetup(options = {}) { return execute(options, true); }
@@ -709,3 +748,26 @@ export function migrateLauncher(options, dryRun = false, includeExisting = false
709
748
  return { status: 'partial', clients: [{ client, status: 'error', codes: [safeCode(error)] }] };
710
749
  }
711
750
  }
751
+ /** Explicit operator change; updates policy and its receipt through normal guarded staging. */
752
+ export function setTransmission(scope, options = {}) {
753
+ if (!['none', 'description', 'excerpt'].includes(scope))
754
+ return { status: 'partial', clients: (options.clients ?? ['codex', 'claude']).map(client => ({ client, status: 'error', codes: ['transmission_invalid_scope'] })) };
755
+ return execute(options, false, { transmission: scope });
756
+ }
757
+ /** Read-only redacted policy state. Does not create host directories or contact a provider. */
758
+ export function showTransmission(options = {}) {
759
+ return { clients: (options.clients ?? ['codex', 'claude']).map(client => {
760
+ try {
761
+ const { privateDir } = resolved(options, client);
762
+ noSymlinks(privateDir);
763
+ const loaded = loadAutomaticHookPolicy(join(privateDir, 'auto-policy.json'));
764
+ if (!loaded.policy)
765
+ return { client, status: 'unavailable', code: loaded.reason };
766
+ return { client, status: 'configured', application_mode: loaded.policy.mode, enabled: loaded.policy.enabled,
767
+ transmission: effectiveTransmission(loaded.policy), transmission_source: loaded.policy.schema_version === 1 ? 'legacy' : effectiveTransmission(loaded.policy) === 'unselected' ? 'unselected' : 'explicit' };
768
+ }
769
+ catch (error) {
770
+ return { client, status: 'error', code: safeCode(error) };
771
+ }
772
+ }) };
773
+ }