aptly 0.1.8 → 0.1.10
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-observe.d.ts +2 -0
- package/dist/bin/aptly-observe.js +66 -0
- package/dist/bin/aptly.js +56 -5
- package/dist/src/cli-help.js +11 -4
- package/dist/src/linux-store-readiness.d.ts +12 -0
- package/dist/src/linux-store-readiness.js +67 -0
- package/dist/src/server.js +34 -1
- package/dist/src/setup.d.ts +52 -0
- package/dist/src/setup.js +322 -15
- 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/update-notifier.js +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/docs/guide/en.md +33 -1
- package/docs/guide/ja.md +33 -1
- package/docs/guide/ko.md +33 -1
- package/docs/guide/zh-CN.md +33 -1
- package/package.json +2 -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';
|
|
@@ -11,6 +11,7 @@ import { Router, defaultPolicy } from './core.js';
|
|
|
11
11
|
import { loadAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
|
|
12
12
|
import { assertPrivateStatePath } from './files.js';
|
|
13
13
|
import { assertWindowsPrivatePath, protectNewWindowsPrivateDirectory, copyWindowsFilePermissions } from './windows-private.js';
|
|
14
|
+
import { STATISTICS_CONFIG_FILE, STATISTICS_KEY_FILE, STATISTICS_DB_FILE, parseStatisticsConfig, serializeStatisticsConfig, readStatistics } from './statistics.js';
|
|
14
15
|
const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
15
16
|
const stringify = (value) => JSON.stringify(value, null, 2) + '\n';
|
|
16
17
|
const fail = (code) => { throw new Error(code); };
|
|
@@ -358,8 +359,11 @@ function prepare(options, client, removing, edit) {
|
|
|
358
359
|
privatePermissions(privateFile.path, 'private_file_permissions');
|
|
359
360
|
observations.push(mcp, hooks, policy, manifest);
|
|
360
361
|
const oldOwner = manifest.before === null ? undefined : ownership(json(manifest.before), client);
|
|
361
|
-
if (removing && !oldOwner)
|
|
362
|
+
if (removing && !oldOwner) {
|
|
363
|
+
if (read(join(privateDir, STATISTICS_OWNERSHIP_FILE)).text !== null)
|
|
364
|
+
fail('statistics_observers_present');
|
|
362
365
|
return { changes, observations, dirs, result: { client, status: 'skipped', codes: ['no_owned_setup'] } };
|
|
366
|
+
}
|
|
363
367
|
const hookValue = hook(client), hooksObject = json(hooks.before), entries = hooksArray(hooksObject);
|
|
364
368
|
const config = client === 'codex' ? toml(mcp.before ?? '') : json(mcp.before), servers = map(config, client === 'codex' ? 'mcp_servers' : 'mcpServers');
|
|
365
369
|
if (removing) {
|
|
@@ -409,6 +413,7 @@ function prepare(options, client, removing, edit) {
|
|
|
409
413
|
policy.after = null;
|
|
410
414
|
manifest.after = null;
|
|
411
415
|
result.status = 'removed';
|
|
416
|
+
appendStatisticsRemoval(options, client, hooksObject, hooks, changes, observations);
|
|
412
417
|
}
|
|
413
418
|
else {
|
|
414
419
|
const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
|
|
@@ -433,11 +438,17 @@ function prepare(options, client, removing, edit) {
|
|
|
433
438
|
else {
|
|
434
439
|
if (!object(servers.aptly))
|
|
435
440
|
fail('mcp_entry_conflict');
|
|
441
|
+
const configuredPolicy = object(servers.aptly.env) ? servers.aptly.env.APTLY_HOOK_POLICY_PATH : undefined;
|
|
442
|
+
const mismatch = configuredPolicy !== undefined && configuredPolicy !== policyPath;
|
|
443
|
+
const detail = mismatch && typeof configuredPolicy === 'string' && configuredPolicy.length > 0 ? {
|
|
444
|
+
policy_location: configuredPolicy === join(resolve(options.home ?? homedir()), client === 'codex' ? '.codex' : '.claude', 'aptly', 'auto-policy.json') ? 'default_home' : 'elsewhere',
|
|
445
|
+
selected_home_source: (client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR) ? 'override' : 'default',
|
|
446
|
+
} : undefined;
|
|
436
447
|
if (edit && oldOwner?.mcp_created && !isDeepStrictEqual(servers.aptly, oldOwner.mcp))
|
|
437
|
-
|
|
448
|
+
throw Object.assign(new Error('managed_mcp_changed'), detail ? { policyConflict: detail } : {});
|
|
449
|
+
if (mismatch)
|
|
450
|
+
throw Object.assign(new Error('mcp_environment_conflict'), { policyConflict: detail });
|
|
438
451
|
const currentEnv = map(servers.aptly, 'env');
|
|
439
|
-
if (currentEnv.APTLY_HOOK_POLICY_PATH !== undefined && currentEnv.APTLY_HOOK_POLICY_PATH !== policyPath)
|
|
440
|
-
fail('mcp_environment_conflict');
|
|
441
452
|
const missing = Object.fromEntries(Object.entries(additions).filter(([key]) => currentEnv[key] === undefined));
|
|
442
453
|
Object.assign(currentEnv, missing);
|
|
443
454
|
mcp.after = client === 'codex' ? addTomlEnv(mcp.before ?? '', missing) : stringify(config);
|
|
@@ -616,6 +627,13 @@ function replace(snapshot, forward) {
|
|
|
616
627
|
}
|
|
617
628
|
}
|
|
618
629
|
}
|
|
630
|
+
function policyRecovery(client) {
|
|
631
|
+
return [`aptly setup --check --client ${client}`, 'Review the selected host configuration directory and its existing policy reference locally; intentional sharing cannot be inferred. Preserve the registration and select the intended host directory before retrying. A policy conflict does not authenticate the launcher or other changed settings. Review all changed registration fields locally before reuse; keep custom or modified launchers unchanged and do not execute an unverified launcher. Do not copy keys, ledgers or trust settings.'];
|
|
632
|
+
}
|
|
633
|
+
function errorResult(client, error) {
|
|
634
|
+
const detail = error?.policyConflict;
|
|
635
|
+
return { client, status: 'error', codes: [safeCode(error), ...(detail ? ['hook_policy_path_conflict'] : [])], ...budgetErrorDetails(error), ...(detail ? { ...detail, recovery: policyRecovery(client) } : {}) };
|
|
636
|
+
}
|
|
619
637
|
function execute(options, removing, edit, captured) {
|
|
620
638
|
const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
|
|
621
639
|
if (clients.some(client => client !== 'codex' && client !== 'claude'))
|
|
@@ -630,7 +648,7 @@ function execute(options, removing, edit, captured) {
|
|
|
630
648
|
return prepare(options, client, removing, edit);
|
|
631
649
|
}
|
|
632
650
|
catch (e) {
|
|
633
|
-
return { changes: [], observations: [], dirs: [], result:
|
|
651
|
+
return { changes: [], observations: [], dirs: [], result: errorResult(client, e) };
|
|
634
652
|
}
|
|
635
653
|
});
|
|
636
654
|
const results = prepared.map(plan => plan.result);
|
|
@@ -697,9 +715,25 @@ function execute(options, removing, edit, captured) {
|
|
|
697
715
|
}
|
|
698
716
|
return { status: results.some(result => result.status === 'error') ? 'partial' : results.every(result => result.status === 'skipped') ? 'skipped' : 'complete', clients: results };
|
|
699
717
|
}
|
|
700
|
-
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']);
|
|
718
|
+
const codes = new Set(['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']);
|
|
701
719
|
function safeCode(error) { return error instanceof Error && codes.has(error.message) ? error.message : 'configuration_io_error'; }
|
|
702
720
|
export function setupHosts(options = {}) { return execute(options, false); }
|
|
721
|
+
/** Snapshot the normal setup plan without applying it; it does not verify a running host. */
|
|
722
|
+
export function checkSetup(options = {}) {
|
|
723
|
+
const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
|
|
724
|
+
if (!clients.length || clients.some(client => client !== 'codex' && client !== 'claude') || options.automatic !== undefined || options.mode !== undefined || options.transmission !== undefined || options.selectUnselectedOnly !== undefined)
|
|
725
|
+
return { status: 'partial', clients: [] };
|
|
726
|
+
const results = clients.map(client => {
|
|
727
|
+
try {
|
|
728
|
+
const plan = prepare(options, client, false);
|
|
729
|
+
return { ...plan.result, status: 'unchanged', codes: [plan.changes.length ? 'setup_check_configure_ready' : 'setup_check_ok', ...plan.result.codes] };
|
|
730
|
+
}
|
|
731
|
+
catch (error) {
|
|
732
|
+
return errorResult(client, error);
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
return { status: results.some(result => result.status === 'error') ? 'partial' : 'complete', clients: results };
|
|
736
|
+
}
|
|
703
737
|
export function removeSetup(options = {}) { return execute(options, true); }
|
|
704
738
|
export function setDefaults(options = {}) { return execute(options, false, { defaults: true }); }
|
|
705
739
|
export function setEnvironment(key, value, options = {}) {
|
|
@@ -737,12 +771,17 @@ export function prepareCredentialReference(options, client) {
|
|
|
737
771
|
result = { client, status: 'unchanged', codes: ['credential_preflight_ok'] };
|
|
738
772
|
}
|
|
739
773
|
catch (error) {
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
774
|
+
if (error?.policyConflict) {
|
|
775
|
+
result = errorResult(client, error);
|
|
776
|
+
}
|
|
777
|
+
else {
|
|
778
|
+
const reason = error?.reason;
|
|
779
|
+
const reasons = ['credential_node_mismatch', 'credential_server_mismatch', 'credential_runtime_unsupported'];
|
|
780
|
+
const migration = migrateLauncher({ ...options, clients: [client] }, true);
|
|
781
|
+
const canMigrate = migration.status === 'complete';
|
|
782
|
+
result = { client, status: 'error', codes: [safeCode(error), ...(reason && reasons.includes(reason) ? [reason] : []), ...(canMigrate ? ['launcher_migration_available'] : [])],
|
|
783
|
+
recovery: canMigrate ? recovery(client) : [`aptly set env OPENAI_API_KEY --client ${client} --check`, 'Keep custom or modified launchers unchanged. Review the host registration locally; use its secure credential environment or a separately reviewed standard registration.'] };
|
|
784
|
+
}
|
|
746
785
|
}
|
|
747
786
|
const check = () => {
|
|
748
787
|
if (!plan)
|
|
@@ -754,7 +793,18 @@ export function prepareCredentialReference(options, client) {
|
|
|
754
793
|
return result;
|
|
755
794
|
}
|
|
756
795
|
catch (error) {
|
|
757
|
-
|
|
796
|
+
// Preserve the concurrent-change guard, but surface a policy mismatch if one is now visible.
|
|
797
|
+
try {
|
|
798
|
+
prepare({ ...options, clients: [client] }, client, false, { credential: true });
|
|
799
|
+
}
|
|
800
|
+
catch (current) {
|
|
801
|
+
if (current?.policyConflict) {
|
|
802
|
+
const detail = errorResult(client, current);
|
|
803
|
+
return { ...detail, codes: [safeCode(error), 'hook_policy_path_conflict'] };
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
const result = errorResult(client, error);
|
|
807
|
+
return result.recovery ? result : { ...result, recovery: recovery(client) };
|
|
758
808
|
}
|
|
759
809
|
};
|
|
760
810
|
return { result, check, commit: () => {
|
|
@@ -780,7 +830,7 @@ export function migrateLauncher(options, dryRun = false, includeExisting = false
|
|
|
780
830
|
return result;
|
|
781
831
|
}
|
|
782
832
|
catch (error) {
|
|
783
|
-
return { status: 'partial', clients: [
|
|
833
|
+
return { status: 'partial', clients: [errorResult(client, error)] };
|
|
784
834
|
}
|
|
785
835
|
}
|
|
786
836
|
/** Explicit operator change; updates policy and its receipt through normal guarded staging. */
|
|
@@ -849,3 +899,260 @@ export function showBudgetStatus(options = {}) {
|
|
|
849
899
|
});
|
|
850
900
|
return { status: clients.some(client => client.status === 'error') ? 'partial' : 'complete', clients };
|
|
851
901
|
}
|
|
902
|
+
const STATISTICS_OWNERSHIP_FILE = 'stats-ownership.json';
|
|
903
|
+
function statisticsOwner(value, client) {
|
|
904
|
+
const valid = ['PostToolUse', 'PostModelRequest', 'SubagentStart', 'SubagentStop'];
|
|
905
|
+
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'))
|
|
906
|
+
fail('statistics_ownership_invalid');
|
|
907
|
+
return value;
|
|
908
|
+
}
|
|
909
|
+
function statisticEntries(value, event, create = false) {
|
|
910
|
+
if (value.hooks === undefined && !create)
|
|
911
|
+
return [];
|
|
912
|
+
const events = map(value, 'hooks');
|
|
913
|
+
if (events[event] === undefined) {
|
|
914
|
+
if (!create)
|
|
915
|
+
return [];
|
|
916
|
+
events[event] = [];
|
|
917
|
+
}
|
|
918
|
+
if (!Array.isArray(events[event]))
|
|
919
|
+
fail('hook_shape_conflict');
|
|
920
|
+
return events[event];
|
|
921
|
+
}
|
|
922
|
+
function statisticsPolicy(options, client, requireRegistration = true) {
|
|
923
|
+
const paths = resolved(options, client), policyPath = join(paths.privateDir, 'auto-policy.json');
|
|
924
|
+
if (requireRegistration) {
|
|
925
|
+
const mcp = read(paths.mcpPath), config = client === 'codex' ? toml(mcp.text ?? '') : json(mcp.text);
|
|
926
|
+
const entry = config[client === 'codex' ? 'mcp_servers' : 'mcpServers']?.aptly;
|
|
927
|
+
if (!object(entry))
|
|
928
|
+
fail('statistics_requires_setup');
|
|
929
|
+
if (entry.env?.APTLY_HOOK_POLICY_PATH !== policyPath)
|
|
930
|
+
fail('statistics_policy_conflict');
|
|
931
|
+
}
|
|
932
|
+
const loaded = loadAutomaticHookPolicy(policyPath);
|
|
933
|
+
if (!loaded.policy)
|
|
934
|
+
fail('statistics_requires_setup');
|
|
935
|
+
return { ...paths, policyPath, stateDirectory: loaded.policy.state_directory };
|
|
936
|
+
}
|
|
937
|
+
function statisticsHooks(root, client, policyPath) {
|
|
938
|
+
const observer = join(root, 'dist', 'bin', 'aptly-observe.js');
|
|
939
|
+
if (read(observer).text === null)
|
|
940
|
+
fail('statistics_observer_missing');
|
|
941
|
+
for (const path of [process.execPath, observer, policyPath])
|
|
942
|
+
if (!isAbsolute(path) || /[\x00-\x1f\x7f]/.test(path))
|
|
943
|
+
fail('statistics_invalid_options');
|
|
944
|
+
const quote = (v) => "'" + v.replaceAll("'", "'\\''") + "'";
|
|
945
|
+
const command = [process.execPath, '--no-warnings', observer, '--client', client, '--policy-path', policyPath].map(quote).join(' ');
|
|
946
|
+
const handler = { type: 'command', command, timeout: 5, statusMessage: 'Aptly local execution statistics' };
|
|
947
|
+
const events = client === 'codex' ? ['PostToolUse', 'SubagentStart', 'PostModelRequest', 'SubagentStop'] : ['PostToolUse', 'SubagentStart', 'SubagentStop'];
|
|
948
|
+
return Object.fromEntries(events.map(event => [event, { ...(event === 'PostToolUse' ? { matcher: client === 'codex' ? '^(spawn_agent|collaborationspawn_agent|collaboration\\.spawn_agent)$' : '^(Agent|Task)$' } : {}), hooks: [{ ...handler }] }]));
|
|
949
|
+
}
|
|
950
|
+
function statisticsSnapshot(path) { const value = read(path); if (value.text !== null) {
|
|
951
|
+
privatePermissions(path, 'private_file_permissions');
|
|
952
|
+
if (lstatSync(path).nlink !== 1)
|
|
953
|
+
fail('unsafe_configuration_file');
|
|
954
|
+
} return { path, before: value.text, after: value.text, mode: value.mode }; }
|
|
955
|
+
function statisticsConfig(snapshot) {
|
|
956
|
+
if (snapshot.before === null)
|
|
957
|
+
return { schema_version: 1, enabled_clients: [] };
|
|
958
|
+
const value = parseStatisticsConfig(json(snapshot.before));
|
|
959
|
+
if (!value)
|
|
960
|
+
fail('statistics_config_invalid');
|
|
961
|
+
return value;
|
|
962
|
+
}
|
|
963
|
+
function possibleStatisticsObserver(entry) {
|
|
964
|
+
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'))));
|
|
965
|
+
}
|
|
966
|
+
function clearCodexMetadata(state, client) { if (client === 'codex') {
|
|
967
|
+
delete state.codex_native_metadata;
|
|
968
|
+
delete state.codex_home;
|
|
969
|
+
} }
|
|
970
|
+
function appendStatisticsRemoval(options, client, hooksObject, hooks, changes, observations) {
|
|
971
|
+
const paths = resolved(options, client), receipt = statisticsSnapshot(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
|
|
972
|
+
observations.push(receipt);
|
|
973
|
+
const stateDirectory = statisticsPolicy(options, client, false).stateDirectory;
|
|
974
|
+
const owned = receipt.before === null ? undefined : statisticsOwner(json(receipt.before), client);
|
|
975
|
+
if (owned && owned.state_directory !== stateDirectory)
|
|
976
|
+
fail('statistics_ownership_invalid');
|
|
977
|
+
const config = statisticsSnapshot(join(stateDirectory, STATISTICS_CONFIG_FILE));
|
|
978
|
+
observations.push(config);
|
|
979
|
+
if (owned) {
|
|
980
|
+
for (const [event, entry] of Object.entries(owned.hooks)) {
|
|
981
|
+
const list = statisticEntries(hooksObject, event), matches = list.filter(v => isDeepStrictEqual(v, entry));
|
|
982
|
+
if (matches.length > 1 || (!matches.length && list.some(possibleStatisticsObserver)))
|
|
983
|
+
fail('managed_hook_changed');
|
|
984
|
+
for (let n = list.length - 1; n >= 0; n--)
|
|
985
|
+
if (isDeepStrictEqual(list[n], entry))
|
|
986
|
+
list.splice(n, 1);
|
|
987
|
+
}
|
|
988
|
+
receipt.after = null;
|
|
989
|
+
hooks.after = stringify(hooksObject);
|
|
990
|
+
}
|
|
991
|
+
if (config.before !== null) {
|
|
992
|
+
const state = statisticsConfig(config);
|
|
993
|
+
state.enabled_clients = state.enabled_clients.filter(c => c !== client);
|
|
994
|
+
clearCodexMetadata(state, client);
|
|
995
|
+
config.after = serializeStatisticsConfig(state);
|
|
996
|
+
}
|
|
997
|
+
for (const snap of [config, receipt])
|
|
998
|
+
if (snap.before !== snap.after)
|
|
999
|
+
changes.push(snap);
|
|
1000
|
+
}
|
|
1001
|
+
/** Explicit collection controls; legacy routing receipt and model/credential settings stay untouched. */
|
|
1002
|
+
export function setStatisticsCollection(enabled, options = {}) {
|
|
1003
|
+
const clients = [...new Set(options.clients ?? ['codex', 'claude'])];
|
|
1004
|
+
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'))
|
|
1005
|
+
return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_invalid_options'] })) };
|
|
1006
|
+
if (process.platform === 'win32')
|
|
1007
|
+
return { status: 'partial', clients: clients.map(client => ({ client, status: 'error', codes: ['statistics_platform_unsupported'] })) };
|
|
1008
|
+
const states = new Set();
|
|
1009
|
+
const plans = clients.map(client => {
|
|
1010
|
+
try {
|
|
1011
|
+
if (!enabled) {
|
|
1012
|
+
const base = resolved(options, client);
|
|
1013
|
+
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)
|
|
1014
|
+
return { changes: [], observations: [], dirs: [], result: { client, status: 'unchanged', codes: ['statistics_disabled'] } };
|
|
1015
|
+
}
|
|
1016
|
+
const paths = statisticsPolicy(options, client, enabled);
|
|
1017
|
+
if (enabled) {
|
|
1018
|
+
try {
|
|
1019
|
+
assertPrivateStatePath(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
|
|
1020
|
+
assertPrivateStatePath(join(paths.stateDirectory, STATISTICS_CONFIG_FILE));
|
|
1021
|
+
}
|
|
1022
|
+
catch {
|
|
1023
|
+
fail('private_directory_permissions');
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
if (states.has(paths.stateDirectory))
|
|
1027
|
+
fail('statistics_shared_state');
|
|
1028
|
+
states.add(paths.stateDirectory);
|
|
1029
|
+
const observations = [], changes = [];
|
|
1030
|
+
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; };
|
|
1031
|
+
const policy = snap(paths.policyPath);
|
|
1032
|
+
if (enabled) {
|
|
1033
|
+
snap(paths.mcpPath, false);
|
|
1034
|
+
const routingReceipt = snap(join(paths.privateDir, 'setup-ownership.json'));
|
|
1035
|
+
if (routingReceipt.before === null)
|
|
1036
|
+
fail('statistics_requires_setup');
|
|
1037
|
+
ownership(json(routingReceipt.before), client);
|
|
1038
|
+
}
|
|
1039
|
+
const hooks = snap(paths.hooksPath, false), config = snap(join(paths.stateDirectory, STATISTICS_CONFIG_FILE));
|
|
1040
|
+
let receipt, unreadableReceipt = false;
|
|
1041
|
+
try {
|
|
1042
|
+
receipt = snap(join(paths.privateDir, STATISTICS_OWNERSHIP_FILE));
|
|
1043
|
+
}
|
|
1044
|
+
catch (error) {
|
|
1045
|
+
if (enabled || safeCode(error) !== 'private_file_permissions')
|
|
1046
|
+
throw error;
|
|
1047
|
+
unreadableReceipt = true;
|
|
1048
|
+
}
|
|
1049
|
+
if (!enabled && !unreadableReceipt && receipt.before === null && config.before === null)
|
|
1050
|
+
return { changes, observations, dirs: [], result: { client, status: 'unchanged', codes: ['statistics_disabled'] } };
|
|
1051
|
+
const key = enabled ? snap(join(paths.stateDirectory, STATISTICS_KEY_FILE)) : undefined;
|
|
1052
|
+
const value = json(hooks.before), originalHooks = structuredClone(value), state = statisticsConfig(config);
|
|
1053
|
+
let old, invalidReceipt = unreadableReceipt;
|
|
1054
|
+
if (receipt && receipt.before !== null)
|
|
1055
|
+
try {
|
|
1056
|
+
old = statisticsOwner(json(receipt.before), client);
|
|
1057
|
+
}
|
|
1058
|
+
catch (error) {
|
|
1059
|
+
if (enabled)
|
|
1060
|
+
throw error;
|
|
1061
|
+
invalidReceipt = true;
|
|
1062
|
+
}
|
|
1063
|
+
if (old && old.state_directory !== paths.stateDirectory) {
|
|
1064
|
+
if (enabled)
|
|
1065
|
+
fail('statistics_ownership_invalid');
|
|
1066
|
+
old = undefined;
|
|
1067
|
+
invalidReceipt = true;
|
|
1068
|
+
}
|
|
1069
|
+
let modified = invalidReceipt;
|
|
1070
|
+
if (old)
|
|
1071
|
+
for (const [event, entry] of Object.entries(old.hooks)) {
|
|
1072
|
+
const list = statisticEntries(value, event), matches = list.filter(v => isDeepStrictEqual(v, entry));
|
|
1073
|
+
if (!matches.length) {
|
|
1074
|
+
if (enabled)
|
|
1075
|
+
fail('managed_hook_changed');
|
|
1076
|
+
if (list.some(possibleStatisticsObserver))
|
|
1077
|
+
modified = true;
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
if (matches.length > 1) {
|
|
1081
|
+
if (enabled)
|
|
1082
|
+
fail('managed_hook_changed');
|
|
1083
|
+
modified = true;
|
|
1084
|
+
continue;
|
|
1085
|
+
}
|
|
1086
|
+
for (let n = list.length - 1; n >= 0; n--)
|
|
1087
|
+
if (isDeepStrictEqual(list[n], entry))
|
|
1088
|
+
list.splice(n, 1);
|
|
1089
|
+
}
|
|
1090
|
+
if (enabled) {
|
|
1091
|
+
if (key.before === null) {
|
|
1092
|
+
try {
|
|
1093
|
+
lstatSync(join(paths.stateDirectory, STATISTICS_DB_FILE));
|
|
1094
|
+
fail('statistics_key_missing');
|
|
1095
|
+
}
|
|
1096
|
+
catch (error) {
|
|
1097
|
+
if (error.code !== 'ENOENT')
|
|
1098
|
+
throw error;
|
|
1099
|
+
}
|
|
1100
|
+
key.after = randomBytes(32).toString('hex') + '\n';
|
|
1101
|
+
}
|
|
1102
|
+
else if (!/^[a-f0-9]{64}\n$/.test(key.before))
|
|
1103
|
+
fail('statistics_key_missing');
|
|
1104
|
+
state.enabled_clients = [...new Set([...state.enabled_clients, client])];
|
|
1105
|
+
if (client === 'codex')
|
|
1106
|
+
clearCodexMetadata(state, client);
|
|
1107
|
+
if (client === 'codex' && options.codexNativeMetadata) {
|
|
1108
|
+
if (state.codex_home !== undefined && state.codex_home !== paths.dir)
|
|
1109
|
+
fail('statistics_config_invalid');
|
|
1110
|
+
state.codex_native_metadata = true;
|
|
1111
|
+
state.codex_home = paths.dir;
|
|
1112
|
+
}
|
|
1113
|
+
const root = resolve(options.packageRoot ?? join(dirname(fileURLToPath(import.meta.url)), '..', ...(import.meta.url.includes('/dist/src/') ? ['..'] : [])));
|
|
1114
|
+
const entries = statisticsHooks(root, client, paths.policyPath);
|
|
1115
|
+
for (const [event, entry] of Object.entries(entries)) {
|
|
1116
|
+
const list = statisticEntries(value, event, true);
|
|
1117
|
+
if (list.some(possibleStatisticsObserver))
|
|
1118
|
+
fail('statistics_observers_present');
|
|
1119
|
+
list.push(entry);
|
|
1120
|
+
}
|
|
1121
|
+
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') });
|
|
1122
|
+
}
|
|
1123
|
+
else {
|
|
1124
|
+
state.enabled_clients = state.enabled_clients.filter(c => c !== client);
|
|
1125
|
+
clearCodexMetadata(state, client);
|
|
1126
|
+
if (receipt)
|
|
1127
|
+
receipt.after = invalidReceipt ? receipt.before : null;
|
|
1128
|
+
}
|
|
1129
|
+
config.after = serializeStatisticsConfig(state);
|
|
1130
|
+
if (!isDeepStrictEqual(value, originalHooks))
|
|
1131
|
+
hooks.after = stringify(value);
|
|
1132
|
+
for (const item of [config, ...(key ? [key] : []), hooks, ...(receipt ? [receipt] : [])])
|
|
1133
|
+
if (item.before !== item.after)
|
|
1134
|
+
changes.push(item);
|
|
1135
|
+
const codes = [enabled ? 'statistics_enabled' : 'statistics_disabled', ...(modified ? ['statistics_observers_retained_modified'] : []), ...(enabled && client === 'codex' ? ['requires_hook_review'] : []), ...(enabled ? ['mcp_restart_required'] : [])];
|
|
1136
|
+
return { changes, observations, dirs: [], result: { client, status: changes.length ? 'configured' : 'unchanged', codes, ...(enabled && client === 'codex' ? { requires_hook_review: true } : {}) } };
|
|
1137
|
+
}
|
|
1138
|
+
catch (error) {
|
|
1139
|
+
return { changes: [], observations: [], dirs: [], result: errorResult(client, error) };
|
|
1140
|
+
}
|
|
1141
|
+
});
|
|
1142
|
+
if (enabled && plans.some(p => p.result.status === 'error'))
|
|
1143
|
+
return { status: 'partial', clients: plans.map(p => p.result.status === 'error' ? p.result : { ...p.result, status: 'skipped', codes: ['other_host_validation_failed'] }) };
|
|
1144
|
+
return execute(options, false, undefined, plans);
|
|
1145
|
+
}
|
|
1146
|
+
/** Snapshot view; no runtime, credentials, provider, budget gate or state creation. */
|
|
1147
|
+
export function showStatistics(options = {}, today = false) {
|
|
1148
|
+
const clients = options.clients ?? ['codex', 'claude'];
|
|
1149
|
+
if (process.platform === 'win32')
|
|
1150
|
+
return { clients: clients.map(client => ({ client, status: 'statistics_platform_unsupported', collection: 'disabled' })) };
|
|
1151
|
+
return { clients: clients.map(client => { try {
|
|
1152
|
+
const path = statisticsPolicy(options, client);
|
|
1153
|
+
return { client, ...readStatistics({ stateDirectory: path.stateDirectory }, { client, today }) };
|
|
1154
|
+
}
|
|
1155
|
+
catch (error) {
|
|
1156
|
+
return { client, status: safeCode(error), collection: 'disabled' };
|
|
1157
|
+
} }) };
|
|
1158
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** The callback is supplied by the statistics store and uses its private installation key. */
|
|
2
|
+
export type CodexBridgeHash = (domain: 'session' | 'task_path', client: 'codex', value: string) => string;
|
|
3
|
+
export type CodexBridge = {
|
|
4
|
+
status: 'matched';
|
|
5
|
+
parentSessionHash: string;
|
|
6
|
+
taskPathHash: string;
|
|
7
|
+
} | {
|
|
8
|
+
status: 'unknown';
|
|
9
|
+
reason: 'metadata_unavailable';
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Read exactly one native child metadata row. No transcript, model, or effort is read.
|
|
13
|
+
* Existing SQLite SHM read marks can change during a read; files are never repaired or created intentionally.
|
|
14
|
+
* The caller must pass only its explicit operator-selected home, never Hook-supplied paths.
|
|
15
|
+
* Pre/post identity checks cannot eliminate a malicious same-account path replacement race.
|
|
16
|
+
*/
|
|
17
|
+
export declare function resolveCodexStatisticsBridge(options: {
|
|
18
|
+
codexHome: string;
|
|
19
|
+
childId: string;
|
|
20
|
+
parentId: string;
|
|
21
|
+
hash: CodexBridgeHash;
|
|
22
|
+
env?: NodeJS.ProcessEnv;
|
|
23
|
+
}): CodexBridge;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
3
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
4
|
+
import { parse } from 'smol-toml';
|
|
5
|
+
import { assertNoRedirectedAncestors, readRegularFile } from './files.js';
|
|
6
|
+
const unknown = { status: 'unknown', reason: 'metadata_unavailable' };
|
|
7
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
8
|
+
const pathPattern = /^\/root(?:\/[a-z0-9_]+)+$/;
|
|
9
|
+
const own = (s) => typeof process.getuid === 'function' && s.uid === process.getuid();
|
|
10
|
+
function safeFile(path) {
|
|
11
|
+
assertNoRedirectedAncestors(path);
|
|
12
|
+
const s = lstatSync(path);
|
|
13
|
+
if (!s.isFile() || s.isSymbolicLink() || s.nlink !== 1 || !own(s) || (s.mode & 0o022))
|
|
14
|
+
throw new Error('unsafe');
|
|
15
|
+
return { dev: s.dev, ino: s.ino };
|
|
16
|
+
}
|
|
17
|
+
function same(a, b) { return a.dev === b.dev && a.ino === b.ino; }
|
|
18
|
+
function optionalFile(path) {
|
|
19
|
+
try {
|
|
20
|
+
return safeFile(path);
|
|
21
|
+
}
|
|
22
|
+
catch (e) {
|
|
23
|
+
if (e.code === 'ENOENT')
|
|
24
|
+
return null;
|
|
25
|
+
throw e;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function header(path, identity) {
|
|
29
|
+
const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
|
|
30
|
+
try {
|
|
31
|
+
const s = fstatSync(fd), bytes = Buffer.alloc(20);
|
|
32
|
+
if (!s.isFile() || s.nlink !== 1 || !own(s) || (s.mode & 0o022) || !same(identity, s) || readSync(fd, bytes, 0, 20, 0) !== 20 ||
|
|
33
|
+
bytes.subarray(0, 16).toString('binary') !== 'SQLite format 3\0' || bytes[18] !== bytes[19] || ![1, 2].includes(bytes[18]))
|
|
34
|
+
throw new Error('unsafe');
|
|
35
|
+
return bytes[18];
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
closeSync(fd);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function canonicalPath(value) {
|
|
42
|
+
return typeof value === 'string' && value.length <= 1024 && pathPattern.test(value) && !value.split('/').slice(2).includes('root');
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Read exactly one native child metadata row. No transcript, model, or effort is read.
|
|
46
|
+
* Existing SQLite SHM read marks can change during a read; files are never repaired or created intentionally.
|
|
47
|
+
* The caller must pass only its explicit operator-selected home, never Hook-supplied paths.
|
|
48
|
+
* Pre/post identity checks cannot eliminate a malicious same-account path replacement race.
|
|
49
|
+
*/
|
|
50
|
+
export function resolveCodexStatisticsBridge(options) {
|
|
51
|
+
try {
|
|
52
|
+
if (process.platform === 'win32' || typeof options?.hash !== 'function' || !uuid.test(options.childId) || !uuid.test(options.parentId) ||
|
|
53
|
+
typeof options.codexHome !== 'string' || !isAbsolute(options.codexHome) || resolve(options.codexHome) !== options.codexHome ||
|
|
54
|
+
(options.env ?? process.env).CODEX_SQLITE_HOME)
|
|
55
|
+
return unknown;
|
|
56
|
+
const home = options.codexHome;
|
|
57
|
+
assertNoRedirectedAncestors(home);
|
|
58
|
+
const directory = lstatSync(home);
|
|
59
|
+
if (!directory.isDirectory() || !own(directory) || (directory.mode & 0o022))
|
|
60
|
+
return unknown;
|
|
61
|
+
const config = join(home, 'config.toml'), configIdentity = optionalFile(config);
|
|
62
|
+
let configBytes;
|
|
63
|
+
if (configIdentity) {
|
|
64
|
+
configBytes = readRegularFile(config, { maxBytes: 1024 * 1024 });
|
|
65
|
+
const parsed = parse(new TextDecoder('utf-8', { fatal: true }).decode(configBytes));
|
|
66
|
+
if (Object.hasOwn(parsed, 'sqlite_home') || !same(configIdentity, safeFile(config)))
|
|
67
|
+
return unknown;
|
|
68
|
+
}
|
|
69
|
+
const dbPath = join(home, 'state_5.sqlite'), dbIdentity = safeFile(dbPath);
|
|
70
|
+
const walPath = `${dbPath}-wal`, shmPath = `${dbPath}-shm`, journalPath = `${dbPath}-journal`;
|
|
71
|
+
const wal = optionalFile(walPath), shm = optionalFile(shmPath);
|
|
72
|
+
if (optionalFile(journalPath))
|
|
73
|
+
return unknown;
|
|
74
|
+
const mode = header(dbPath, dbIdentity);
|
|
75
|
+
if ((mode === 2 && (!wal || !shm)) || (mode === 1 && (wal || shm)))
|
|
76
|
+
return unknown;
|
|
77
|
+
let db;
|
|
78
|
+
let row;
|
|
79
|
+
try {
|
|
80
|
+
db = new DatabaseSync(dbPath, { readOnly: true, allowExtension: false });
|
|
81
|
+
db.exec('PRAGMA query_only = ON; PRAGMA trusted_schema = OFF');
|
|
82
|
+
const schema = db.prepare("SELECT type FROM sqlite_schema WHERE name = 'threads'").all();
|
|
83
|
+
if (schema.length !== 1 || schema[0].type !== 'table')
|
|
84
|
+
return unknown;
|
|
85
|
+
const columns = db.prepare('PRAGMA table_info(threads)').all();
|
|
86
|
+
for (const [name, pk, notnull] of [['id', 1, 0], ['source', 0, 1], ['agent_path', 0, 0]]) {
|
|
87
|
+
const found = columns.filter(c => c.name === name);
|
|
88
|
+
if (found.length !== 1 || found[0].type !== 'TEXT' || found[0].pk !== pk || found[0].notnull !== notnull)
|
|
89
|
+
return unknown;
|
|
90
|
+
}
|
|
91
|
+
const rows = db.prepare('SELECT id, source, agent_path FROM threads WHERE id = ? LIMIT 2').all(options.childId);
|
|
92
|
+
if (rows.length !== 1)
|
|
93
|
+
return unknown;
|
|
94
|
+
row = rows[0];
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
db?.close();
|
|
98
|
+
}
|
|
99
|
+
const directoryAfter = lstatSync(home);
|
|
100
|
+
if (!same(dbIdentity, safeFile(dbPath)) || !same(directory, directoryAfter) || !own(directoryAfter) || (directoryAfter.mode & 0o022) ||
|
|
101
|
+
(wal ? !same(wal, safeFile(walPath)) : optionalFile(walPath) !== null) ||
|
|
102
|
+
(shm ? !same(shm, safeFile(shmPath)) : optionalFile(shmPath) !== null) || optionalFile(journalPath) ||
|
|
103
|
+
(configIdentity ? !same(configIdentity, safeFile(config)) || !configBytes.equals(readRegularFile(config, { maxBytes: 1024 * 1024 })) : optionalFile(config) !== null))
|
|
104
|
+
return unknown;
|
|
105
|
+
if (!row || row.id !== options.childId || typeof row.source !== 'string' || row.source.length > 65536 || !canonicalPath(row.agent_path))
|
|
106
|
+
return unknown;
|
|
107
|
+
const source = JSON.parse(row.source);
|
|
108
|
+
if (!source || typeof source !== 'object')
|
|
109
|
+
return unknown;
|
|
110
|
+
const spawn = source.subagent?.thread_spawn;
|
|
111
|
+
if (!spawn || spawn.parent_thread_id !== options.parentId || spawn.agent_path !== row.agent_path)
|
|
112
|
+
return unknown;
|
|
113
|
+
const parentSessionHash = options.hash('session', 'codex', options.parentId), taskPathHash = options.hash('task_path', 'codex', row.agent_path);
|
|
114
|
+
if (!/^[a-f0-9]{64}$/.test(parentSessionHash) || !/^[a-f0-9]{64}$/.test(taskPathHash))
|
|
115
|
+
return unknown;
|
|
116
|
+
return { status: 'matched', parentSessionHash, taskPathHash };
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
return unknown;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { isAbsolute, join } from 'node:path';
|
|
2
|
+
import { assertPrivateStatePath, readRegularFile } from './files.js';
|
|
3
|
+
import { isRecord } from './types.js';
|
|
4
|
+
/** Metadata-only policy reader; deliberately has no provider or credential dependency. */
|
|
5
|
+
export function statisticsState(path) {
|
|
6
|
+
try {
|
|
7
|
+
assertPrivateStatePath(path);
|
|
8
|
+
const value = JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 4096 }).toString('utf8'));
|
|
9
|
+
if (!isRecord(value) || ![1, 2].includes(value.schema_version) || value.kind !== 'aptly-auto-hook' || value.issuer !== 'operator_installation' || typeof value.enabled !== 'boolean' || !['defaults', 'advisory'].includes(String(value.mode)) || typeof value.state_directory !== 'string' || !isAbsolute(value.state_directory))
|
|
10
|
+
return null;
|
|
11
|
+
const keys = ['schema_version', 'kind', 'mode', 'issuer', 'enabled', 'state_directory', ...(value.schema_version === 2 ? ['transmission'] : [])];
|
|
12
|
+
if (Object.keys(value).length !== keys.length || Object.keys(value).some(k => !keys.includes(k)) || value.schema_version === 2 && !['none', 'description', 'excerpt', 'unselected'].includes(String(value.transmission)))
|
|
13
|
+
return null;
|
|
14
|
+
assertPrivateStatePath(join(value.state_directory, '.stats-check'));
|
|
15
|
+
return value.state_directory;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|