aptly 0.1.8 → 0.1.9

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/bin/aptly.js CHANGED
@@ -10,9 +10,10 @@ import { exportDiagnosticReport } from '../src/report.js';
10
10
  import { fetchModelInfo, saveModelInfo } from '../src/model-info.js';
11
11
  import { errorCode } from '../src/types.js';
12
12
  import { budgetErrorDetails } from '../src/budget.js';
13
- import { setupHosts, removeSetup, setDefaults, setEnvironment, configurableEnvironmentKeys, migrateLauncher, setTransmission, showTransmission, showBudgetStatus } from '../src/setup.js';
13
+ import { checkSetup, setupHosts, removeSetup, setDefaults, setEnvironment, configurableEnvironmentKeys, migrateLauncher, setTransmission, showTransmission, showBudgetStatus } from '../src/setup.js';
14
14
  import { readEnvironmentValue, readTransmissionChoice } from '../src/cli-input.js';
15
15
  import { prepareApiKey } from '../src/credential-setup.js';
16
+ import { linuxStoreReadiness } from '../src/linux-store-readiness.js';
16
17
  import { updateGlobalInstallation } from '../src/update.js';
17
18
  import { updateNotification } from '../src/update-notifier.js';
18
19
  import { resolveCliHelp } from '../src/cli-help.js';
