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.
@@ -0,0 +1,236 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, openSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { loadAutomaticHookPolicy } from './automatic-hook.js';
5
+ import { assertPrivateStatePath, readRegularFile } from './files.js';
6
+ import { hasSufficientTaskText } from './context-sufficiency.js';
7
+ const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
8
+ /** One caller-supplied supplement, never an automatic native spawn or a retry chain. */
9
+ export class ContextRetries {
10
+ entries = new Map();
11
+ router;
12
+ policyPath;
13
+ now;
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 (hash(this.router.policy) !== entry.catalog)
34
+ return 'catalog_changed';
35
+ return undefined;
36
+ }
37
+ register(seed, current) {
38
+ try {
39
+ this.router.load();
40
+ const original = this.router.state.requests[seed.request_id];
41
+ if (original && (original.state !== 'complete' || original.result?.status !== 'needs_context'))
42
+ return { reason: original.state === 'unknown' ? 'outcome_unknown' : 'context_retry_not_eligible' };
43
+ }
44
+ catch {
45
+ return { reason: 'ledger_error' };
46
+ }
47
+ const retry_id = hash(['aptly-context-retry-v1', seed.request_id]);
48
+ const previous = this.entries.get(retry_id);
49
+ if (previous)
50
+ return { retry_id }; // No renewal or replacement of a ticket.
51
+ if (this.entries.size >= 128)
52
+ return { reason: 'context_retry_capacity' };
53
+ this.entries.set(retry_id, { seed: structuredClone(seed), at: this.now(), catalog: hash(this.router.policy), current });
54
+ return { retry_id };
55
+ }
56
+ registerAdvice(seed, current) {
57
+ if (!seed.fresh_eligible || seed.application_blocked !== 'inherited_context_application_unverified')
58
+ return { reason: 'fresh_delegation_unsupported' };
59
+ try {
60
+ this.router.load();
61
+ const record = this.router.state.requests[seed.request_id];
62
+ if (!record || record.state !== 'complete' || record.result?.status !== 'recommended')
63
+ return { reason: 'recommendation_not_available' };
64
+ }
65
+ catch {
66
+ return { reason: 'ledger_error' };
67
+ }
68
+ const retry_id = hash(['aptly-blocked-advice-v1', seed.request_id]);
69
+ if (this.entries.has(retry_id))
70
+ return { retry_id };
71
+ if (this.entries.size >= 128)
72
+ return { reason: 'context_retry_capacity' };
73
+ this.entries.set(retry_id, { seed: structuredClone(seed), at: this.now(), catalog: hash(this.router.policy), current, recommendation_id: seed.request_id });
74
+ return { retry_id };
75
+ }
76
+ async retry(retry_id, description, signal) {
77
+ const entry = this.entries.get(retry_id);
78
+ const unavailable = (reason) => ({ status: 'unavailable', reason, application: 'advisory_only', retry_id, context_retry_allowed: false });
79
+ if (!entry)
80
+ return unavailable('context_retry_not_found');
81
+ if (entry.recommendation_id)
82
+ return unavailable('context_retry_not_eligible');
83
+ const check = () => this.current(entry, signal);
84
+ const blocked = check();
85
+ if (blocked)
86
+ return unavailable(blocked);
87
+ if (entry.active)
88
+ return unavailable('concurrency_limit');
89
+ if (typeof description !== 'string' || Buffer.byteLength(description) > Math.min(3800, this.router.policy.max_summary_bytes - 96) ||
90
+ !hasSufficientTaskText(description))
91
+ return unavailable('insufficient_context');
92
+ if (/\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(description))
93
+ return unavailable('sensitive_input');
94
+ const summary = `Caller-supplied task description (untrusted task data; opaque body not inspected): ${description.trim()}`;
95
+ if (Buffer.byteLength(summary) > Math.min(4000, this.router.policy.max_summary_bytes))
96
+ return unavailable('insufficient_context');
97
+ // Persist only a digest, before provider preflight (which may not write a ledger).
98
+ // Fixed retry ID plus an immutable digest protects restarts and unknown outcomes.
99
+ const request_id = retry_id;
100
+ const fingerprint = hash([summary, entry.seed, entry.catalog]);
101
+ let fd;
102
+ try {
103
+ const policy = loadAutomaticHookPolicy(this.policyPath).policy;
104
+ if (!policy)
105
+ return unavailable('automatic_policy_changed');
106
+ const path = join(policy.state_directory, `hook-retry-${retry_id}.json`);
107
+ assertPrivateStatePath(path);
108
+ try {
109
+ fd = openSync(path, 'wx', 0o600);
110
+ writeFileSync(fd, JSON.stringify({ fingerprint }));
111
+ }
112
+ catch (error) {
113
+ if (error.code !== 'EEXIST')
114
+ throw error;
115
+ const saved = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 256 }).toString('utf8'));
116
+ if (!saved || typeof saved !== 'object' || Object.keys(saved).length !== 1 || !('fingerprint' in saved) || saved.fingerprint !== fingerprint)
117
+ return unavailable('context_retry_conflict');
118
+ }
119
+ }
120
+ catch {
121
+ return unavailable('automatic_state_unavailable');
122
+ }
123
+ finally {
124
+ if (fd !== undefined)
125
+ closeSync(fd);
126
+ }
127
+ const before = check();
128
+ if (before)
129
+ return unavailable(before);
130
+ entry.active = true;
131
+ const cancel = () => { entry.cancelled = true; };
132
+ signal?.addEventListener('abort', cancel, { once: true });
133
+ try {
134
+ const result = await this.router.advise({ request_id, client: entry.seed.client,
135
+ task: { summary, operation: 'analysis', context_sufficient: true }, eligible_profile_ids: entry.seed.eligible_profile_ids,
136
+ constraints: { model_pinned: false, effort_pinned: false, role_pinned: false, fork_inherits: false } });
137
+ const after = check();
138
+ if (after)
139
+ return unavailable(after);
140
+ const defaults = result.status === 'recommended' && result.profile && !entry.seed.application_blocked ? {
141
+ ...(entry.seed.fill_model !== false ? { model: result.profile.model } : {}),
142
+ ...(entry.seed.client === 'codex' && entry.seed.fill_effort !== false && result.profile.reasoning_effort ? { reasoning_effort: result.profile.reasoning_effort } : {})
143
+ } : undefined;
144
+ return { ...result, retry_id, request_id, context_retry_allowed: false,
145
+ spawn_application: { status: entry.seed.application_blocked ? 'blocked' : 'caller_review_required',
146
+ reason: entry.seed.application_blocked ?? 'native_execution_not_observed' },
147
+ ...(defaults ? { next_call: { tool: entry.seed.client === 'claude' ? 'Agent' : 'spawn_agent', set_if_unspecified: defaults, preserve: 'all_other_arguments_and_history' } } : {}),
148
+ next_step: result.status === 'recommended'
149
+ ? 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.' : ''}`
150
+ : `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.`
151
+ : 'Stop this recovery attempt. Report the outcome; do not create another retry ID or spawn with an unresolved recommendation.' };
152
+ }
153
+ finally {
154
+ entry.active = false;
155
+ signal?.removeEventListener('abort', cancel);
156
+ }
157
+ }
158
+ /** Caller-declared independent work only; never rewrites or executes the blocked call. */
159
+ prepareFresh(retry_id, task_name, standalone_task, declaration, signal) {
160
+ const reject = (reason) => ({ status: 'rejected', reason, application: 'advisory_only', source_retry_id: retry_id, execution: 'not_observed' });
161
+ const entry = this.entries.get(retry_id);
162
+ if (!entry)
163
+ return reject('context_retry_not_found');
164
+ const blocked = this.current(entry, signal);
165
+ if (blocked)
166
+ return reject(blocked);
167
+ if (entry.seed.client !== 'codex' || entry.seed.application_blocked !== 'inherited_context_application_unverified' || entry.seed.fresh_eligible !== true)
168
+ return reject('fresh_delegation_unsupported');
169
+ if (!declaration || declaration.history_requirement !== 'not_required')
170
+ return reject('history_requirement_preserved');
171
+ if (declaration.independent_task !== true)
172
+ return reject('independent_task_not_declared');
173
+ if (declaration.same_task !== true)
174
+ return reject('task_scope_changed');
175
+ if (declaration.original_call_outcome !== 'blocked')
176
+ return reject('original_execution_not_confirmed_blocked');
177
+ if (declaration.standalone_context_complete !== true)
178
+ return reject('standalone_context_incomplete');
179
+ 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))
180
+ return reject('insufficient_context');
181
+ if (/\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(task_name + '\n' + standalone_task))
182
+ return reject('sensitive_input');
183
+ if (entry.active || this.router.active)
184
+ return reject('concurrency_limit');
185
+ try {
186
+ this.router.load();
187
+ const record = this.router.state.requests[entry.recommendation_id ?? retry_id];
188
+ if (!record)
189
+ return reject('recommendation_not_found');
190
+ if (record.state !== 'complete')
191
+ return reject('outcome_unknown');
192
+ const result = record.result;
193
+ this.router.validateOutcome(result);
194
+ if (result.status !== 'recommended' || !result.profile)
195
+ return reject('recommendation_not_available');
196
+ const profile = this.router.policy.profiles.find(p => p.id === result.profile_id);
197
+ 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)
198
+ return reject('profile_changed');
199
+ const preparation_id = hash(['aptly-fresh-delegation-v1', retry_id]);
200
+ const fingerprint = hash([entry.seed, entry.catalog, profile, declaration, task_name, standalone_task]);
201
+ const policy = loadAutomaticHookPolicy(this.policyPath).policy;
202
+ if (!policy)
203
+ return reject('automatic_policy_changed');
204
+ const path = join(policy.state_directory, `hook-fresh-${preparation_id}.json`);
205
+ assertPrivateStatePath(path);
206
+ let fd;
207
+ try {
208
+ try {
209
+ fd = openSync(path, 'wx', 0o600);
210
+ writeFileSync(fd, JSON.stringify({ fingerprint }));
211
+ }
212
+ catch (error) {
213
+ if (error.code !== 'EEXIST')
214
+ throw error;
215
+ const previous = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 256 }).toString('utf8'));
216
+ if (!previous || typeof previous !== 'object' || Object.keys(previous).length !== 1 || !('fingerprint' in previous) || previous.fingerprint !== fingerprint)
217
+ return reject('fresh_delegation_conflict');
218
+ }
219
+ }
220
+ finally {
221
+ if (fd !== undefined)
222
+ closeSync(fd);
223
+ }
224
+ const changed = this.current(entry, signal);
225
+ if (changed)
226
+ return reject(changed);
227
+ return { status: 'prepared', reason: 'caller_declared_independent', application: 'advisory_only', source_retry_id: retry_id, preparation_id,
228
+ profile_id: profile.id, profile: structuredClone(profile), intent_provenance: 'caller_declared_not_verified', original_invocation: 'deny_returned_execution_not_observed', execution: 'not_observed',
229
+ next_call: { tool: 'spawn_agent', arguments: { task_name, message: standalone_task, fork_turns: 'none', model: profile.model, reasoning_effort: profile.reasoning_effort } },
230
+ 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.' };
231
+ }
232
+ catch {
233
+ return reject('fresh_delegation_unavailable');
234
+ }
235
+ }
236
+ }
@@ -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,8 +7,60 @@ 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;
11
+ recordRetry(retry_id: string, result: Record<string, unknown>): void;
12
+ lookupRetry(retry_id: string): {
13
+ status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending' | 'awaiting_context' | 'blocked';
14
+ preflight: 'observed';
15
+ correlation_id?: string;
16
+ classification: 'unknown' | 'evaluating' | 'not_requested' | 'provider_requested' | 'cache_hit' | 'local_outcome';
17
+ recommendation: 'not_produced' | 'produced';
18
+ application: 'not_attempted' | 'blocked' | 'arguments_updated';
19
+ execution: 'not_observed';
20
+ constraint_provenance: 'unknown';
21
+ reason: string;
22
+ profile_id?: string;
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
+ scope: string;
52
+ retention_seconds: number;
53
+ capacity: number;
54
+ } | {
55
+ scope: string;
56
+ retention_seconds: number;
57
+ capacity: number;
58
+ preflight: string;
59
+ reason: string;
60
+ execution: string;
61
+ };
10
62
  lookup(client: unknown, event: unknown): {
11
- status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending';
63
+ status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending' | 'awaiting_context' | 'blocked';
12
64
  preflight: 'observed';
13
65
  correlation_id?: string;
14
66
  classification: 'unknown' | 'evaluating' | 'not_requested' | 'provider_requested' | 'cache_hit' | 'local_outcome';
@@ -19,6 +71,33 @@ export declare class RoutingObservations {
19
71
  reason: string;
20
72
  profile_id?: string;
21
73
  request_id?: string;
74
+ retry_id?: string;
75
+ context_retry?: {
76
+ outcome?: {
77
+ status: string;
78
+ reason: string;
79
+ classification: string;
80
+ recommendation: 'produced' | 'not_produced';
81
+ application: 'blocked' | 'not_attempted';
82
+ request_id: string;
83
+ profile_id?: string;
84
+ };
85
+ last_attempt: {
86
+ status: string;
87
+ reason: string;
88
+ };
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
+ };
22
101
  scope: string;
23
102
  retention_seconds: number;
24
103
  capacity: number;
@@ -13,12 +13,54 @@ export class RoutingObservations {
13
13
  this.prune();
14
14
  if (!value.correlation_id)
15
15
  return;
16
+ const previous = this.entries.get(value.correlation_id);
17
+ const recovery = previous?.value.context_retry;
18
+ const fresh = previous?.value.fresh_delegation;
16
19
  this.entries.delete(value.correlation_id);
17
- this.entries.set(value.correlation_id, { at: this.now(), value: structuredClone(value) });
20
+ this.entries.set(value.correlation_id, { at: previous?.at ?? this.now(), value: structuredClone({ ...value,
21
+ ...(recovery ? { retry_id: previous.value.retry_id, context_retry: recovery } : {}), ...(fresh ? { retry_id: previous.value.retry_id, fresh_delegation: fresh } : {}) }) });
18
22
  while (this.entries.size > 128)
19
23
  this.entries.delete(this.entries.keys().next().value);
20
24
  }
21
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
+ }
36
+ recordRetry(retry_id, result) {
37
+ this.prune();
38
+ const entry = [...this.entries.values()].find(entry => entry.value.retry_id === retry_id);
39
+ if (!entry)
40
+ return;
41
+ const status = ['recommended', 'needs_context', 'unavailable', 'keep_current'].includes(String(result.status)) ? String(result.status) : 'unavailable';
42
+ const reason = typeof result.reason === 'string' && /^[a-z_]{1,64}$/.test(result.reason) ? result.reason : 'invalid_response';
43
+ const last_attempt = { status, reason };
44
+ const previous = entry.value.context_retry;
45
+ let outcome = previous?.outcome;
46
+ // Rejected duplicates/conflicts must not overwrite an earlier classification.
47
+ if (result.request_id === retry_id) {
48
+ const application = result.spawn_application;
49
+ outcome = { status, reason, request_id: retry_id,
50
+ classification: result.reason === 'outcome_unknown' ? 'unknown' : result.cached === true ? 'cache_hit' : typeof result.latency_ms === 'number' ? 'provider_requested' : 'local_outcome',
51
+ recommendation: status === 'recommended' ? 'produced' : 'not_produced',
52
+ application: application && typeof application === 'object' && 'status' in application && application.status === 'blocked' ? 'blocked' : 'not_attempted',
53
+ ...(typeof result.profile_id === 'string' && /^(codex|claude)-(simple|routine|deep)$/.test(result.profile_id) ? { profile_id: result.profile_id } : {}) };
54
+ }
55
+ // Keep the original timestamp and preflight stage; lookup never renews retention.
56
+ entry.value = { ...entry.value, context_retry: { ...(outcome ? { outcome } : {}), last_attempt } };
57
+ }
58
+ lookupRetry(retry_id) {
59
+ this.prune();
60
+ const entry = [...this.entries.values()].find(entry => entry.value.retry_id === retry_id);
61
+ return { scope: 'this_process_recent_calls', retention_seconds: 600, capacity: 128,
62
+ ...(entry ? structuredClone(entry.value) : { preflight: 'not_observed', reason: 'no_matching_observation', execution: 'not_observed' }) };
63
+ }
22
64
  lookup(client, event) {
23
65
  this.prune();
24
66
  const correlation_id = automaticCallId(client, event);
@@ -10,14 +10,21 @@ import { loadConfiguration, loadHostContext } from './config.js';
10
10
  import { automaticHook, loadAutomaticHookPolicy, initialHookObservation } from './automatic-hook.js';
11
11
  import { SpawnContexts } from './spawn-context.js';
12
12
  import { RoutingObservations } from './routing-observations.js';
13
+ import { ContextRetries } from './context-retry.js';
13
14
  const taskSchema = z.object({ summary: z.string().min(1).max(4000), operation: z.enum(['read_only', 'write', 'review', 'analysis']), context_sufficient: z.boolean() }).strict();
14
15
  const constraintsSchema = z.object({ model_pinned: z.boolean().optional(), effort_pinned: z.boolean().optional(), role_pinned: z.boolean().optional(), fork_inherits: z.boolean().optional(), provenance_verified: z.boolean().optional() }).strict();
15
16
  const hookSchema = { client: z.enum(['codex', 'claude']), event: z.record(z.string(), z.unknown()) };
17
+ const observationSchema = z.object({ client: hookSchema.client.optional(), event: hookSchema.event.optional(), retry_id: z.string().regex(/^[a-f0-9]{64}$/).optional() }).strict().superRefine((input, ctx) => {
18
+ const valid = input.retry_id !== undefined ? input.client === undefined && input.event === undefined : input.client !== undefined && input.event !== undefined;
19
+ if (!valid)
20
+ ctx.addIssue({ code: 'custom', message: 'Supply only {client,event} or only {retry_id}.' });
21
+ });
16
22
  const content = (result) => ({ content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
17
23
  export function createServer({ env = process.env } = {}) {
18
24
  const { router, mode, modelInfo, credentialStatus, disabledClients } = runtime(env);
19
25
  const observations = new RoutingObservations();
20
26
  const contexts = new SpawnContexts();
27
+ const retries = new ContextRetries(router, env.APTLY_HOOK_POLICY_PATH);
21
28
  const server = new McpServer({ name: 'aptly', version: VERSION });
22
29
  const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: mode === 'decisions' };
23
30
  const evidence = (client, event) => {
@@ -32,12 +39,13 @@ export function createServer({ env = process.env } = {}) {
32
39
  recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
33
40
  model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
34
41
  credential_status: credentialStatus,
35
- automatic_hook: { status: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).reason, mode: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).policy?.mode ?? 'disabled', host_settings_verified: false, context_tool: 'prepare_spawn_context', context_scope: 'this_process_exact_event_5_minutes', observation_tool: 'get_spawn_routing_observation', observation_scope: 'this_process_recent_calls', execution_observation: 'not_supported' },
42
+ automatic_hook: { status: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).reason, mode: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).policy?.mode ?? 'disabled', host_settings_verified: false, context_tool: 'prepare_spawn_context', context_scope: 'this_process_exact_event_5_minutes', context_retry_tool: 'retry_spawn_recommendation', context_retry_limit: 1, 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',
43
+ guarantee: { scope: 'enabled_trusted_connected_supported_hook_only', missing_hook_detectable: false, unavailable_host_hook: 'host_controls_fallback', eligible_defaults_failure: 'deny', inherited_application: 'defaults_deny_advisory_feedback', caller_recovery: 'model_driven_not_guaranteed' } },
36
44
  }));
