aptly 0.1.21 → 0.2.0

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.
Files changed (43) hide show
  1. package/README.en.md +6 -11
  2. package/README.ja.md +6 -11
  3. package/README.md +6 -11
  4. package/README.zh-CN.md +6 -11
  5. package/dist/bin/aptly.js +50 -10
  6. package/dist/src/antigravity-catalog.d.ts +38 -0
  7. package/dist/src/antigravity-catalog.js +64 -0
  8. package/dist/src/antigravity-hook.d.ts +14 -0
  9. package/dist/src/antigravity-hook.js +84 -0
  10. package/dist/src/antigravity-runtime.d.ts +9 -0
  11. package/dist/src/antigravity-runtime.js +46 -0
  12. package/dist/src/automatic-hook.js +4 -4
  13. package/dist/src/cli-help.js +7 -4
  14. package/dist/src/context-retry.js +1 -1
  15. package/dist/src/core.d.ts +10 -5
  16. package/dist/src/core.js +73 -29
  17. package/dist/src/doctor.d.ts +1 -0
  18. package/dist/src/doctor.js +1 -1
  19. package/dist/src/provider.js +9 -3
  20. package/dist/src/server.d.ts +6 -5
  21. package/dist/src/server.js +41 -3
  22. package/dist/src/setup.d.ts +2 -1
  23. package/dist/src/setup.js +15 -13
  24. package/dist/src/stable-runtime.d.ts +4 -0
  25. package/dist/src/stable-runtime.js +119 -18
  26. package/dist/src/types.d.ts +3 -2
  27. package/dist/src/update.d.ts +19 -0
  28. package/dist/src/update.js +84 -0
  29. package/dist/src/version.d.ts +1 -1
  30. package/dist/src/version.js +1 -1
  31. package/docs/guide/en/advanced.md +81 -0
  32. package/docs/guide/en/configuration.md +16 -1
  33. package/docs/guide/en/installation.md +20 -3
  34. package/docs/guide/ja/advanced.md +81 -0
  35. package/docs/guide/ja/configuration.md +16 -1
  36. package/docs/guide/ja/installation.md +20 -3
  37. package/docs/guide/ko/advanced.md +81 -0
  38. package/docs/guide/ko/configuration.md +16 -1
  39. package/docs/guide/ko/installation.md +20 -3
  40. package/docs/guide/zh-CN/advanced.md +81 -0
  41. package/docs/guide/zh-CN/configuration.md +16 -1
  42. package/docs/guide/zh-CN/installation.md +20 -3
  43. package/package.json +1 -1
package/dist/src/setup.js CHANGED
@@ -540,20 +540,19 @@ function prepare(options, client, removing, edit) {
540
540
  const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
541
541
  const additions = { APTLY_HOOK_POLICY_PATH: policyPath, ROUTER_LEDGER_PATH: join(stateDir, 'ledger.json') };
542
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
+ }
543
548
  // Explicit migration may replace an exact-owned unavailable/older generation.
544
549
  // Its bytes are never executed or trusted for credential injection; only the
545
550
  // replacement made from this CLI's verified source is used after commit.
546
- const ownedStableMigration = edit && 'migrate' in edit && oldOwner?.mcp_created && isDeepStrictEqual(servers.aptly, oldOwner.mcp) ? stableReference(servers.aptly, { home: options.home }) : null;
547
- const existingStable = ownedStableMigration ?? validateStableRegistration(servers.aptly, { home: options.home });
548
- 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)
549
554
  fail('stable_launcher_migration_required');
550
- const stableRequested = options.launcher === 'stable' || !!existingStable;
551
- if (stableRequested && (servers.aptly === undefined || !!(edit && 'migrate' in edit)))
552
- stableRuntime = planStableRuntime({ packageRoot: root, home: options.home });
553
- if (edit && 'migrate' in edit) {
554
- if (!oldOwner || !object(servers.aptly) || (oldOwner.mcp_created ? !isDeepStrictEqual(servers.aptly, oldOwner.mcp) : !edit.includeExisting))
555
- fail('launcher_migration_not_owned');
556
- const entry = servers.aptly;
555
+ if (migration) {
557
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])))
558
557
  fail('launcher_migration_not_standard');
559
558
  if (!entries.some(entry => isDeepStrictEqual(entry, oldOwner.hook)) || !isDeepStrictEqual(json(policy.before), oldOwner.policy))
@@ -562,6 +561,9 @@ function prepare(options, client, removing, edit) {
562
561
  if (entry.env?.[key] !== value)
563
562
  fail('managed_entry_changed');
564
563
  }
