aptly 0.1.2 → 0.1.4

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.
@@ -7,14 +7,17 @@ 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';
11
13
  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
14
  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
15
  const hookSchema = { client: z.enum(['codex', 'claude']), event: z.record(z.string(), z.unknown()) };
14
16
  const content = (result) => ({ content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
15
17
  export function createServer({ env = process.env } = {}) {
16
18
  const { router, mode, modelInfo, credentialStatus, disabledClients } = runtime(env);
17
- let lastAutomaticHook = null;
19
+ const observations = new RoutingObservations();
20
+ const contexts = new SpawnContexts();
18
21
  const server = new McpServer({ name: 'aptly', version: VERSION });
19
22
  const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: mode === 'decisions' };
20
23
  const evidence = (client, event) => {
@@ -29,8 +32,28 @@ export function createServer({ env = process.env } = {}) {
29
32
  recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
30
33
  model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
31
34
  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 },
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' },
33
36
  }));
37
+ 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)));
41
+ server.registerTool('prepare_spawn_context', {
42
+ 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
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
44
+ inputSchema: { ...hookSchema, description: z.string().max(4000) }
45
+ }, async ({ client, event, description }, extra) => {
46
+ const policy = loadAutomaticHookPolicy(env.APTLY_HOOK_POLICY_PATH);
47
+ if (!policy.policy?.enabled)
48
+ return content({ status: 'rejected', reason: policy.reason });
49
+ if (extra.signal.aborted)
50
+ return content({ status: 'rejected', reason: 'context_cancelled' });
51
+ return content(contexts.register(client, event, description, router.policy.max_summary_bytes));
52
+ });
53
+ server.registerTool('cancel_spawn_context', {
54
+ description: 'Revoke one exact registered spawn context in this process. Does not cancel native execution or undo a provider request.',
55
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, inputSchema: hookSchema
56
+ }, async ({ client, event }) => content(contexts.cancel(client, event)));
34
57
  server.registerTool('recommend_agent', {
35
58
  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
59
  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() }
@@ -42,17 +65,20 @@ export function createServer({ env = process.env } = {}) {
42
65
  return content({ ...precedence, evidence_status: loaded.reason, configuration_status: config.error ?? 'ok', application: 'advisory_only' });
43
66
  });
44
67
  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,
68
+ 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
69
  inputSchema: { ...hookSchema, task: taskSchema.optional() }
47
70
  }, async ({ client, event, task }, extra) => {
71
+ observations.begin(client, event);
48
72
  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;
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) });
74
+ observations.record(result.observation);
51
75
  return { content: [{ type: 'text', text: JSON.stringify(result.output) }] };
52
76
  }
53
77
  const input = hookInput({ client, event, policy: router.policy });
54
- if (!input)
78
+ if (!input) {
79
+ observations.record({ ...initialHookObservation(client, event), status: 'preserved', reason: 'invalid_event' });
55
80
  return { content: [{ type: 'text', text: '{}' }] };
81
+ }
56
82
  const before = evidence(client, event);
57
83
  input.constraints = before.precedence.constraints;
58
84
  if (task)
@@ -65,6 +91,12 @@ export function createServer({ env = process.env } = {}) {
65
91
  before.config.context_path === after.config.context_path && before.precedence.status === 'eligible' && after.precedence.status === 'eligible' &&
66
92
  before.loaded.fingerprint === after.loaded.fingerprint && JSON.stringify(before.loaded.context) === JSON.stringify(after.loaded.context);
67
93
  const output = hookOutput({ client, event, recommendation, mode: apply ? 'apply' : 'shadow', compatibilityVerified: apply, policy: router.policy });
94
+ observations.record({ ...initialHookObservation(client, event), status: output.hookSpecificOutput ? 'arguments_updated' : 'preserved',
95
+ reason: output.hookSpecificOutput ? 'legacy_arguments_updated' : recommendation.status === 'recommended' ? 'legacy_application_blocked' : recommendation.reason,
96
+ classification: recommendation.cached ? 'cache_hit' : typeof recommendation.latency_ms === 'number' ? 'provider_requested' : 'local_outcome',
97
+ recommendation: recommendation.status === 'recommended' ? 'produced' : 'not_produced',
98
+ application: output.hookSpecificOutput ? 'arguments_updated' : recommendation.status === 'recommended' ? 'blocked' : 'not_attempted',
99
+ ...(recommendation.profile_id ? { profile_id: recommendation.profile_id } : {}), request_id: input.request_id });
68
100
  return { content: [{ type: 'text', text: JSON.stringify(output) }] };
69
101
  });
