aptly 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,134 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, openSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { loadAutomaticHookPolicy } from './automatic-hook.js';
5
+ import { assertPrivateStatePath, readRegularFile } from './files.js';
6
+ const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
7
+ /** One caller-supplied supplement, never an automatic native spawn or a retry chain. */
8
+ export class ContextRetries {
9
+ entries = new Map();
10
+ router;
11
+ policyPath;
12
+ now;
13
+ constructor(router, policyPath, now = Date.now) { this.router = router; this.policyPath = policyPath; this.now = now; }
14
+ register(seed, current) {
15
+ try {
16
+ this.router.load();
17
+ const original = this.router.state.requests[seed.request_id];
18
+ if (original && (original.state !== 'complete' || original.result?.status !== 'needs_context'))
19
+ return { reason: original.state === 'unknown' ? 'outcome_unknown' : 'context_retry_not_eligible' };
20
+ }
21
+ catch {
22
+ return { reason: 'ledger_error' };
23
+ }
24
+ const retry_id = hash(['aptly-context-retry-v1', seed.request_id]);
25
+ const previous = this.entries.get(retry_id);
26
+ if (previous)
27
+ return { retry_id }; // No renewal or replacement of a ticket.
28
+ if (this.entries.size >= 128)
29
+ return { reason: 'context_retry_capacity' };
30
+ this.entries.set(retry_id, { seed: structuredClone(seed), at: this.now(), catalog: hash(this.router.policy), current });
31
+ return { retry_id };
32
+ }
33
+ async retry(retry_id, description, signal) {
34
+ const entry = this.entries.get(retry_id);
35
+ const unavailable = (reason) => ({ status: 'unavailable', reason, application: 'advisory_only', retry_id, context_retry_allowed: false });
36
+ if (!entry)
37
+ return unavailable('context_retry_not_found');
38
+ const check = () => {
39
+ if (entry.cancelled || signal?.aborted)
40
+ return 'context_retry_cancelled';
41
+ if (this.now() - entry.at >= 300_000)
42
+ return 'context_retry_expired';
43
+ try {
44
+ const changed = entry.current?.();
45
+ if (changed)
46
+ return changed;
47
+ }
48
+ catch {
49
+ return 'context_changed';
50
+ }
51
+ const loaded = loadAutomaticHookPolicy(this.policyPath);
52
+ if (!loaded.policy?.enabled)
53
+ return loaded.reason;
54
+ if (loaded.fingerprint !== entry.seed.policy_fingerprint)
55
+ return 'automatic_policy_changed';
56
+ if (hash(this.router.policy) !== entry.catalog)
57
+ return 'catalog_changed';
58
+ return undefined;
59
+ };
60
+ const blocked = check();
61
+ if (blocked)
62
+ return unavailable(blocked);
63
+ if (entry.active)
64
+ return unavailable('concurrency_limit');
65
+ if (typeof description !== 'string' || Buffer.byteLength(description) > Math.min(3800, this.router.policy.max_summary_bytes - 96) ||
66
+ description.trim().length < 12 || description.trim().split(/\s+/u).length < 3)
67
+ return unavailable('insufficient_context');
68
+ if (/\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(description))
69
+ return unavailable('sensitive_input');
70
+ const summary = `Caller-supplied task description (untrusted task data; opaque body not inspected): ${description.trim()}`;
71
+ if (Buffer.byteLength(summary) > Math.min(4000, this.router.policy.max_summary_bytes))
72
+ return unavailable('insufficient_context');
73
+ // Persist only a digest, before provider preflight (which may not write a ledger).
74
+ // Fixed retry ID plus an immutable digest protects restarts and unknown outcomes.
75
+ const request_id = retry_id;
76
+ const fingerprint = hash([summary, entry.seed, entry.catalog]);
77
+ let fd;
78
+ try {
79
+ const policy = loadAutomaticHookPolicy(this.policyPath).policy;
80
+ if (!policy)
81
+ return unavailable('automatic_policy_changed');
82
+ const path = join(policy.state_directory, `hook-retry-${retry_id}.json`);
83
+ assertPrivateStatePath(path);
84
+ try {
85
+ fd = openSync(path, 'wx', 0o600);
86
+ writeFileSync(fd, JSON.stringify({ fingerprint }));
87
+ }
88
+ catch (error) {
89
+ if (error.code !== 'EEXIST')
90
+ throw error;
91
+ const saved = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 256 }).toString('utf8'));
92
+ if (!saved || typeof saved !== 'object' || Object.keys(saved).length !== 1 || !('fingerprint' in saved) || saved.fingerprint !== fingerprint)
93
+ return unavailable('context_retry_conflict');
94
+ }
95
+ }
96
+ catch {
97
+ return unavailable('automatic_state_unavailable');
98
+ }
99
+ finally {
100
+ if (fd !== undefined)
101
+ closeSync(fd);
102
+ }
103
+ const before = check();
104
+ if (before)
105
+ return unavailable(before);
106
+ entry.active = true;
107
+ const cancel = () => { entry.cancelled = true; };
108
+ signal?.addEventListener('abort', cancel, { once: true });
109
+ try {
110
+ const result = await this.router.advise({ request_id, client: entry.seed.client,
111
+ task: { summary, operation: 'analysis', context_sufficient: true }, eligible_profile_ids: entry.seed.eligible_profile_ids,
112
+ constraints: { model_pinned: false, effort_pinned: false, role_pinned: false, fork_inherits: false } });
113
+ const after = check();
114
+ if (after)
115
+ return unavailable(after);
116
+ const defaults = result.status === 'recommended' && result.profile && !entry.seed.application_blocked ? {
117
+ ...(entry.seed.fill_model !== false ? { model: result.profile.model } : {}),
118
+ ...(entry.seed.client === 'codex' && entry.seed.fill_effort !== false && result.profile.reasoning_effort ? { reasoning_effort: result.profile.reasoning_effort } : {})
119
+ } : undefined;
120
+ return { ...result, retry_id, request_id, context_retry_allowed: false,
121
+ spawn_application: { status: entry.seed.application_blocked ? 'blocked' : 'caller_review_required',
122
+ reason: entry.seed.application_blocked ?? 'native_execution_not_observed' },
123
+ ...(defaults ? { next_call: { tool: entry.seed.client === 'claude' ? 'Agent' : 'spawn_agent', set_if_unspecified: defaults, preserve: 'all_other_arguments_and_history' } } : {}),
124
+ next_step: result.status === 'recommended'
125
+ ? entry.seed.application_blocked ? 'Report the application constraint and preserve original history and arguments. This profile is advice only.'
126
+ : `Context supplementation is complete; do not call retry_spawn_recommendation again. Caller review means the parent checks arguments, not a request for new user approval. To perform the already requested delegation, on the next native ${entry.seed.client === 'claude' ? 'Agent' : 'spawn_agent'} call, include these previously unspecified fields: ${JSON.stringify(defaults)}. Do not submit another model/effort-omitted call: it will be blocked again. Preserve all other arguments, explicit choices, history, roles and permissions. This response does not execute a child.`
127
+ : 'Stop this recovery attempt. Report the outcome; do not create another retry ID or spawn with an unresolved recommendation.' };
128
+ }
129
+ finally {
130
+ entry.active = false;
131
+ signal?.removeEventListener('abort', cancel);
132
+ }
133
+ }
134
+ }
@@ -1,4 +1,4 @@
1
- import type { UnknownRecord, RoutingInput, RoutingPolicy } from './types.ts';
1
+ import type { UnknownRecord, RoutingInput, Profile, RoutingPolicy } from './types.ts';
2
2
  export interface HookOptions {
3
3
  client?: unknown;
4
4
  event?: unknown;
@@ -6,6 +6,7 @@ export interface HookOptions {
6
6
  mode?: string;
7
7
  compatibilityVerified?: boolean;
8
8
  policy?: RoutingPolicy;
9
+ fillUnspecified?: boolean;
9
10
  }
10
11
  export interface HookOutput {
11
12
  hookSpecificOutput?: {
@@ -17,4 +18,8 @@ export interface HookOutput {
17
18
  /** Extract only a task label and safe structural features, never prompt/message/transcript. */
18
19
  export declare function hookInput({ client, event, policy }?: HookOptions): RoutingInput | null;
19
20
  /** Native Hook JSON, defaulting to no permission or argument intervention. */
20
- export declare function hookOutput({ client, event, recommendation, mode, compatibilityVerified, policy }?: HookOptions): HookOutput;
21
+ export declare function hookOutput({ client, event, recommendation, mode, compatibilityVerified, policy, fillUnspecified }?: HookOptions): HookOutput;
22
+ export declare const effortKeys: readonly ['effort', 'reasoning_effort', 'model_reasoning_effort'];
23
+ /** Presence is a pin, not evidence of its source. Never replace a specified half. */
24
+ export declare function profilePreservesChoices(input: UnknownRecord, profile: Profile): boolean;
25
+ export declare function validatedHookProfile(client: unknown, recommendation: unknown, policy: RoutingPolicy): Profile | undefined;
package/dist/src/hook.js CHANGED
@@ -61,26 +61,19 @@ export function hookInput({ client, event, policy = defaultPolicy } = {}) {
61
61
  };
62
62
  }
63
63
  /** Native Hook JSON, defaulting to no permission or argument intervention. */
64
- export function hookOutput({ client, event, recommendation, mode = 'shadow', compatibilityVerified = false, policy = defaultPolicy } = {}) {
64
+ export function hookOutput({ client, event, recommendation, mode = 'shadow', compatibilityVerified = false, policy = defaultPolicy, fillUnspecified = false } = {}) {
65
65
  if (mode !== 'apply' || compatibilityVerified !== true)
66
66
  return {};
67
67
  const found = target(client, event);
68
68
  if (!found || !object(recommendation) || recommendation.status !== 'recommended')
69
69
  return {};
70
70
  const pins = constraints(found.client, found.input);
71
- if (['model_pinned', 'effort_pinned', 'role_pinned', 'fork_inherits'].some(k => pins[k]))
71
+ if (pins.role_pinned || pins.fork_inherits || (!fillUnspecified && (pins.model_pinned || pins.effort_pinned)))
72
72
  return {};
73
- const profile = policy.profiles.find(p => p.client === client && p.id === recommendation.profile_id);
74
- if (!profile || !isSupportedProfile(profile) || recommendation.policy_version !== policy.version ||
75
- recommendation.catalog_version !== policy.catalog_version)
73
+ const profile = validatedHookProfile(client, recommendation, policy);
74
+ if (!profile)
76
75
  return {};
77
- // Select executable values solely from the trusted catalog. Reject conflicting
78
- // copies instead of letting a provider supply arbitrary model/effort strings.
79
- if (own(recommendation, 'model') || own(recommendation, 'reasoning_effort') || own(recommendation, 'effort'))
80
- return {};
81
- const suppliedProfile = recommendation.profile;
82
- if (!object(suppliedProfile) || Object.keys(suppliedProfile).length !== Object.keys(profile).length ||
83
- Object.entries(profile).some(([key, value]) => suppliedProfile[key] !== value))
76
+ if (fillUnspecified && !profilePreservesChoices(found.input, profile))
84
77
  return {};
85
78
  let updatedInput;
86
79
  try {
@@ -89,8 +82,9 @@ export function hookOutput({ client, event, recommendation, mode = 'shadow', com
89
82
  catch {
90
83
  return {};
91
84
  }
92
- updatedInput.model = profile.model;
93
- if (client === 'codex')
85
+ if (!own(found.input, 'model'))
86
+ updatedInput.model = profile.model;
87
+ if (client === 'codex' && !effortKeys.some(key => own(found.input, key)))
94
88
  updatedInput.reasoning_effort = profile.reasoning_effort;
95
89
  return { hookSpecificOutput: {
96
90
  hookEventName: 'PreToolUse',
@@ -100,3 +94,27 @@ export function hookOutput({ client, event, recommendation, mode = 'shadow', com
100
94
  updatedInput,
101
95
  } };
102
96
  }
97
+ export const effortKeys = ['effort', 'reasoning_effort', 'model_reasoning_effort'];
98
+ /** Presence is a pin, not evidence of its source. Never replace a specified half. */
99
+ export function profilePreservesChoices(input, profile) {
100
+ if (own(input, 'model') && input.model !== profile.model)
101
+ return false;
102
+ return effortKeys.every(key => !own(input, key) || (typeof input[key] === 'string' && profile.reasoning_effort === input[key]));
103
+ }
104
+ export function validatedHookProfile(client, recommendation, policy) {
105
+ if (!object(recommendation) || recommendation.status !== 'recommended')
106
+ return undefined;
107
+ const profile = policy.profiles.find(p => p.client === client && p.id === recommendation.profile_id);
108
+ if (!profile || !isSupportedProfile(profile) || recommendation.policy_version !== policy.version ||
109
+ recommendation.catalog_version !== policy.catalog_version)
110
+ return undefined;
111
+ // Select executable values solely from the trusted catalog. Reject conflicting
112
+ // copies instead of letting a provider supply arbitrary model/effort strings.
113
+ if (own(recommendation, 'model') || own(recommendation, 'reasoning_effort') || own(recommendation, 'effort'))
114
+ return undefined;
115
+ const suppliedProfile = recommendation.profile;
116
+ if (!object(suppliedProfile) || Object.keys(suppliedProfile).length !== Object.keys(profile).length ||
117
+ Object.entries(profile).some(([key, value]) => suppliedProfile[key] !== value))
118
+ return undefined;
119
+ return profile;
120
+ }
@@ -0,0 +1,90 @@
1
+ import type { AutomaticHookObservation } from './automatic-hook.ts';
2
+ /** Process-local, bounded diagnostics; absence is never proof that a host bypassed MCP. */
3
+ export declare class RoutingObservations {
4
+ private entries;
5
+ private now;
6
+ constructor(now?: () => number);
7
+ private prune;
8
+ record(value: AutomaticHookObservation): void;
9
+ begin(client: unknown, event: unknown): void;
10
+ recordRetry(retry_id: string, result: Record<string, unknown>): void;
11
+ lookupRetry(retry_id: string): {
12
+ status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending' | 'awaiting_context' | 'blocked';
13
+ preflight: 'observed';
14
+ correlation_id?: string;
15
+ classification: 'unknown' | 'evaluating' | 'not_requested' | 'provider_requested' | 'cache_hit' | 'local_outcome';
16
+ recommendation: 'not_produced' | 'produced';
17
+ application: 'not_attempted' | 'blocked' | 'arguments_updated';
18
+ execution: 'not_observed';
19
+ constraint_provenance: 'unknown';
20
+ reason: string;
21
+ profile_id?: string;
22
+ request_id?: string;
23
+ retry_id?: string;
24
+ context_retry?: {
25
+ outcome?: {
26
+ status: string;
27
+ reason: string;
28
+ classification: string;
29
+ recommendation: 'produced' | 'not_produced';
30
+ application: 'blocked' | 'not_attempted';
31
+ request_id: string;
32
+ profile_id?: string;
33
+ };
34
+ last_attempt: {
35
+ status: string;
36
+ reason: string;
37
+ };
38
+ };
39
+ scope: string;
40
+ retention_seconds: number;
41
+ capacity: number;
42
+ } | {
43
+ scope: string;
44
+ retention_seconds: number;
45
+ capacity: number;
46
+ preflight: string;
47
+ reason: string;
48
+ execution: string;
49
+ };
50
+ lookup(client: unknown, event: unknown): {
51
+ status: 'arguments_updated' | 'advisory' | 'preserved' | 'pending' | 'awaiting_context' | 'blocked';
52
+ preflight: 'observed';
53
+ correlation_id?: string;
54
+ classification: 'unknown' | 'evaluating' | 'not_requested' | 'provider_requested' | 'cache_hit' | 'local_outcome';
55
+ recommendation: 'not_produced' | 'produced';
56
+ application: 'not_attempted' | 'blocked' | 'arguments_updated';
57
+ execution: 'not_observed';
58
+ constraint_provenance: 'unknown';
59
+ reason: string;
60
+ profile_id?: string;
61
+ request_id?: string;
62
+ retry_id?: string;
63
+ context_retry?: {
64
+ outcome?: {
65
+ status: string;
66
+ reason: string;
67
+ classification: string;
68
+ recommendation: 'produced' | 'not_produced';
69
+ application: 'blocked' | 'not_attempted';
70
+ request_id: string;
71
+ profile_id?: string;
72
+ };
73
+ last_attempt: {
74
+ status: string;
75
+ reason: string;
76
+ };
77
+ };
78
+ scope: string;
79
+ retention_seconds: number;
80
+ capacity: number;
81
+ } | {
82
+ scope: string;
83
+ retention_seconds: number;
84
+ capacity: number;
85
+ preflight: string;
86
+ reason: string;
87
+ correlation_id?: string | undefined;
88
+ execution: string;
89
+ };
90
+ }
@@ -0,0 +1,61 @@
1
+ import { automaticCallId, initialHookObservation } from './automatic-hook.js';
2
+ /** Process-local, bounded diagnostics; absence is never proof that a host bypassed MCP. */
3
+ export class RoutingObservations {
4
+ entries = new Map();
5
+ now;
6
+ constructor(now = Date.now) { this.now = now; }
7
+ prune() {
8
+ for (const [id, entry] of this.entries)
9
+ if (this.now() - entry.at >= 600_000)
10
+ this.entries.delete(id);
11
+ }
12
+ record(value) {
13
+ this.prune();
14
+ if (!value.correlation_id)
15
+ return;
16
+ const previous = this.entries.get(value.correlation_id);
17
+ const recovery = previous?.value.context_retry;
18
+ this.entries.delete(value.correlation_id);
19
+ this.entries.set(value.correlation_id, { at: previous?.at ?? this.now(), value: structuredClone({ ...value,
20
+ ...(recovery ? { retry_id: previous.value.retry_id, context_retry: recovery } : {}) }) });
21
+ while (this.entries.size > 128)
22
+ this.entries.delete(this.entries.keys().next().value);
23
+ }
24
+ begin(client, event) { this.record(initialHookObservation(client, event)); }
25
+ recordRetry(retry_id, result) {
26
+ this.prune();
27
+ const entry = [...this.entries.values()].find(entry => entry.value.retry_id === retry_id);
28
+ if (!entry)
29
+ return;
30
+ const status = ['recommended', 'needs_context', 'unavailable', 'keep_current'].includes(String(result.status)) ? String(result.status) : 'unavailable';
31
+ const reason = typeof result.reason === 'string' && /^[a-z_]{1,64}$/.test(result.reason) ? result.reason : 'invalid_response';
32
+ const last_attempt = { status, reason };
33
+ const previous = entry.value.context_retry;
34
+ let outcome = previous?.outcome;
35
+ // Rejected duplicates/conflicts must not overwrite an earlier classification.
36
+ if (result.request_id === retry_id) {
37
+ const application = result.spawn_application;
38
+ outcome = { status, reason, request_id: retry_id,
39
+ classification: result.reason === 'outcome_unknown' ? 'unknown' : result.cached === true ? 'cache_hit' : typeof result.latency_ms === 'number' ? 'provider_requested' : 'local_outcome',
40
+ recommendation: status === 'recommended' ? 'produced' : 'not_produced',
41
+ application: application && typeof application === 'object' && 'status' in application && application.status === 'blocked' ? 'blocked' : 'not_attempted',
42
+ ...(typeof result.profile_id === 'string' && /^(codex|claude)-(simple|routine|deep)$/.test(result.profile_id) ? { profile_id: result.profile_id } : {}) };
43
+ }
44
+ // Keep the original timestamp and preflight stage; lookup never renews retention.
45
+ entry.value = { ...entry.value, context_retry: { ...(outcome ? { outcome } : {}), last_attempt } };
46
+ }
47
+ lookupRetry(retry_id) {
48
+ this.prune();
49
+ const entry = [...this.entries.values()].find(entry => entry.value.retry_id === retry_id);
50
+ return { scope: 'this_process_recent_calls', retention_seconds: 600, capacity: 128,
51
+ ...(entry ? structuredClone(entry.value) : { preflight: 'not_observed', reason: 'no_matching_observation', execution: 'not_observed' }) };
52
+ }
53
+ lookup(client, event) {
54
+ this.prune();
55
+ const correlation_id = automaticCallId(client, event);
56
+ const found = correlation_id ? this.entries.get(correlation_id) : undefined;
57
+ return { scope: 'this_process_recent_calls', retention_seconds: 600, capacity: 128,
58
+ ...(found ? structuredClone(found.value) : { preflight: 'not_observed', reason: correlation_id ? 'no_matching_observation' : 'invalid_event',
59
+ ...(correlation_id ? { correlation_id } : {}), execution: 'not_observed' }) };
60
+ }
61
+ }
@@ -7,14 +7,24 @@ 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 } from './automatic-hook.js';
10
+ import { automaticHook, loadAutomaticHookPolicy, initialHookObservation } from './automatic-hook.js';
11
+ import { SpawnContexts } from './spawn-context.js';
12
+ import { RoutingObservations } from './routing-observations.js';
13
+ import { ContextRetries } from './context-retry.js';
11
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();
12
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();
13
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
+ });
14
22
  const content = (result) => ({ content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
15
23
  export function createServer({ env = process.env } = {}) {
16
24
  const { router, mode, modelInfo, credentialStatus, disabledClients } = runtime(env);
17
- let lastAutomaticHook = null;
25
+ const observations = new RoutingObservations();
26
+ const contexts = new SpawnContexts();
27
+ const retries = new ContextRetries(router, env.APTLY_HOOK_POLICY_PATH);
18
28
  const server = new McpServer({ name: 'aptly', version: VERSION });
19
29
  const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: mode === 'decisions' };
20
30
  const evidence = (client, event) => {
@@ -29,12 +39,47 @@ export function createServer({ env = process.env } = {}) {
29
39
  recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
30
40
  model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
31
41
  credential_status: credentialStatus,
32
- automatic_hook: { status: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).reason, mode: loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH).policy?.mode ?? 'disabled', host_settings_verified: false, last_result: lastAutomaticHook },
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' } },
33
44
  }));
45
+ server.registerTool('get_spawn_routing_observation', {
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)));
49
+ server.registerTool('prepare_spawn_context', {
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.',
51
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
52
+ inputSchema: { ...hookSchema, description: z.string().max(4000) }
53
+ }, async ({ client, event, description }, extra) => {
54
+ const policy = loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH);
55
+ if (!policy.policy?.enabled)
56
+ return content({ status: 'rejected', reason: policy.reason });
57
+ if (extra.signal.aborted)
58
+ return content({ status: 'rejected', reason: 'context_cancelled' });
59
+ return content(contexts.register(client, event, description, router.policy.max_summary_bytes));
60
+ });
61
+ server.registerTool('cancel_spawn_context', {
62
+ description: 'Revoke one exact registered spawn context in this process. Does not cancel native execution or undo a provider request.',
63
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, inputSchema: hookSchema
64
+ }, async ({ client, event }) => content(contexts.cancel(client, event)));
34
65
  server.registerTool('recommend_agent', {
35
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,
36
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() }
37
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
+ });
38
83
  server.registerTool('get_routing_precedence', {
39
84
  description: 'Explain preserved choices and unknown effective setting sources. Never classifies, reads a transcript, or changes permissions.', annotations: { ...annotations, openWorldHint: false }, inputSchema: hookSchema
40
85
  }, async ({ client, event }) => {
@@ -42,17 +87,20 @@ export function createServer({ env = process.env } = {}) {
42
87
  return content({ ...precedence, evidence_status: loaded.reason, configuration_status: config.error ?? 'ok', application: 'advisory_only' });
43
88
  });
44
89
  server.registerTool('route_spawn_hook', {
45
- description: 'Native PreToolUse Hook. An installed operator policy can select unpinned fresh-agent defaults through Decisions; otherwise the legacy evidence-gated path remains shadow by default. Explicit choices, role/fork/resume and failures preserve the call. Optional task never supplies policy.', annotations,
90
+ description: 'Native PreToolUse preflight for supported spawns. Installed policy evaluates unspecified defaults, including inherited calls; application preserves explicit choices, roles, resume and history. Incompatible history yields advice without rewriting. The host executes; optional task never supplies policy.', annotations,
46
91
  inputSchema: { ...hookSchema, task: taskSchema.optional() }
47
92
  }, async ({ client, event, task }, extra) => {
93
+ observations.begin(client, event);
48
94
  if (env.APTLY_HOOK_POLICY_PATH !== undefined) {
49
- const result = await automaticHook({ client, event, router, policyPath: env.APTLY_HOOK_POLICY_PATH, signal: extra.signal });
50
- lastAutomaticHook = result.observation;
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) });
96
+ observations.record(result.observation);
51
97
  return { content: [{ type: 'text', text: JSON.stringify(result.output) }] };
52
98
  }
53
99
  const input = hookInput({ client, event, policy: router.policy });
54
- if (!input)
100
+ if (!input) {
101
+ observations.record({ ...initialHookObservation(client, event), status: 'preserved', reason: 'invalid_event' });
55
102
  return { content: [{ type: 'text', text: '{}' }] };
103
+ }
56
104
  const before = evidence(client, event);
57
105
  input.constraints = before.precedence.constraints;
58
106
  if (task)
@@ -65,6 +113,12 @@ export function createServer({ env = process.env } = {}) {
65
113
  before.config.context_path === after.config.context_path && before.precedence.status === 'eligible' && after.precedence.status === 'eligible' &&
66
114
  before.loaded.fingerprint === after.loaded.fingerprint && JSON.stringify(before.loaded.context) === JSON.stringify(after.loaded.context);
67
115
  const output = hookOutput({ client, event, recommendation, mode: apply ? 'apply' : 'shadow', compatibilityVerified: apply, policy: router.policy });
116
+ observations.record({ ...initialHookObservation(client, event), status: output.hookSpecificOutput ? 'arguments_updated' : 'preserved',
117
+ reason: output.hookSpecificOutput ? 'legacy_arguments_updated' : recommendation.status === 'recommended' ? 'legacy_application_blocked' : recommendation.reason,
118
+ classification: recommendation.cached ? 'cache_hit' : typeof recommendation.latency_ms === 'number' ? 'provider_requested' : 'local_outcome',
119
+ recommendation: recommendation.status === 'recommended' ? 'produced' : 'not_produced',
120
+ application: output.hookSpecificOutput ? 'arguments_updated' : recommendation.status === 'recommended' ? 'blocked' : 'not_attempted',
121
+ ...(recommendation.profile_id ? { profile_id: recommendation.profile_id } : {}), request_id: input.request_id });
68
122
  return { content: [{ type: 'text', text: JSON.stringify(output) }] };
69
123
  });
70
124
  return server;
@@ -0,0 +1,15 @@
1
+ export interface SpawnContext {
2
+ summary?: string;
3
+ fingerprint?: string;
4
+ reason?: string;
5
+ }
6
+ /** Explicit, process-local handoff. Tombstones prevent expiry/cancellation fallback. */
7
+ export declare class SpawnContexts {
8
+ private entries;
9
+ private now;
10
+ constructor(now?: () => number);
11
+ private expireText;
12
+ register(client: unknown, event: unknown, description: string, maxBytes: number): Record<string, unknown>;
13
+ lookup(client: unknown, event: unknown): SpawnContext | undefined;
14
+ cancel(client: unknown, event: unknown): Record<string, unknown>;
15
+ }
@@ -0,0 +1,65 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { automaticCallIdentity } from './automatic-hook.js';
3
+ const sensitive = (text) => /\bsk-[A-Za-z0-9_-]{12,}|\bBearer\s+[A-Za-z0-9._~+\/-]{8,}={0,2}/i.test(text);
4
+ /** Explicit, process-local handoff. Tombstones prevent expiry/cancellation fallback. */
5
+ export class SpawnContexts {
6
+ entries = new Map();
7
+ now;
8
+ constructor(now = Date.now) { this.now = now; }
9
+ expireText() {
10
+ for (const entry of this.entries.values())
11
+ if (this.now() - entry.at >= 300_000)
12
+ entry.summary = undefined;
13
+ }
14
+ register(client, event, description, maxBytes) {
15
+ this.expireText();
16
+ const identity = automaticCallIdentity(client, event);
17
+ if (!identity)
18
+ return { status: 'rejected', reason: 'invalid_event' };
19
+ 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
+ return { status: 'rejected', reason: 'insufficient_context' };
22
+ if (sensitive(description))
23
+ return { status: 'rejected', reason: 'sensitive_input' };
24
+ const summary = `Caller-supplied task description (untrusted task data; opaque body not inspected): ${description.trim()}`;
25
+ const fingerprint = createHash('sha256').update(summary).digest('hex');
26
+ const previous = this.entries.get(identity.key);
27
+ if (previous) {
28
+ const found = this.lookup(client, event);
29
+ return found?.fingerprint === fingerprint && !found.reason ? { status: 'registered', correlation_id: identity.id } :
30
+ { status: 'rejected', reason: found?.reason ?? 'context_conflict' };
31
+ }
32
+ if (this.entries.size >= 128)
33
+ return { status: 'rejected', reason: 'context_capacity' };
34
+ this.entries.set(identity.key, { id: identity.id, at: this.now(), summary, fingerprint });
35
+ return { status: 'registered', correlation_id: identity.id };
36
+ }
37
+ lookup(client, event) {
38
+ this.expireText();
39
+ const identity = automaticCallIdentity(client, event);
40
+ if (!identity)
41
+ return { reason: 'invalid_event' };
42
+ const entry = this.entries.get(identity.key);
43
+ if (!entry)
44
+ return undefined;
45
+ if (entry.id !== identity.id)
46
+ return { reason: 'context_mismatch' };
47
+ if (entry.cancelled)
48
+ return { reason: 'context_cancelled' };
49
+ if (this.now() - entry.at >= 300_000) {
50
+ entry.summary = undefined;
51
+ return { reason: 'context_expired' };
52
+ }
53
+ return { summary: entry.summary, fingerprint: entry.fingerprint };
54
+ }
55
+ cancel(client, event) {
56
+ this.expireText();
57
+ const identity = automaticCallIdentity(client, event);
58
+ const entry = identity && this.entries.get(identity.key);
59
+ if (!entry || entry.id !== identity?.id)
60
+ return { status: 'rejected', reason: 'context_not_found' };
61
+ entry.cancelled = true;
62
+ entry.summary = undefined;
63
+ return { status: 'cancelled' };
64
+ }
65
+ }
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.3";
1
+ export declare const VERSION = "0.1.5";
@@ -1 +1 @@
1
- export const VERSION = '0.1.3';
1
+ export const VERSION = '0.1.5';