@@ -126,6 +127,14 @@ try {
126
127
  if (checkOnly && fromStdin)
127
128
  throw new Error('set_invalid_options');
128
129
  const credential = key === 'OPENAI_API_KEY' ? prepareApiKey({ clients, packageRoot }) : undefined;
130
+ if (credential && credential.result.clients.some(client => client.status !== 'error')) {
131
+ const readiness = linuxStoreReadiness();
132
+ if (readiness) {
133
+ credential.result.clients = credential.result.clients.map(client => client.status === 'error' ? client : ({ ...client, status: readiness.status === 'unavailable' ? 'error' : client.status, codes: [...client.codes, ...(readiness.status === 'unavailable' ? ['secure_store_unavailable'] : []), readiness.code] }));
134
+ if (readiness.status === 'unavailable')
135
+ credential.result.status = 'partial';
136
+ }
137
+ }
129
138
  let value = '';
130
139
  if (credential && (checkOnly || credential.result.status === 'partial')) {
131
140
  output(credential.result);
@@ -159,6 +168,7 @@ try {
159
168
  let mode;
160
169
  let transmission;
161
170
  let automatic = false;
171
+ let check = false;
162
172
  let migrate = false;
163
173
  let dryRun = false;
164
174
  let includeExisting = false;
@@ -168,6 +178,10 @@ try {
168
178
  if (seen.has(flag))
169
179
  throw new Error('setup_invalid_options');
170
180
  seen.add(flag);
181
+ if (flag === '--check' && command === 'setup') {
182
+ check = true;
183
+ continue;
184
+ }
171
185
  if (flag === '--migrate-launcher' && command === 'setup') {
172
186
  migrate = true;
173
187
  continue;
@@ -195,9 +209,9 @@ try {
195
209
  throw new Error('setup_invalid_options');
196
210
  }
197
211
  const packageRoot = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../' : '../../', import.meta.url));
198
- if ((migrate && (clients.length !== 1 || automatic || seen.has('--mode') || seen.has('--transmission'))) || ((dryRun || includeExisting) && !migrate))
212
+ if ((check && [...seen].some(flag => !['--check', '--client'].includes(flag))) || (migrate && (clients.length !== 1 || automatic || seen.has('--mode') || seen.has('--transmission'))) || ((dryRun || includeExisting) && !migrate))
199
213
  throw new Error('setup_invalid_options');
200
- const result = migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot, transmission }) : removeSetup({ clients });
214
+ const result = check ? checkSetup({ clients, packageRoot }) : migrate ? migrateLauncher({ clients, packageRoot }, dryRun, includeExisting) : command === 'setup' ? setupHosts({ clients, mode, automatic, packageRoot, transmission }) : removeSetup({ clients });
201
215
  output(result);
202
216
  if (result.status === 'partial' && !automatic)
203
217
  process.exitCode = 1;
@@ -13,11 +13,11 @@ const entries = {
13
13
  config: { usage: 'aptly config codex|claude', description: 'Print a registration fragment only. Does not edit host configuration or classify. Preserve existing launchers and merge settings as described in the guide.', positional: ['client'] },
14
14
  set: { usage: 'aptly set default [--client codex|claude|all]\n aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]\n aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]', description: 'Set operator-controlled defaults, environment values or transmission scope. Use the subcommand help for input, preservation and restart details.' },
15
15
  'set default': { usage: 'aptly set default [--client codex|claude|all]', description: 'Fill missing MCP environment defaults for both clients by default. Preserve existing values, inherited budget bindings and launchers. Does not reset budget usage or caches. Interactive runs ask only for unselected transmission scope (Enter: none); noninteractive runs do not opt in. Restart MCP after changes.', options: { '--client': client } },
16
- 'set env': { usage: 'aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]', description: 'Set a supported value using hidden input; --stdin explicitly reads standard input. --client defaults to all. --check is only for OPENAI_API_KEY and checks registration without reading/storing a key.\nOPENAI_API_KEY uses OS credential storage; host files contain references only. Values are never accepted as command arguments. Existing launchers are preserved. Restart MCP after changes.\nBudget defaults: ' + Object.entries(budgetEnvironmentDefaults).map(([key, value]) => key + '=' + value).join(', ') + '. Only literal 0 disables a ceiling; the per-call rate stays positive.\nSupported environment keys: $ENV_KEYS', options: { '--client': client, '--stdin': true, '--check': true }, positional: ['environment'] },
16
+ 'set env': { usage: 'aptly set env ENV_KEY [--client codex|claude|all] [--stdin | --check]', description: 'Set a supported value using hidden input; --stdin explicitly reads standard input. --client defaults to all. --check is only for OPENAI_API_KEY and checks registration and Linux store readiness without reading/storing a key.\nOPENAI_API_KEY uses OS credential storage; host files contain references only. Values are never accepted as command arguments. Existing launchers are preserved. Restart MCP after changes.\nBudget defaults: ' + Object.entries(budgetEnvironmentDefaults).map(([key, value]) => key + '=' + value).join(', ') + '. Only literal 0 disables a ceiling; the per-call rate stays positive.\nSupported environment keys: $ENV_KEYS', options: { '--client': client, '--stdin': true, '--check': true }, positional: ['environment'] },
17
17
  'set transmission': { usage: 'aptly set transmission none|description|excerpt [--client codex|claude|all]\n aptly set transmission --show [--client codex|claude|all]', description: 'Control automatic task-data transmission to OpenAI Decisions, not developer telemetry. none disables automatic transmission; description permits caller-provided descriptions only; excerpt permits native excerpts. Direct recommendations remain separate explicit requests. --show reads redacted registration state. Restart MCP after changes.', options: { '--client': client, '--show': true }, positional: ['scope'] },
18
18
  budget: { usage: 'aptly budget status [--client codex|claude|all]', description: 'Inspect local per-ledger budget limits and reserved usage. No reset/refill command is provided.' },
19
19
  'budget status': { usage: 'aptly budget status [--client codex|claude|all]', description: 'Read registered host budget settings and ledger metadata; defaults to both clients. No credentials, provider calls, configuration writes or ledger/gate initialization.\nLiteral 0 ceilings display Unlimited; reservations are not OpenAI billing. This is a registration/permitted-environment snapshot, not verification of running custom launchers. An existing gate is held briefly and can be busy.', options: { '--client': client } },
20
- setup: { usage: 'aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--transmission none|description|excerpt] [--automatic]\n aptly setup --client codex|claude --migrate-launcher [--include-existing] [--dry-run]', description: 'Register MCP and PreToolUse Hooks while preserving unrelated settings and existing launchers. Omitted --mode preserves an existing mode; a new policy defaults to defaults. New transmission remains unselected unless explicitly chosen.\n--automatic skips CI, APTLY_SKIP_SETUP=1 and absent host directories.\n--migrate-launcher reviews a single owned standard launcher; --include-existing explicitly includes an eligible preserved registration. --dry-run validates migration without writing. Do not combine migration with --automatic, --mode or --transmission. --include-existing and --dry-run require --migrate-launcher.\nNo keys are stored. Restart the host/MCP; Codex requires native /hooks trust review.', options: { '--client': client, '--mode': ['defaults', 'advisory'], '--transmission': scope, '--automatic': true, '--migrate-launcher': true, '--include-existing': true, '--dry-run': true } },
20
+ setup: { usage: 'aptly setup [--client codex|claude|all] [--mode defaults|advisory] [--transmission none|description|excerpt] [--automatic]\n aptly setup --check [--client codex|claude|all]\n aptly setup --client codex|claude --migrate-launcher [--include-existing] [--dry-run]', description: 'Register MCP and PreToolUse Hooks while preserving unrelated settings and existing launchers. Omitted --mode preserves an existing mode; a new policy defaults to defaults. New transmission remains unselected unless explicitly chosen.\n--check snapshots the normal setup plan without writing; only --client may be combined with it. It does not verify a running host.\n--automatic skips CI, APTLY_SKIP_SETUP=1 and absent host directories.\n--migrate-launcher reviews a single owned standard launcher; --include-existing explicitly includes an eligible preserved registration. --dry-run validates migration without writing. Do not combine migration with --automatic, --mode or --transmission. --include-existing and --dry-run require --migrate-launcher.\nNo keys are stored. Restart the host/MCP; Codex requires native /hooks trust review.', options: { '--client': client, '--mode': ['defaults', 'advisory'], '--transmission': scope, '--automatic': true, '--check': true, '--migrate-launcher': true, '--include-existing': true, '--dry-run': true } },
21
21
  remove: { usage: 'aptly remove [--client codex|claude|all]', description: 'Remove only unchanged Aptly-owned registration for both clients by default. Preserve modified/user-owned entries, keys and ledger history. Restart host/MCP after removal.', options: { '--client': client } },
22
22
  update: { usage: 'aptly update', description: 'Update this verified global npm installation within the same prefix. Stop other hosts/MCP/CLI writers first. Local/source/unverified installations are rejected. Lifecycle setup is not run: run aptly setup and restart hosts afterward. Existing launchers and keys are preserved.' },
23
23
  report: { usage: 'aptly report [--format md|json|both] [--output-dir DIR]', description: 'Write redacted local diagnostic attachments. Default format: both; directory: reports. No uploads or classification API probes. Review attachments before sharing.', options: { '--format': ['md', 'json', 'both'], '--output-dir': 'path' } },
@@ -90,6 +90,8 @@ export function resolveCliHelp(argv, { environmentKeys = [] } = {}) {
90
90
  return { kind: 'error', code: 'invalid_help_options' };
91
91
  if (path === 'setup') {
92
92
  const migrate = seen.has('--migrate-launcher');
93
+ if (seen.has('--check') && [...seen].some(flag => !['--check', '--client'].includes(flag)))
94
+ return { kind: 'error', code: 'invalid_help_options' };
93
95
  if ((seen.has('--dry-run') || seen.has('--include-existing')) && !migrate)
94
96
  return { kind: 'error', code: 'invalid_help_options' };
95
97
  if (migrate && (seen.has('--automatic') || seen.has('--mode') || seen.has('--transmission') || values.get('--client') === 'all'))
@@ -0,0 +1,12 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ export interface LinuxReadinessOptions {
3
+ platform?: NodeJS.Platform;
4
+ env?: NodeJS.ProcessEnv;
5
+ execute?: typeof spawnSync;
6
+ }
7
+ export interface StoreReadiness {
8
+ status: 'unavailable' | 'unverified';
9
+ code: string;
10
+ }
11
+ /** Passive metadata only: never query, activate, unlock, or write the Secret Service. */
12
+ export declare function linuxStoreReadiness(options?: LinuxReadinessOptions): StoreReadiness | undefined;
@@ -0,0 +1,67 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { accessSync, constants, statSync } from 'node:fs';
3
+ import { isAbsolute, resolve } from 'node:path';
4
+ // Locate programs without running them. Empty PATH entries have shell cwd semantics.
5
+ function executable(name, path, absoluteOnly = false) {
6
+ for (const dir of (path ?? '/usr/bin:/bin').split(':')) {
7
+ if (absoluteOnly && !isAbsolute(dir))
8
+ continue;
9
+ const candidate = resolve(dir || '.', name);
10
+ try {
11
+ if (statSync(candidate).isFile()) {
12
+ accessSync(candidate, constants.X_OK);
13
+ return candidate;
14
+ }
15
+ }
16
+ catch { /* try next PATH entry */ }
17
+ }
18
+ }
19
+ /** Passive metadata only: never query, activate, unlock, or write the Secret Service. */
20
+ export function linuxStoreReadiness(options = {}) {
21
+ if ((options.platform ?? process.platform) !== 'linux')
22
+ return undefined;
23
+ const env = options.env ?? process.env;
24
+ if (!executable('secret-tool', env.PATH))
25
+ return { status: 'unavailable', code: 'secure_store_secret_tool_missing' };
26
+ const address = env.DBUS_SESSION_BUS_ADDRESS;
27
+ if (!address || !/^unix:(?:path|abstract)=[^,;\s]+(?:,guid=[a-fA-F0-9]{32})?$/.test(address))
28
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
29
+ if (address.startsWith('unix:path=') && !isAbsolute(address.slice('unix:path='.length).split(',')[0]))
30
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
31
+ const socket = address.match(/^unix:path=([^,%]+)(?:,guid=[a-fA-F0-9]{32})?$/)?.[1];
32
+ if (socket && isAbsolute(socket)) {
33
+ try {
34
+ statSync(socket);
35
+ }
36
+ catch (error) {
37
+ if (error.code === 'ENOENT')
38
+ return { status: 'unavailable', code: 'secure_store_bus_missing' };
39
+ }
40
+ }
41
+ const gdbus = executable('gdbus', env.PATH, true);
42
+ if (!gdbus)
43
+ return { status: 'unverified', code: 'secure_store_probe_unavailable' };
44
+ const call = (method, extra = []) => {
45
+ try {
46
+ const result = (options.execute ?? spawnSync)(gdbus, ['call', '--address', address, '--dest', 'org.freedesktop.DBus', '--object-path', '/org/freedesktop/DBus', '--method', `org.freedesktop.DBus.${method}`, ...extra], { env: { PATH: env.PATH ?? '/usr/bin:/bin', LC_ALL: 'C' }, encoding: 'utf8', timeout: 2000, maxBuffer: 65536 });
47
+ return !result.error && result.status === 0 && typeof result.stdout === 'string' ? result.stdout.trim() : undefined;
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ };
53
+ const owner = call('NameHasOwner', ['org.freedesktop.secrets']);
54
+ if (owner === '(true,)')
55
+ return { status: 'unverified', code: 'secure_store_service_present_unverified' };
56
+ if (owner !== '(false,)')
57
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
58
+ const names = call('ListActivatableNames');
59
+ // gdbus prints a GVariant string array. Accept only its narrow standard shape.
60
+ if (names === '(@as [],)')
61
+ return { status: 'unavailable', code: 'secure_store_service_missing' };
62
+ if (names === undefined || !/^\(\[(?:\s*'[^'\\]*'\s*(?:,\s*'[^'\\]*'\s*)*)?\],\)$/.test(names))
63
+ return { status: 'unverified', code: 'secure_store_bus_unverified' };
64
+ if (names.includes("'org.freedesktop.secrets'"))
65
+ return { status: 'unverified', code: 'secure_store_service_activatable_unverified' };
66
+ return { status: 'unavailable', code: 'secure_store_service_missing' };
67
+ }
@@ -16,6 +16,8 @@ export interface SetupClientResult {
16
16
  codes: string[];
17
17
  invalid_budget_keys?: string[];
18
18
  budget_error?: string;
19
+ policy_location?: 'default_home' | 'elsewhere';
20
+ selected_home_source?: 'default' | 'override';
19
21
  requires_hook_review?: boolean;
20
22
  recovery?: string[];
21
23
  transmission?: string;
@@ -35,6 +37,8 @@ export interface SetupResult {
35
37
  }
36
38
  export declare const configurableEnvironmentKeys: readonly string[];
37
39
  export declare function setupHosts(options?: SetupOptions): SetupResult;
40
+ /** Snapshot the normal setup plan without applying it; it does not verify a running host. */
41
+ export declare function checkSetup(options?: SetupOptions): SetupResult;
38
42
  export declare function removeSetup(options?: SetupOptions): SetupResult;
39
43
  export declare function setDefaults(options?: SetupOptions): SetupResult;
40
44
  export declare function setEnvironment(key: string, value: string, options?: SetupOptions): SetupResult;
package/dist/src/setup.js CHANGED
@@ -433,11 +433,17 @@ function prepare(options, client, removing, edit) {
433
433
  else {
434
434
  if (!object(servers.aptly))
435
435
  fail('mcp_entry_conflict');
436
+ const configuredPolicy = object(servers.aptly.env) ? servers.aptly.env.APTLY_HOOK_POLICY_PATH : undefined;
437
+ const mismatch = configuredPolicy !== undefined && configuredPolicy !== policyPath;
438
+ const detail = mismatch && typeof configuredPolicy === 'string' && configuredPolicy.length > 0 ? {
439
+ policy_location: configuredPolicy === join(resolve(options.home ?? homedir()), client === 'codex' ? '.codex' : '.claude', 'aptly', 'auto-policy.json') ? 'default_home' : 'elsewhere',
440
+ selected_home_source: (client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR) ? 'override' : 'default',
441
+ } : undefined;
436
442
  if (edit && oldOwner?.mcp_created && !isDeepStrictEqual(servers.aptly, oldOwner.mcp))
437
- fail('managed_mcp_changed');
443
+ throw Object.assign(new Error('managed_mcp_changed'), detail ? { policyConflict: detail } : {});
444
+ if (mismatch)
445
+ throw Object.assign(new Error('mcp_environment_conflict'), { policyConflict: detail });
438
446
  const currentEnv = map(servers.aptly, 'env');
439
- if (currentEnv.APTLY_HOOK_POLICY_PATH !== undefined && currentEnv.APTLY_HOOK_POLICY_PATH !== policyPath)
440
- fail('mcp_environment_conflict');
441
447
  const missing = Object.fromEntries(Object.entries(additions).filter(([key]) => currentEnv[key] === undefined));
442
448
  Object.assign(currentEnv, missing);
443
449
  mcp.after = client === 'codex' ? addTomlEnv(mcp.before ?? '', missing) : stringify(config);
@@ -616,6 +622,13 @@ function replace(snapshot, forward) {
616
622
  }
617
623
  }
618
624
  }
625
+ function policyRecovery(client) {
626
+ return [`aptly setup --check --client ${client}`, 'Review the selected host configuration directory and its existing policy reference locally; intentional sharing cannot be inferred. Preserve the registration and select the intended host directory before retrying. A policy conflict does not authenticate the launcher or other changed settings. Review all changed registration fields locally before reuse; keep custom or modified launchers unchanged and do not execute an unverified launcher. Do not copy keys, ledgers or trust settings.'];
627
+ }
628
+ function errorResult(client, error) {
629
+ const detail = error?.policyConflict;
630
+ return { client, status: 'error', codes: [safeCode(error), ...(detail ? ['hook_policy_path_conflict'] : [])], ...budgetErrorDetails(error), ...(detail ? { ...detail, recovery: policyRecovery(client) } : {}) };
631
+ }
619
632
  function execute(options, removing, edit, captured) {
620
633
  const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
621
634
  if (clients.some(client => client !== 'codex' && client !== 'claude'))
@@ -630,7 +643,7 @@ function execute(options, removing, edit, captured) {
630
643
  return prepare(options, client, removing, edit);
631
644
  }
632
645
  catch (e) {
633
- return { changes: [], observations: [], dirs: [], result: { client, status: 'error', codes: [safeCode(e)], ...budgetErrorDetails(e) } };
646
+ return { changes: [], observations: [], dirs: [], result: errorResult(client, e) };
634
647
  }
635
648
  });
636
649
  const results = prepared.map(plan => plan.result);
@@ -700,6 +713,22 @@ function execute(options, removing, edit, captured) {
700
713
  const codes = new Set(['unsafe_ledger', 'invalid_ledger', 'budget_ledger_unconfigured', 'invalid_budget_configuration', 'ledger_locked', 'ledger_error', 'transmission_selection_changed', 'transmission_invalid_scope', 'launcher_migration_not_owned', 'launcher_migration_not_standard', 'credential_launcher_unverified', 'environment_invalid_value', 'environment_sensitive_value', 'environment_key_unsupported', 'environment_secret_key_unsupported', 'unsafe_directory', 'unsafe_symlink', 'unsafe_configuration_file', 'invalid_json', 'invalid_json_object', 'configuration_shape_conflict', 'hook_shape_conflict', 'invalid_toml', 'unsupported_toml_layout', 'relative_configuration_directory', 'invalid_ownership', 'managed_hook_changed', 'managed_mcp_changed', 'managed_entry_changed', 'managed_policy_changed', 'mcp_entry_conflict', 'mcp_environment_conflict', 'existing_routing_hook_conflict', 'policy_conflict', 'existing_hook_not_owned', 'concurrent_configuration_change', 'private_directory_permissions', 'private_file_permissions']);
701
714
  function safeCode(error) { return error instanceof Error && codes.has(error.message) ? error.message : 'configuration_io_error'; }
702
715
  export function setupHosts(options = {}) { return execute(options, false); }
716
+ /** Snapshot the normal setup plan without applying it; it does not verify a running host. */
717
+ export function checkSetup(options = {}) {
718
+ const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
719
+ if (!clients.length || clients.some(client => client !== 'codex' && client !== 'claude') || options.automatic !== undefined || options.mode !== undefined || options.transmission !== undefined || options.selectUnselectedOnly !== undefined)
720
+ return { status: 'partial', clients: [] };
721
+ const results = clients.map(client => {
722
+ try {
723
+ const plan = prepare(options, client, false);
724
+ return { ...plan.result, status: 'unchanged', codes: [plan.changes.length ? 'setup_check_configure_ready' : 'setup_check_ok', ...plan.result.codes] };
725
+ }
726
+ catch (error) {
727
+ return errorResult(client, error);
728
+ }
729
+ });
730
+ return { status: results.some(result => result.status === 'error') ? 'partial' : 'complete', clients: results };
731
+ }
703
732
  export function removeSetup(options = {}) { return execute(options, true); }
704
733
  export function setDefaults(options = {}) { return execute(options, false, { defaults: true }); }
705
734
  export function setEnvironment(key, value, options = {}) {
@@ -737,12 +766,17 @@ export function prepareCredentialReference(options, client) {
737
766
  result = { client, status: 'unchanged', codes: ['credential_preflight_ok'] };
738
767
  }
739
768
  catch (error) {
740
- const reason = error?.reason;
741
- const reasons = ['credential_node_mismatch', 'credential_server_mismatch', 'credential_runtime_unsupported'];
742
- const migration = migrateLauncher({ ...options, clients: [client] }, true);
743
- const canMigrate = migration.status === 'complete';
744
- result = { client, status: 'error', codes: [safeCode(error), ...(reason && reasons.includes(reason) ? [reason] : []), ...(canMigrate ? ['launcher_migration_available'] : [])],
745
- recovery: canMigrate ? recovery(client) : [`aptly set env OPENAI_API_KEY --client ${client} --check`, 'Keep custom or modified launchers unchanged. Review the host registration locally; use its secure credential environment or a separately reviewed standard registration.'] };
769
+ if (error?.policyConflict) {
770
+ result = errorResult(client, error);
771
+ }
772
+ else {
773
+ const reason = error?.reason;
774
+ const reasons = ['credential_node_mismatch', 'credential_server_mismatch', 'credential_runtime_unsupported'];
775
+ const migration = migrateLauncher({ ...options, clients: [client] }, true);
776
+ const canMigrate = migration.status === 'complete';
777
+ result = { client, status: 'error', codes: [safeCode(error), ...(reason && reasons.includes(reason) ? [reason] : []), ...(canMigrate ? ['launcher_migration_available'] : [])],
778
+ recovery: canMigrate ? recovery(client) : [`aptly set env OPENAI_API_KEY --client ${client} --check`, 'Keep custom or modified launchers unchanged. Review the host registration locally; use its secure credential environment or a separately reviewed standard registration.'] };
779
+ }
746
780
  }
747
781
  const check = () => {
748
782
  if (!plan)
@@ -754,7 +788,18 @@ export function prepareCredentialReference(options, client) {
754
788
  return result;
755
789
  }
756
790
  catch (error) {
757
- return { client, status: 'error', codes: [safeCode(error)], recovery: recovery(client) };
791
+ // Preserve the concurrent-change guard, but surface a policy mismatch if one is now visible.
792
+ try {
793
+ prepare({ ...options, clients: [client] }, client, false, { credential: true });
794
+ }
795
+ catch (current) {
796
+ if (current?.policyConflict) {
797
+ const detail = errorResult(client, current);
798
+ return { ...detail, codes: [safeCode(error), 'hook_policy_path_conflict'] };
799
+ }
800
+ }
801
+ const result = errorResult(client, error);
802
+ return result.recovery ? result : { ...result, recovery: recovery(client) };
758
803
  }
759
804
  };
760
805
  return { result, check, commit: () => {
@@ -780,7 +825,7 @@ export function migrateLauncher(options, dryRun = false, includeExisting = false
780
825
  return result;
781
826
  }
782
827
  catch (error) {
783
- return { status: 'partial', clients: [{ client, status: 'error', codes: [safeCode(error)] }] };
828
+ return { status: 'partial', clients: [errorResult(client, error)] };
784
829
  }
785
830
  }
786
831
  /** Explicit operator change; updates policy and its receipt through normal guarded staging. */
@@ -23,7 +23,7 @@ function newer(candidate, current) {
23
23
  }
24
24
  function eligible(o) {
25
25
  return o.stdinIsTTY && o.stderrIsTTY && o.stdoutIsTTY !== false && !o.env.CI && o.env.APTLY_NO_UPDATE_NOTIFIER !== '1' && !!version(o.currentVersion) &&
26
- ['--version', 'config', 'setup', 'remove', 'set', 'report'].includes(o.command) && !o.args.some(arg => arg === '--help' || arg === '-h') && !o.args.includes('--automatic') && !(o.command === 'set' && o.args[0] === 'transmission' && o.args.includes('--show'));
26
+ ['--version', 'config', 'setup', 'remove', 'set', 'report'].includes(o.command) && !o.args.some(arg => arg === '--help' || arg === '-h') && !o.args.includes('--automatic') && !o.args.includes('--check') && !(o.command === 'set' && o.args[0] === 'transmission' && o.args.includes('--show'));
27
27
  }
28
28
  function directory(path) {
29
29
  if (!isAbsolute(path))
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.8";
1
+ export declare const VERSION = "0.1.9";
@@ -1 +1 @@
1
- export const VERSION = '0.1.8';
1
+ export const VERSION = '0.1.9';
package/docs/guide/en.md CHANGED
@@ -114,7 +114,9 @@ Restart MCP, then inspect `provider`, candidates, and `credential_status` with `
114
114
 
115
115
  These options require Aptly 0.1.2 or later and are not in npm 0.1.1. To test from source, run `npm ci --ignore-scripts` and `npm run build`, then replace `aptly` below with `node bin/aptly.ts`.
116
116
 
117
- Key setup diagnoses selected hosts before input or storage. If any host fails, it does not prompt or change any host. `--check` does not access keys or the credential store. `credential_node_mismatch`, `credential_server_mismatch`, and `credential_runtime_unsupported` identify incompatible Node paths, server paths, and OS-store support respectively.
117
+ Key setup diagnoses selected hosts before input or storage. If any host fails, it does not prompt or change any host. `--check` does not access keys or the credential store.
118
+
119
+ From Aptly 0.1.9, on Linux, `--check` also checks for an executable `secret-tool` and, when a safe explicit session-bus address and `gdbus` are available, reads bus metadata without activating or accessing the credential service. Confirmed failures report `secure_store_unavailable` with `secure_store_secret_tool_missing`, `secure_store_bus_missing`, or `secure_store_service_missing` before input. `secure_store_bus_unverified`, `secure_store_probe_unavailable`, and service-present or activatable unverified codes mean readiness is unknown; a running or activatable service does not prove it is unlocked or writable. Install `secret-tool` and a Secret Service provider, and run from the intended desktop session when needed. The actual store operation can still fail. For SSH or headless sessions, supply `OPENAI_API_KEY` securely to the host MCP process when `APTLY_SECRET_BACKEND` is absent; preserve an existing authentication wrapper or environment. `credential_node_mismatch`, `credential_server_mismatch`, and `credential_runtime_unsupported` identify incompatible Node paths, server paths, and OS-store support respectively.
118
120
 
119
121
  If only Claude failed, diagnose that host and review migration only when `launcher_migration_available` is returned:
120
122
 
@@ -127,6 +129,8 @@ aptly set env OPENAI_API_KEY --client claude
127
129
 
128
130
  `--dry-run` makes no changes. Migration replaces the Node/server paths of a receipt-matching, Aptly-owned standard registration with the current build. It preserves environment settings, Hooks, policy and other hosts, accesses no credentials, and never executes the old launcher. Custom wrappers and missing or modified ownership records are rejected. Review such registrations locally; use the wrapper's secure environment or a separately reviewed standard registration. Do not edit or delete ownership records to bypass validation.
129
131
 
132
+ From Aptly 0.1.9, `aptly setup --check --client codex|claude|all` reads the normal setup plan without writing files or creating directories. It is a snapshot, not a check of the running host. Only `--client` can be combined with `--check`. If `hook_policy_path_conflict` appears, review the selected host configuration directory and existing policy reference locally, then select the intended host directory before retrying. Setup preserves the existing configuration and does not move or copy the policy; launcher migration does not resolve this mismatch.
133
+
130
134
  If `launcher_migration_not_owned` refers to a preserved registration (`mcp_created: false`), **Aptly 0.1.3 or later** offers the explicit `--include-existing` opt-in. Install 0.1.3 or later, then run:
131
135
 
132
136
  ```sh
package/docs/guide/ja.md CHANGED
@@ -114,7 +114,9 @@ API キーは macOS Keychain、インストール済みの Linux `secret-tool`
114
114
 
115
115
  以下のオプションは Aptly 0.1.2 以降で利用でき、npm 0.1.1 には含まれません。ソースから試す場合は `npm ci --ignore-scripts` と `npm run build` を実行し、以下の `aptly` を `node bin/aptly.ts` に置き換えます。
116
116
 
117
- キー設定は入力・保存前に対象ホストを診断します。いずれかが失敗すると入力を求めず、全ホストを変更しません。`--check` はキーや資格情報ストアにアクセスしません。`credential_node_mismatch`、`credential_server_mismatch`、`credential_runtime_unsupported` はそれぞれ Node パス、サーバーパス、OS ストア対応の不一致を示します。
117
+ キー設定は入力・保存前に対象ホストを診断します。いずれかが失敗すると入力を求めず、全ホストを変更しません。`--check` はキーや資格情報ストアにアクセスしません。
118
+
119
+ Aptly 0.1.9 以降、Linux の `--check` は実行可能な `secret-tool` も確認し、安全な明示的セッションバスアドレスと `gdbus` がある場合、資格情報サービスを起動・アクセスせずにバスメタデータを読み取ります。確実な失敗は入力前に `secure_store_unavailable` と `secure_store_secret_tool_missing`、`secure_store_bus_missing`、`secure_store_service_missing` のいずれかで通知します。`secure_store_bus_unverified`、`secure_store_probe_unavailable`、サービスの存在・起動可能を示す未確認コードは準備状態が不明であることを意味します。サービスの存在や起動可能性はロック解除や書き込み可能を保証しません。必要に応じて `secret-tool` と Secret Service プロバイダーをインストールし、使用するデスクトップセッションで実行してください。実際の保存は失敗する場合があります。SSH やヘッドレスセッションでは、`APTLY_SECRET_BACKEND` がない場合に `OPENAI_API_KEY` をホスト MCP プロセスへ安全に渡してください。既存の認証ラッパーや環境は保持してください。`credential_node_mismatch`、`credential_server_mismatch`、`credential_runtime_unsupported` はそれぞれ Node パス、サーバーパス、OS ストア対応の不一致を示します。
118
120
 
119
121
  Claude だけが失敗した場合は次の順序で診断し、`launcher_migration_available` の場合にのみ移行を検討してください。
120
122
 
@@ -127,6 +129,8 @@ aptly set env OPENAI_API_KEY --client claude
127
129
 
128
130
  `--dry-run` は変更しません。移行は所有記録と一致する Aptly の標準登録に限り、Node・サーバーパスを現在のビルドへ更新します。環境設定・Hook・ポリシー・他のホストを保持し、資格情報へのアクセスや古い起動プログラムの実行は行いません。独自ラッパー、所有記録のない登録、変更済みの登録は拒否します。その場合は登録をローカルで確認し、ラッパーの安全な環境変数受け渡しを使うか、別途確認した標準登録へ切り替えてください。検証を回避するために所有記録を編集・削除しないでください。
129
131
 
132
+ Aptly 0.1.9 以降、`aptly setup --check --client codex|claude|all` は通常の設定計画を読み取るだけで、ファイルやディレクトリを作成しません。実行中のホストを検証するものではなく、確認時点の状態を示します。`--check` と組み合わせられるのは `--client` のみです。`hook_policy_path_conflict` が表示された場合は、選択したホスト設定ディレクトリと既存のポリシー参照をローカルで確認し、意図したホストディレクトリを選択してから再試行してください。設定は既存の構成を保持し、ポリシーを移動またはコピーしません。ランチャーの移行ではこの不一致を解決できません。
133
+
130
134
  `launcher_migration_not_owned` が既存の登録を保持した状態(`mcp_created: false`)を指す場合、**Aptly 0.1.3 以降では** `--include-existing` を明示して移行できます。0.1.3 以降をインストールし、次を実行してください。
131
135
 
132
136
  ```sh
package/docs/guide/ko.md CHANGED
@@ -114,7 +114,9 @@ API 키는 macOS Keychain, Linux의 설치된 `secret-tool`, 또는 Windows Cred
114
114
 
115
115
  아래 옵션은 Aptly 0.1.2부터 지원하며 npm 0.1.1에는 없습니다. 소스에서 시험하려면 `npm ci --ignore-scripts`와 `npm run build` 후 `aptly` 대신 `node bin/aptly.ts`를 사용합니다.
116
116
 
117
- 키 설정은 입력·저장 전에 선택한 호스트를 진단합니다. 하나라도 실패하면 입력을 받지 않고 모든 호스트를 그대로 둡니다. `--check`는 키나 자격 저장소에 접근하지 않습니다. `credential_node_mismatch`, `credential_server_mismatch`, `credential_runtime_unsupported`는 각각 Node 경로, 서버 경로, OS 저장소 지원의 불일치입니다.
117
+ 키 설정은 입력·저장 전에 선택한 호스트를 진단합니다. 하나라도 실패하면 입력을 받지 않고 모든 호스트를 그대로 둡니다. `--check`는 키나 자격 저장소에 접근하지 않습니다.
118
+
119
+ Aptly 0.1.9부터 Linux에서 `--check`는 실행 가능한 `secret-tool`도 확인하고, 안전한 명시적 세션 버스 주소와 `gdbus`가 있으면 자격 증명 서비스를 활성화하거나 접근하지 않고 버스 메타데이터를 읽습니다. 확실한 실패는 입력 전에 `secure_store_unavailable`과 함께 `secure_store_secret_tool_missing`, `secure_store_bus_missing`, `secure_store_service_missing` 중 하나로 알립니다. `secure_store_bus_unverified`, `secure_store_probe_unavailable` 및 서비스 존재·활성화 가능 미확인 코드는 준비 상태를 알 수 없다는 뜻이며, 서비스가 실행 중이거나 활성화 가능해도 잠금 해제 또는 쓰기 가능을 보장하지 않습니다. 필요한 경우 `secret-tool`과 Secret Service 제공자를 설치하고 사용할 데스크톱 세션에서 실행하십시오. 실제 저장은 여전히 실패할 수 있습니다. SSH 또는 헤드리스 세션에서는 `APTLY_SECRET_BACKEND`가 없는 경우 호스트 MCP 프로세스에 `OPENAI_API_KEY`를 안전하게 전달하십시오. 기존 인증 래퍼나 환경은 보존하십시오. `credential_node_mismatch`, `credential_server_mismatch`, `credential_runtime_unsupported`는 각각 Node 경로, 서버 경로, OS 저장소 지원의 불일치입니다.
118
120
 
119
121
  Claude만 실패했다면 다음 순서로 진단하고, `launcher_migration_available`일 때만 이전을 검토하십시오:
120
122
 
@@ -127,6 +129,8 @@ aptly set env OPENAI_API_KEY --client claude
127
129
 
128
130
  `--dry-run`은 변경하지 않습니다. 이전 명령은 소유 기록과 일치하는 Aptly 표준 등록의 Node·서버 경로를 현재 빌드로 바꿉니다. 기존 환경·Hook·정책·다른 호스트는 보존하며 키를 읽거나 저장하지 않습니다. 오래된 실행 파일을 실행하지 않습니다. 사용자 래퍼, 소유 기록이 없거나 수정된 등록은 거절합니다. 이 경우 로컬에서 등록을 검토하고 래퍼의 안전한 환경 전달을 사용하거나 별도로 검토한 표준 등록으로 전환하십시오. 소유 기록을 삭제하거나 편집해 검증을 우회하지 마십시오.
129
131
 
132
+ Aptly 0.1.9부터 `aptly setup --check --client codex|claude|all`은 일반 설정 계획을 읽기만 하며 파일이나 디렉터리를 만들지 않습니다. 실행 중인 호스트를 검증하지 않는 시점별 확인입니다. `--check`에는 `--client`만 함께 사용할 수 있습니다. `hook_policy_path_conflict`가 나타나면 선택된 호스트 설정 디렉터리와 기존 정책 참조를 로컬에서 확인하고, 의도한 호스트 디렉터리를 선택한 뒤 다시 시도하십시오. 설정은 기존 구성을 보존하며 정책을 이동하거나 복사하지 않습니다. 실행기 이전으로 이 불일치를 해결할 수는 없습니다.
133
+
130
134
  `launcher_migration_not_owned`가 나오고 기존 등록을 보존한 상태(`mcp_created: false`)라면, **Aptly 0.1.3부터** `--include-existing`으로 명시적으로 이전할 수 있습니다. 0.1.3 이상을 설치한 뒤 다음 명령을 실행하십시오:
131
135
 
132
136
  ```sh
@@ -114,7 +114,9 @@ API 密钥通过 macOS Keychain、已安装的 Linux `secret-tool` 或 Windows C
114
114
 
115
115
  以下选项需要 Aptly 0.1.2 或更高版本,npm 0.1.1 不包含这些选项。如需从源码测试,请运行 `npm ci --ignore-scripts` 和 `npm run build`,然后将下文的 `aptly` 替换为 `node bin/aptly.ts`。
116
116
 
117
- 密钥设置会在输入和保存前诊断所选宿主。任一宿主失败时,不提示输入,也不修改任何宿主。`--check` 不访问密钥或凭据存储。`credential_node_mismatch`、`credential_server_mismatch` 和 `credential_runtime_unsupported` 分别表示 Node 路径、服务器路径及 OS 存储支持不兼容。
117
+ 密钥设置会在输入和保存前诊断所选宿主。任一宿主失败时,不提示输入,也不修改任何宿主。`--check` 不访问密钥或凭据存储。
118
+
119
+ 从 Aptly 0.1.9 起,在 Linux 上,`--check` 还会检查可执行的 `secret-tool`;如果有安全的显式会话总线地址和 `gdbus`,则只读取总线元数据,不启动或访问凭据服务。确认失败时,会在输入前报告 `secure_store_unavailable`,并附带 `secure_store_secret_tool_missing`、`secure_store_bus_missing` 或 `secure_store_service_missing`。`secure_store_bus_unverified`、`secure_store_probe_unavailable` 以及服务存在或可启动的未确认代码表示准备状态未知;服务存在或可启动并不能证明它已解锁或可写。必要时请安装 `secret-tool` 和 Secret Service 提供程序,并在目标桌面会话中运行。实际保存仍可能失败。对于 SSH 或无桌面会话,当 `APTLY_SECRET_BACKEND` 不存在时,请将 `OPENAI_API_KEY` 安全地传给宿主 MCP 进程,并保留现有认证包装程序或环境。`credential_node_mismatch`、`credential_server_mismatch` 和 `credential_runtime_unsupported` 分别表示 Node 路径、服务器路径及 OS 存储支持不兼容。
118
120
 
119
121
  如果只有 Claude 失败,按以下顺序诊断,仅在返回 `launcher_migration_available` 时考虑迁移:
120
122
 
@@ -127,6 +129,8 @@ aptly set env OPENAI_API_KEY --client claude
127
129
 
128
130
  `--dry-run` 不修改文件。迁移仅将与所有权记录一致的 Aptly 标准注册的 Node 和服务器路径更新到当前构建,保留环境设置、Hook、策略及其他宿主,不访问凭据,也不执行旧启动程序。自定义包装程序、缺少所有权记录或已修改的注册会被拒绝。请在本地检查此类注册,使用包装程序的安全环境传递方式,或切换到另行审核的标准注册。不要编辑或删除所有权记录以绕过验证。
129
131
 
132
+ 从 Aptly 0.1.9 起,`aptly setup --check --client codex|claude|all` 只读取常规设置计划,不会写入文件或创建目录。结果是当前时点的快照,不验证运行中的主机。`--check` 只能与 `--client` 组合使用。如果出现 `hook_policy_path_conflict`,请在本地检查所选主机配置目录和现有策略引用,选择预期的主机目录后重试。设置会保留现有配置,不会移动或复制策略;迁移启动器不能解决此不匹配。
133
+
130
134
  如果 `launcher_migration_not_owned` 对应的是保留的注册(`mcp_created: false`),**Aptly 0.1.3 或更高版本**提供显式选项 `--include-existing`。请安装 0.1.3 或更高版本,然后运行:
131
135
 
132
136
  ```sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aptly",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {