aptly 0.1.20 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/src/setup.js CHANGED
@@ -112,6 +112,46 @@ function newTomlBlock(entry) {
112
112
  lines.push(`${key} = ${q(value)}`);
113
113
  return lines.concat(blockEnd, '').join('\n');
114
114
  }
115
+ /** Codex may put new tables before the trailing comment of its last table. */
116
+ function rewriteOwnedCodexBlock(text, receiptBlock, previous, replacement) {
117
+ if (!receiptBlock)
118
+ return fail('managed_mcp_changed');
119
+ if (text.includes(receiptBlock))
120
+ return text.replace(receiptBlock, () => replacement);
121
+ const expected = { mcp_servers: { aptly: previous } };
122
+ const matches = (block) => {
123
+ try {
124
+ return isDeepStrictEqual(toml(block), expected);
125
+ }
126
+ catch {
127
+ return false;
128
+ }
129
+ };
130
+ if (!matches(receiptBlock))
131
+ return fail('managed_mcp_changed');
132
+ const lines = text.split(/(?<=\n)/);
133
+ const trimmed = lines.map(line => line.trim());
134
+ const markers = (marker) => trimmed.flatMap((line, index) => line === marker ? [index] : []);
135
+ const starts = markers(blockStart), ends = markers(blockEnd);
136
+ if (starts.length !== 1 || ends.length !== 1 || starts[0] >= ends[0])
137
+ return fail('managed_mcp_changed');
138
+ const [start] = starts, [end] = ends;
139
+ const headers = trimmed.flatMap((line, index) => index > start && index < end && line.startsWith('[') ? [index] : []);
140
+ if (headers.length < 2 || trimmed[headers[0]] !== '[mcp_servers.aptly]' ||
141
+ trimmed[headers[1]] !== '[mcp_servers.aptly.env]')
142
+ return fail('managed_mcp_changed');
143
+ const nextTable = headers[2] ?? end;
144
+ let blockEndAt = nextTable;
145
+ while (blockEndAt > start && !trimmed[blockEndAt - 1])
146
+ blockEndAt--;
147
+ // Refuse to remove operator comments or accept additional settings in the two owned tables.
148
+ const owned = lines.slice(start + 1, blockEndAt);
149
+ const containsComment = owned.some(line => line.replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, '').includes('#'));
150
+ if (containsComment || !matches(owned.join('')))
151
+ return fail('managed_mcp_changed');
152
+ // Move the end marker back to its own block. Keep intervening tables and all text around them.
153
+ return lines.slice(0, start).join('') + replacement + lines.slice(blockEndAt, end).join('') + lines.slice(end + 1).join('');
154
+ }
115
155
  /** Append only the owned env table/keys; validation rejects inline/ambiguous layouts. */
116
156
  function addTomlEnv(text, additions) {
117
157
  if (!Object.keys(additions).length)
@@ -450,9 +490,7 @@ function prepare(options, client, removing, edit) {
450
490
  if (!isDeepStrictEqual(servers.aptly, owned.mcp))
451
491
  fail('managed_mcp_changed');
452
492
  if (client === 'codex') {
453
- if (!owned.toml_block || !(mcp.before ?? '').includes(owned.toml_block))
454
- fail('managed_mcp_changed');
455
- mcp.after = (mcp.before ?? '').replace(owned.toml_block, '');
493
+ mcp.after = rewriteOwnedCodexBlock(mcp.before ?? '', owned.toml_block, owned.mcp, '');
456
494
  const expected = structuredClone(config);
457
495
  delete expected.mcp_servers.aptly;
458
496
  // An empty mcp_servers parent is semantically harmless after removing our section.
@@ -502,20 +540,19 @@ function prepare(options, client, removing, edit) {
502
540
  const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
503
541
  const additions = { APTLY_HOOK_POLICY_PATH: policyPath, ROUTER_LEDGER_PATH: join(stateDir, 'ledger.json') };
504
542
  let created = false, tomlBlock;
543
+ const migration = edit && 'migrate' in edit ? edit : undefined;
544
+ const entry = servers.aptly;
545
+ if (migration && (!oldOwner || !object(entry) || (oldOwner.mcp_created ? !isDeepStrictEqual(entry, oldOwner.mcp) : !migration.includeExisting))) {
546
+ fail('launcher_migration_not_owned');
547
+ }
505
548
  // Explicit migration may replace an exact-owned unavailable/older generation.
506
549
  // Its bytes are never executed or trusted for credential injection; only the
507
550
  // replacement made from this CLI's verified source is used after commit.
508
- const ownedStableMigration = edit && 'migrate' in edit && oldOwner?.mcp_created && isDeepStrictEqual(servers.aptly, oldOwner.mcp) ? stableReference(servers.aptly, { home: options.home }) : null;
509
- const existingStable = ownedStableMigration ?? validateStableRegistration(servers.aptly, { home: options.home });
510
- if (options.launcher === 'stable' && servers.aptly !== undefined && !existingStable && !(edit && 'migrate' in edit))
551
+ const ownedStableMigration = migration && oldOwner?.mcp_created ? stableReference(entry, { home: options.home }) : null;
552
+ const existingStable = ownedStableMigration ?? validateStableRegistration(entry, { home: options.home });
553
+ if (options.launcher && entry !== undefined && options.launcher !== existingStable?.launcher && !migration)
511
554
  fail('stable_launcher_migration_required');
512
- const stableRequested = options.launcher === 'stable' || !!existingStable;
513
- if (stableRequested && (servers.aptly === undefined || !!(edit && 'migrate' in edit)))
514
- stableRuntime = planStableRuntime({ packageRoot: root, home: options.home });
515
- if (edit && 'migrate' in edit) {
516
- if (!oldOwner || !object(servers.aptly) || (oldOwner.mcp_created ? !isDeepStrictEqual(servers.aptly, oldOwner.mcp) : !edit.includeExisting))
517
- fail('launcher_migration_not_owned');
518
- const entry = servers.aptly;
555
+ if (migration) {
519
556
  if (!existingStable && (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])))
520
557
  fail('launcher_migration_not_standard');
521
558
  if (!entries.some(entry => isDeepStrictEqual(entry, oldOwner.hook)) || !isDeepStrictEqual(json(policy.before), oldOwner.policy))
@@ -524,6 +561,9 @@ function prepare(options, client, removing, edit) {
524
561
  if (entry.env?.[key] !== value)
525
562
  fail('managed_entry_changed');
526
563
  }
564
+ const managedLauncher = options.launcher ?? existingStable?.launcher;
565
+ if (managedLauncher && (entry === undefined || migration))
566
+ stableRuntime = planStableRuntime({ packageRoot: root, home: options.home, launcher: managedLauncher });
527
567
  if (servers.aptly === undefined) {
528
568
  created = true;
529
569
  servers.aptly = { ...(client === 'claude' ? { type: 'stdio' } : {}), command: stableRuntime?.descriptor.command ?? process.execPath, args: stableRuntime?.descriptor.args ?? [join(root, 'dist', 'src', 'server.js')], ...(client === 'codex' ? { env_vars: ['OPENAI_API_KEY'] } : {}), env: { ROUTER_PROVIDER: edit && 'defaults' in edit ? 'decisions' : env.ROUTER_PROVIDER === 'fixture' ? 'fixture' : 'decisions', ...additions } };
@@ -566,7 +606,7 @@ function prepare(options, client, removing, edit) {
566
606
  else
567
607
  mcp.after = stringify(config);
568
608
  }
569
- else if (edit) {
609
+ else if (edit && !(client === 'codex' && oldOwner?.mcp_created)) {
570
610
  mcp.after = client === 'codex' ? updateTomlEnv(mcp.after, updates) : stringify(config);
571
611
  if (client === 'codex' && 'migrate' in edit && !oldOwner?.mcp_created)
572
612
  mcp.after = updateTomlLauncher(mcp.after, servers.aptly);
@@ -618,18 +658,15 @@ function prepare(options, client, removing, edit) {
618
658
  const owner = oldOwner ?? { schema_version: 1, kind: 'aptly-setup-ownership', client, hook: hookValue, policy: policyValue, policy_created: policy.before === null, mcp_created: created, ...(created ? { mcp: servers.aptly } : {}), env_added: envAdded, ...(tomlBlock ? { toml_block: tomlBlock } : {}) };
619
659
  if (edit && oldOwner) {
620
660
  if (oldOwner.mcp_created) {
621
- owner.mcp = structuredClone(servers.aptly);
622
661
  if (client === 'codex') {
623
- const oldBlock = oldOwner.toml_block;
624
- if (!oldBlock || !(mcp.before ?? '').includes(oldBlock))
625
- fail('managed_mcp_changed');
626
662
  const nextBlock = newTomlBlock(servers.aptly);
627
- const rendered = (mcp.before ?? '').replace(oldBlock, nextBlock);
663
+ const rendered = rewriteOwnedCodexBlock(mcp.before ?? '', oldOwner.toml_block, oldOwner.mcp, nextBlock);
628
664
  if (!isDeepStrictEqual(toml(rendered), config))
629
665
  fail('managed_mcp_changed');
630
666
  mcp.after = rendered;
631
667
  owner.toml_block = nextBlock;
632
668
  }
669
+ owner.mcp = structuredClone(servers.aptly);
633
670
  }
634
671
  else {
635
672
  const prior = client === 'codex' ? toml(mcp.before ?? '') : json(mcp.before);
@@ -670,7 +707,7 @@ function prepare(options, client, removing, edit) {
670
707
  result.transmission_review = reviewMatches(review.after, options, client, policyValue) ? 'complete' : 'required';
671
708
  const snapshotOutdated = !!existingStable && !stableRuntime && 'version' in existingStable && existingStable.version !== json(read(join(root, 'package.json')).text).version;
672
709
  if (snapshotOutdated)
673
- result.recovery = [`aptly setup --client ${client} --migrate-launcher --launcher stable --dry-run`];
710
+ result.recovery = [`aptly setup --client ${client} --migrate-launcher --launcher ${existingStable.launcher} --dry-run`];
674
711
  if (client === 'codex')
675
712
  result.requires_hook_review = true;
676
713
  result.codes = [...(snapshotOutdated ? ['stable_snapshot_outdated'] : []), ...(client === 'codex' ? ['requires_hook_review'] : []), ...(result.transmission === 'unselected' ? ['transmission_selection_required'] : result.transmission_source === 'legacy' ? ['legacy_transmission_excerpt'] : []), ...(requestedScope !== undefined || result.budget?.restart_required ? ['mcp_restart_required'] : [])];
@@ -752,7 +789,7 @@ function execute(options, removing, edit, captured) {
752
789
  if (clients.some(client => client !== 'codex' && client !== 'claude'))
753
790
  return { status: 'partial', clients: [] };
754
791
  const env = options.env ?? process.env;
755
- if (options.launcher !== undefined && (options.launcher !== 'stable' || removing || !!(edit && !('migrate' in edit))))
792
+ if (options.launcher !== undefined && (!['stable', 'npx'].includes(options.launcher) || removing || !!(edit && !('migrate' in edit)) || (options.automatic && options.launcher === 'npx')))
756
793
  return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['stable_launcher_invalid_options'] })) };
757
794
  if (options.transmission !== undefined && !['none', 'description', 'excerpt'].includes(options.transmission))
758
795
  return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['transmission_invalid_scope'] })) };
@@ -767,7 +804,7 @@ function execute(options, removing, edit, captured) {
767
804
  }
768
805
  });
769
806
  const results = prepared.map(plan => plan.result);
770
- if ((edit || options.launcher === 'stable') && results.some(result => result.status === 'error'))
807
+ if ((edit || options.launcher !== undefined) && results.some(result => result.status === 'error'))
771
808
  return { status: 'partial', clients: results.map(result => result.status === 'error' ? result : { ...result, status: 'skipped', codes: ['other_host_validation_failed'] }) };
772
809
  // Each host is independent; prepare every host before committing any host.
773
810
  for (const plan of prepared) {
@@ -1014,14 +1051,14 @@ export function setPolicySource(options, dryRun = false) {
1014
1051
  fail('managed_mcp_changed');
1015
1052
  if (!isDeepStrictEqual(expected, entry))
1016
1053
  fail('managed_mcp_changed');
1017
- const previousBlock = newTomlBlock(entry);
1018
- if (!mcp.before.includes(owner.toml_block) && !mcp.before.includes(previousBlock))
1019
- fail('managed_mcp_changed');
1054
+ const previous = structuredClone(entry);
1055
+ const previousBlock = newTomlBlock(previous);
1056
+ const oldBlock = mcp.before.includes(owner.toml_block) ? owner.toml_block : previousBlock;
1020
1057
  entry.env.APTLY_HOOK_POLICY_PATH = CODEX_HOME_POLICY_SOURCE;
1021
1058
  if (!vars.includes('CODEX_HOME'))
1022
1059
  entry.env_vars = [...vars, 'CODEX_HOME'];
1023
- const nextBlock = newTomlBlock(entry), oldBlock = mcp.before.includes(owner.toml_block) ? owner.toml_block : previousBlock;
1024
- mcp.after = mcp.before.replace(oldBlock, nextBlock);
1060
+ const nextBlock = newTomlBlock(entry);
1061
+ mcp.after = rewriteOwnedCodexBlock(mcp.before, oldBlock, previous, nextBlock);
1025
1062
  if (!isDeepStrictEqual(toml(mcp.after), config))
1026
1063
  fail('managed_mcp_changed');
1027
1064
  owner.mcp = structuredClone(entry);
@@ -4,6 +4,7 @@ export declare const stableRuntimeLimits: Readonly<{
4
4
  fileBytes: number;
5
5
  manifestBytes: number;
6
6
  }>;
7
+ export type ManagedLauncher = 'stable' | 'npx';
7
8
  export interface StableFile {
8
9
  readonly path: string;
9
10
  readonly size: number;
@@ -30,6 +31,7 @@ export interface StableRegistration {
30
31
  readonly generation: string;
31
32
  readonly manifest: StableManifest;
32
33
  readonly integrity: 'full' | 'metadata';
34
+ readonly launcher: ManagedLauncher;
33
35
  }
34
36
  export interface StableRuntimePlan extends StableRegistration {
35
37
  readonly descriptor: {
@@ -43,6 +45,7 @@ export interface StableReference {
43
45
  readonly args: readonly ['serve'];
44
46
  readonly generation: string;
45
47
  readonly runtimeRoot: string;
48
+ readonly launcher: ManagedLauncher;
46
49
  }
47
50
  /** Shape only. Reads OS alias metadata, never runtime bytes or credentials. */
48
51
  export declare function stableReference(entry: unknown, { home }?: {
@@ -52,6 +55,7 @@ export declare function planStableRuntime(options: {
52
55
  packageRoot: string;
53
56
  home?: string;
54
57
  nodePath?: string;
58
+ launcher?: ManagedLauncher;
55
59
  }): StableRuntimePlan;
56
60
  export declare function materializeStableRuntime(plan: StableRuntimePlan): void;
57
61
  export declare function validateStableRegistration(entry: unknown, { home, metadataOnly }?: {
@@ -44,6 +44,7 @@ function canonicalAllowed(path) {
44
44
  }
45
45
  return current;
46
46
  }
47
+ const launchName = (mode) => mode === 'npx' ? 'launch-npx' : 'launch';
47
48
  /** Shape only. Reads OS alias metadata, never runtime bytes or credentials. */
48
49
  export function stableReference(entry, { home = homedir() } = {}) {
49
50
  const command = object(entry) ? entry.command : undefined;
@@ -58,10 +59,10 @@ export function stableReference(entry, { home = homedir() } = {}) {
58
59
  if (!cleanAbsolute(command) || Object.hasOwn(entry, 'url') || (entry.type !== undefined && entry.type !== 'stdio') || !Array.isArray(entry.args) || entry.args.length !== 1 || entry.args[0] !== 'serve')
59
60
  fail('stable_runtime_unverified');
60
61
  const suffix = relative(base, candidate).split(sep);
61
- if (suffix.length !== 2 || !/^[a-f0-9]{64}$/.test(suffix[0]) || suffix[1] !== 'launch')
62
+ if (suffix.length !== 2 || !/^[a-f0-9]{64}$/.test(suffix[0]) || !['launch', 'launch-npx'].includes(suffix[1]))
62
63
  fail('stable_runtime_unverified');
63
64
  const runtimeRoot = join(baseFor(canonicalHome), suffix[0]);
64
- return frozen({ command: join(runtimeRoot, 'launch'), args: ['serve'], generation: suffix[0], runtimeRoot });
65
+ return frozen({ command: join(runtimeRoot, suffix[1]), args: ['serve'], generation: suffix[0], runtimeRoot, launcher: suffix[1] === 'launch-npx' ? 'npx' : 'stable' });
65
66
  }
66
67
  function platform() { if (process.platform === 'win32')
67
68
  fail('stable_launcher_platform_unsupported'); }
@@ -150,6 +151,81 @@ async function main(){
150
151
  main().catch(()=>{if(!quiet){process.stderr.write('aptly: stable_runtime_unavailable\n');process.exitCode=1;}});
151
152
  `;
152
153
  const bootstrapHash = digest(bootstrap);
154
+ // Adapt the verified bootstrap without changing any released stable generation.
155
+ const npxBootstrap = [
156
+ ["path.join(root,'launch')", "path.join(root,'launch-npx')"],
157
+ ["if(mode!=='serve'&&mode!=='observe')bad();if(mode==='serve'&&process.argv.length!==3)bad();",
158
+ "if(mode!=='serve'&&mode!=='serve-verified'&&mode!=='observe')bad();if(!quiet&&process.argv.length!==3)bad();"],
159
+ ["if(mode==='serve'){const server", "if(mode==='serve')await runNpx(m,payload);\n else if(mode==='serve-verified'){restoreHostPath();const server"],
160
+ ].reduce((source, [before, after]) => {
161
+ if (source.split(before).length !== 2)
162
+ fail('stable_runtime_unverified');
163
+ return source.replace(before, () => after);
164
+ }, bootstrap)
165
+ + String.raw `
166
+ function restoreHostPath(){
167
+ const present=process.env.APTLY_HOST_PATH_PRESENT,value=process.env.APTLY_HOST_PATH;
168
+ delete process.env.APTLY_HOST_PATH_PRESENT;delete process.env.APTLY_HOST_PATH;
169
+ if(present==='1'&&value!==undefined)process.env.PATH=value;
170
+ else if(present==='0'&&value===undefined)delete process.env.PATH;
171
+ else bad();
172
+ }
173
+ async function runNpx(m,payload){
174
+ const processes=require('node:child_process');
175
+ const bin=path.dirname(process.execPath),prefix=path.dirname(bin);
176
+ const candidates=[path.join(prefix,'lib/node_modules/npm/bin/npx-cli.js'),path.join(prefix,'share/nodejs/npm/bin/npx-cli.js')];
177
+ const npx=candidates.find(file=>{
178
+ try{
179
+ let current=file;
180
+ if(!fs.lstatSync(file).isFile())return false;
181
+ for(;;){
182
+ const s=fs.lstatSync(current);
183
+ const stickyRoot=s.isDirectory()&&s.uid===0&&(s.mode&512)!==0;
184
+ if(s.isSymbolicLink()||((s.mode&18)&&!stickyRoot)||(process.getuid&&s.uid!==0&&s.uid!==process.getuid()))return false;
185
+ const parent=path.dirname(current);if(parent===current)return true;current=parent;
186
+ }
187
+ }catch{return false;}
188
+ });
189
+ if(!npx)bad();
190
+ const work=fs.mkdtempSync(path.join(root,'.npx-session-'));
191
+ const quote=value=>"'"+value.replaceAll("'","'\\''")+"'";
192
+ try{
193
+ const modules=path.join(work,'node_modules');
194
+ fs.mkdirSync(modules,{mode:0o700});
195
+ fs.symlinkSync(payload,path.join(modules,'aptly'),'dir');
196
+ fs.writeFileSync(path.join(work,'package.json'),JSON.stringify({name:'aptly-launcher',private:true,dependencies:{aptly:m.version}}),{mode:0o600});
197
+ for(const name of ['user-npmrc','global-npmrc'])fs.writeFileSync(path.join(work,name),'',{mode:0o600});
198
+ const env=Object.fromEntries(Object.entries(process.env).filter(([name])=>!/^npm_/i.test(name)&&!['NODE_OPTIONS','NODE_PATH','NODE_REPL_EXTERNAL_MODULE','INIT_CWD'].includes(name)));
199
+ delete env.APTLY_HOST_PATH;delete env.APTLY_HOST_PATH_PRESENT;
200
+ env.APTLY_HOST_PATH_PRESENT=Object.hasOwn(process.env,'PATH')?'1':'0';
201
+ if(env.APTLY_HOST_PATH_PRESENT==='1')env.APTLY_HOST_PATH=process.env.PATH;
202
+ Object.assign(env,{PATH:bin+':/usr/bin:/bin',npm_config_cache:path.join(work,'cache'),npm_config_userconfig:path.join(work,'user-npmrc'),
203
+ npm_config_globalconfig:path.join(work,'global-npmrc'),npm_config_registry:'https://registry.npmjs.org/',npm_config_update_notifier:'false',
204
+ npm_config_prefix:path.join(work,'global'),npm_config_global:'false',npm_config_script_shell:'/bin/sh',
205
+ npm_config_audit:'false',npm_config_fund:'false',npm_config_loglevel:'silent'});
206
+ const command='exec '+quote(process.execPath)+' --no-warnings '+quote(path.join(root,'bootstrap.cjs'))+' serve-verified';
207
+ const child=processes.spawn(process.execPath,[npx,'--offline','--no','--ignore-scripts','--package=aptly@'+m.version,'--call',command],
208
+ {cwd:work,env,stdio:['inherit','inherit','ignore'],detached:true});
209
+ let killTimer,stopping=false;
210
+ const signals=['SIGINT','SIGTERM','SIGHUP'];
211
+ const forward=signal=>{
212
+ if(!child.pid)return;
213
+ stopping=true;
214
+ try{process.kill(-child.pid,signal);}catch{}
215
+ killTimer??=setTimeout(()=>{try{process.kill(-child.pid,'SIGKILL');}catch{}},2000);
216
+ };
217
+ const handlers=new Map(signals.map(signal=>[signal,()=>forward(signal)]));
218
+ for(const [signal,handle]of handlers)process.on(signal,handle);
219
+ try{
220
+ const code=await new Promise((resolve,reject)=>{child.once('error',reject);child.once('close',resolve);});
221
+ if(code!==0&&!stopping)bad();
222
+ }finally{clearTimeout(killTimer);for(const [signal,handle]of handlers)process.off(signal,handle);}
223
+ }finally{fs.rmSync(work,{recursive:true,force:true});}
224
+ }
225
+ `;
226
+ const npxBootstrapHash = digest(npxBootstrap);
227
+ const bootstrapFor = (mode) => mode === 'npx' ? npxBootstrap : bootstrap;
228
+ const hashFor = (mode) => mode === 'npx' ? npxBootstrapHash : bootstrapHash;
153
229
  function sourceFiles(packageRoot) {
154
230
  const root = canonicalAllowed(packageRoot), files = [];
155
231
  let bytes = 0;
@@ -263,12 +339,12 @@ function sourceFiles(packageRoot) {
263
339
  return { files, version: metadata.version };
264
340
  }
265
341
  function manifestBody(manifest) { return { schema_version: manifest.schema_version, kind: manifest.kind, version: manifest.version, home: manifest.home, node_path: manifest.node_path, launcher_revision: manifest.launcher_revision, bootstrap_sha256: manifest.bootstrap_sha256, launcher_sha256: manifest.launcher_sha256, files: manifest.files }; }
266
- function readManifest(root, home) {
342
+ function readManifest(root, home, mode) {
267
343
  const value = JSON.parse(readPrivate(join(root, 'manifest.json'), stableRuntimeLimits.manifestBytes).toString('utf8'));
268
- if (!exact(value, ['schema_version', 'kind', 'version', 'home', 'node_path', 'launcher_revision', 'bootstrap_sha256', 'launcher_sha256', 'files', 'generation']) || value.schema_version !== 1 || value.kind !== 'aptly-stable-runtime' || value.launcher_revision !== 1 || value.home !== home || !cleanAbsolute(value.node_path) || typeof value.version !== 'string' || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(value.version) || value.bootstrap_sha256 !== bootstrapHash || !Array.isArray(value.files) || value.files.length > stableRuntimeLimits.files)
344
+ if (!exact(value, ['schema_version', 'kind', 'version', 'home', 'node_path', 'launcher_revision', 'bootstrap_sha256', 'launcher_sha256', 'files', 'generation']) || value.schema_version !== 1 || value.kind !== 'aptly-stable-runtime' || value.launcher_revision !== 1 || value.home !== home || !cleanAbsolute(value.node_path) || typeof value.version !== 'string' || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(value.version) || value.bootstrap_sha256 !== hashFor(mode) || !Array.isArray(value.files) || value.files.length > stableRuntimeLimits.files)
269
345
  fail('stable_runtime_unverified');
270
- const expectedLauncher = launcher(value.node_path, home);
271
- if (value.launcher_sha256 !== digest(expectedLauncher) || readPrivate(join(root, 'launch'), 65536).toString('utf8') !== expectedLauncher || readPrivate(join(root, 'bootstrap.cjs'), 65536).toString('utf8') !== bootstrap || (lstatSync(join(root, 'launch')).mode & 0o100) === 0)
346
+ const expectedLauncher = launcher(value.node_path, home, mode), entry = join(root, launchName(mode));
347
+ if (value.launcher_sha256 !== digest(expectedLauncher) || readPrivate(entry, 65536).toString('utf8') !== expectedLauncher || readPrivate(join(root, 'bootstrap.cjs'), 65536).toString('utf8') !== bootstrapFor(mode) || (lstatSync(entry).mode & 0o100) === 0)
272
348
  fail('stable_runtime_unverified');
273
349
  let bytes = 0, previous = '';
274
350
  for (const f of value.files) {
@@ -329,10 +405,26 @@ export function planStableRuntime(options) {
329
405
  platform();
330
406
  try {
331
407
  const root = canonicalAllowed(options.packageRoot), home = canonicalAllowed(options.home ?? homedir()), nodePath = options.nodePath ?? process.execPath;
408
+ const mode = options.launcher ?? 'stable';
332
409
  if (!cleanAbsolute(home) || !cleanAbsolute(nodePath) || !cleanAbsolute(options.packageRoot))
333
410
  fail('stable_source_unverified');
334
411
  // Existing parents may be absent in a dry run; never create them here.
335
412
  safeAncestors(home);
413
+ if (mode === 'npx') {
414
+ const prefix = dirname(dirname(nodePath));
415
+ const cli = ['lib/node_modules/npm/bin/npx-cli.js', 'share/nodejs/npm/bin/npx-cli.js'].some(relative => {
416
+ const file = join(prefix, relative);
417
+ try {
418
+ safeAncestors(file);
419
+ return lstatSync(file).isFile();
420
+ }
421
+ catch {
422
+ return false;
423
+ }
424
+ });
425
+ if (!cli)
426
+ fail('stable_source_unverified');
427
+ }
336
428
  let existing = baseFor(home);
337
429
  while (!existsSync(existing)) {
338
430
  const parent = dirname(existing);
@@ -344,11 +436,13 @@ export function planStableRuntime(options) {
344
436
  assertNoRedirectedAncestors(existing);
345
437
  if (existsSync(baseFor(home)))
346
438
  privatePath(baseFor(home), true);
347
- const captured = sourceFiles(root), body = { schema_version: 1, kind: 'aptly-stable-runtime', version: captured.version, home, node_path: nodePath, launcher_revision: 1, bootstrap_sha256: bootstrapHash, launcher_sha256: digest(launcher(nodePath, home)), files: captured.files.map(({ path, size, sha256 }) => ({ path, size, sha256 })) };
439
+ const captured = sourceFiles(root);
440
+ const body = { schema_version: 1, kind: 'aptly-stable-runtime', version: captured.version, home, node_path: nodePath, launcher_revision: 1, bootstrap_sha256: hashFor(mode), launcher_sha256: digest(launcher(nodePath, home, mode)), files: captured.files.map(({ path, size, sha256 }) => ({ path, size, sha256 })) };
348
441
  const generation = digest(JSON.stringify(body)), runtimeRoot = join(baseFor(home), generation), manifest = { ...body, generation };
349
442
  if (Buffer.byteLength(JSON.stringify(manifest) + '\n') > stableRuntimeLimits.manifestBytes)
350
443
  fail('stable_runtime_limit');
351
- const plan = frozen({ command: join(runtimeRoot, 'launch'), args: ['serve'], packageRoot: join(runtimeRoot, 'payload'), payloadRoot: join(runtimeRoot, 'payload'), runtimeRoot, version: captured.version, generation, manifest, integrity: 'full', descriptor: { command: join(runtimeRoot, 'launch'), args: ['serve'] } });
444
+ const command = join(runtimeRoot, launchName(mode));
445
+ const plan = frozen({ command, args: ['serve'], packageRoot: join(runtimeRoot, 'payload'), payloadRoot: join(runtimeRoot, 'payload'), runtimeRoot, version: captured.version, generation, manifest, integrity: 'full', launcher: mode, descriptor: { command, args: ['serve'] } });
352
446
  if (existsSync(runtimeRoot) && !validateStableRegistration(plan.descriptor, { home }))
353
447
  fail('stable_runtime_unverified');
354
448
  plans.set(plan, { root, files: captured.files });
@@ -439,8 +533,8 @@ export function materializeStableRuntime(plan) {
439
533
  ensureDirectory(dirname(target), true);
440
534
  writeDurable(target, data, 0o600);
441
535
  }
442
- writeDurable(join(stage, 'bootstrap.cjs'), bootstrap, 0o600);
443
- writeDurable(join(stage, 'launch'), launcher(plan.manifest.node_path, plan.manifest.home), 0o700);
536
+ writeDurable(join(stage, 'bootstrap.cjs'), bootstrapFor(plan.launcher), 0o600);
537
+ writeDurable(join(stage, launchName(plan.launcher)), launcher(plan.manifest.node_path, plan.manifest.home, plan.launcher), 0o700);
444
538
  writeDurable(join(stage, 'manifest.json'), JSON.stringify(plan.manifest) + '\n', 0o600);
445
539
  validatePayload(stage, plan.manifest, false);
446
540
  assertSource(plan, captured);
@@ -500,13 +594,13 @@ export function validateStableRegistration(entry, { home = homedir(), metadataOn
500
594
  return null;
501
595
  platform();
502
596
  try {
503
- const selectedHome = canonicalAllowed(home), { command, runtimeRoot } = reference;
597
+ const selectedHome = canonicalAllowed(home), { command, runtimeRoot, launcher: mode } = reference;
504
598
  checkedRoot(runtimeRoot, selectedHome);
505
- const before = identity(join(runtimeRoot, 'manifest.json')), manifest = readManifest(runtimeRoot, selectedHome);
599
+ const before = identity(join(runtimeRoot, 'manifest.json')), manifest = readManifest(runtimeRoot, selectedHome, mode);
506
600
  validatePayload(runtimeRoot, manifest, metadataOnly);
507
601
  if (before !== identity(join(runtimeRoot, 'manifest.json')))
508
602
  fail('stable_runtime_unverified');
509
- return frozen({ command, args: ['serve'], packageRoot: join(runtimeRoot, 'payload'), runtimeRoot, version: manifest.version, generation: manifest.generation, manifest, integrity: metadataOnly ? 'metadata' : 'full' });
603
+ return frozen({ command, args: ['serve'], packageRoot: join(runtimeRoot, 'payload'), runtimeRoot, version: manifest.version, generation: manifest.generation, manifest, integrity: metadataOnly ? 'metadata' : 'full', launcher: mode });
510
604
  }
511
605
  catch {
512
606
  fail('stable_runtime_unverified');
@@ -528,7 +622,14 @@ export function stableObserverCommand(registration, client, policyPath) {
528
622
  fail('stable_runtime_unverified');
529
623
  }
530
624
  }
531
- function launcher(nodePath, home) {
625
+ function launcher(nodePath, home, mode) {
626
+ const name = launchName(mode);
627
+ const requireNpm = mode === 'npx' ? ` if [ "$quiet" -eq 0 ]; then
628
+ prefix=\${candidate%/*/*}
629
+ qualify_file "$prefix/lib/node_modules/npm/bin/npx-cli.js" private ||
630
+ qualify_file "$prefix/share/nodejs/npm/bin/npx-cli.js" private || return 1
631
+ fi
632
+ ` : '';
532
633
  return `#!/bin/sh
533
634
  # Aptly immutable stable launcher v1. No login profiles or shell evaluation.
534
635
  quiet=0
@@ -538,7 +639,7 @@ unset NODE_OPTIONS NODE_PATH NODE_REPL_EXTERNAL_MODULE
538
639
  for utility in /usr/bin/env /usr/bin/uname /usr/bin/id /usr/bin/stat /usr/bin/sort /usr/bin/readlink /bin/date /bin/sleep; do
539
640
  [ -x "$utility" ] || stop
540
641
  done
541
- case "$0" in /*/launch) root=\${0%/launch};; *) stop;; esac
642
+ case "$0" in /*/${name}) root=\${0%/${name}};; *) stop;; esac
542
643
  kernel=$(/usr/bin/uname -s) || stop
543
644
  case "$kernel" in Darwin|Linux) :;; *) stop;; esac
544
645
  owner=$(/usr/bin/id -u) || stop
@@ -601,12 +702,12 @@ private_file() {
601
702
  [ "$user" = "$owner" ] && [ "$((0$bits & 077))" -eq 0 ] && [ "$links" = 1 ]
602
703
  }
603
704
  # Reject directories/FIFOs/links and unsafe ancestry BEFORE opening hash input.
604
- private_file "$root/launch" && [ -x "$root/launch" ] || stop
705
+ private_file "$root/${name}" && [ -x "$root/${name}" ] || stop
605
706
  private_file "$root/bootstrap.cjs" || stop
606
707
  if [ -x /usr/bin/sha256sum ]; then sum=$(/usr/bin/env -i PATH=/usr/bin:/bin LC_ALL=C /usr/bin/sha256sum "$root/bootstrap.cjs" 2>/dev/null) || stop
607
708
  elif [ -x /usr/bin/shasum ]; then sum=$(/usr/bin/env -i PATH=/usr/bin:/bin LC_ALL=C /usr/bin/shasum -a 256 "$root/bootstrap.cjs" 2>/dev/null) || stop
608
709
  else stop; fi
609
- [ "\${sum%% *}" = ${quote(bootstrapHash)} ] || stop
710
+ [ "\${sum%% *}" = ${quote(hashFor(mode))} ] || stop
610
711
  count=0
611
712
  seen=
612
713
  try_node() {
@@ -636,7 +737,7 @@ try_node() {
636
737
  kill "$watchdog" 2>/dev/null; wait "$watchdog" 2>/dev/null
637
738
  budget || stop
638
739
  [ "$status" -eq 0 ] || return 1
639
- # APTLY_OBSERVER_BEGIN
740
+ ${requireNpm} # APTLY_OBSERVER_BEGIN
640
741
  if [ "$quiet" -eq 1 ]; then
641
742
  exec 3<&0 || stop
642
743
  observer_child=
@@ -11,3 +11,22 @@ export interface UpdateDependencies {
11
11
  export declare function updateGlobalInstallation(options: {
12
12
  packageRoot: string;
13
13
  }, dependencies?: UpdateDependencies): UpdateResult;
14
+ type UpdateClient = 'codex' | 'claude';
15
+ type MigrationResult = {
16
+ client: UpdateClient;
17
+ status: 'configured' | 'unchanged' | 'skipped' | 'error';
18
+ codes: string[];
19
+ requires_hook_review?: boolean;
20
+ };
21
+ type UpdateMigrationResult = UpdateResult & {
22
+ migration?: MigrationResult;
23
+ migrations?: MigrationResult[];
24
+ };
25
+ /** Update first, then let the verified fresh CLI migrate the selected or existing owned hosts. */
26
+ export declare function updateGlobalAndMigrate(options: {
27
+ packageRoot: string;
28
+ client?: UpdateClient;
29
+ }, dependencies?: UpdateDependencies & {
30
+ platform?: NodeJS.Platform;
31
+ }): UpdateMigrationResult;
32
+ export {};
@@ -66,3 +66,87 @@ export function updateGlobalInstallation(options, dependencies = {}) {
66
66
  return { status: 'error', codes: [code] };
67
67
  }
68
68
  }
69
+ function readMigration(raw, client, exitedWithError) {
70
+ if (typeof raw !== 'string' || Buffer.byteLength(raw) > 65536)
71
+ return;
72
+ try {
73
+ const value = JSON.parse(raw);
74
+ if (!value || !Array.isArray(value.clients) || value.clients.length !== 1)
75
+ return;
76
+ const result = value.clients[0];
77
+ if (!result || result.client !== client || !Array.isArray(result.codes) || result.codes.length > 64 ||
78
+ !result.codes.every((code) => typeof code === 'string' && /^[a-z0-9_]{1,100}$/.test(code)) ||
79
+ (result.requires_hook_review !== undefined && typeof result.requires_hook_review !== 'boolean'))
80
+ return;
81
+ const valid = exitedWithError
82
+ ? value.status === 'partial' && result.status === 'error' && result.codes.length > 0
83
+ : value.status === 'complete' && ['configured', 'unchanged'].includes(result.status) && result.codes.includes('launcher_migrated');
84
+ if (!valid)
85
+ return;
86
+ return { client, status: result.status, codes: result.codes, ...(result.requires_hook_review !== undefined ? { requires_hook_review: result.requires_hook_review } : {}) };
87
+ }
88
+ catch {
89
+ return;
90
+ }
91
+ }
92
+ function runMigration(cli, client, dependencies, automatic) {
93
+ const failure = (code) => ({ client, status: 'error', codes: [code] });
94
+ let raw, exitedWithError = false;
95
+ try {
96
+ // Inherit the caller's selected host homes. The new CLI revalidates ownership.
97
+ raw = (dependencies.run ?? runNpm)(dependencies.nodePath ?? process.execPath, [cli, 'setup', '--client', client, '--migrate-launcher', '--launcher', 'npx'], 120000);
98
+ }
99
+ catch (error) {
100
+ const child = error;
101
+ if (child?.code === 'ETIMEDOUT' || child?.code === 'ENOBUFS' || typeof child?.signal === 'string')
102
+ return failure('launcher_migration_unverified');
103
+ if (child?.status !== 1)
104
+ return failure('launcher_migration_failed');
105
+ exitedWithError = true;
106
+ raw = child.stdout;
107
+ }
108
+ const result = readMigration(raw, client, exitedWithError);
109
+ if (!result)
110
+ return failure('launcher_migration_failed');
111
+ if (automatic && result.status === 'error' && result.codes.length === 1 && ['launcher_migration_not_owned', 'launcher_migration_not_standard'].includes(result.codes[0]))
112
+ return { ...result, status: 'skipped' };
113
+ return result;
114
+ }
115
+ /** Update first, then let the verified fresh CLI migrate the selected or existing owned hosts. */
116
+ export function updateGlobalAndMigrate(options, dependencies = {}) {
117
+ const supported = ['darwin', 'linux'].includes(dependencies.platform ?? process.platform);
118
+ if (!supported && options.client)
119
+ return { status: 'error', codes: ['npx_launcher_platform_unsupported'] };
120
+ const updated = updateGlobalInstallation(options, dependencies);
121
+ if (updated.status !== 'complete' || !supported)
122
+ return updated;
123
+ const errorResult = (code) => ({ status: 'error', version: updated.version, codes: ['package_updated', code, 'mcp_restart_required'] });
124
+ const migrate = (client, automatic) => {
125
+ try {
126
+ if (lstatSync(options.packageRoot).isSymbolicLink() || verifyPackage(options.packageRoot) !== updated.version)
127
+ failed('update_result_unverified');
128
+ }
129
+ catch {
130
+ return { client, status: 'error', codes: ['update_result_unverified'] };
131
+ }
132
+ return runMigration(join(options.packageRoot, 'dist', 'bin', 'aptly.js'), client, dependencies, automatic);
133
+ };
134
+ if (options.client) {
135
+ const migration = migrate(options.client, false);
136
+ if (migration.status === 'error') {
137
+ const [first] = migration.codes;
138
+ return errorResult(['update_result_unverified', 'launcher_migration_unverified'].includes(first) ? first : 'launcher_migration_failed');
139
+ }
140
+ return { status: 'complete', version: updated.version, codes: ['package_updated', 'launcher_migrated', 'mcp_restart_required'], migration };
141
+ }
142
+ const clients = ['codex', 'claude'];
143
+ const migrations = clients.map(client => migrate(client, true));
144
+ const errors = migrations.filter(result => result.status === 'error');
145
+ if (errors.length) {
146
+ const codes = new Set(errors.map(result => ['update_result_unverified', 'launcher_migration_unverified'].includes(result.codes[0]) ? result.codes[0] : 'launcher_migration_failed'));
147
+ return { status: 'error', version: updated.version, codes: ['package_updated', ...codes, 'mcp_restart_required'], migrations };
148
+ }
149
+ if (migrations.every(result => result.status === 'skipped'))
150
+ return { ...updated, migrations };
151
+ return { status: 'complete', version: updated.version, codes: ['package_updated', 'launcher_migrated', 'mcp_restart_required'], migrations };
152
+ }
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.20";
1
+ export declare const VERSION = "0.1.22";
@@ -1 +1 @@
1
- export const VERSION = '0.1.20';
1
+ export const VERSION = '0.1.22';
@@ -74,7 +74,7 @@ aptly setup --client codex --migrate-launcher --launcher stable --dry-run
74
74
  aptly setup --client codex --migrate-launcher --launcher stable
75
75
  ```
76
76
 
77
- After updating global Aptly, run the same command to update the preserved copy. Ordinary `setup` does not replace it; an old copy reports `stable_snapshot_outdated`. Migration updates owned MCP and statistics observers together. Modified launchers and Hooks are not adopted. To target a preserved standard registration, review it and add `--include-existing`. Approve changed Codex Hooks again in `/hooks`.
77
+ If you continue using stable, run the same command after updating global Aptly to update the preserved copy. Ordinary `setup` does not replace it; an old copy reports `stable_snapshot_outdated`. Migration updates owned MCP and statistics observers together. Modified launchers and Hooks are not adopted. To target a preserved standard registration, review it and add `--include-existing`. Approve changed Codex Hooks again in `/hooks`.
78
78
 
79
79
  <details>
80
80
  <summary>Launcher limits and recovery</summary>
@@ -87,6 +87,21 @@ If ownership matches, a missing, damaged, or older-format copy can be explicitly
87
87
 
88
88
  </details>
89
89
 
90
+ ### Managed npx launcher
91
+
92
+ On macOS and Linux, bare `aptly update` updates the package, then attempts to migrate unchanged Aptly-owned Codex and Claude Code registrations in the configuration homes selected by the current environment to managed npx. Direct and stable registrations are eligible; custom or unmanaged registrations and absent registrations are left alone. Failures are reported per host, so one host can succeed while another fails. The first `aptly update` from 0.1.21 only updates the package; run it again with the new CLI. On Windows, bare update changes only the package.
93
+
94
+ Node.js 24 or later with bundled npm is required. Aptly preserves a pinned snapshot of the installed package and dependencies, then runs `npx` offline in an isolated working directory with clean npm configuration. MCP startup does not contact the registry or select `latest`.
95
+
96
+ To migrate one host explicitly, review the dry run before applying it. For Claude Code, replace `codex` with `claude`.
97
+
98
+ ```sh
99
+ aptly setup --client codex --migrate-launcher --launcher npx --dry-run
100
+ aptly setup --client codex --migrate-launcher --launcher npx
101
+ ```
102
+
103
+ `aptly update --client codex --launcher npx` also targets one host. Explicit managed migration is unsupported on Windows. Check package and migration results separately. Hooks and credentials are preserved subject to ownership checks. Trust changed Codex Hooks again in `/hooks`, then restart the host.
104
+
90
105
  <a id="guide-models-and-environment"></a>
91
106
 
92
107
  ## Models and environment variables