aptly 0.1.12 → 0.1.14
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 +21 -4
- package/dist/src/automatic-hook.d.ts +7 -0
- package/dist/src/automatic-hook.js +33 -15
- package/dist/src/cli-help.js +7 -6
- package/dist/src/context-retry.d.ts +10 -0
- package/dist/src/context-retry.js +16 -3
- package/dist/src/core.d.ts +2 -0
- package/dist/src/core.js +39 -35
- package/dist/src/doctor.d.ts +87 -0
- package/dist/src/doctor.js +182 -0
- package/dist/src/files.js +2 -2
- package/dist/src/host-paths.d.ts +10 -0
- package/dist/src/host-paths.js +15 -0
- package/dist/src/query-snapshot.d.ts +17 -0
- package/dist/src/query-snapshot.js +112 -0
- package/dist/src/server.js +2 -0
- package/dist/src/setup.d.ts +8 -5
- package/dist/src/setup.js +248 -60
- package/dist/src/stable-runtime.d.ts +61 -0
- package/dist/src/stable-runtime.js +694 -0
- package/dist/src/statistics.d.ts +48 -2
- package/dist/src/statistics.js +87 -6
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/docs/guide/en/advanced.md +6 -0
- package/docs/guide/en/configuration.md +27 -1
- package/docs/guide/en/installation.md +2 -2
- package/docs/guide/en/statistics.md +4 -0
- package/docs/guide/en/transmission.md +7 -5
- package/docs/guide/en/troubleshooting.md +4 -2
- package/docs/guide/en.md +2 -0
- package/docs/guide/ja/advanced.md +6 -0
- package/docs/guide/ja/configuration.md +27 -1
- package/docs/guide/ja/installation.md +2 -2
- package/docs/guide/ja/statistics.md +4 -0
- package/docs/guide/ja/transmission.md +7 -5
- package/docs/guide/ja/troubleshooting.md +4 -2
- package/docs/guide/ja.md +2 -0
- package/docs/guide/ko/advanced.md +6 -0
- package/docs/guide/ko/configuration.md +27 -1
- package/docs/guide/ko/installation.md +2 -2
- package/docs/guide/ko/statistics.md +4 -0
- package/docs/guide/ko/transmission.md +7 -5
- package/docs/guide/ko/troubleshooting.md +4 -2
- package/docs/guide/ko.md +2 -0
- package/docs/guide/zh-CN/advanced.md +6 -0
- package/docs/guide/zh-CN/configuration.md +27 -1
- package/docs/guide/zh-CN/installation.md +2 -2
- package/docs/guide/zh-CN/statistics.md +4 -0
- package/docs/guide/zh-CN/transmission.md +7 -5
- package/docs/guide/zh-CN/troubleshooting.md +4 -2
- package/docs/guide/zh-CN.md +2 -0
- package/package.json +1 -1
package/dist/src/setup.js
CHANGED
|
@@ -8,11 +8,14 @@ import { parse } from 'smol-toml';
|
|
|
8
8
|
import { resolveCatalog } from './catalog.js';
|
|
9
9
|
import { budgetEnvironmentDefaults, budgetEnvironmentKeys, parseBudgetValue, resolveBudgetSettings, budgetErrorDetails } from './budget.js';
|
|
10
10
|
import { Router, defaultPolicy } from './core.js';
|
|
11
|
-
import {
|
|
11
|
+
import { planStableRuntime, materializeStableRuntime, validateStableRegistration, stableReference, stableObserverCommand } from './stable-runtime.js';
|
|
12
|
+
import { resolveHostPaths as resolved } from './host-paths.js';
|
|
13
|
+
import { QuerySnapshot } from './query-snapshot.js';
|
|
14
|
+
import { loadAutomaticHookPolicy, queryAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
|
|
12
15
|
import { assertPrivateStatePath } from './files.js';
|
|
13
16
|
import { CODEX_HOME_POLICY_SOURCE, resolvePolicySource } from './policy-source.js';
|
|
14
17
|
import { assertWindowsPrivatePath, protectNewWindowsPrivateDirectory, copyWindowsFilePermissions } from './windows-private.js';
|
|
15
|
-
import { STATISTICS_CONFIG_FILE, STATISTICS_KEY_FILE, STATISTICS_DB_FILE, parseStatisticsConfig, serializeStatisticsConfig,
|
|
18
|
+
import { STATISTICS_CONFIG_FILE, STATISTICS_KEY_FILE, STATISTICS_DB_FILE, parseStatisticsConfig, serializeStatisticsConfig, readStatisticsQuery, initializeStatisticsStore } from './statistics.js';
|
|
16
19
|
const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
17
20
|
const stringify = (value) => JSON.stringify(value, null, 2) + '\n';
|
|
18
21
|
const fail = (code) => { throw new Error(code); };
|
|
@@ -188,7 +191,8 @@ function validateEnvironmentValue(key, value) {
|
|
|
188
191
|
}
|
|
189
192
|
}
|
|
190
193
|
}
|
|
191
|
-
|
|
194
|
+
const candidateEnvironmentAliases = { APTLY_CLAUDE_MODELS: 'CLAUDE_MODELS', APTLY_CODEX_MODELS: 'CODEX_MODELS' };
|
|
195
|
+
function environmentInheritance(entry, environment, client) {
|
|
192
196
|
if (client === 'codex' && entry.env_vars !== undefined && (!Array.isArray(entry.env_vars) || entry.env_vars.some((key) => typeof key !== 'string')))
|
|
193
197
|
fail('configuration_shape_conflict');
|
|
194
198
|
const permitted = client === 'codex' ? (entry.env_vars ?? []) : [], keys = new Set(), values = {};
|
|
@@ -202,14 +206,27 @@ function budgetInheritance(entry, environment, client) {
|
|
|
202
206
|
for (const key of Object.keys(environment))
|
|
203
207
|
if ((key.startsWith('APTLY_MAX_') || key.startsWith('APTLY_ESTIMATED_')) && (client === 'claude' || permitted.includes(key)))
|
|
204
208
|
values[key] = environment[key];
|
|
209
|
+
for (const key of Object.entries(candidateEnvironmentAliases).flat()) {
|
|
210
|
+
const descriptor = Object.getOwnPropertyDescriptor(environment, key);
|
|
211
|
+
// A declared Codex passthrough remains external even when this CLI cannot observe its value.
|
|
212
|
+
if (client === 'codex' ? !permitted.includes(key) : !descriptor || ('value' in descriptor && descriptor.value === undefined))
|
|
213
|
+
continue;
|
|
214
|
+
keys.add(key);
|
|
215
|
+
if (descriptor) {
|
|
216
|
+
if (!('value' in descriptor))
|
|
217
|
+
fail('environment_invalid_value');
|
|
218
|
+
if (descriptor.value !== undefined)
|
|
219
|
+
values[key] = descriptor.value;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
205
222
|
return { keys, values };
|
|
206
223
|
}
|
|
207
224
|
function editEnvironment(current, edit, client, inherited) {
|
|
208
225
|
const updates = {};
|
|
209
226
|
if ('defaults' in edit) {
|
|
210
227
|
for (const [key, value] of Object.entries(defaultEnvironment)) {
|
|
211
|
-
const alias = key
|
|
212
|
-
if (current[key] === undefined && (!alias || current[alias] === undefined) && !
|
|
228
|
+
const alias = candidateEnvironmentAliases[key];
|
|
229
|
+
if (current[key] === undefined && (!alias || current[alias] === undefined) && !inherited.keys.has(key) && (!alias || !inherited.keys.has(alias)))
|
|
213
230
|
updates[key] = value;
|
|
214
231
|
}
|
|
215
232
|
}
|
|
@@ -333,17 +350,6 @@ function policyReferenceMatches(entry, client, policyPath, options) {
|
|
|
333
350
|
return source === policyPath;
|
|
334
351
|
return client === 'codex' && entry.env?.CODEX_HOME === undefined && Array.isArray(entry.env_vars) && entry.env_vars.every((x) => typeof x === 'string') && entry.env_vars.includes('CODEX_HOME') && selectedCliPolicyPath(options) === policyPath;
|
|
335
352
|
}
|
|
336
|
-
function resolved(options, client) {
|
|
337
|
-
const home = resolve(options.home ?? homedir()), env = options.env ?? process.env;
|
|
338
|
-
const override = client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR;
|
|
339
|
-
if (override && !isAbsolute(override))
|
|
340
|
-
fail('relative_configuration_directory');
|
|
341
|
-
if (client === 'codex' && override !== undefined)
|
|
342
|
-
resolvePolicySource(CODEX_HOME_POLICY_SOURCE, env);
|
|
343
|
-
const dir = override || join(home, client === 'codex' ? '.codex' : '.claude');
|
|
344
|
-
const mcpPath = client === 'codex' ? join(dir, 'config.toml') : override ? join(dir, '.claude.json') : join(home, '.claude.json');
|
|
345
|
-
return { dir, mcpPath, hooksPath: join(dir, client === 'codex' ? 'hooks.json' : 'settings.json'), privateDir: join(dir, 'aptly') };
|
|
346
|
-
}
|
|
347
353
|
function ownership(value, client) {
|
|
348
354
|
if (value.schema_version !== 1 || value.kind !== 'aptly-setup-ownership' || value.client !== client || !object(value.hook) || typeof value.mcp_created !== 'boolean' || !object(value.env_added) || !object(value.policy) || typeof value.policy_created !== 'boolean')
|
|
349
355
|
fail('invalid_ownership');
|
|
@@ -356,7 +362,21 @@ function ownership(value, client) {
|
|
|
356
362
|
return value;
|
|
357
363
|
}
|
|
358
364
|
/** Compatibility restriction only: this does not authenticate arbitrary launcher code. */
|
|
359
|
-
function requireCredentialRuntime(entry, root) {
|
|
365
|
+
function requireCredentialRuntime(entry, root, home, planned) {
|
|
366
|
+
const plannedMatch = planned && entry.command === planned.descriptor.command && isDeepStrictEqual(entry.args, planned.descriptor.args);
|
|
367
|
+
const stable = plannedMatch ? null : validateStableRegistration(entry, { home });
|
|
368
|
+
if (stable || plannedMatch) {
|
|
369
|
+
const payload = stable?.packageRoot ?? root;
|
|
370
|
+
try {
|
|
371
|
+
const server = read(join(payload, 'dist/src/server.js')).text, runtime = read(join(payload, 'dist/src/runtime.js')).text;
|
|
372
|
+
if (!server?.includes('./runtime.js') || !runtime?.includes('APTLY_SECRET_BACKEND') || !runtime.includes('APTLY_SECRET_CLIENT'))
|
|
373
|
+
fail('credential_launcher_unverified');
|
|
374
|
+
}
|
|
375
|
+
catch {
|
|
376
|
+
fail('credential_launcher_unverified');
|
|
377
|
+
}
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
360
380
|
const allowed = [join(root, 'dist', 'src', 'server.js'), join(root, 'src', 'server.ts')];
|
|
361
381
|
const incompatible = (reason) => { throw Object.assign(new Error('credential_launcher_unverified'), { reason }); };
|
|
362
382
|
if (entry.command !== process.execPath)
|
|
@@ -408,6 +428,7 @@ function prepare(options, client, removing, edit) {
|
|
|
408
428
|
if (privateFile.before !== null)
|
|
409
429
|
privatePermissions(privateFile.path, 'private_file_permissions');
|
|
410
430
|
observations.push(mcp, hooks, policy, manifest);
|
|
431
|
+
let stableRuntime;
|
|
411
432
|
const oldOwner = manifest.before === null ? undefined : ownership(json(manifest.before), client);
|
|
412
433
|
if (removing && !oldOwner) {
|
|
413
434
|
if (read(join(privateDir, STATISTICS_OWNERSHIP_FILE)).text !== null)
|
|
@@ -481,11 +502,21 @@ function prepare(options, client, removing, edit) {
|
|
|
481
502
|
const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
|
|
482
503
|
const additions = { APTLY_HOOK_POLICY_PATH: policyPath, ROUTER_LEDGER_PATH: join(stateDir, 'ledger.json') };
|
|
483
504
|
let created = false, tomlBlock;
|
|
505
|
+
// Explicit migration may replace an exact-owned unavailable/older generation.
|
|
506
|
+
// Its bytes are never executed or trusted for credential injection; only the
|
|
507
|
+
// 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))
|
|
511
|
+
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 });
|
|
484
515
|
if (edit && 'migrate' in edit) {
|
|
485
516
|
if (!oldOwner || !object(servers.aptly) || (oldOwner.mcp_created ? !isDeepStrictEqual(servers.aptly, oldOwner.mcp) : !edit.includeExisting))
|
|
486
517
|
fail('launcher_migration_not_owned');
|
|
487
518
|
const entry = servers.aptly;
|
|
488
|
-
if (typeof entry.command !== 'string' || !isAbsolute(entry.command) || !['node', 'node.exe'].includes(basename(entry.command).toLowerCase()) || !Array.isArray(entry.args) || entry.args.length !== 1 || typeof entry.args[0] !== 'string' || !isAbsolute(entry.args[0]) || !/(?:^|[\\/])(?:dist[\\/]src[\\/]server\.js|src[\\/]server\.ts)$/.test(entry.args[0]))
|
|
519
|
+
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])))
|
|
489
520
|
fail('launcher_migration_not_standard');
|
|
490
521
|
if (!entries.some(entry => isDeepStrictEqual(entry, oldOwner.hook)) || !isDeepStrictEqual(json(policy.before), oldOwner.policy))
|
|
491
522
|
fail('managed_entry_changed');
|
|
@@ -495,7 +526,7 @@ function prepare(options, client, removing, edit) {
|
|
|
495
526
|
}
|
|
496
527
|
if (servers.aptly === undefined) {
|
|
497
528
|
created = true;
|
|
498
|
-
servers.aptly = { ...(client === 'claude' ? { type: 'stdio' } : {}), command: process.execPath, 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 } };
|
|
529
|
+
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 } };
|
|
499
530
|
}
|
|
500
531
|
else {
|
|
501
532
|
if (!object(servers.aptly))
|
|
@@ -518,14 +549,14 @@ function prepare(options, client, removing, edit) {
|
|
|
518
549
|
mcp.after = client === 'codex' ? addTomlEnv(mcp.before ?? '', missing) : stringify(config);
|
|
519
550
|
}
|
|
520
551
|
if (edit && 'migrate' in edit) {
|
|
521
|
-
servers.aptly.command = process.execPath;
|
|
522
|
-
servers.aptly.args = [join(root, 'dist', 'src', 'server.js')];
|
|
552
|
+
servers.aptly.command = stableRuntime?.descriptor.command ?? process.execPath;
|
|
553
|
+
servers.aptly.args = stableRuntime?.descriptor.args ?? [join(root, 'dist', 'src', 'server.js')];
|
|
523
554
|
}
|
|
524
555
|
if ((edit && ('credential' in edit || 'migrate' in edit)) || servers.aptly.env?.APTLY_HOOK_POLICY_PATH === CODEX_HOME_POLICY_SOURCE)
|
|
525
|
-
requireCredentialRuntime(servers.aptly, root);
|
|
556
|
+
requireCredentialRuntime(servers.aptly, root, options.home, stableRuntime);
|
|
526
557
|
const currentEnv = map(servers.aptly, 'env');
|
|
527
|
-
const originalEnvKeys = new Set(Object.keys(currentEnv)),
|
|
528
|
-
const updates = edit ? editEnvironment(currentEnv, edit, client,
|
|
558
|
+
const originalEnvKeys = new Set(Object.keys(currentEnv)), inheritedEnvironment = environmentInheritance(servers.aptly, env, client);
|
|
559
|
+
const updates = edit ? editEnvironment(currentEnv, edit, client, inheritedEnvironment) : {};
|
|
529
560
|
Object.assign(currentEnv, updates);
|
|
530
561
|
if (created) {
|
|
531
562
|
if (client === 'codex') {
|
|
@@ -618,15 +649,17 @@ function prepare(options, client, removing, edit) {
|
|
|
618
649
|
if (requestedScope !== undefined)
|
|
619
650
|
owner.policy = structuredClone(policyValue);
|
|
620
651
|
if (edit && ('defaults' in edit || ('key' in edit && budgetEnvironmentKeys.includes(edit.key)))) {
|
|
621
|
-
const budget = resolveBudgetSettings({ ...
|
|
652
|
+
const budget = resolveBudgetSettings({ ...inheritedEnvironment.values, ...currentEnv });
|
|
622
653
|
result.budget = { limits: { ...budget.limits }, added: budgetEnvironmentKeys.filter(key => Object.hasOwn(updates, key) && !originalEnvKeys.has(key)),
|
|
623
654
|
updated: budgetEnvironmentKeys.filter(key => Object.hasOwn(updates, key) && originalEnvKeys.has(key)),
|
|
624
655
|
preserved: budgetEnvironmentKeys.filter(key => !Object.hasOwn(updates, key) && currentEnv[key] !== undefined),
|
|
625
|
-
inherited: budgetEnvironmentKeys.filter(key => currentEnv[key] === undefined &&
|
|
656
|
+
inherited: budgetEnvironmentKeys.filter(key => currentEnv[key] === undefined && inheritedEnvironment.keys.has(key)), restart_required: budgetEnvironmentKeys.some(key => Object.hasOwn(updates, key)) };
|
|
626
657
|
}
|
|
627
658
|
result.transmission = effectiveTransmission(policyValue);
|
|
628
659
|
result.transmission_source = policyValue.schema_version === 1 ? 'legacy' : policyValue.transmission === 'unselected' ? 'unselected' : 'explicit';
|
|
629
660
|
manifest.after = stringify(owner);
|
|
661
|
+
if (edit && 'migrate' in edit && stableRuntime)
|
|
662
|
+
appendStatisticsLauncherMigration(options, client, root, servers.aptly, stableRuntime, policyPath, hooksObject, hooks, changes, observations);
|
|
630
663
|
const review = transmissionReviewSnapshot(options, client);
|
|
631
664
|
observations.push(review);
|
|
632
665
|
if (requestedScope !== undefined) {
|
|
@@ -635,9 +668,12 @@ function prepare(options, client, removing, edit) {
|
|
|
635
668
|
changes.push(review);
|
|
636
669
|
}
|
|
637
670
|
result.transmission_review = reviewMatches(review.after, options, client, policyValue) ? 'complete' : 'required';
|
|
671
|
+
const snapshotOutdated = !!existingStable && !stableRuntime && 'version' in existingStable && existingStable.version !== json(read(join(root, 'package.json')).text).version;
|
|
672
|
+
if (snapshotOutdated)
|
|
673
|
+
result.recovery = [`aptly setup --client ${client} --migrate-launcher --launcher stable --dry-run`];
|
|
638
674
|
if (client === 'codex')
|
|
639
675
|
result.requires_hook_review = true;
|
|
640
|
-
result.codes = [...(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'] : [])];
|
|
676
|
+
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'] : [])];
|
|
641
677
|
dirs.push(dir, privateDir, stateDir);
|
|
642
678
|
}
|
|
643
679
|
// Validate complete desired data before any host file is changed.
|
|
@@ -651,7 +687,7 @@ function prepare(options, client, removing, edit) {
|
|
|
651
687
|
const markerIndex = changes.findIndex(item => item.reviewPrivate);
|
|
652
688
|
if (markerIndex >= 0)
|
|
653
689
|
changes.push(...changes.splice(markerIndex, 1));
|
|
654
|
-
return { changes, observations, dirs, result };
|
|
690
|
+
return { changes, observations, dirs, result, ...(stableRuntime ? { stableRuntime } : {}) };
|
|
655
691
|
}
|
|
656
692
|
/** Secure sibling staging is short-lived and never a backup; original settings stay in memory. */
|
|
657
693
|
function replace(snapshot, forward) {
|
|
@@ -709,13 +745,15 @@ function policyRecovery(client) {
|
|
|
709
745
|
}
|
|
710
746
|
function errorResult(client, error) {
|
|
711
747
|
const detail = error?.policyConflict;
|
|
712
|
-
return { client, status: 'error', codes: [safeCode(error), ...(detail ? ['hook_policy_path_conflict'] : [])], ...budgetErrorDetails(error), ...(detail ? { ...detail, recovery: policyRecovery(client) } : {}) };
|
|
748
|
+
return { client, status: 'error', codes: [safeCode(error), ...(detail ? ['hook_policy_path_conflict'] : [])], ...budgetErrorDetails(error), ...(detail ? { ...detail, recovery: policyRecovery(client) } : ['stable_runtime_unverified', 'stable_runtime_busy', 'stable_snapshot_outdated'].includes(safeCode(error)) ? { recovery: [`aptly setup --client ${client} --migrate-launcher --launcher stable --dry-run`, 'Review unavailable, modified or busy runtime state locally; do not delete shared generations or locks while referenced or being written.'] } : {}) };
|
|
713
749
|
}
|
|
714
750
|
function execute(options, removing, edit, captured) {
|
|
715
751
|
const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
|
|
716
752
|
if (clients.some(client => client !== 'codex' && client !== 'claude'))
|
|
717
753
|
return { status: 'partial', clients: [] };
|
|
718
754
|
const env = options.env ?? process.env;
|
|
755
|
+
if (options.launcher !== undefined && (options.launcher !== 'stable' || removing || !!(edit && !('migrate' in edit))))
|
|
756
|
+
return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['stable_launcher_invalid_options'] })) };
|
|
719
757
|
if (options.transmission !== undefined && !['none', 'description', 'excerpt'].includes(options.transmission))
|
|
720
758
|
return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['transmission_invalid_scope'] })) };
|
|
721
759
|
if (!removing && options.automatic && (env.APTLY_SKIP_SETUP === '1' || !!env.CI))
|
|
@@ -729,7 +767,7 @@ function execute(options, removing, edit, captured) {
|
|
|
729
767
|
}
|
|
730
768
|
});
|
|
731
769
|
const results = prepared.map(plan => plan.result);
|
|
732
|
-
if (edit && results.some(result => result.status === 'error'))
|
|
770
|
+
if ((edit || options.launcher === 'stable') && results.some(result => result.status === 'error'))
|
|
733
771
|
return { status: 'partial', clients: results.map(result => result.status === 'error' ? result : { ...result, status: 'skipped', codes: ['other_host_validation_failed'] }) };
|
|
734
772
|
// Each host is independent; prepare every host before committing any host.
|
|
735
773
|
for (const plan of prepared) {
|
|
@@ -738,6 +776,10 @@ function execute(options, removing, edit, captured) {
|
|
|
738
776
|
const written = [], madeDirs = [];
|
|
739
777
|
try {
|
|
740
778
|
validateObservations(plan);
|
|
779
|
+
if (plan.stableRuntime) {
|
|
780
|
+
materializeStableRuntime(plan.stableRuntime);
|
|
781
|
+
validateObservations(plan);
|
|
782
|
+
}
|
|
741
783
|
for (const path of plan.dirs) {
|
|
742
784
|
noSymlinks(path);
|
|
743
785
|
try {
|
|
@@ -792,18 +834,21 @@ function execute(options, removing, edit, captured) {
|
|
|
792
834
|
}
|
|
793
835
|
return { status: results.some(result => result.status === 'error') ? 'partial' : results.every(result => result.status === 'skipped') ? 'skipped' : 'complete', clients: results };
|
|
794
836
|
}
|
|
795
|
-
const codes = new Set(['policy_source_home_invalid', 'policy_source_requires_setup', 'policy_source_invalid_options', 'transmission_review_requires_setup', 'transmission_review_invalid_options', 'statistics_requires_setup', 'statistics_policy_conflict', 'statistics_config_invalid', 'statistics_ownership_invalid', 'statistics_observers_present', 'statistics_key_missing', 'statistics_shared_state', 'statistics_platform_unsupported', 'statistics_invalid_options', 'statistics_observer_missing', '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']);
|
|
837
|
+
const codes = new Set(['stable_launcher_platform_unsupported', 'stable_runtime_unverified', 'stable_launcher_migration_required', 'stable_launcher_invalid_options', 'stable_source_unverified', 'stable_source_changed', 'stable_runtime_limit', 'stable_plan_unverified', 'stable_runtime_busy', 'policy_source_home_invalid', 'policy_source_requires_setup', 'policy_source_invalid_options', 'transmission_review_requires_setup', 'transmission_review_invalid_options', 'statistics_requires_setup', 'statistics_policy_conflict', 'statistics_config_invalid', 'statistics_ownership_invalid', 'statistics_observers_present', 'statistics_key_missing', 'statistics_shared_state', 'statistics_platform_unsupported', 'statistics_invalid_options', 'statistics_observer_missing', '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']);
|
|
796
838
|
function safeCode(error) { return error instanceof Error && codes.has(error.message) ? error.message : 'configuration_io_error'; }
|
|
797
839
|
export function setupHosts(options = {}) { return execute(options, false); }
|
|
798
840
|
/** Snapshot the normal setup plan without applying it; it does not verify a running host. */
|
|
799
841
|
export function checkSetup(options = {}) {
|
|
800
842
|
const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
|
|
801
|
-
if (!clients.length || clients.some(client => client !== 'codex' && client !== 'claude') || options.automatic !== undefined || options.mode !== undefined || options.transmission !== undefined || options.selectUnselectedOnly !== undefined)
|
|
843
|
+
if (!clients.length || clients.some(client => client !== 'codex' && client !== 'claude') || options.automatic !== undefined || options.mode !== undefined || options.transmission !== undefined || options.selectUnselectedOnly !== undefined || options.launcher !== undefined)
|
|
802
844
|
return { status: 'partial', clients: [] };
|
|
803
845
|
const results = clients.map(client => {
|
|
804
846
|
try {
|
|
805
847
|
const plan = prepare(options, client, false);
|
|
806
|
-
|
|
848
|
+
const paths = resolved(options, client), config = client === 'codex' ? toml(read(paths.mcpPath).text ?? '') : json(read(paths.mcpPath).text);
|
|
849
|
+
const command = config[client === 'codex' ? 'mcp_servers' : 'mcpServers']?.aptly?.command;
|
|
850
|
+
const pinned = typeof command === 'string' && /[\\/]\.nvm[\\/]versions[\\/]node[\\/]/.test(command);
|
|
851
|
+
return { ...plan.result, status: 'unchanged', codes: [plan.changes.length ? 'setup_check_configure_ready' : 'setup_check_ok', ...plan.result.codes, ...(pinned ? ['launcher_pinned_to_versioned_node'] : [])] };
|
|
807
852
|
}
|
|
808
853
|
catch (error) {
|
|
809
854
|
return errorResult(client, error);
|
|
@@ -907,7 +952,7 @@ export function migrateLauncher(options, dryRun = false, includeExisting = false
|
|
|
907
952
|
return { status: 'complete', clients: [{ client, status: 'unchanged', codes: [plan.changes.length ? 'launcher_migration_available' : 'launcher_current'], requires_hook_review: client === 'codex' }] };
|
|
908
953
|
const result = execute(options, false, edit, [plan]);
|
|
909
954
|
if (result.status === 'complete')
|
|
910
|
-
result.clients[0].codes.push('launcher_migrated', 'mcp_restart_required');
|
|
955
|
+
result.clients[0].codes.push('launcher_migrated', 'mcp_restart_required', ...(!plan.stableRuntime && read(join(resolved(options, client).privateDir, STATISTICS_OWNERSHIP_FILE)).text !== null ? ['statistics_observer_migration_required'] : []));
|
|
911
956
|
return result;
|
|
912
957
|
}
|
|
913
958
|
catch (error) {
|
|
@@ -948,7 +993,7 @@ export function setPolicySource(options, dryRun = false) {
|
|
|
948
993
|
if (!loadAutomaticHookPolicy(policyPath).policy || !isDeepStrictEqual(json(policy.before), owner.policy))
|
|
949
994
|
fail('managed_policy_changed');
|
|
950
995
|
const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
|
|
951
|
-
requireCredentialRuntime(entry, root);
|
|
996
|
+
requireCredentialRuntime(entry, root, options.home);
|
|
952
997
|
if (entry.env.CODEX_HOME !== undefined)
|
|
953
998
|
fail('mcp_environment_conflict');
|
|
954
999
|
if (entry.env_vars !== undefined && (!Array.isArray(entry.env_vars) || entry.env_vars.some((v) => typeof v !== 'string')))
|
|
@@ -1182,23 +1227,99 @@ export function prepareTransmissionReview(options = {}) {
|
|
|
1182
1227
|
return merge(applied.clients, applied.status);
|
|
1183
1228
|
} };
|
|
1184
1229
|
}
|
|
1185
|
-
/**
|
|
1230
|
+
/** Query context only: no credential lookup, native discovery or configuration repair. */
|
|
1231
|
+
function queryContext(options, client, snapshot, statistics, policyMissing) {
|
|
1232
|
+
const paths = resolved(options, client), mcp = snapshot.read(paths.mcpPath);
|
|
1233
|
+
const config = client === 'codex' ? toml(mcp?.toString('utf8') ?? '') : json(mcp?.toString('utf8') ?? null);
|
|
1234
|
+
const servers = config[client === 'codex' ? 'mcp_servers' : 'mcpServers'], entry = servers?.aptly;
|
|
1235
|
+
let failed = (servers !== undefined && !object(servers)) || (entry !== undefined && (!object(entry) || (entry.env !== undefined && !object(entry.env))));
|
|
1236
|
+
let statisticsExpected = false;
|
|
1237
|
+
let expected = failed || (object(entry?.env) && Object.hasOwn(entry.env, 'APTLY_HOOK_POLICY_PATH'));
|
|
1238
|
+
try {
|
|
1239
|
+
const receipt = snapshot.read(join(paths.privateDir, 'setup-ownership.json'), { privateFile: true });
|
|
1240
|
+
if (receipt) {
|
|
1241
|
+
expected = true;
|
|
1242
|
+
ownership(json(receipt.toString('utf8')), client);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
catch {
|
|
1246
|
+
failed = true;
|
|
1247
|
+
expected = true;
|
|
1248
|
+
}
|
|
1249
|
+
if (statistics || policyMissing)
|
|
1250
|
+
try {
|
|
1251
|
+
const statOwner = snapshot.read(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE), { privateFile: true });
|
|
1252
|
+
if (statOwner) {
|
|
1253
|
+
expected = true;
|
|
1254
|
+
statisticsOwner(json(statOwner.toString('utf8')), client);
|
|
1255
|
+
statisticsExpected = true;
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
catch {
|
|
1259
|
+
failed = true;
|
|
1260
|
+
expected = true;
|
|
1261
|
+
}
|
|
1262
|
+
if (policyMissing && !expected)
|
|
1263
|
+
try {
|
|
1264
|
+
// A normal remove retains a disabled config and history; this is not broken setup.
|
|
1265
|
+
const bytes = snapshot.read(join(paths.privateDir, 'state', STATISTICS_CONFIG_FILE), { privateFile: true, maxBytes: 8192, singleLink: true });
|
|
1266
|
+
if (bytes) {
|
|
1267
|
+
const state = parseStatisticsConfig(JSON.parse(bytes.toString('utf8')));
|
|
1268
|
+
if (!state) {
|
|
1269
|
+
failed = true;
|
|
1270
|
+
expected = true;
|
|
1271
|
+
}
|
|
1272
|
+
else
|
|
1273
|
+
expected = state.enabled_clients.includes(client);
|
|
1274
|
+
}
|
|
1275
|
+
else
|
|
1276
|
+
for (const name of [STATISTICS_KEY_FILE, STATISTICS_DB_FILE])
|
|
1277
|
+
if (snapshot.track(join(paths.privateDir, 'state', name), { privateFile: true, singleLink: true, identityOnly: true }))
|
|
1278
|
+
expected = true;
|
|
1279
|
+
}
|
|
1280
|
+
catch {
|
|
1281
|
+
failed = true;
|
|
1282
|
+
expected = true;
|
|
1283
|
+
}
|
|
1284
|
+
return { entry, expected, failed, paths, statisticsExpected };
|
|
1285
|
+
}
|
|
1286
|
+
/** Redacted policy query; aggregate status is query completion, not host readiness. */
|
|
1186
1287
|
export function showTransmission(options = {}) {
|
|
1187
|
-
|
|
1288
|
+
const outcomes = (options.clients ?? ['codex', 'claude']).map(client => {
|
|
1289
|
+
const snapshot = new QuerySnapshot();
|
|
1290
|
+
try {
|
|
1291
|
+
const { privateDir } = resolved(options, client), loaded = queryAutomaticHookPolicy(join(privateDir, 'auto-policy.json'), snapshot);
|
|
1292
|
+
let expected = false, contextFailed = false;
|
|
1188
1293
|
try {
|
|
1189
|
-
const
|
|
1190
|
-
|
|
1191
|
-
|
|
1294
|
+
const context = queryContext(options, client, snapshot, false, !loaded.policy);
|
|
1295
|
+
expected = context.expected;
|
|
1296
|
+
// Local policy contents cannot certify a conflicting/missing MCP policy binding.
|
|
1297
|
+
// Preserve legacy client fields; aggregate health reports the failed query contract.
|
|
1298
|
+
contextFailed = context.failed || (expected && (!object(context.entry) || !policyReferenceMatches(context.entry, client, join(privateDir, 'auto-policy.json'), options)));
|
|
1299
|
+
}
|
|
1300
|
+
catch {
|
|
1301
|
+
contextFailed = true;
|
|
1302
|
+
}
|
|
1303
|
+
const legacy = () => {
|
|
1192
1304
|
if (!loaded.policy)
|
|
1193
1305
|
return { client, status: 'unavailable', code: loaded.reason };
|
|
1306
|
+
// Preserve validation of the acknowledgement but read it only once for this query.
|
|
1307
|
+
const markerPath = join(privateDir, TRANSMISSION_REVIEW_FILE);
|
|
1308
|
+
validateReviewPrivate(markerPath);
|
|
1309
|
+
const marker = snapshot.read(markerPath, { privateFile: true, singleLink: true });
|
|
1194
1310
|
return { client, status: 'configured', application_mode: loaded.policy.mode, enabled: loaded.policy.enabled,
|
|
1195
|
-
transmission_review: reviewMatches(
|
|
1311
|
+
transmission_review: reviewMatches(marker?.toString('utf8') ?? null, options, client, loaded.policy) ? 'complete' : 'required',
|
|
1196
1312
|
transmission: effectiveTransmission(loaded.policy), transmission_source: loaded.policy.schema_version === 1 ? 'legacy' : effectiveTransmission(loaded.policy) === 'unselected' ? 'unselected' : 'explicit' };
|
|
1197
|
-
}
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
}
|
|
1201
|
-
}
|
|
1313
|
+
};
|
|
1314
|
+
const result = legacy();
|
|
1315
|
+
snapshot.verify();
|
|
1316
|
+
return { result, failed: contextFailed || loaded.availability === 'error' || (loaded.availability === 'absent' && expected) };
|
|
1317
|
+
}
|
|
1318
|
+
catch (error) {
|
|
1319
|
+
return { result: { client, status: 'error', code: safeCode(error) }, failed: true };
|
|
1320
|
+
}
|
|
1321
|
+
});
|
|
1322
|
+
return { status: outcomes.some(o => o.failed) ? 'partial' : 'complete', clients: outcomes.map(o => o.result) };
|
|
1202
1323
|
}
|
|
1203
1324
|
/** Registration snapshot only. Never loads credentials, starts a server or creates a ledger/gate. */
|
|
1204
1325
|
export function showBudgetStatus(options = {}) {
|
|
@@ -1265,6 +1386,7 @@ function statisticEntries(value, event, create = false) {
|
|
|
1265
1386
|
}
|
|
1266
1387
|
function statisticsPolicy(options, client, requireRegistration = true) {
|
|
1267
1388
|
const paths = resolved(options, client), policyPath = join(paths.privateDir, 'auto-policy.json');
|
|
1389
|
+
let stable = null;
|
|
1268
1390
|
if (requireRegistration) {
|
|
1269
1391
|
const mcp = read(paths.mcpPath), config = client === 'codex' ? toml(mcp.text ?? '') : json(mcp.text);
|
|
1270
1392
|
const entry = config[client === 'codex' ? 'mcp_servers' : 'mcpServers']?.aptly;
|
|
@@ -1272,25 +1394,56 @@ function statisticsPolicy(options, client, requireRegistration = true) {
|
|
|
1272
1394
|
fail('statistics_requires_setup');
|
|
1273
1395
|
if (!policyReferenceMatches(entry, client, policyPath, options))
|
|
1274
1396
|
fail('statistics_policy_conflict');
|
|
1397
|
+
stable = validateStableRegistration(entry, { home: options.home });
|
|
1275
1398
|
}
|
|
1276
1399
|
const loaded = loadAutomaticHookPolicy(policyPath);
|
|
1277
1400
|
if (!loaded.policy)
|
|
1278
1401
|
fail('statistics_requires_setup');
|
|
1279
|
-
return { ...paths, policyPath, stateDirectory: loaded.policy.state_directory };
|
|
1402
|
+
return { ...paths, policyPath, stateDirectory: loaded.policy.state_directory, stable };
|
|
1280
1403
|
}
|
|
1281
|
-
function statisticsHooks(root, client, policyPath) {
|
|
1404
|
+
function statisticsHooks(root, client, policyPath, stable) {
|
|
1282
1405
|
const observer = join(root, 'dist', 'bin', 'aptly-observe.js');
|
|
1283
|
-
if (read(observer).text === null)
|
|
1406
|
+
if (!stable && read(observer).text === null)
|
|
1284
1407
|
fail('statistics_observer_missing');
|
|
1285
1408
|
for (const path of [process.execPath, observer, policyPath])
|
|
1286
1409
|
if (!isAbsolute(path) || /[\x00-\x1f\x7f]/.test(path))
|
|
1287
1410
|
fail('statistics_invalid_options');
|
|
1288
1411
|
const quote = (v) => "'" + v.replaceAll("'", "'\\''") + "'";
|
|
1289
|
-
const command = [process.execPath, '--no-warnings', observer, '--client', client, '--policy-path', policyPath].map(quote).join(' ');
|
|
1412
|
+
const command = stable ? stableObserverCommand(stable, client, policyPath) : [process.execPath, '--no-warnings', observer, '--client', client, '--policy-path', policyPath].map(quote).join(' ');
|
|
1290
1413
|
const handler = { type: 'command', command, timeout: 5, statusMessage: 'Aptly local execution statistics' };
|
|
1291
1414
|
const events = client === 'codex' ? ['PostToolUse', 'SubagentStart', 'PostModelRequest', 'SubagentStop'] : ['PostToolUse', 'SubagentStart', 'SubagentStop'];
|
|
1292
1415
|
return Object.fromEntries(events.map(event => [event, { ...(event === 'PostToolUse' ? { matcher: client === 'codex' ? '^(spawn_agent|collaborationspawn_agent|collaboration\\.spawn_agent)$' : '^(Agent|Task)$' } : {}), hooks: [{ ...handler }] }]));
|
|
1293
1416
|
}
|
|
1417
|
+
function appendStatisticsLauncherMigration(options, client, root, entry, planned, policyPath, hooksObject, hooks, changes, observations) {
|
|
1418
|
+
const paths = resolved(options, client), receipt = statisticsSnapshot(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
|
|
1419
|
+
observations.push(receipt);
|
|
1420
|
+
if (receipt.before === null) {
|
|
1421
|
+
for (const name of ['PostToolUse', 'SubagentStart', 'PostModelRequest', 'SubagentStop'])
|
|
1422
|
+
if (statisticEntries(hooksObject, name).some(possibleStatisticsObserver))
|
|
1423
|
+
fail('statistics_observers_present');
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1426
|
+
const owner = statisticsOwner(json(receipt.before), client), policy = loadAutomaticHookPolicy(policyPath).policy;
|
|
1427
|
+
if (!policy || owner.state_directory !== policy.state_directory)
|
|
1428
|
+
fail('statistics_policy_conflict');
|
|
1429
|
+
for (const [event, definition] of Object.entries(owner.hooks)) {
|
|
1430
|
+
const list = statisticEntries(hooksObject, event), matches = list.filter(v => isDeepStrictEqual(v, definition));
|
|
1431
|
+
if (matches.length !== 1)
|
|
1432
|
+
fail('managed_hook_changed');
|
|
1433
|
+
}
|
|
1434
|
+
const stable = planned ?? validateStableRegistration(entry, { home: options.home });
|
|
1435
|
+
const next = statisticsHooks(root, client, policyPath, stable);
|
|
1436
|
+
for (const [event, definition] of Object.entries(owner.hooks)) {
|
|
1437
|
+
const list = statisticEntries(hooksObject, event);
|
|
1438
|
+
list.splice(list.findIndex(v => isDeepStrictEqual(v, definition)), 1);
|
|
1439
|
+
}
|
|
1440
|
+
for (const [event, definition] of Object.entries(next))
|
|
1441
|
+
statisticEntries(hooksObject, event, true).push(definition);
|
|
1442
|
+
receipt.after = stringify({ ...owner, hooks: next, hooks_fingerprint: createHash('sha256').update(JSON.stringify(next)).digest('hex') });
|
|
1443
|
+
hooks.after = stringify(hooksObject);
|
|
1444
|
+
if (receipt.after !== receipt.before)
|
|
1445
|
+
changes.push(receipt);
|
|
1446
|
+
}
|
|
1294
1447
|
function statisticsSnapshot(path) { const value = read(path); if (value.text !== null) {
|
|
1295
1448
|
privatePermissions(path, 'private_file_permissions');
|
|
1296
1449
|
if (lstatSync(path).nlink !== 1)
|
|
@@ -1305,7 +1458,7 @@ function statisticsConfig(snapshot) {
|
|
|
1305
1458
|
return value;
|
|
1306
1459
|
}
|
|
1307
1460
|
function possibleStatisticsObserver(entry) {
|
|
1308
|
-
return object(entry) && Array.isArray(entry.hooks) && entry.hooks.some((h) => object(h) && h.type === 'command' && (h.statusMessage === 'Aptly local execution statistics' || (typeof h.command === 'string' && h.command.includes('aptly-observe.js'))));
|
|
1461
|
+
return object(entry) && Array.isArray(entry.hooks) && entry.hooks.some((h) => object(h) && h.type === 'command' && (h.statusMessage === 'Aptly local execution statistics' || (typeof h.command === 'string' && (h.command.includes('aptly-observe.js') || /[\/]aptly[\/]runtimes[\/][a-f0-9]{64}[\/]launch['"]?\s+['"]?observe\b/.test(h.command)))));
|
|
1309
1462
|
}
|
|
1310
1463
|
function clearCodexMetadata(state, client) { if (client === 'codex') {
|
|
1311
1464
|
delete state.codex_native_metadata;
|
|
@@ -1349,7 +1502,7 @@ export function setStatisticsCollection(enabled, options = {}) {
|
|
|
1349
1502
|
return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_invalid_options'] })) };
|
|
1350
1503
|
if (process.platform === 'win32')
|
|
1351
1504
|
return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_platform_unsupported'] })) };
|
|
1352
|
-
const states = new Set();
|
|
1505
|
+
const states = new Set(), initializationPaths = new Map();
|
|
1353
1506
|
const plans = clients.map(client => {
|
|
1354
1507
|
try {
|
|
1355
1508
|
if (!enabled) {
|
|
@@ -1370,6 +1523,7 @@ export function setStatisticsCollection(enabled, options = {}) {
|
|
|
1370
1523
|
if (states.has(paths.stateDirectory))
|
|
1371
1524
|
fail('statistics_shared_state');
|
|
1372
1525
|
states.add(paths.stateDirectory);
|
|
1526
|
+
initializationPaths.set(client, paths.stateDirectory);
|
|
1373
1527
|
const observations = [], changes = [];
|
|
1374
1528
|
const snap = (path, privateFile = true) => { const result = privateFile ? statisticsSnapshot(path) : (() => { const v = read(path); return { path, before: v.text, after: v.text, mode: v.mode }; })(); observations.push(result); return result; };
|
|
1375
1529
|
const policy = snap(paths.policyPath);
|
|
@@ -1455,7 +1609,7 @@ export function setStatisticsCollection(enabled, options = {}) {
|
|
|
1455
1609
|
state.codex_home = paths.dir;
|
|
1456
1610
|
}
|
|
1457
1611
|
const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
|
|
1458
|
-
const entries = statisticsHooks(root, client, paths.policyPath);
|
|
1612
|
+
const entries = statisticsHooks(root, client, paths.policyPath, paths.stable);
|
|
1459
1613
|
for (const [event, entry] of Object.entries(entries)) {
|
|
1460
1614
|
const list = statisticEntries(value, event, true);
|
|
1461
1615
|
if (list.some(possibleStatisticsObserver))
|
|
@@ -1485,18 +1639,52 @@ export function setStatisticsCollection(enabled, options = {}) {
|
|
|
1485
1639
|
});
|
|
1486
1640
|
if (enabled && plans.some(p => p.result.status === 'error'))
|
|
1487
1641
|
return { status: 'partial', clients: plans.map(p => p.result.status === 'error' ? p.result : { ...p.result, status: 'skipped', codes: ['other_host_validation_failed'] }) };
|
|
1488
|
-
|
|
1642
|
+
const applied = execute(options, false, undefined, plans);
|
|
1643
|
+
if (!enabled || applied.status !== 'complete')
|
|
1644
|
+
return applied;
|
|
1645
|
+
// Configuration was applied successfully; initialization failures are reported
|
|
1646
|
+
// as partial setup, never rolled back or hidden as a complete activation.
|
|
1647
|
+
const initialized = applied.clients.map(result => {
|
|
1648
|
+
try {
|
|
1649
|
+
initializeStatisticsStore({ stateDirectory: initializationPaths.get(result.client) });
|
|
1650
|
+
return result;
|
|
1651
|
+
}
|
|
1652
|
+
catch {
|
|
1653
|
+
return { ...result, status: 'error', codes: [...result.codes, 'statistics_store_initialization_failed'] };
|
|
1654
|
+
}
|
|
1655
|
+
});
|
|
1656
|
+
return { status: initialized.some(result => result.status === 'error') ? 'partial' : 'complete', clients: initialized };
|
|
1489
1657
|
}
|
|
1490
1658
|
/** Snapshot view; no runtime, credentials, provider, budget gate or state creation. */
|
|
1491
1659
|
export function showStatistics(options = {}, today = false) {
|
|
1492
1660
|
const clients = options.clients ?? ['codex', 'claude'];
|
|
1493
1661
|
if (process.platform === 'win32')
|
|
1494
|
-
return { clients: clients.map(client => ({ client, status: 'statistics_platform_unsupported', collection: 'disabled' })) };
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1662
|
+
return { status: 'partial', clients: clients.map(client => ({ client, status: 'statistics_platform_unsupported', collection: 'disabled' })) };
|
|
1663
|
+
const outcomes = clients.map(client => {
|
|
1664
|
+
const snapshot = new QuerySnapshot();
|
|
1665
|
+
try {
|
|
1666
|
+
const paths = resolved(options, client), policyPath = join(paths.privateDir, 'auto-policy.json');
|
|
1667
|
+
const loaded = queryAutomaticHookPolicy(policyPath, snapshot);
|
|
1668
|
+
const context = queryContext(options, client, snapshot, true, !loaded.policy);
|
|
1669
|
+
if (!object(context.entry)) {
|
|
1670
|
+
snapshot.verify();
|
|
1671
|
+
return { result: { client, status: 'statistics_requires_setup', collection: 'disabled' }, failed: context.failed || !!loaded.policy || loaded.availability === 'error' || context.expected };
|
|
1672
|
+
}
|
|
1673
|
+
if (!policyReferenceMatches(context.entry, client, policyPath, options)) {
|
|
1674
|
+
snapshot.verify();
|
|
1675
|
+
return { result: { client, status: 'statistics_policy_conflict', collection: 'disabled' }, failed: context.failed || loaded.availability !== 'absent' || context.expected };
|
|
1676
|
+
}
|
|
1677
|
+
if (!loaded.policy) {
|
|
1678
|
+
snapshot.verify();
|
|
1679
|
+
return { result: { client, status: 'statistics_requires_setup', collection: 'disabled' }, failed: context.failed || loaded.availability === 'error' || context.expected };
|
|
1680
|
+
}
|
|
1681
|
+
const outcome = readStatisticsQuery({ stateDirectory: loaded.policy.state_directory }, { client, today }, snapshot, context.statisticsExpected);
|
|
1682
|
+
snapshot.verify();
|
|
1683
|
+
return { result: { client, ...outcome.result }, failed: outcome.failed || context.failed };
|
|
1498
1684
|
}
|
|
1499
1685
|
catch (error) {
|
|
1500
|
-
return { client, status: safeCode(error), collection: 'disabled' };
|
|
1501
|
-
}
|
|
1686
|
+
return { result: { client, status: safeCode(error), collection: 'disabled' }, failed: true };
|
|
1687
|
+
}
|
|
1688
|
+
});
|
|
1689
|
+
return { status: outcomes.some(o => o.failed) ? 'partial' : 'complete', clients: outcomes.map(o => o.result) };
|
|
1502
1690
|
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export declare const stableRuntimeLimits: Readonly<{
|
|
2
|
+
files: 12000;
|
|
3
|
+
totalBytes: number;
|
|
4
|
+
fileBytes: number;
|
|
5
|
+
manifestBytes: number;
|
|
6
|
+
}>;
|
|
7
|
+
export interface StableFile {
|
|
8
|
+
readonly path: string;
|
|
9
|
+
readonly size: number;
|
|
10
|
+
readonly sha256: string;
|
|
11
|
+
}
|
|
12
|
+
export interface StableManifest {
|
|
13
|
+
readonly schema_version: 1;
|
|
14
|
+
readonly kind: 'aptly-stable-runtime';
|
|
15
|
+
readonly version: string;
|
|
16
|
+
readonly home: string;
|
|
17
|
+
readonly node_path: string;
|
|
18
|
+
readonly launcher_revision: 1;
|
|
19
|
+
readonly bootstrap_sha256: string;
|
|
20
|
+
readonly launcher_sha256: string;
|
|
21
|
+
readonly files: readonly StableFile[];
|
|
22
|
+
readonly generation: string;
|
|
23
|
+
}
|
|
24
|
+
export interface StableRegistration {
|
|
25
|
+
readonly command: string;
|
|
26
|
+
readonly args: readonly ['serve'];
|
|
27
|
+
readonly packageRoot: string;
|
|
28
|
+
readonly runtimeRoot: string;
|
|
29
|
+
readonly version: string;
|
|
30
|
+
readonly generation: string;
|
|
31
|
+
readonly manifest: StableManifest;
|
|
32
|
+
readonly integrity: 'full' | 'metadata';
|
|
33
|
+
}
|
|
34
|
+
export interface StableRuntimePlan extends StableRegistration {
|
|
35
|
+
readonly descriptor: {
|
|
36
|
+
readonly command: string;
|
|
37
|
+
readonly args: readonly ['serve'];
|
|
38
|
+
};
|
|
39
|
+
readonly payloadRoot: string;
|
|
40
|
+
}
|
|
41
|
+
export interface StableReference {
|
|
42
|
+
readonly command: string;
|
|
43
|
+
readonly args: readonly ['serve'];
|
|
44
|
+
readonly generation: string;
|
|
45
|
+
readonly runtimeRoot: string;
|
|
46
|
+
}
|
|
47
|
+
/** Shape only. Reads OS alias metadata, never runtime bytes or credentials. */
|
|
48
|
+
export declare function stableReference(entry: unknown, { home }?: {
|
|
49
|
+
home?: string;
|
|
50
|
+
}): StableReference | null;
|
|
51
|
+
export declare function planStableRuntime(options: {
|
|
52
|
+
packageRoot: string;
|
|
53
|
+
home?: string;
|
|
54
|
+
nodePath?: string;
|
|
55
|
+
}): StableRuntimePlan;
|
|
56
|
+
export declare function materializeStableRuntime(plan: StableRuntimePlan): void;
|
|
57
|
+
export declare function validateStableRegistration(entry: unknown, { home, metadataOnly }?: {
|
|
58
|
+
home?: string;
|
|
59
|
+
metadataOnly?: boolean;
|
|
60
|
+
}): StableRegistration | null;
|
|
61
|
+
export declare function stableObserverCommand(registration: StableRegistration, client: 'codex' | 'claude', policyPath: string): string;
|