564
+ const managedLauncher = options.launcher ?? existingStable?.launcher;
565
+ if (managedLauncher && (entry === undefined || migration))
566
+ stableRuntime = planStableRuntime({ packageRoot: root, home: options.home, launcher: managedLauncher });
565
567
  if (servers.aptly === undefined) {
566
568
  created = true;
567
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 } };
@@ -705,7 +707,7 @@ function prepare(options, client, removing, edit) {
705
707
  result.transmission_review = reviewMatches(review.after, options, client, policyValue) ? 'complete' : 'required';
706
708
  const snapshotOutdated = !!existingStable && !stableRuntime && 'version' in existingStable && existingStable.version !== json(read(join(root, 'package.json')).text).version;
707
709
  if (snapshotOutdated)
708
- 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`];
709
711
  if (client === 'codex')
710
712
  result.requires_hook_review = true;
711
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'] : [])];
@@ -787,7 +789,7 @@ function execute(options, removing, edit, captured) {
787
789
  if (clients.some(client => client !== 'codex' && client !== 'claude'))
788
790
  return { status: 'partial', clients: [] };
789
791
  const env = options.env ?? process.env;
790
- 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')))
791
793
  return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['stable_launcher_invalid_options'] })) };
792
794
  if (options.transmission !== undefined && !['none', 'description', 'excerpt'].includes(options.transmission))
793
795
  return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['transmission_invalid_scope'] })) };
@@ -802,7 +804,7 @@ function execute(options, removing, edit, captured) {
802
804
  }
803
805
  });
804
806
  const results = prepared.map(plan => plan.result);
805
- if ((edit || options.launcher === 'stable') && results.some(result => result.status === 'error'))
807
+ if ((edit || options.launcher !== undefined) && results.some(result => result.status === 'error'))
806
808
  return { status: 'partial', clients: results.map(result => result.status === 'error' ? result : { ...result, status: 'skipped', codes: ['other_host_validation_failed'] }) };
807
809
  // Each host is independent; prepare every host before committing any host.
808
810
  for (const plan of prepared) {
@@ -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=
@@ -1,11 +1,12 @@
1
1
  export type Client = 'codex' | 'claude';
2
+ export type RecommendationClient = Client | 'antigravity';
2
3
  export type UnknownRecord = Record<string, unknown>;
3
4
  export type JsonValue = null | boolean | number | string | JsonValue[] | {
4
5
  [key: string]: JsonValue;
5
6
  };
6
7
  export interface Profile {
7
8
  id: string;
8
- client: Client;
9
+ client: RecommendationClient;
9
10
  model: string;
10
11
  reasoning_effort?: string;
11
12
  }
@@ -23,7 +24,7 @@ export interface RoutingTask {
23
24
  }
24
25
  export interface RoutingInput {
25
26
  request_id: string;
26
- client: Client;
27
+ client: RecommendationClient;
27
28
  task: RoutingTask;
28
29
  eligible_profile_ids: string[];
29
30
  constraints: RoutingConstraints;
@@ -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.21";
1
+ export declare const VERSION = "0.2.0";
@@ -1 +1 @@
1
- export const VERSION = '0.1.21';
1
+ export const VERSION = '0.2.0';
@@ -11,6 +11,7 @@
11
11
  - [Codex example](#guide-codex-configuration)
12
12
  - [Claude Code example](#guide-claude-configuration)
13
13
  - [Direct recommendations](#guide-direct-recommendations)
14
+ - [Antigravity CLI model recommendations](#guide-antigravity-advisory)
14
15
  - [Explicit description for opaque spawns (0.1.4+)](#guide-explicit-spawn-context)
15
16
  - [Retry with additional context (0.1.5+)](#guide-context-retry)
16
17
  - [Prepare a separate independent delegation (0.1.6+)](#guide-fresh-delegation)
@@ -123,6 +124,86 @@ If any of `model_pinned`, `effort_pinned`, `role_pinned`, or `fork_inherits` in
123
124
 
124
125
  The direct recommendation's `application: advisory_only` does not verify host settings or model access, or authorize execution. To retrieve a completed result again, keep the same ID, input, policy, and ledger. `unknown` means the outcome is uncertain; do not blindly retry with a new ID. A new request whose input has changed because context was added uses a different ID.
125
126
 
127
+ <a id="guide-antigravity-advisory"></a>
128
+
129
+ ## Antigravity CLI model recommendations
130
+
131
+ Add the entry below to `.agents/mcp_config.json` in a trusted workspace. Replace `command` with the absolute path to your installed `aptly` executable and retain only the candidates listed by `agy models`.
132
+
133
+ ```json
134
+ {
135
+ "mcpServers": {
136
+ "aptly-antigravity": {
137
+ "command": "/absolute/path/to/aptly",
138
+ "args": [
139
+ "serve",
140
+ "--client",
141
+ "antigravity"
142
+ ],
143
+ "env": {
144
+ "ROUTER_PROVIDER": "fixture",
145
+ "APTLY_ANTIGRAVITY_MODELS": "[\"gemini-4-hydrogen-medium\",\"gemini-4-carbon-medium\",\"gemini-4-neon-medium\"]"
146
+ }
147
+ }
148
+ }
149
+ }
150
+ ```
151
+
152
+ The suggested catalog uses Hydrogen Medium for simple work, Carbon Medium for routine work, and Neon Medium for deep work. Add `gemini-4-neon-high` to make it eligible for deep tasks that need more detailed reasoning. An omitted list or `[]` returns `no_candidates`. Aptly does not independently verify model access for your account.
153
+
154
+ Check the server in `/mcp` and call `recommend_agent` with the arguments below. Approve that tool when prompted. If you preapprove it for headless use, use the exact permission `mcp(aptly-antigravity/recommend_agent)`.
155
+
156
+ ```json
157
+ {
158
+ "request_id": "agy-sort-001",
159
+ "client": "antigravity",
160
+ "task": {
161
+ "summary": "Sort the supplied numbers [3, 1, 2] in ascending order.",
162
+ "operation": "analysis",
163
+ "context_sufficient": true
164
+ }
165
+ }
166
+ ```
167
+
168
+ The example uses local fixture rules. Pass the returned `profile.model` to `agy --model` when starting a new Antigravity CLI session. To use a native subagent, select its settings yourself. Aptly leaves the current session and native subagent settings untouched.
169
+
170
+ To use the Decisions API, set `ROUTER_PROVIDER` to `decisions` and set `APTLY_ANTIGRAVITY_STATE_DIR` to the absolute path to an existing private directory (mode `700` on POSIX). Aptly keeps this budget and request history separate from existing Codex and Claude Code state. Supply `OPENAI_API_KEY` to the MCP process through a trusted launch environment and keep it out of configuration files and command arguments.
171
+
172
+ A `recommend_agent` call may incur a charge when it sends a request to OpenAI Decisions. Aptly sends `request_id` to the OpenAI Decisions API in the `X-Client-Request-Id` header. The body contains `client`, `task.summary`, `task.operation`, `task.context_sufficient`, and candidate profile IDs and descriptions. Use a random ID free of sensitive information and reuse it only with the same request input. Installing or configuring the server does not trigger classification. See [what Aptly sends](transmission.md#guide-transmission-limits).
173
+
174
+ [Antigravity MCP](https://antigravity.google/docs/mcp?tab=cli) · [Permissions](https://antigravity.google/docs/cli-permissions)
175
+
176
+ <a id="guide-antigravity-hook"></a>
177
+
178
+ ### Automatic tier selection for Antigravity CLI
179
+
180
+ Enable automatic selection per workspace. Add the Hook below to `.agents/hooks.json` in a trusted workspace. If Antigravity CLI cannot find `aptly` on `PATH`, use the executable's absolute path.
181
+
182
+ ```json
183
+ {
184
+ "aptly-antigravity": {
185
+ "PreToolUse": [
186
+ {
187
+ "matcher": "^invoke_subagent$",
188
+ "hooks": [
189
+ {
190
+ "type": "command",
191
+ "command": "aptly antigravity-hook",
192
+ "timeout": 20
193
+ }
194
+ ]
195
+ }
196
+ ]
197
+ }
198
+ }
199
+ ```
200
+
201
+ When starting Antigravity CLI from the workspace root, set `APTLY_ANTIGRAVITY_AUTO_WORKSPACE` to that absolute directory. For Decisions, also set `ROUTER_PROVIDER=decisions`, a private `APTLY_ANTIGRAVITY_STATE_DIR`, and `OPENAI_API_KEY` in the same launch environment. Supply the key through the launch environment and keep it out of the Hook configuration and arguments. Use `ROUTER_PROVIDER=fixture` to check the Hook locally. Restart Antigravity CLI and check the registration in `/hooks`. The working directory and single workspace reported by the Hook event must match the configured root.
202
+
203
+ The Hook supports a single, flat invocation of the built-in `self` agent with model and effort unset. The Hook sets `Model` to one of `flash_lite`, `flash`, or `pro`. Antigravity resolves the model for that tier. The Hook preserves explicit choices and leaves the host to check permissions and proceed with the original arguments if it cannot verify the input or obtain a recommendation.
204
+
205
+ In Decisions mode, the Hook uses the child's `Prompt` as the task description when it meets the length limit. The request includes the client, operation, context sufficiency flag, tier candidates and descriptions, and a hashed request ID. Automatic and direct recommendations have separate request history and budgets. Enable the Hook only for approved workspaces and check whether child prompts may contain sensitive information. To turn off automatic selection, unset `APTLY_ANTIGRAVITY_AUTO_WORKSPACE` and restart Antigravity CLI.
206
+
126
207
  <a id="guide-explicit-spawn-context"></a>
127
208
 
128
209
  ## Explicit description for opaque spawns (0.1.4+)
@@ -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