aptly 0.1.9 → 0.1.11
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/README.en.md +10 -10
- package/README.ja.md +10 -10
- package/README.md +10 -10
- package/README.zh-CN.md +10 -10
- package/dist/bin/aptly-observe.d.ts +2 -0
- package/dist/bin/aptly-observe.js +66 -0
- package/dist/bin/aptly.js +59 -17
- package/dist/src/cli-help.js +18 -11
- package/dist/src/cli-input.d.ts +19 -1
- package/dist/src/cli-input.js +23 -11
- package/dist/src/policy-source.d.ts +3 -0
- package/dist/src/policy-source.js +11 -0
- package/dist/src/server.d.ts +1 -1
- package/dist/src/server.js +44 -2
- package/dist/src/setup.d.ts +69 -0
- package/dist/src/setup.js +605 -6
- package/dist/src/statistics-codex.d.ts +23 -0
- package/dist/src/statistics-codex.js +121 -0
- package/dist/src/statistics-policy.d.ts +2 -0
- package/dist/src/statistics-policy.js +20 -0
- package/dist/src/statistics.d.ts +90 -0
- package/dist/src/statistics.js +472 -0
- package/dist/src/transmission-review-cli.d.ts +11 -0
- package/dist/src/transmission-review-cli.js +35 -0
- package/dist/src/update-notifier.js +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/docs/ADVISORY_USAGE.md +1 -1
- package/docs/DRAFT_0_1_0.md +1 -1
- package/docs/guide/en/advanced.md +217 -0
- package/docs/guide/en/benchmarks.md +32 -0
- package/docs/guide/en/budget.md +45 -0
- package/docs/guide/en/configuration.md +104 -0
- package/docs/guide/en/installation.md +114 -0
- package/docs/guide/en/routing.md +61 -0
- package/docs/guide/en/statistics.md +43 -0
- package/docs/guide/en/transmission.md +71 -0
- package/docs/guide/en/troubleshooting.md +99 -0
- package/docs/guide/en.md +80 -477
- package/docs/guide/ja/advanced.md +217 -0
- package/docs/guide/ja/benchmarks.md +32 -0
- package/docs/guide/ja/budget.md +45 -0
- package/docs/guide/ja/configuration.md +104 -0
- package/docs/guide/ja/installation.md +114 -0
- package/docs/guide/ja/routing.md +61 -0
- package/docs/guide/ja/statistics.md +43 -0
- package/docs/guide/ja/transmission.md +71 -0
- package/docs/guide/ja/troubleshooting.md +99 -0
- package/docs/guide/ja.md +80 -477
- package/docs/guide/ko/advanced.md +217 -0
- package/docs/guide/ko/benchmarks.md +32 -0
- package/docs/guide/ko/budget.md +45 -0
- package/docs/guide/ko/configuration.md +104 -0
- package/docs/guide/ko/installation.md +114 -0
- package/docs/guide/ko/routing.md +61 -0
- package/docs/guide/ko/statistics.md +43 -0
- package/docs/guide/ko/transmission.md +71 -0
- package/docs/guide/ko/troubleshooting.md +99 -0
- package/docs/guide/ko.md +80 -477
- package/docs/guide/zh-CN/advanced.md +217 -0
- package/docs/guide/zh-CN/benchmarks.md +32 -0
- package/docs/guide/zh-CN/budget.md +45 -0
- package/docs/guide/zh-CN/configuration.md +104 -0
- package/docs/guide/zh-CN/installation.md +114 -0
- package/docs/guide/zh-CN/routing.md +61 -0
- package/docs/guide/zh-CN/statistics.md +43 -0
- package/docs/guide/zh-CN/transmission.md +71 -0
- package/docs/guide/zh-CN/troubleshooting.md +99 -0
- package/docs/guide/zh-CN.md +80 -477
- package/package.json +3 -2
package/dist/src/setup.js
CHANGED
|
@@ -2,7 +2,7 @@ import { lstatSync, readFileSync, mkdirSync, chmodSync, openSync, writeFileSync,
|
|
|
2
2
|
import { homedir } from 'node:os';
|
|
3
3
|
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
|
-
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
|
6
6
|
import { isDeepStrictEqual } from 'node:util';
|
|
7
7
|
import { parse } from 'smol-toml';
|
|
8
8
|
import { resolveCatalog } from './catalog.js';
|
|
@@ -10,7 +10,9 @@ import { budgetEnvironmentDefaults, budgetEnvironmentKeys, parseBudgetValue, res
|
|
|
10
10
|
import { Router, defaultPolicy } from './core.js';
|
|
11
11
|
import { loadAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
|
|
12
12
|
import { assertPrivateStatePath } from './files.js';
|
|
13
|
+
import { CODEX_HOME_POLICY_SOURCE, resolvePolicySource } from './policy-source.js';
|
|
13
14
|
import { assertWindowsPrivatePath, protectNewWindowsPrivateDirectory, copyWindowsFilePermissions } from './windows-private.js';
|
|
15
|
+
import { STATISTICS_CONFIG_FILE, STATISTICS_KEY_FILE, STATISTICS_DB_FILE, parseStatisticsConfig, serializeStatisticsConfig, readStatistics } from './statistics.js';
|
|
14
16
|
const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
15
17
|
const stringify = (value) => JSON.stringify(value, null, 2) + '\n';
|
|
16
18
|
const fail = (code) => { throw new Error(code); };
|
|
@@ -102,7 +104,7 @@ const q = (value) => JSON.stringify(value);
|
|
|
102
104
|
const blockStart = '# aptly managed MCP start v1';
|
|
103
105
|
const blockEnd = '# aptly managed MCP end v1';
|
|
104
106
|
function newTomlBlock(entry) {
|
|
105
|
-
const lines = [blockStart, '[mcp_servers.aptly]', `command = ${q(entry.command)}`, `args = ${JSON.stringify(entry.args)}`,
|
|
107
|
+
const lines = [blockStart, '[mcp_servers.aptly]', `command = ${q(entry.command)}`, `args = ${JSON.stringify(entry.args)}`, `env_vars = ${JSON.stringify(entry.env_vars ?? [])}`, '[mcp_servers.aptly.env]'];
|
|
106
108
|
for (const [key, value] of Object.entries(entry.env))
|
|
107
109
|
lines.push(`${key} = ${q(value)}`);
|
|
108
110
|
return lines.concat(blockEnd, '').join('\n');
|
|
@@ -290,6 +292,42 @@ function updateTomlLauncher(text, entry) {
|
|
|
290
292
|
fail('unsupported_toml_layout');
|
|
291
293
|
return rendered;
|
|
292
294
|
}
|
|
295
|
+
/** Replace an unambiguous env_vars assignment, preserving every existing forwarded name. */
|
|
296
|
+
function updateTomlForwarding(text, names) {
|
|
297
|
+
const original = toml(text), expected = structuredClone(original);
|
|
298
|
+
if (names === undefined)
|
|
299
|
+
delete expected.mcp_servers.aptly.env_vars;
|
|
300
|
+
else
|
|
301
|
+
expected.mcp_servers.aptly.env_vars = names;
|
|
302
|
+
const headers = [...text.matchAll(/^\s*\[([^\n]+)\][ \t]*(?:#[^\n]*)?\r?$/gm)];
|
|
303
|
+
const header = headers.find(h => { try {
|
|
304
|
+
return toml(h[0] + '\naptly_probe = true\n').mcp_servers?.aptly?.aptly_probe === true;
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
return false;
|
|
308
|
+
} });
|
|
309
|
+
if (!header)
|
|
310
|
+
fail('unsupported_toml_layout');
|
|
311
|
+
const start = header.index + header[0].length, end = headers.find(h => h.index > header.index)?.index ?? text.length;
|
|
312
|
+
let body = text.slice(start, end);
|
|
313
|
+
const line = /^[ \t]*env_vars[ \t]*=[^\n]*(?:\n|$)/gm, matches = [...body.matchAll(line)];
|
|
314
|
+
if (matches.length > 1 || (original.mcp_servers.aptly.env_vars !== undefined && matches.length !== 1))
|
|
315
|
+
fail('unsupported_toml_layout');
|
|
316
|
+
if (matches.length)
|
|
317
|
+
body = body.replace(line, () => names === undefined ? '' : `env_vars = ${JSON.stringify(names)}\n`);
|
|
318
|
+
else if (names !== undefined)
|
|
319
|
+
body = '\n' + `env_vars = ${JSON.stringify(names)}\n` + body.replace(/^\r?\n/, '');
|
|
320
|
+
const rendered = text.slice(0, start) + body + text.slice(end);
|
|
321
|
+
if (!isDeepStrictEqual(toml(rendered), expected))
|
|
322
|
+
fail('unsupported_toml_layout');
|
|
323
|
+
return rendered;
|
|
324
|
+
}
|
|
325
|
+
function policyReferenceMatches(entry, client, policyPath, options) {
|
|
326
|
+
const source = entry.env?.APTLY_HOOK_POLICY_PATH;
|
|
327
|
+
if (source !== CODEX_HOME_POLICY_SOURCE)
|
|
328
|
+
return source === policyPath;
|
|
329
|
+
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') && resolvePolicySource(source, options.env ?? process.env, options.home) === policyPath;
|
|
330
|
+
}
|
|
293
331
|
function resolved(options, client) {
|
|
294
332
|
const home = resolve(options.home ?? homedir()), env = options.env ?? process.env;
|
|
295
333
|
const override = client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR;
|
|
@@ -302,6 +340,12 @@ function resolved(options, client) {
|
|
|
302
340
|
function ownership(value, client) {
|
|
303
341
|
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')
|
|
304
342
|
fail('invalid_ownership');
|
|
343
|
+
if (value.policy_source_previous !== undefined && (client !== 'codex' || value.mcp_created || typeof value.policy_source_previous !== 'string' || !isAbsolute(value.policy_source_previous) || Object.hasOwn(value.env_added, 'APTLY_HOOK_POLICY_PATH')))
|
|
344
|
+
fail('invalid_ownership');
|
|
345
|
+
if (value.env_vars_added !== undefined && (client !== 'codex' || value.mcp_created || !Array.isArray(value.env_vars_added) || value.env_vars_added.length !== 1 || value.env_vars_added[0] !== 'CODEX_HOME'))
|
|
346
|
+
fail('invalid_ownership');
|
|
347
|
+
if (value.env_vars_was_absent !== undefined && (client !== 'codex' || value.mcp_created || typeof value.env_vars_was_absent !== 'boolean' || !value.env_vars_added))
|
|
348
|
+
fail('invalid_ownership');
|
|
305
349
|
return value;
|
|
306
350
|
}
|
|
307
351
|
/** Compatibility restriction only: this does not authenticate arbitrary launcher code. */
|
|
@@ -358,8 +402,11 @@ function prepare(options, client, removing, edit) {
|
|
|
358
402
|
privatePermissions(privateFile.path, 'private_file_permissions');
|
|
359
403
|
observations.push(mcp, hooks, policy, manifest);
|
|
360
404
|
const oldOwner = manifest.before === null ? undefined : ownership(json(manifest.before), client);
|
|
361
|
-
if (removing && !oldOwner)
|
|
405
|
+
if (removing && !oldOwner) {
|
|
406
|
+
if (read(join(privateDir, STATISTICS_OWNERSHIP_FILE)).text !== null)
|
|
407
|
+
fail('statistics_observers_present');
|
|
362
408
|
return { changes, observations, dirs, result: { client, status: 'skipped', codes: ['no_owned_setup'] } };
|
|
409
|
+
}
|
|
363
410
|
const hookValue = hook(client), hooksObject = json(hooks.before), entries = hooksArray(hooksObject);
|
|
364
411
|
const config = client === 'codex' ? toml(mcp.before ?? '') : json(mcp.before), servers = map(config, client === 'codex' ? 'mcp_servers' : 'mcpServers');
|
|
365
412
|
if (removing) {
|
|
@@ -401,6 +448,18 @@ function prepare(options, client, removing, edit) {
|
|
|
401
448
|
delete servers.aptly.env[key];
|
|
402
449
|
}
|
|
403
450
|
mcp.after = client === 'codex' ? removeTomlEnv(mcp.before ?? '', owned.env_added) : stringify(config);
|
|
451
|
+
if (owned.policy_source_previous !== undefined) {
|
|
452
|
+
if (servers.aptly.env?.APTLY_HOOK_POLICY_PATH !== CODEX_HOME_POLICY_SOURCE)
|
|
453
|
+
fail('managed_entry_changed');
|
|
454
|
+
mcp.after = updateTomlEnv(mcp.after, { APTLY_HOOK_POLICY_PATH: owned.policy_source_previous });
|
|
455
|
+
}
|
|
456
|
+
if (client === 'codex' && owned.env_vars_added?.length) {
|
|
457
|
+
const names = toml(mcp.after).mcp_servers?.aptly?.env_vars;
|
|
458
|
+
if (!Array.isArray(names) || owned.env_vars_added.some(name => names.filter((x) => x === name).length !== 1))
|
|
459
|
+
fail('managed_entry_changed');
|
|
460
|
+
const remaining = names.filter((name) => !owned.env_vars_added.includes(name));
|
|
461
|
+
mcp.after = updateTomlForwarding(mcp.after, owned.env_vars_was_absent && remaining.length === 0 ? undefined : remaining);
|
|
462
|
+
}
|
|
404
463
|
}
|
|
405
464
|
const p = json(policy.before);
|
|
406
465
|
if (!isDeepStrictEqual(p, owned.policy))
|
|
@@ -409,6 +468,7 @@ function prepare(options, client, removing, edit) {
|
|
|
409
468
|
policy.after = null;
|
|
410
469
|
manifest.after = null;
|
|
411
470
|
result.status = 'removed';
|
|
471
|
+
appendStatisticsRemoval(options, client, hooksObject, hooks, changes, observations);
|
|
412
472
|
}
|
|
413
473
|
else {
|
|
414
474
|
const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
|
|
@@ -434,7 +494,9 @@ function prepare(options, client, removing, edit) {
|
|
|
434
494
|
if (!object(servers.aptly))
|
|
435
495
|
fail('mcp_entry_conflict');
|
|
436
496
|
const configuredPolicy = object(servers.aptly.env) ? servers.aptly.env.APTLY_HOOK_POLICY_PATH : undefined;
|
|
437
|
-
|
|
497
|
+
if (oldOwner?.policy_source_previous !== undefined && configuredPolicy !== CODEX_HOME_POLICY_SOURCE)
|
|
498
|
+
fail('managed_entry_changed');
|
|
499
|
+
const mismatch = configuredPolicy !== undefined && !policyReferenceMatches(servers.aptly, client, policyPath, options);
|
|
438
500
|
const detail = mismatch && typeof configuredPolicy === 'string' && configuredPolicy.length > 0 ? {
|
|
439
501
|
policy_location: configuredPolicy === join(resolve(options.home ?? homedir()), client === 'codex' ? '.codex' : '.claude', 'aptly', 'auto-policy.json') ? 'default_home' : 'elsewhere',
|
|
440
502
|
selected_home_source: (client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR) ? 'override' : 'default',
|
|
@@ -452,7 +514,7 @@ function prepare(options, client, removing, edit) {
|
|
|
452
514
|
servers.aptly.command = process.execPath;
|
|
453
515
|
servers.aptly.args = [join(root, 'dist', 'src', 'server.js')];
|
|
454
516
|
}
|
|
455
|
-
if (edit && ('credential' in edit || 'migrate' in edit))
|
|
517
|
+
if ((edit && ('credential' in edit || 'migrate' in edit)) || servers.aptly.env?.APTLY_HOOK_POLICY_PATH === CODEX_HOME_POLICY_SOURCE)
|
|
456
518
|
requireCredentialRuntime(servers.aptly, root);
|
|
457
519
|
const currentEnv = map(servers.aptly, 'env');
|
|
458
520
|
const originalEnvKeys = new Set(Object.keys(currentEnv)), inheritedBudget = budgetInheritance(servers.aptly, env, client);
|
|
@@ -558,6 +620,14 @@ function prepare(options, client, removing, edit) {
|
|
|
558
620
|
result.transmission = effectiveTransmission(policyValue);
|
|
559
621
|
result.transmission_source = policyValue.schema_version === 1 ? 'legacy' : policyValue.transmission === 'unselected' ? 'unselected' : 'explicit';
|
|
560
622
|
manifest.after = stringify(owner);
|
|
623
|
+
const review = transmissionReviewSnapshot(options, client);
|
|
624
|
+
observations.push(review);
|
|
625
|
+
if (requestedScope !== undefined) {
|
|
626
|
+
review.after = transmissionReviewMarker(options, client, policyValue);
|
|
627
|
+
if (review.after !== review.before)
|
|
628
|
+
changes.push(review);
|
|
629
|
+
}
|
|
630
|
+
result.transmission_review = reviewMatches(review.after, options, client, policyValue) ? 'complete' : 'required';
|
|
561
631
|
if (client === 'codex')
|
|
562
632
|
result.requires_hook_review = true;
|
|
563
633
|
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'] : [])];
|
|
@@ -571,12 +641,17 @@ function prepare(options, client, removing, edit) {
|
|
|
571
641
|
changes.push(snapshot);
|
|
572
642
|
if (!removing && changes.length)
|
|
573
643
|
result.status = 'configured';
|
|
644
|
+
const markerIndex = changes.findIndex(item => item.reviewPrivate);
|
|
645
|
+
if (markerIndex >= 0)
|
|
646
|
+
changes.push(...changes.splice(markerIndex, 1));
|
|
574
647
|
return { changes, observations, dirs, result };
|
|
575
648
|
}
|
|
576
649
|
/** Secure sibling staging is short-lived and never a backup; original settings stay in memory. */
|
|
577
650
|
function replace(snapshot, forward) {
|
|
578
651
|
const expected = forward ? snapshot.before : snapshot.after, next = forward ? snapshot.after : snapshot.before;
|
|
579
652
|
const check = () => {
|
|
653
|
+
if (snapshot.reviewPrivate)
|
|
654
|
+
validateReviewPrivate(snapshot.path);
|
|
580
655
|
const current = read(snapshot.path);
|
|
581
656
|
if (current.text !== expected || (process.platform !== 'win32' && expected !== null && current.mode !== snapshot.mode))
|
|
582
657
|
fail('concurrent_configuration_change');
|
|
@@ -710,7 +785,7 @@ function execute(options, removing, edit, captured) {
|
|
|
710
785
|
}
|
|
711
786
|
return { status: results.some(result => result.status === 'error') ? 'partial' : results.every(result => result.status === 'skipped') ? 'skipped' : 'complete', clients: results };
|
|
712
787
|
}
|
|
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']);
|
|
788
|
+
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']);
|
|
714
789
|
function safeCode(error) { return error instanceof Error && codes.has(error.message) ? error.message : 'configuration_io_error'; }
|
|
715
790
|
export function setupHosts(options = {}) { return execute(options, false); }
|
|
716
791
|
/** Snapshot the normal setup plan without applying it; it does not verify a running host. */
|
|
@@ -745,8 +820,12 @@ export function setCredentialReference(options = {}) { return execute(options, f
|
|
|
745
820
|
/** Include unchanged files: a no-op reference update must still detect prompt-time edits. */
|
|
746
821
|
function validateObservations(plan, written = []) {
|
|
747
822
|
for (const snapshot of plan.observations) {
|
|
823
|
+
if (snapshot.reviewPrivate)
|
|
824
|
+
validateReviewPrivate(snapshot.path);
|
|
748
825
|
const current = read(snapshot.path);
|
|
749
826
|
const expected = written.includes(snapshot) ? snapshot.after : snapshot.before;
|
|
827
|
+
if (!written.includes(snapshot) && snapshot.identity && reviewIdentity(snapshot.path) !== snapshot.identity)
|
|
828
|
+
fail('concurrent_configuration_change');
|
|
750
829
|
if (current.text !== expected || (process.platform !== 'win32' && expected !== null && current.mode !== snapshot.mode))
|
|
751
830
|
fail('concurrent_configuration_change');
|
|
752
831
|
}
|
|
@@ -828,12 +907,274 @@ export function migrateLauncher(options, dryRun = false, includeExisting = false
|
|
|
828
907
|
return { status: 'partial', clients: [errorResult(client, error)] };
|
|
829
908
|
}
|
|
830
909
|
}
|
|
910
|
+
/** Explicitly select a per-Codex-home policy without moving any state. */
|
|
911
|
+
export function setPolicySource(options, dryRun = false) {
|
|
912
|
+
if (options.clients?.length !== 1 || options.clients[0] !== 'codex' || options.automatic !== undefined || options.mode !== undefined || options.transmission !== undefined || options.selectUnselectedOnly !== undefined)
|
|
913
|
+
return { status: 'partial', clients: [{ client: 'codex', status: 'error', codes: ['policy_source_invalid_options'] }] };
|
|
914
|
+
const client = 'codex';
|
|
915
|
+
try {
|
|
916
|
+
const paths = resolved(options, client), policyPath = join(paths.privateDir, 'auto-policy.json');
|
|
917
|
+
// Validate the selector even when CODEX_HOME is present but empty.
|
|
918
|
+
if (resolvePolicySource(CODEX_HOME_POLICY_SOURCE, options.env ?? process.env, options.home) !== policyPath)
|
|
919
|
+
fail('policy_source_home_invalid');
|
|
920
|
+
const snap = (path) => { const file = read(path); return { path, before: file.text, after: file.text, mode: file.mode }; };
|
|
921
|
+
const mcp = snap(paths.mcpPath), hooks = snap(paths.hooksPath), policy = snap(policyPath), manifest = snap(join(paths.privateDir, 'setup-ownership.json'));
|
|
922
|
+
for (const dir of [paths.privateDir, join(paths.privateDir, 'state')]) {
|
|
923
|
+
try {
|
|
924
|
+
checkedDirectory(dir);
|
|
925
|
+
privatePermissions(dir, 'private_directory_permissions');
|
|
926
|
+
}
|
|
927
|
+
catch (e) {
|
|
928
|
+
if (e.code !== 'ENOENT')
|
|
929
|
+
throw e;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
if (policy.before === null || manifest.before === null || mcp.before === null || hooks.before === null)
|
|
933
|
+
fail('policy_source_requires_setup');
|
|
934
|
+
privatePermissions(policy.path, 'private_file_permissions');
|
|
935
|
+
privatePermissions(manifest.path, 'private_file_permissions');
|
|
936
|
+
const owner = ownership(json(manifest.before), client), config = toml(mcp.before), entry = config.mcp_servers?.aptly;
|
|
937
|
+
if (!object(entry) || !object(entry.env))
|
|
938
|
+
fail('mcp_entry_conflict');
|
|
939
|
+
if (!hooksArray(json(hooks.before)).some(item => isDeepStrictEqual(item, owner.hook)))
|
|
940
|
+
fail('managed_hook_changed');
|
|
941
|
+
if (!loadAutomaticHookPolicy(policyPath).policy || !isDeepStrictEqual(json(policy.before), owner.policy))
|
|
942
|
+
fail('managed_policy_changed');
|
|
943
|
+
const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
|
|
944
|
+
requireCredentialRuntime(entry, root);
|
|
945
|
+
if (entry.env.CODEX_HOME !== undefined)
|
|
946
|
+
fail('mcp_environment_conflict');
|
|
947
|
+
if (entry.env_vars !== undefined && (!Array.isArray(entry.env_vars) || entry.env_vars.some((v) => typeof v !== 'string')))
|
|
948
|
+
fail('configuration_shape_conflict');
|
|
949
|
+
const source = entry.env.APTLY_HOOK_POLICY_PATH, ownedSource = owner.mcp_created ? owner.mcp?.env?.APTLY_HOOK_POLICY_PATH : owner.env_added.APTLY_HOOK_POLICY_PATH;
|
|
950
|
+
const defaultPath = join(resolve(options.home ?? homedir()), '.codex', 'aptly', 'auto-policy.json');
|
|
951
|
+
if (![policyPath, defaultPath, CODEX_HOME_POLICY_SOURCE].includes(source) || (ownedSource !== undefined && ![policyPath, defaultPath, CODEX_HOME_POLICY_SOURCE].includes(ownedSource)) || (owner.mcp_created && ownedSource === undefined))
|
|
952
|
+
fail('managed_entry_changed');
|
|
953
|
+
const vars = entry.env_vars ?? [];
|
|
954
|
+
if (owner.mcp_created) {
|
|
955
|
+
if (!object(owner.mcp) || !owner.toml_block)
|
|
956
|
+
fail('invalid_ownership');
|
|
957
|
+
const expected = structuredClone(owner.mcp);
|
|
958
|
+
expected.env.APTLY_HOOK_POLICY_PATH = source;
|
|
959
|
+
expected.env_vars = vars;
|
|
960
|
+
const priorVars = owner.mcp.env_vars ?? [];
|
|
961
|
+
if (!isDeepStrictEqual(vars, priorVars) && !isDeepStrictEqual(vars, [...priorVars, 'CODEX_HOME']))
|
|
962
|
+
fail('managed_mcp_changed');
|
|
963
|
+
if (!isDeepStrictEqual(expected, entry))
|
|
964
|
+
fail('managed_mcp_changed');
|
|
965
|
+
const previousBlock = newTomlBlock(entry);
|
|
966
|
+
if (!mcp.before.includes(owner.toml_block) && !mcp.before.includes(previousBlock))
|
|
967
|
+
fail('managed_mcp_changed');
|
|
968
|
+
entry.env.APTLY_HOOK_POLICY_PATH = CODEX_HOME_POLICY_SOURCE;
|
|
969
|
+
if (!vars.includes('CODEX_HOME'))
|
|
970
|
+
entry.env_vars = [...vars, 'CODEX_HOME'];
|
|
971
|
+
const nextBlock = newTomlBlock(entry), oldBlock = mcp.before.includes(owner.toml_block) ? owner.toml_block : previousBlock;
|
|
972
|
+
mcp.after = mcp.before.replace(oldBlock, nextBlock);
|
|
973
|
+
if (!isDeepStrictEqual(toml(mcp.after), config))
|
|
974
|
+
fail('managed_mcp_changed');
|
|
975
|
+
owner.mcp = structuredClone(entry);
|
|
976
|
+
owner.toml_block = nextBlock;
|
|
977
|
+
}
|
|
978
|
+
else {
|
|
979
|
+
for (const [key, value] of Object.entries(owner.env_added))
|
|
980
|
+
if (key !== 'APTLY_HOOK_POLICY_PATH' && entry.env[key] !== value)
|
|
981
|
+
fail('managed_entry_changed');
|
|
982
|
+
if (owner.policy_source_previous !== undefined && source !== CODEX_HOME_POLICY_SOURCE)
|
|
983
|
+
fail('managed_entry_changed');
|
|
984
|
+
const preexistingSelector = ownedSource === undefined && owner.policy_source_previous === undefined && source === CODEX_HOME_POLICY_SOURCE;
|
|
985
|
+
if (!vars.includes('CODEX_HOME')) {
|
|
986
|
+
if (owner.env_vars_added?.length)
|
|
987
|
+
fail('managed_entry_changed');
|
|
988
|
+
mcp.after = updateTomlForwarding(mcp.after, [...vars, 'CODEX_HOME']);
|
|
989
|
+
owner.env_vars_added = [...(owner.env_vars_added ?? []), 'CODEX_HOME'];
|
|
990
|
+
if (entry.env_vars === undefined)
|
|
991
|
+
owner.env_vars_was_absent = true;
|
|
992
|
+
}
|
|
993
|
+
mcp.after = updateTomlEnv(mcp.after, { APTLY_HOOK_POLICY_PATH: CODEX_HOME_POLICY_SOURCE });
|
|
994
|
+
if (ownedSource !== undefined)
|
|
995
|
+
owner.env_added.APTLY_HOOK_POLICY_PATH = CODEX_HOME_POLICY_SOURCE;
|
|
996
|
+
else if (!preexistingSelector && owner.policy_source_previous === undefined)
|
|
997
|
+
owner.policy_source_previous = source;
|
|
998
|
+
}
|
|
999
|
+
manifest.after = stringify(owner);
|
|
1000
|
+
const changes = [mcp, manifest].filter(item => item.before !== item.after);
|
|
1001
|
+
const plan = { changes, observations: [mcp, hooks, policy, manifest], dirs: [], result: { client, status: changes.length ? 'configured' : 'unchanged', codes: changes.length ? ['policy_source_selected', 'mcp_restart_required'] : ['policy_source_current'] } };
|
|
1002
|
+
if (dryRun)
|
|
1003
|
+
return { status: 'complete', clients: [{ ...plan.result, status: 'unchanged', codes: [changes.length ? 'policy_source_selection_available' : 'policy_source_current'] }] };
|
|
1004
|
+
return execute(options, false, { migrate: true }, [plan]);
|
|
1005
|
+
}
|
|
1006
|
+
catch (error) {
|
|
1007
|
+
return { status: 'partial', clients: [errorResult(client, error)] };
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
831
1010
|
/** Explicit operator change; updates policy and its receipt through normal guarded staging. */
|
|
832
1011
|
export function setTransmission(scope, options = {}) {
|
|
833
1012
|
if (!['none', 'description', 'excerpt'].includes(scope))
|
|
834
1013
|
return { status: 'partial', clients: (options.clients ?? ['codex', 'claude']).map(client => ({ client, status: 'error', codes: ['transmission_invalid_scope'] })) };
|
|
835
1014
|
return execute(options, false, { transmission: scope });
|
|
836
1015
|
}
|
|
1016
|
+
const TRANSMISSION_REVIEW_FILE = 'transmission-review.json';
|
|
1017
|
+
function reviewIdentity(path) {
|
|
1018
|
+
try {
|
|
1019
|
+
const stat = lstatSync(path);
|
|
1020
|
+
return `${stat.dev}:${stat.ino}:${stat.uid}:${stat.nlink}`;
|
|
1021
|
+
}
|
|
1022
|
+
catch (error) {
|
|
1023
|
+
if (error.code === 'ENOENT')
|
|
1024
|
+
return 'missing';
|
|
1025
|
+
throw error;
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
function validateReviewPrivate(path) {
|
|
1029
|
+
noSymlinks(path);
|
|
1030
|
+
for (const [target, directory] of [[dirname(path), true], [path, false]]) {
|
|
1031
|
+
try {
|
|
1032
|
+
const stat = lstatSync(target);
|
|
1033
|
+
if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile() || stat.nlink !== 1))
|
|
1034
|
+
fail('unsafe_configuration_file');
|
|
1035
|
+
if (process.platform !== 'win32' && process.getuid && stat.uid !== process.getuid())
|
|
1036
|
+
fail(directory ? 'private_directory_permissions' : 'private_file_permissions');
|
|
1037
|
+
privatePermissions(target, directory ? 'private_directory_permissions' : 'private_file_permissions');
|
|
1038
|
+
}
|
|
1039
|
+
catch (error) {
|
|
1040
|
+
if (error.code !== 'ENOENT')
|
|
1041
|
+
throw error;
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
function transmissionReviewSnapshot(options, client) {
|
|
1046
|
+
const path = join(resolved(options, client).privateDir, TRANSMISSION_REVIEW_FILE);
|
|
1047
|
+
validateReviewPrivate(path);
|
|
1048
|
+
const source = read(path);
|
|
1049
|
+
return { path, before: source.text, after: source.text, mode: source.mode, reviewPrivate: true, identity: reviewIdentity(path) };
|
|
1050
|
+
}
|
|
1051
|
+
function transmissionReviewMarker(options, client, policy) {
|
|
1052
|
+
const paths = resolved(options, client), scope = effectiveTransmission(policy);
|
|
1053
|
+
// A local UI acknowledgement, not authentication or authorization of host code.
|
|
1054
|
+
const binding = { selected_home: resolve(paths.dir), policyPath: join(paths.privateDir, 'auto-policy.json'),
|
|
1055
|
+
state_directory: resolve(policy.state_directory), schema_version: policy.schema_version, effective_scope: scope,
|
|
1056
|
+
provenance: policy.schema_version === 1 ? 'legacy' : scope === 'unselected' ? 'unselected' : 'explicit' };
|
|
1057
|
+
return stringify({ schema_version: 1, revision: 1, client, binding_sha256: createHash('sha256').update(JSON.stringify(binding)).digest('hex') });
|
|
1058
|
+
}
|
|
1059
|
+
function reviewMatches(text, options, client, policy) {
|
|
1060
|
+
if (text === null || effectiveTransmission(policy) === 'unselected')
|
|
1061
|
+
return false;
|
|
1062
|
+
try {
|
|
1063
|
+
return isDeepStrictEqual(JSON.parse(text), JSON.parse(transmissionReviewMarker(options, client, policy)));
|
|
1064
|
+
}
|
|
1065
|
+
catch {
|
|
1066
|
+
return false;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
/** Read-only, two-phase local acknowledgement. Recheck every captured host before writing. */
|
|
1070
|
+
export function prepareTransmissionReview(options = {}) {
|
|
1071
|
+
options = { ...options, home: resolve(options.home ?? homedir()), env: { ...(options.env ?? process.env) }, ...(options.clients ? { clients: [...options.clients] } : {}) };
|
|
1072
|
+
const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
|
|
1073
|
+
const plans = [], candidates = [];
|
|
1074
|
+
if (!clients.length || clients.some(client => !['codex', 'claude'].includes(client)) || options.automatic !== undefined || options.mode !== undefined || options.transmission !== undefined || options.selectUnselectedOnly !== undefined) {
|
|
1075
|
+
const result = { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['transmission_review_invalid_options'] })) };
|
|
1076
|
+
return { result, candidates: [], apply: () => result };
|
|
1077
|
+
}
|
|
1078
|
+
const results = clients.map(client => {
|
|
1079
|
+
try {
|
|
1080
|
+
const paths = resolved(options, client), policyPath = join(paths.privateDir, 'auto-policy.json');
|
|
1081
|
+
const mcp = read(paths.mcpPath), config = client === 'codex' ? toml(mcp.text ?? '') : json(mcp.text);
|
|
1082
|
+
const entry = config[client === 'codex' ? 'mcp_servers' : 'mcpServers']?.aptly;
|
|
1083
|
+
const policySource = read(policyPath), ownerSource = read(join(paths.privateDir, 'setup-ownership.json'));
|
|
1084
|
+
if (entry === undefined && policySource.text === null && ownerSource.text === null)
|
|
1085
|
+
return { client, status: 'skipped', codes: ['host_not_configured'] };
|
|
1086
|
+
if (!object(entry) || !policyReferenceMatches(entry, client, policyPath, options) || policySource.text === null || ownerSource.text === null)
|
|
1087
|
+
fail('transmission_review_requires_setup');
|
|
1088
|
+
const loaded = loadAutomaticHookPolicy(policyPath);
|
|
1089
|
+
if (!loaded.policy)
|
|
1090
|
+
fail('policy_conflict');
|
|
1091
|
+
const policy = loaded.policy, owner = ownership(json(ownerSource.text), client);
|
|
1092
|
+
if (!isDeepStrictEqual(policy, owner.policy))
|
|
1093
|
+
fail('managed_policy_changed');
|
|
1094
|
+
const hooksSource = read(paths.hooksPath), hookSettings = json(hooksSource.text);
|
|
1095
|
+
if (!Array.isArray(hookSettings.hooks?.PreToolUse) || !hookSettings.hooks.PreToolUse.some((value) => isDeepStrictEqual(value, owner.hook)) || !isDeepStrictEqual(owner.hook, hook(client)))
|
|
1096
|
+
fail('transmission_review_requires_setup');
|
|
1097
|
+
if (!object(entry.env) || entry.env.ROUTER_LEDGER_PATH === undefined)
|
|
1098
|
+
fail('transmission_review_requires_setup');
|
|
1099
|
+
// Use the existing explicit-change validator without executing a setup repair.
|
|
1100
|
+
const plan = prepare(options, client, false, { transmission: effectiveTransmission(policy) === 'unselected' ? 'none' : effectiveTransmission(policy) });
|
|
1101
|
+
for (const [path, source] of [[paths.mcpPath, mcp], [policyPath, policySource], [join(paths.privateDir, 'setup-ownership.json'), ownerSource], [paths.hooksPath, hooksSource]]) {
|
|
1102
|
+
const captured = plan.observations.find(snapshot => snapshot.path === path);
|
|
1103
|
+
if (!captured || captured.before !== source.text || captured.mode !== source.mode)
|
|
1104
|
+
fail('concurrent_configuration_change');
|
|
1105
|
+
}
|
|
1106
|
+
for (const snapshot of plan.observations) {
|
|
1107
|
+
snapshot.identity = reviewIdentity(snapshot.path);
|
|
1108
|
+
if (snapshot.path === policyPath || snapshot.path === join(paths.privateDir, 'setup-ownership.json')) {
|
|
1109
|
+
validateReviewPrivate(snapshot.path);
|
|
1110
|
+
snapshot.reviewPrivate = true;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
const review = plan.observations.find(snapshot => snapshot.path === join(paths.privateDir, TRANSMISSION_REVIEW_FILE));
|
|
1114
|
+
const complete = reviewMatches(review.before, options, client, policy);
|
|
1115
|
+
const state = { client, status: 'unchanged', codes: [complete ? 'transmission_review_complete' : 'transmission_review_required'], transmission_review: complete ? 'complete' : 'required', transmission: effectiveTransmission(policy), transmission_source: policy.schema_version === 1 ? 'legacy' : effectiveTransmission(policy) === 'unselected' ? 'unselected' : 'explicit' };
|
|
1116
|
+
if (!complete || options.forceReview) {
|
|
1117
|
+
plans.push({ ...plan, changes: [], dirs: [], result: state });
|
|
1118
|
+
candidates.push({ client, transmission: effectiveTransmission(policy), transmission_source: state.transmission_source, selected_home_source: (client === 'codex' ? (options.env ?? process.env).CODEX_HOME : (options.env ?? process.env).CLAUDE_CONFIG_DIR) ? 'override' : 'default', application_mode: policy.mode, enabled: policy.enabled });
|
|
1119
|
+
}
|
|
1120
|
+
return state;
|
|
1121
|
+
}
|
|
1122
|
+
catch (error) {
|
|
1123
|
+
return errorResult(client, error);
|
|
1124
|
+
}
|
|
1125
|
+
});
|
|
1126
|
+
const result = { status: results.some(value => value.status === 'error') ? 'partial' : results.every(value => value.status === 'skipped') ? 'skipped' : 'complete', clients: results };
|
|
1127
|
+
if (result.status === 'partial') {
|
|
1128
|
+
result.clients = results.map(initial => plans.some(plan => plan.result.client === initial.client) ? { ...initial, status: 'skipped', codes: ['other_host_validation_failed'] } : initial);
|
|
1129
|
+
return { result, candidates: [], apply: () => result };
|
|
1130
|
+
}
|
|
1131
|
+
return { result, candidates, apply: (choice) => {
|
|
1132
|
+
const merge = (updates, status) => ({ status, clients: results.map(initial => updates.find(updated => updated.client === initial.client) ?? initial) });
|
|
1133
|
+
if (!['keep', 'none', 'description', 'excerpt'].includes(choice))
|
|
1134
|
+
return merge(plans.map(plan => ({ ...plan.result, status: 'error', codes: ['transmission_invalid_scope'] })), 'partial');
|
|
1135
|
+
if (!plans.length)
|
|
1136
|
+
return result;
|
|
1137
|
+
const commits = [];
|
|
1138
|
+
const failures = [];
|
|
1139
|
+
// All preflight checks precede every write; commits retain per-client rollback.
|
|
1140
|
+
for (const plan of plans) {
|
|
1141
|
+
const client = plan.result.client;
|
|
1142
|
+
try {
|
|
1143
|
+
validateObservations(plan);
|
|
1144
|
+
const currentPolicy = loadAutomaticHookPolicy(join(resolved(options, client).privateDir, 'auto-policy.json')).policy;
|
|
1145
|
+
if (!currentPolicy)
|
|
1146
|
+
fail('policy_conflict');
|
|
1147
|
+
if ((choice === 'keep' && effectiveTransmission(currentPolicy) !== 'unselected') || (currentPolicy.schema_version === 2 && choice === effectiveTransmission(currentPolicy))) {
|
|
1148
|
+
const marker = plan.observations.find(snapshot => snapshot.path === join(resolved(options, client).privateDir, TRANSMISSION_REVIEW_FILE));
|
|
1149
|
+
marker.after = transmissionReviewMarker(options, client, currentPolicy);
|
|
1150
|
+
commits.push({ ...plan, changes: marker.before === marker.after ? [] : [marker], result: { ...plan.result, status: marker.before === marker.after ? 'unchanged' : 'configured', codes: ['transmission_review_complete'], transmission_review: 'complete' } });
|
|
1151
|
+
}
|
|
1152
|
+
else {
|
|
1153
|
+
const scope = choice === 'keep' ? 'none' : choice;
|
|
1154
|
+
const next = prepare(options, client, false, { transmission: scope });
|
|
1155
|
+
validateObservations(plan);
|
|
1156
|
+
for (const original of plan.observations) {
|
|
1157
|
+
const fresh = next.observations.find(snapshot => snapshot.path === original.path);
|
|
1158
|
+
if (!fresh || fresh.before !== original.before || fresh.mode !== original.mode)
|
|
1159
|
+
fail('concurrent_configuration_change');
|
|
1160
|
+
}
|
|
1161
|
+
// Capture the original prompt-time observations, including unchanged files.
|
|
1162
|
+
next.observations = plan.observations.map(original => next.observations.find(snapshot => snapshot.path === original.path) ? Object.assign(next.observations.find(snapshot => snapshot.path === original.path), { identity: original.identity, reviewPrivate: original.reviewPrivate }) : original);
|
|
1163
|
+
next.dirs = [];
|
|
1164
|
+
next.result.codes.push('transmission_review_complete');
|
|
1165
|
+
commits.push(next);
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
catch (error) {
|
|
1169
|
+
failures.push({ ...plan.result, ...errorResult(client, error) });
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
if (failures.length)
|
|
1173
|
+
return merge(plans.map(plan => failures.find(failed => failed.client === plan.result.client) ?? { ...plan.result, status: 'skipped', codes: ['other_host_validation_failed'] }), 'partial');
|
|
1174
|
+
const applied = execute({ ...options, clients: plans.map(plan => plan.result.client) }, false, undefined, commits);
|
|
1175
|
+
return merge(applied.clients, applied.status);
|
|
1176
|
+
} };
|
|
1177
|
+
}
|
|
837
1178
|
/** Read-only redacted policy state. Does not create host directories or contact a provider. */
|
|
838
1179
|
export function showTransmission(options = {}) {
|
|
839
1180
|
return { clients: (options.clients ?? ['codex', 'claude']).map(client => {
|
|
@@ -844,6 +1185,7 @@ export function showTransmission(options = {}) {
|
|
|
844
1185
|
if (!loaded.policy)
|
|
845
1186
|
return { client, status: 'unavailable', code: loaded.reason };
|
|
846
1187
|
return { client, status: 'configured', application_mode: loaded.policy.mode, enabled: loaded.policy.enabled,
|
|
1188
|
+
transmission_review: reviewMatches(transmissionReviewSnapshot(options, client).before, options, client, loaded.policy) ? 'complete' : 'required',
|
|
847
1189
|
transmission: effectiveTransmission(loaded.policy), transmission_source: loaded.policy.schema_version === 1 ? 'legacy' : effectiveTransmission(loaded.policy) === 'unselected' ? 'unselected' : 'explicit' };
|
|
848
1190
|
}
|
|
849
1191
|
catch (error) {
|
|
@@ -894,3 +1236,260 @@ export function showBudgetStatus(options = {}) {
|
|
|
894
1236
|
});
|
|
895
1237
|
return { status: clients.some(client => client.status === 'error') ? 'partial' : 'complete', clients };
|
|
896
1238
|
}
|
|
1239
|
+
const STATISTICS_OWNERSHIP_FILE = 'stats-ownership.json';
|
|
1240
|
+
function statisticsOwner(value, client) {
|
|
1241
|
+
const valid = ['PostToolUse', 'PostModelRequest', 'SubagentStart', 'SubagentStop'];
|
|
1242
|
+
if (value.schema_version !== 1 || value.kind !== 'aptly-statistics-ownership' || value.client !== client || typeof value.state_directory !== 'string' || !isAbsolute(value.state_directory) || !object(value.hooks) || Object.keys(value.hooks).some(k => !valid.includes(k)) || Object.values(value.hooks).some(v => !object(v) || !Array.isArray(v.hooks)) || value.hooks_fingerprint !== createHash('sha256').update(JSON.stringify(value.hooks)).digest('hex'))
|
|
1243
|
+
fail('statistics_ownership_invalid');
|
|
1244
|
+
return value;
|
|
1245
|
+
}
|
|
1246
|
+
function statisticEntries(value, event, create = false) {
|
|
1247
|
+
if (value.hooks === undefined && !create)
|
|
1248
|
+
return [];
|
|
1249
|
+
const events = map(value, 'hooks');
|
|
1250
|
+
if (events[event] === undefined) {
|
|
1251
|
+
if (!create)
|
|
1252
|
+
return [];
|
|
1253
|
+
events[event] = [];
|
|
1254
|
+
}
|
|
1255
|
+
if (!Array.isArray(events[event]))
|
|
1256
|
+
fail('hook_shape_conflict');
|
|
1257
|
+
return events[event];
|
|
1258
|
+
}
|
|
1259
|
+
function statisticsPolicy(options, client, requireRegistration = true) {
|
|
1260
|
+
const paths = resolved(options, client), policyPath = join(paths.privateDir, 'auto-policy.json');
|
|
1261
|
+
if (requireRegistration) {
|
|
1262
|
+
const mcp = read(paths.mcpPath), config = client === 'codex' ? toml(mcp.text ?? '') : json(mcp.text);
|
|
1263
|
+
const entry = config[client === 'codex' ? 'mcp_servers' : 'mcpServers']?.aptly;
|
|
1264
|
+
if (!object(entry))
|
|
1265
|
+
fail('statistics_requires_setup');
|
|
1266
|
+
if (!policyReferenceMatches(entry, client, policyPath, options))
|
|
1267
|
+
fail('statistics_policy_conflict');
|
|
1268
|
+
}
|
|
1269
|
+
const loaded = loadAutomaticHookPolicy(policyPath);
|
|
1270
|
+
if (!loaded.policy)
|
|
1271
|
+
fail('statistics_requires_setup');
|
|
1272
|
+
return { ...paths, policyPath, stateDirectory: loaded.policy.state_directory };
|
|
1273
|
+
}
|
|
1274
|
+
function statisticsHooks(root, client, policyPath) {
|
|
1275
|
+
const observer = join(root, 'dist', 'bin', 'aptly-observe.js');
|
|
1276
|
+
if (read(observer).text === null)
|
|
1277
|
+
fail('statistics_observer_missing');
|
|
1278
|
+
for (const path of [process.execPath, observer, policyPath])
|
|
1279
|
+
if (!isAbsolute(path) || /[\x00-\x1f\x7f]/.test(path))
|
|
1280
|
+
fail('statistics_invalid_options');
|
|
1281
|
+
const quote = (v) => "'" + v.replaceAll("'", "'\\''") + "'";
|
|
1282
|
+
const command = [process.execPath, '--no-warnings', observer, '--client', client, '--policy-path', policyPath].map(quote).join(' ');
|
|
1283
|
+
const handler = { type: 'command', command, timeout: 5, statusMessage: 'Aptly local execution statistics' };
|
|
1284
|
+
const events = client === 'codex' ? ['PostToolUse', 'SubagentStart', 'PostModelRequest', 'SubagentStop'] : ['PostToolUse', 'SubagentStart', 'SubagentStop'];
|
|
1285
|
+
return Object.fromEntries(events.map(event => [event, { ...(event === 'PostToolUse' ? { matcher: client === 'codex' ? '^(spawn_agent|collaborationspawn_agent|collaboration\\.spawn_agent)$' : '^(Agent|Task)$' } : {}), hooks: [{ ...handler }] }]));
|
|
1286
|
+
}
|
|
1287
|
+
function statisticsSnapshot(path) { const value = read(path); if (value.text !== null) {
|
|
1288
|
+
privatePermissions(path, 'private_file_permissions');
|
|
1289
|
+
if (lstatSync(path).nlink !== 1)
|
|
1290
|
+
fail('unsafe_configuration_file');
|
|
1291
|
+
} return { path, before: value.text, after: value.text, mode: value.mode }; }
|
|
1292
|
+
function statisticsConfig(snapshot) {
|
|
1293
|
+
if (snapshot.before === null)
|
|
1294
|
+
return { schema_version: 1, enabled_clients: [] };
|
|
1295
|
+
const value = parseStatisticsConfig(json(snapshot.before));
|
|
1296
|
+
if (!value)
|
|
1297
|
+
fail('statistics_config_invalid');
|
|
1298
|
+
return value;
|
|
1299
|
+
}
|
|
1300
|
+
function possibleStatisticsObserver(entry) {
|
|
1301
|
+
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'))));
|
|
1302
|
+
}
|
|
1303
|
+
function clearCodexMetadata(state, client) { if (client === 'codex') {
|
|
1304
|
+
delete state.codex_native_metadata;
|
|
1305
|
+
delete state.codex_home;
|
|
1306
|
+
} }
|
|
1307
|
+
function appendStatisticsRemoval(options, client, hooksObject, hooks, changes, observations) {
|
|
1308
|
+
const paths = resolved(options, client), receipt = statisticsSnapshot(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
|
|
1309
|
+
observations.push(receipt);
|
|
1310
|
+
const stateDirectory = statisticsPolicy(options, client, false).stateDirectory;
|
|
1311
|
+
const owned = receipt.before === null ? undefined : statisticsOwner(json(receipt.before), client);
|
|
1312
|
+
if (owned && owned.state_directory !== stateDirectory)
|
|
1313
|
+
fail('statistics_ownership_invalid');
|
|
1314
|
+
const config = statisticsSnapshot(join(stateDirectory, STATISTICS_CONFIG_FILE));
|
|
1315
|
+
observations.push(config);
|
|
1316
|
+
if (owned) {
|
|
1317
|
+
for (const [event, entry] of Object.entries(owned.hooks)) {
|
|
1318
|
+
const list = statisticEntries(hooksObject, event), matches = list.filter(v => isDeepStrictEqual(v, entry));
|
|
1319
|
+
if (matches.length > 1 || (!matches.length && list.some(possibleStatisticsObserver)))
|
|
1320
|
+
fail('managed_hook_changed');
|
|
1321
|
+
for (let n = list.length - 1; n >= 0; n--)
|
|
1322
|
+
if (isDeepStrictEqual(list[n], entry))
|
|
1323
|
+
list.splice(n, 1);
|
|
1324
|
+
}
|
|
1325
|
+
receipt.after = null;
|
|
1326
|
+
hooks.after = stringify(hooksObject);
|
|
1327
|
+
}
|
|
1328
|
+
if (config.before !== null) {
|
|
1329
|
+
const state = statisticsConfig(config);
|
|
1330
|
+
state.enabled_clients = state.enabled_clients.filter(c => c !== client);
|
|
1331
|
+
clearCodexMetadata(state, client);
|
|
1332
|
+
config.after = serializeStatisticsConfig(state);
|
|
1333
|
+
}
|
|
1334
|
+
for (const snap of [config, receipt])
|
|
1335
|
+
if (snap.before !== snap.after)
|
|
1336
|
+
changes.push(snap);
|
|
1337
|
+
}
|
|
1338
|
+
/** Explicit collection controls; legacy routing receipt and model/credential settings stay untouched. */
|
|
1339
|
+
export function setStatisticsCollection(enabled, options = {}) {
|
|
1340
|
+
const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
|
|
1341
|
+
if (typeof enabled !== 'boolean' || !clients.length || clients.some(c => !['codex', 'claude'].includes(c)) || options.automatic || options.mode || options.transmission || options.selectUnselectedOnly || (!enabled && options.codexNativeMetadata !== undefined) || options.codexNativeMetadata && !clients.includes('codex'))
|
|
1342
|
+
return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_invalid_options'] })) };
|
|
1343
|
+
if (process.platform === 'win32')
|
|
1344
|
+
return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_platform_unsupported'] })) };
|
|
1345
|
+
const states = new Set();
|
|
1346
|
+
const plans = clients.map(client => {
|
|
1347
|
+
try {
|
|
1348
|
+
if (!enabled) {
|
|
1349
|
+
const base = resolved(options, client);
|
|
1350
|
+
if (read(join(base.privateDir, 'auto-policy.json')).text === null && read(join(base.privateDir, STATISTICS_OWNERSHIP_FILE)).text === null && read(join(base.privateDir, 'state', STATISTICS_CONFIG_FILE)).text === null)
|
|
1351
|
+
return { changes: [], observations: [], dirs: [], result: { client, status: 'unchanged', codes: ['statistics_disabled'] } };
|
|
1352
|
+
}
|
|
1353
|
+
const paths = statisticsPolicy(options, client, enabled);
|
|
1354
|
+
if (enabled) {
|
|
1355
|
+
try {
|
|
1356
|
+
assertPrivateStatePath(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
|
|
1357
|
+
assertPrivateStatePath(join(paths.stateDirectory, STATISTICS_CONFIG_FILE));
|
|
1358
|
+
}
|
|
1359
|
+
catch {
|
|
1360
|
+
fail('private_directory_permissions');
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
if (states.has(paths.stateDirectory))
|
|
1364
|
+
fail('statistics_shared_state');
|
|
1365
|
+
states.add(paths.stateDirectory);
|
|
1366
|
+
const observations = [], changes = [];
|
|
1367
|
+
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; };
|
|
1368
|
+
const policy = snap(paths.policyPath);
|
|
1369
|
+
if (enabled) {
|
|
1370
|
+
snap(paths.mcpPath, false);
|
|
1371
|
+
const routingReceipt = snap(join(paths.privateDir, 'setup-ownership.json'));
|
|
1372
|
+
if (routingReceipt.before === null)
|
|
1373
|
+
fail('statistics_requires_setup');
|
|
1374
|
+
ownership(json(routingReceipt.before), client);
|
|
1375
|
+
}
|
|
1376
|
+
const hooks = snap(paths.hooksPath, false), config = snap(join(paths.stateDirectory, STATISTICS_CONFIG_FILE));
|
|
1377
|
+
let receipt, unreadableReceipt = false;
|
|
1378
|
+
try {
|
|
1379
|
+
receipt = snap(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
|
|
1380
|
+
}
|
|
1381
|
+
catch (error) {
|
|
1382
|
+
if (enabled || safeCode(error) !== 'private_file_permissions')
|
|
1383
|
+
throw error;
|
|
1384
|
+
unreadableReceipt = true;
|
|
1385
|
+
}
|
|
1386
|
+
if (!enabled && !unreadableReceipt && receipt.before === null && config.before === null)
|
|
1387
|
+
return { changes, observations, dirs: [], result: { client, status: 'unchanged', codes: ['statistics_disabled'] } };
|
|
1388
|
+
const key = enabled ? snap(join(paths.stateDirectory, STATISTICS_KEY_FILE)) : undefined;
|
|
1389
|
+
const value = json(hooks.before), originalHooks = structuredClone(value), state = statisticsConfig(config);
|
|
1390
|
+
let old, invalidReceipt = unreadableReceipt;
|
|
1391
|
+
if (receipt && receipt.before !== null)
|
|
1392
|
+
try {
|
|
1393
|
+
old = statisticsOwner(json(receipt.before), client);
|
|
1394
|
+
}
|
|
1395
|
+
catch (error) {
|
|
1396
|
+
if (enabled)
|
|
1397
|
+
throw error;
|
|
1398
|
+
invalidReceipt = true;
|
|
1399
|
+
}
|
|
1400
|
+
if (old && old.state_directory !== paths.stateDirectory) {
|
|
1401
|
+
if (enabled)
|
|
1402
|
+
fail('statistics_ownership_invalid');
|
|
1403
|
+
old = undefined;
|
|
1404
|
+
invalidReceipt = true;
|
|
1405
|
+
}
|
|
1406
|
+
let modified = invalidReceipt;
|
|
1407
|
+
if (old)
|
|
1408
|
+
for (const [event, entry] of Object.entries(old.hooks)) {
|
|
1409
|
+
const list = statisticEntries(value, event), matches = list.filter(v => isDeepStrictEqual(v, entry));
|
|
1410
|
+
if (!matches.length) {
|
|
1411
|
+
if (enabled)
|
|
1412
|
+
fail('managed_hook_changed');
|
|
1413
|
+
if (list.some(possibleStatisticsObserver))
|
|
1414
|
+
modified = true;
|
|
1415
|
+
continue;
|
|
1416
|
+
}
|
|
1417
|
+
if (matches.length > 1) {
|
|
1418
|
+
if (enabled)
|
|
1419
|
+
fail('managed_hook_changed');
|
|
1420
|
+
modified = true;
|
|
1421
|
+
continue;
|
|
1422
|
+
}
|
|
1423
|
+
for (let n = list.length - 1; n >= 0; n--)
|
|
1424
|
+
if (isDeepStrictEqual(list[n], entry))
|
|
1425
|
+
list.splice(n, 1);
|
|
1426
|
+
}
|
|
1427
|
+
if (enabled) {
|
|
1428
|
+
if (key.before === null) {
|
|
1429
|
+
try {
|
|
1430
|
+
lstatSync(join(paths.stateDirectory, STATISTICS_DB_FILE));
|
|
1431
|
+
fail('statistics_key_missing');
|
|
1432
|
+
}
|
|
1433
|
+
catch (error) {
|
|
1434
|
+
if (error.code !== 'ENOENT')
|
|
1435
|
+
throw error;
|
|
1436
|
+
}
|
|
1437
|
+
key.after = randomBytes(32).toString('hex') + '\n';
|
|
1438
|
+
}
|
|
1439
|
+
else if (!/^[a-f0-9]{64}\n$/.test(key.before))
|
|
1440
|
+
fail('statistics_key_missing');
|
|
1441
|
+
state.enabled_clients = [...new Set([...state.enabled_clients, client])];
|
|
1442
|
+
if (client === 'codex')
|
|
1443
|
+
clearCodexMetadata(state, client);
|
|
1444
|
+
if (client === 'codex' && options.codexNativeMetadata) {
|
|
1445
|
+
if (state.codex_home !== undefined && state.codex_home !== paths.dir)
|
|
1446
|
+
fail('statistics_config_invalid');
|
|
1447
|
+
state.codex_native_metadata = true;
|
|
1448
|
+
state.codex_home = paths.dir;
|
|
1449
|
+
}
|
|
1450
|
+
const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
|
|
1451
|
+
const entries = statisticsHooks(root, client, paths.policyPath);
|
|
1452
|
+
for (const [event, entry] of Object.entries(entries)) {
|
|
1453
|
+
const list = statisticEntries(value, event, true);
|
|
1454
|
+
if (list.some(possibleStatisticsObserver))
|
|
1455
|
+
fail('statistics_observers_present');
|
|
1456
|
+
list.push(entry);
|
|
1457
|
+
}
|
|
1458
|
+
receipt.after = stringify({ schema_version: 1, kind: 'aptly-statistics-ownership', client, state_directory: paths.stateDirectory, hooks: entries, hooks_fingerprint: createHash('sha256').update(JSON.stringify(entries)).digest('hex') });
|
|
1459
|
+
}
|
|
1460
|
+
else {
|
|
1461
|
+
state.enabled_clients = state.enabled_clients.filter(c => c !== client);
|
|
1462
|
+
clearCodexMetadata(state, client);
|
|
1463
|
+
if (receipt)
|
|
1464
|
+
receipt.after = invalidReceipt ? receipt.before : null;
|
|
1465
|
+
}
|
|
1466
|
+
config.after = serializeStatisticsConfig(state);
|
|
1467
|
+
if (!isDeepStrictEqual(value, originalHooks))
|
|
1468
|
+
hooks.after = stringify(value);
|
|
1469
|
+
for (const item of [config, ...(key ? [key] : []), hooks, ...(receipt ? [receipt] : [])])
|
|
1470
|
+
if (item.before !== item.after)
|
|
1471
|
+
changes.push(item);
|
|
1472
|
+
const codes = [enabled ? 'statistics_enabled' : 'statistics_disabled', ...(modified ? ['statistics_observers_retained_modified'] : []), ...(enabled && client === 'codex' ? ['requires_hook_review'] : []), ...(enabled ? ['mcp_restart_required'] : [])];
|
|
1473
|
+
return { changes, observations, dirs: [], result: { client, status: changes.length ? 'configured' : 'unchanged', codes, ...(enabled && client === 'codex' ? { requires_hook_review: true } : {}) } };
|
|
1474
|
+
}
|
|
1475
|
+
catch (error) {
|
|
1476
|
+
return { changes: [], observations: [], dirs: [], result: errorResult(client, error) };
|
|
1477
|
+
}
|
|
1478
|
+
});
|
|
1479
|
+
if (enabled && plans.some(p => p.result.status === 'error'))
|
|
1480
|
+
return { status: 'partial', clients: plans.map(p => p.result.status === 'error' ? p.result : { ...p.result, status: 'skipped', codes: ['other_host_validation_failed'] }) };
|
|
1481
|
+
return execute(options, false, undefined, plans);
|
|
1482
|
+
}
|
|
1483
|
+
/** Snapshot view; no runtime, credentials, provider, budget gate or state creation. */
|
|
1484
|
+
export function showStatistics(options = {}, today = false) {
|
|
1485
|
+
const clients = options.clients ?? ['codex', 'claude'];
|
|
1486
|
+
if (process.platform === 'win32')
|
|
1487
|
+
return { clients: clients.map(client => ({ client, status: 'statistics_platform_unsupported', collection: 'disabled' })) };
|
|
1488
|
+
return { clients: clients.map(client => { try {
|
|
1489
|
+
const path = statisticsPolicy(options, client);
|
|
1490
|
+
return { client, ...readStatistics({ stateDirectory: path.stateDirectory }, { client, today }) };
|
|
1491
|
+
}
|
|
1492
|
+
catch (error) {
|
|
1493
|
+
return { client, status: safeCode(error), collection: 'disabled' };
|
|
1494
|
+
} }) };
|
|
1495
|
+
}
|