37
45
  server.registerTool('get_spawn_routing_observation', {
38
- description: 'Look up one exact spawn event in this MCP process (128 calls, 10 minutes). No provider call. Missing records do not prove bypass; argument updates never prove native child execution.',
39
- annotations: { ...annotations, openWorldHint: false }, inputSchema: hookSchema
40
- }, async ({ client, event }) => content(observations.lookup(client, event)));
46
+ description: 'Look up an exact spawn event OR a Hook-issued retry_id in this MCP process (128 calls, 10 minutes). Supply only {client,event} or only {retry_id}. Original preflight and context_retry outcome are separate; no provider call. Missing records never prove bypass; execution remains not_observed.',
47
+ annotations: { ...annotations, openWorldHint: false }, inputSchema: observationSchema
48
+ }, async (input) => content(input.retry_id !== undefined ? observations.lookupRetry(input.retry_id) : observations.lookup(input.client, input.event)));
41
49
  server.registerTool('prepare_spawn_context', {
42
50
  description: 'Register a bounded untrusted description for an exact upcoming spawn event in this MCP process for five minutes. Requires enabled automatic policy. No provider call, file fetching, execution or permissions. The caller must know the real session/call IDs and exact original invocation; invented IDs do not connect to native Hooks.',
43
51
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
@@ -58,6 +66,29 @@ export function createServer({ env = process.env } = {}) {
58
66
  description: 'Recommend an allowlisted profile for a supplied task only; never inspects host settings, spawns, or authorizes an agent. Optional constraints describe caller-declared choices to preserve; omitted flags are not claims about current host settings. Decisions mode may incur a bounded classification request.', annotations,
59
67
  inputSchema: { request_id: z.string().min(1).max(96), client: z.enum(['codex', 'claude']), task: taskSchema, eligible_profile_ids: z.array(z.string()).min(1).max(20).optional(), constraints: constraintsSchema.optional() }
60
68
  }, async (input) => content({ ...await router.advise(input), provider: mode }));
69
+ server.registerTool('retry_spawn_recommendation', {
70
+ description: 'Supply one bounded task description after an Aptly Hook returns needs_context and a retry_id. Use the same MCP process within five minutes; no native call IDs are needed. May make one paid classification; duplicate input reuses its request identity, changed input conflicts. Never spawns or changes history. If still needs_context/unavailable, stop; do not create another ID. A blocked spawn_application remains advisory.',
71
+ annotations, inputSchema: { retry_id: z.string().regex(/^[a-f0-9]{64}$/), description: z.string().max(4000) }
72
+ }, async ({ retry_id, description }, extra) => {
73
+ let result;
74
+ try {
75
+ result = await retries.retry(retry_id, description, extra.signal);
76
+ }
77
+ catch {
78
+ result = { status: 'unavailable', reason: 'context_retry_unavailable', application: 'advisory_only', retry_id, context_retry_allowed: false };
79
+ }
80
+ observations.recordRetry(retry_id, result);
81
+ return content(result);
82
+ });
83
+ server.registerTool('prepare_fresh_delegation', {
84
+ 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.',
85
+ 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),
86
+ 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() }
87
+ }, async ({ retry_id, task_name, standalone_task, declaration }, extra) => {
88
+ const result = retries.prepareFresh(retry_id, task_name, standalone_task, declaration, extra.signal);
89
+ observations.recordFresh(retry_id, result);
90
+ return content(result);
91
+ });
61
92
  server.registerTool('get_routing_precedence', {
62
93
  description: 'Explain preserved choices and unknown effective setting sources. Never classifies, reads a transcript, or changes permissions.', annotations: { ...annotations, openWorldHint: false }, inputSchema: hookSchema
63
94
  }, async ({ client, event }) => {
@@ -70,7 +101,7 @@ export function createServer({ env = process.env } = {}) {
70
101
  }, async ({ client, event, task }, extra) => {
71
102
  observations.begin(client, event);
72
103
  if (env.APTLY_HOOK_POLICY_PATH !== undefined) {
73
- const result = await automaticHook({ client, event, router, policyPath: env.APTLY_HOOK_POLICY_PATH, signal: extra.signal, context: () => contexts.lookup(client, event), onObservation: value => observations.record(value) });
104
+ 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) });
74
105
  observations.record(result.observation);
75
106
  return { content: [{ type: 'text', text: JSON.stringify(result.output) }] };
76
107
  }