70
102
  return server;
@@ -31,6 +31,6 @@ export declare function prepareCredentialReference(options: SetupOptions, client
31
31
  check: () => SetupClientResult;
32
32
  commit: () => SetupClientResult;
33
33
  };
34
- /** Only an explicitly selected, receipt-matching standard registration is eligible. */
35
- export declare function migrateLauncher(options: SetupOptions, dryRun?: boolean): SetupResult;
34
+ /** Preserved standard registrations require a separate explicit opt-in; ownership stays unchanged. */
35
+ export declare function migrateLauncher(options: SetupOptions, dryRun?: boolean, includeExisting?: boolean): SetupResult;
36
36
  export {};
package/dist/src/setup.js CHANGED
@@ -234,6 +234,34 @@ function updateTomlEnv(text, updates) {
234
234
  fail('unsupported_toml_layout');
235
235
  return text;
236
236
  }
237
+ /** Replace only unambiguous single-line launcher assignments in an existing table. */
238
+ function updateTomlLauncher(text, entry) {
239
+ const original = toml(text), expected = structuredClone(original);
240
+ expected.mcp_servers.aptly.command = entry.command;
241
+ expected.mcp_servers.aptly.args = entry.args;
242
+ const headers = [...text.matchAll(/^\s*\[([^\n]+)\][ \t]*(?:#[^\n]*)?\r?$/gm)];
243
+ const header = headers.find(h => { try {
244
+ return toml(h[0] + '\naptly_probe = true\n').mcp_servers?.aptly?.aptly_probe === true;
245
+ }
246
+ catch {
247
+ return false;
248
+ } });
249
+ if (!header)
250
+ fail('unsupported_toml_layout');
251
+ const start = header.index + header[0].length, end = headers.find(h => h.index > header.index)?.index ?? text.length;
252
+ let body = text.slice(start, end);
253
+ for (const key of ['command', 'args']) {
254
+ const assignment = new RegExp('^[ \\t]*' + key + '[ \\t]*=[^\\n]*(?:\\n|$)', 'gm');
255
+ const matches = [...body.matchAll(assignment)];
256
+ if (matches.length !== 1 || !isDeepStrictEqual(toml(matches[0][0])[key], original.mcp_servers.aptly[key]))
257
+ fail('unsupported_toml_layout');
258
+ body = body.replace(assignment, () => key + ' = ' + JSON.stringify(entry[key]) + (matches[0][0].endsWith('\r\n') ? '\r\n' : matches[0][0].endsWith('\n') ? '\n' : ''));
259
+ }
260
+ const rendered = text.slice(0, start) + body + text.slice(end);
261
+ if (!isDeepStrictEqual(toml(rendered), expected))
262
+ fail('unsupported_toml_layout');
263
+ return rendered;
264
+ }
237
265
  function resolved(options, client) {
238
266
  const home = resolve(options.home ?? homedir()), env = options.env ?? process.env;
239
267
  const override = client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR;
@@ -359,13 +387,16 @@ function prepare(options, client, removing, edit) {
359
387
  const additions = { APTLY_HOOK_POLICY_PATH: policyPath, ROUTER_LEDGER_PATH: join(stateDir, 'ledger.json') };
360
388
  let created = false, tomlBlock;
361
389
  if (edit && 'migrate' in edit) {
362
- if (!oldOwner?.mcp_created || !object(servers.aptly) || !isDeepStrictEqual(servers.aptly, oldOwner.mcp))
390
+ if (!oldOwner || !object(servers.aptly) || (oldOwner.mcp_created ? !isDeepStrictEqual(servers.aptly, oldOwner.mcp) : !edit.includeExisting))
363
391
  fail('launcher_migration_not_owned');
364
392
  const entry = servers.aptly;
365
393
  if (typeof entry.command !== 'string' || !isAbsolute(entry.command) || !['node', 'node.exe'].includes(basename(entry.command).toLowerCase()) || !Array.isArray(entry.args) || entry.args.length !== 1 || typeof entry.args[0] !== 'string' || !isAbsolute(entry.args[0]) || !/(?:^|[\\/])(?:dist[\\/]src[\\/]server\.js|src[\\/]server\.ts)$/.test(entry.args[0]))
366
394
  fail('launcher_migration_not_standard');
367
395
  if (!entries.some(entry => isDeepStrictEqual(entry, oldOwner.hook)) || !isDeepStrictEqual(json(policy.before), oldOwner.policy))
368
396
  fail('managed_entry_changed');
397
+ for (const [key, value] of Object.entries(oldOwner.env_added))
398
+ if (entry.env?.[key] !== value)
399
+ fail('managed_entry_changed');
369
400
  }
370
401
  if (servers.aptly === undefined) {
371
402
  created = true;
@@ -400,8 +431,11 @@ function prepare(options, client, removing, edit) {
400
431
  else
401
432
  mcp.after = stringify(config);
402
433
  }
403
- else if (edit)
434
+ else if (edit) {
404
435
  mcp.after = client === 'codex' ? updateTomlEnv(mcp.after, updates) : stringify(config);
436
+ if (client === 'codex' && 'migrate' in edit && !oldOwner?.mcp_created)
437
+ mcp.after = updateTomlLauncher(mcp.after, servers.aptly);
438
+ }
405
439
  const existingRoute = entries.filter(routeHook);
406
440
  if (existingRoute.some(entry => !isDeepStrictEqual(entry, hookValue)))
407
441
  fail('existing_routing_hook_conflict');
@@ -656,16 +690,17 @@ export function prepareCredentialReference(options, client) {
656
690
  return execute({ ...options, clients: [client] }, false, { credential: true }, [plan]).clients[0];
657
691
  } };
658
692
  }
659
- /** Only an explicitly selected, receipt-matching standard registration is eligible. */
660
- export function migrateLauncher(options, dryRun = false) {
693
+ /** Preserved standard registrations require a separate explicit opt-in; ownership stays unchanged. */
694
+ export function migrateLauncher(options, dryRun = false, includeExisting = false) {
661
695
  const client = options.clients?.[0];
662
696
  if (options.clients?.length !== 1 || !client || !['codex', 'claude'].includes(client) || options.automatic || options.mode)
663
697
  return { status: 'partial', clients: [] };
664
698
  try {
665
- const plan = prepare(options, client, false, { migrate: true });
699
+ const edit = { migrate: true, includeExisting };
700
+ const plan = prepare(options, client, false, edit);
666
701
  if (dryRun)
667
702
  return { status: 'complete', clients: [{ client, status: 'unchanged', codes: [plan.changes.length ? 'launcher_migration_available' : 'launcher_current'], requires_hook_review: client === 'codex' }] };
668
- const result = execute(options, false, { migrate: true }, [plan]);
703
+ const result = execute(options, false, edit, [plan]);
669
704
  if (result.status === 'complete')
670
705
  result.clients[0].codes.push('launcher_migrated', 'mcp_restart_required');
671
706
  return result;
@@ -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
+ }
@@ -0,0 +1,14 @@
1
+ export interface UpdateNotificationOptions {
2
+ command: string;
3
+ args: readonly string[];
4
+ env: NodeJS.ProcessEnv;
5
+ stderrIsTTY: boolean;
6
+ stdoutIsTTY?: boolean;
7
+ stdinIsTTY: boolean;
8
+ currentVersion: string;
9
+ cachePath?: string;
10
+ fetch?: typeof globalThis.fetch;
11
+ now?: number;
12
+ }
13
+ /** Returns one stderr hint; never prints, reads credentials, or changes installed code. */
14
+ export declare function updateNotification(options: UpdateNotificationOptions): Promise<string | null>;
@@ -0,0 +1,179 @@
1
+ // Optional interactive CLI hint only. Never used by MCP, routing, or provider code.
2
+ import { mkdirSync, lstatSync, openSync, closeSync, writeFileSync, renameSync, unlinkSync } from 'node:fs';
3
+ import { dirname, join, isAbsolute, parse } from 'node:path';
4
+ import { homedir } from 'node:os';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { assertNoRedirectedAncestors, assertPrivateStatePath, readRegularFile } from './files.js';
7
+ import { protectNewWindowsPrivateDirectory } from './windows-private.js';
8
+ const registry = 'https://registry.npmjs.org/aptly/latest';
9
+ const ttl = 24 * 60 * 60 * 1000, cooldown = 60 * 60 * 1000, maximumBody = 16 * 1024, timeout = 800;
10
+ function version(value) {
11
+ if (typeof value !== 'string' || value.length > 64 || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value))
12
+ return null;
13
+ const parts = value.split('.').map(Number);
14
+ return parts.every(Number.isSafeInteger) ? parts : null;
15
+ }
16
+ function newer(candidate, current) {
17
+ const a = version(candidate), b = version(current);
18
+ for (let i = 0; i < 3; i++) {
19
+ if (a[i] !== b[i])
20
+ return a[i] > b[i];
21
+ }
22
+ return false;
23
+ }
24
+ function eligible(o) {
25
+ return o.stdinIsTTY && o.stderrIsTTY && o.stdoutIsTTY !== false && !o.env.CI && o.env.APTLY_NO_UPDATE_NOTIFIER !== '1' && !!version(o.currentVersion) &&
26
+ ['help', '--help', '-h', '--version', 'config', 'setup', 'remove', 'set', 'report'].includes(o.command) && !o.args.includes('--automatic');
27
+ }
28
+ function directory(path) {
29
+ if (!isAbsolute(path))
30
+ throw Error('cache_path');
31
+ const parent = dirname(path);
32
+ if (parent !== path) {
33
+ try {
34
+ assertNoRedirectedAncestors(parent);
35
+ }
36
+ catch (error) {
37
+ if (error.code !== 'ENOENT')
38
+ throw error;
39
+ directory(parent);
40
+ }
41
+ }
42
+ let created = false;
43
+ try {
44
+ mkdirSync(path, { mode: 0o700 });
45
+ created = true;
46
+ }
47
+ catch (error) {
48
+ if (error.code !== 'EEXIST')
49
+ throw error;
50
+ }
51
+ assertNoRedirectedAncestors(path);
52
+ if (!lstatSync(path).isDirectory())
53
+ throw Error('cache_path');
54
+ if (created && process.platform === 'win32')
55
+ protectNewWindowsPrivateDirectory(path);
56
+ }
57
+ function readCache(path, now) {
58
+ assertPrivateStatePath(path);
59
+ try {
60
+ const c = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 1024 }).toString('utf8'));
61
+ if (!c || Array.isArray(c) || Object.keys(c).sort().join(',') !== 'checked_at,failed,latest,schema_version' || c.schema_version !== 1 ||
62
+ !Number.isSafeInteger(c.checked_at) || c.checked_at < 0 || c.checked_at > now || typeof c.failed !== 'boolean' ||
63
+ (c.latest !== null && !version(c.latest)) || (!c.failed && c.latest === null))
64
+ return null;
65
+ return c;
66
+ }
67
+ catch (error) {
68
+ if (error.code === 'ENOENT' || error instanceof SyntaxError)
69
+ return null;
70
+ throw error;
71
+ }
72
+ }
73
+ function writeCache(path, c) {
74
+ let stage;
75
+ try {
76
+ assertPrivateStatePath(path);
77
+ stage = join(dirname(path), '.aptly-update-' + randomUUID());
78
+ const fd = openSync(stage, 'wx', 0o600);
79
+ try {
80
+ writeFileSync(fd, JSON.stringify(c) + '\n');
81
+ }
82
+ finally {
83
+ closeSync(fd);
84
+ }
85
+ assertPrivateStatePath(stage);
86
+ assertPrivateStatePath(path);
87
+ renameSync(stage, path);
88
+ stage = undefined;
89
+ }
90
+ finally {
91
+ if (stage)
92
+ try {
93
+ unlinkSync(stage);
94
+ }
95
+ catch { /* Best-effort cleanup of our stage only. */ }
96
+ }
97
+ }
98
+ async function latestStable(fetcher) {
99
+ const controller = new AbortController();
100
+ let timer;
101
+ let reader;
102
+ const work = async () => {
103
+ const response = await fetcher(registry, { signal: controller.signal, redirect: 'error', credentials: 'omit', headers: { accept: 'application/json' } });
104
+ if (!response.ok || !response.body)
105
+ throw Error('registry_response');
106
+ const size = response.headers.get('content-length');
107
+ if (size !== null && (!/^\d+$/.test(size) || Number(size) > maximumBody))
108
+ throw Error('registry_size');
109
+ reader = response.body.getReader();
110
+ let total = 0;
111
+ const chunks = [];
112
+ for (;;) {
113
+ const chunk = await reader.read();
114
+ if (chunk.done)
115
+ break;
116
+ total += chunk.value.byteLength;
117
+ if (total > maximumBody)
118
+ throw Error('registry_size');
119
+ chunks.push(chunk.value);
120
+ }
121
+ const bytes = new Uint8Array(total);
122
+ let offset = 0;
123
+ for (const chunk of chunks) {
124
+ bytes.set(chunk, offset);
125
+ offset += chunk.byteLength;
126
+ }
127
+ const metadata = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
128
+ if (!metadata || metadata.name !== 'aptly' || !version(metadata.version))
129
+ throw Error('registry_metadata');
130
+ return metadata.version;
131
+ };
132
+ try {
133
+ return await Promise.race([work(), new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(Error('registry_timeout')); }, timeout); })]);
134
+ }
135
+ finally {
136
+ if (timer)
137
+ clearTimeout(timer);
138
+ controller.abort();
139
+ if (reader)
140
+ void reader.cancel().catch(() => { });
141
+ }
142
+ }
143
+ /** Returns one stderr hint; never prints, reads credentials, or changes installed code. */
144
+ export async function updateNotification(options) {
145
+ if (!eligible(options))
146
+ return null;
147
+ const now = options.now ?? Date.now();
148
+ if (!Number.isSafeInteger(now) || now < 0)
149
+ return null;
150
+ const path = options.cachePath ?? join(homedir(), '.cache', 'aptly', 'update-check.json');
151
+ let cached;
152
+ try {
153
+ if (!isAbsolute(path) || parse(path).root === path)
154
+ return null;
155
+ directory(dirname(path));
156
+ cached = readCache(path, now);
157
+ }
158
+ catch {
159
+ return null;
160
+ }
161
+ if (cached && now - cached.checked_at < (cached.failed ? cooldown : ttl))
162
+ return !cached.failed && cached.latest && newer(cached.latest, options.currentVersion) ? hint(cached.latest, options.currentVersion) : null;
163
+ try {
164
+ const latest = await latestStable(options.fetch ?? globalThis.fetch);
165
+ try {
166
+ writeCache(path, { schema_version: 1, checked_at: now, latest, failed: false });
167
+ }
168
+ catch { /* Notification must not make CLI commands fail. */ }
169
+ return newer(latest, options.currentVersion) ? hint(latest, options.currentVersion) : null;
170
+ }
171
+ catch {
172
+ try {
173
+ writeCache(path, { schema_version: 1, checked_at: now, latest: null, failed: true });
174
+ }
175
+ catch { /* Silent best effort; no provider/ledger fallback. */ }
176
+ return null;
177
+ }
178
+ }
179
+ function hint(latest, current) { return `Aptly ${latest} is available (installed: ${current}). Run aptly update to update this global installation; use the installation guide for local installs.`; }
@@ -0,0 +1,13 @@
1
+ export interface UpdateResult {
2
+ status: 'complete' | 'error';
3
+ codes: string[];
4
+ version?: string;
5
+ }
6
+ export interface UpdateDependencies {
7
+ nodePath?: string;
8
+ run?: (executable: string, args: readonly string[], timeout: number) => string;
9
+ }
10
+ /** Explicit global-only update. Never invokes a shell, PATH npm, setup, or an existing host launcher. */
11
+ export declare function updateGlobalInstallation(options: {
12
+ packageRoot: string;
13
+ }, dependencies?: UpdateDependencies): UpdateResult;
@@ -0,0 +1,68 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { lstatSync, readFileSync, realpathSync } from 'node:fs';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+ const failed = (code) => { throw new Error(code); };
5
+ const runNpm = (executable, args, timeout) => execFileSync(executable, [...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout, maxBuffer: 1024 * 1024, windowsHide: true });
6
+ const metadata = (root) => JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
7
+ const canonical = (path) => realpathSync(path);
8
+ function absoluteOutput(output) {
9
+ const path = output.trim();
10
+ if (!path || !isAbsolute(path) || /[\r\n\0]/.test(path))
11
+ failed('update_global_install_unverified');
12
+ return resolve(path);
13
+ }
14
+ function verifyPackage(root) {
15
+ const pkg = metadata(root);
16
+ if (pkg.name !== 'aptly' || typeof pkg.version !== 'string' || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(pkg.version) || pkg.bin?.aptly !== 'dist/bin/aptly.js')
17
+ failed('update_global_install_unverified');
18
+ const cli = join(root, 'dist', 'bin', 'aptly.js');
19
+ if (!lstatSync(cli).isFile() || canonical(cli) !== join(canonical(root), 'dist', 'bin', 'aptly.js'))
20
+ failed('update_global_install_unverified');
21
+ return pkg.version;
22
+ }
23
+ /** Explicit global-only update. Never invokes a shell, PATH npm, setup, or an existing host launcher. */
24
+ export function updateGlobalInstallation(options, dependencies = {}) {
25
+ let stage = 'update_global_install_unverified';
26
+ try {
27
+ const node = dependencies.nodePath ?? process.execPath, run = dependencies.run ?? runNpm;
28
+ if (!isAbsolute(node) || !isAbsolute(options.packageRoot))
29
+ failed(stage);
30
+ const nodeDirectory = dirname(node);
31
+ const npm = process.platform === 'win32' ? join(nodeDirectory, 'node_modules', 'npm', 'bin', 'npm-cli.js') : resolve(nodeDirectory, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js');
32
+ if (!lstatSync(npm).isFile() || metadata(dirname(dirname(npm))).name !== 'npm')
33
+ failed(stage);
34
+ const invoke = (args, timeout = 15000) => run(node, [npm, ...args], timeout);
35
+ const npmVersion = invoke(['--version']).trim().match(/^(\d+)\.(\d+)\.(\d+)$/);
36
+ if (!npmVersion || !npmVersion.slice(1).every(part => Number.isSafeInteger(Number(part))))
37
+ failed('update_npm_unsupported');
38
+ const prefix = absoluteOutput(invoke(['prefix', '--global'])), root = absoluteOutput(invoke(['root', '--global']));
39
+ const expectedRoot = process.platform === 'win32' ? join(prefix, 'node_modules') : join(prefix, 'lib', 'node_modules');
40
+ if (canonical(root) !== canonical(expectedRoot))
41
+ failed(stage);
42
+ const target = join(root, 'aptly');
43
+ if (lstatSync(target).isSymbolicLink() || !lstatSync(target).isDirectory() || canonical(target) !== canonical(options.packageRoot))
44
+ failed(stage);
45
+ verifyPackage(target);
46
+ // Query the same effective global npm configuration used for installation.
47
+ // A successful dry-run does not prove the on-disk package was updated.
48
+ stage = 'update_configuration_unverified';
49
+ const dryRun = invoke(['config', 'get', 'dry-run', '--global', '--prefix', prefix]).trim();
50
+ if (dryRun === 'true')
51
+ failed('update_dry_run_enabled');
52
+ if (dryRun !== 'false')
53
+ failed(stage);
54
+ // Explicit prefix pins the operation to the verified installation, including custom prefixes.
55
+ // Lifecycle scripts remain disabled: updating code must not rewrite host registration or trust.
56
+ stage = 'update_install_failed';
57
+ invoke(['install', '-g', 'aptly@latest', '--ignore-scripts', '--prefix', prefix], 120000);
58
+ stage = 'update_result_unverified';
59
+ if (lstatSync(target).isSymbolicLink() || canonical(target) !== canonical(options.packageRoot))
60
+ failed(stage);
61
+ const version = verifyPackage(target);
62
+ return { status: 'complete', codes: ['package_updated', 'host_configuration_preserved', 'setup_required', 'mcp_restart_required'], version };
63
+ }
64
+ catch (error) {
65
+ const code = error instanceof Error && ['update_global_install_unverified', 'update_npm_unsupported', 'update_dry_run_enabled'].includes(error.message) ? error.message : stage;
66
+ return { status: 'error', codes: [code] };
67
+ }
68
+ }
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.2";
1
+ export declare const VERSION = "0.1.4";
@@ -1 +1 @@
1
- export const VERSION = '0.1.2';
1
+ export const VERSION = '0.1.4';