package/dist/src/setup.js CHANGED
@@ -507,15 +507,19 @@ function prepare(options, client, removing, edit) {
507
507
  /** Secure sibling staging is short-lived and never a backup; original settings stay in memory. */
508
508
  function replace(snapshot, forward) {
509
509
  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');
510
+ const check = () => {
511
+ const current = read(snapshot.path);
512
+ if (current.text !== expected || (process.platform !== 'win32' && expected !== null && current.mode !== snapshot.mode))
513
+ fail('concurrent_configuration_change');
514
+ };
515
+ check();
512
516
  if (next === null) {
513
517
  if (expected !== null)
514
518
  unlinkSync(snapshot.path);
515
519
  return;
516
520
  }
517
521
  const stage = join(dirname(snapshot.path), `.aptly-stage-${randomUUID()}`);
518
- let fd;
522
+ let fd, staged = true;
519
523
  try {
520
524
  fd = openSync(stage, 'wx', 0o600);
521
525
  if (process.platform === 'win32' && expected !== null) {
@@ -529,21 +533,23 @@ function replace(snapshot, forward) {
529
533
  writeFileSync(fd, next);
530
534
  closeSync(fd);
531
535
  fd = undefined;
532
- if (read(snapshot.path).text !== expected)
533
- fail('concurrent_configuration_change');
536
+ if (process.platform !== 'win32')
537
+ chmodSync(stage, snapshot.mode);
538
+ check();
534
539
  renameSync(stage, snapshot.path);
535
- if (process.platform !== 'win32' && snapshot.mode !== 0o600)
536
- chmodSync(snapshot.path, snapshot.mode);
540
+ staged = false;
537
541
  }
538
542
  finally {
539
543
  if (fd !== undefined)
540
544
  closeSync(fd);
541
- try {
542
- unlinkSync(stage);
543
- }
544
- catch (e) {
545
- if (e.code !== 'ENOENT')
546
- throw e;
545
+ if (staged) {
546
+ try {
547
+ unlinkSync(stage);
548
+ }
549
+ catch (e) {
550
+ if (e.code !== 'ENOENT')
551
+ throw e;
552
+ }
547
553
  }
548
554
  }
549
555
  }
@@ -602,13 +608,16 @@ function execute(options, removing, edit, captured) {
602
608
  validateObservations(plan, written);
603
609
  }
604
610
  catch (e) {
605
- let rollbackConflict = false;
611
+ let rollbackConflict = false, rollbackFailure = false;
606
612
  for (const snapshot of written.reverse()) {
607
613
  try {
608
614
  replace(snapshot, false);
609
615
  }
610
- catch {
611
- rollbackConflict = true;
616
+ catch (error) {
617
+ if (safeCode(error) === 'concurrent_configuration_change')
618
+ rollbackConflict = true;
619
+ else
620
+ rollbackFailure = true;
612
621
  }
613
622
  }
614
623
  for (const path of madeDirs.reverse()) {
@@ -618,7 +627,7 @@ function execute(options, removing, edit, captured) {
618
627
  catch { /* Never remove another writer's files. */ }
619
628
  }
620
629
  plan.result.status = 'error';
621
- plan.result.codes = [safeCode(e), ...(rollbackConflict ? ['rollback_concurrent_change'] : [])];
630
+ plan.result.codes = [safeCode(e), ...(rollbackConflict ? ['rollback_concurrent_change'] : []), ...(rollbackFailure ? ['rollback_failed'] : [])];
622
631
  }
623
632
  }
624
633
  return { status: results.some(result => result.status === 'error') ? 'partial' : results.every(result => result.status === 'skipped') ? 'skipped' : 'complete', clients: results };
@@ -1,5 +1,6 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { automaticCallIdentity } from './automatic-hook.js';
3
+ import { hasSufficientTaskText } from './context-sufficiency.js';
3
4
  const sensitive = (text) => /\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(text);
4
5
  /** Explicit, process-local handoff. Tombstones prevent expiry/cancellation fallback. */
5
6
  export class SpawnContexts {
@@ -17,7 +18,7 @@ export class SpawnContexts {
17
18
  if (!identity)
18
19
  return { status: 'rejected', reason: 'invalid_event' };
19
20
  if (typeof description !== 'string' || Buffer.byteLength(description) > Math.min(3800, maxBytes - 96) ||
20
- description.trim().length < 12 || description.trim().split(/\s+/u).length < 3)
21
+ !hasSufficientTaskText(description))
21
22
  return { status: 'rejected', reason: 'insufficient_context' };
22
23
  if (sensitive(description))
23
24
  return { status: 'rejected', reason: 'sensitive_input' };
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.4";
1
+ export declare const VERSION = "0.1.6";
@@ -1 +1 @@
1
- export const VERSION = '0.1.4';
1
+ export const VERSION = '0.1.6';
@@ -1,6 +1,7 @@
1
- type Runner = (executable: string, args: readonly string[], input: string) => string;
1
+ type Runner = (executable: string, args: readonly string[], input: string, timeoutMs: number) => string;
2
2
  interface WindowsPrivateOptions {
3
3
  execute?: Runner;
4
+ timeoutMs?: number;
4
5
  }
5
6
  /** Preserve the existing file DACL, including inheritance protection, before writing stage content. */
6
7
  export declare function copyWindowsFilePermissions(source: string, target: string, options?: WindowsPrivateOptions): void;