aptly 0.1.12 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/bin/aptly.js +21 -4
  2. package/dist/src/automatic-hook.d.ts +7 -0
  3. package/dist/src/automatic-hook.js +33 -15
  4. package/dist/src/cli-help.js +7 -6
  5. package/dist/src/context-retry.d.ts +10 -0
  6. package/dist/src/context-retry.js +16 -3
  7. package/dist/src/core.d.ts +2 -0
  8. package/dist/src/core.js +39 -35
  9. package/dist/src/doctor.d.ts +87 -0
  10. package/dist/src/doctor.js +182 -0
  11. package/dist/src/files.js +2 -2
  12. package/dist/src/host-paths.d.ts +10 -0
  13. package/dist/src/host-paths.js +15 -0
  14. package/dist/src/query-snapshot.d.ts +17 -0
  15. package/dist/src/query-snapshot.js +112 -0
  16. package/dist/src/server.js +2 -0
  17. package/dist/src/setup.d.ts +8 -5
  18. package/dist/src/setup.js +248 -60
  19. package/dist/src/stable-runtime.d.ts +61 -0
  20. package/dist/src/stable-runtime.js +694 -0
  21. package/dist/src/statistics.d.ts +48 -2
  22. package/dist/src/statistics.js +87 -6
  23. package/dist/src/version.d.ts +1 -1
  24. package/dist/src/version.js +1 -1
  25. package/docs/guide/en/advanced.md +6 -0
  26. package/docs/guide/en/configuration.md +27 -1
  27. package/docs/guide/en/installation.md +2 -2
  28. package/docs/guide/en/statistics.md +4 -0
  29. package/docs/guide/en/transmission.md +7 -5
  30. package/docs/guide/en/troubleshooting.md +4 -2
  31. package/docs/guide/en.md +2 -0
  32. package/docs/guide/ja/advanced.md +6 -0
  33. package/docs/guide/ja/configuration.md +27 -1
  34. package/docs/guide/ja/installation.md +2 -2
  35. package/docs/guide/ja/statistics.md +4 -0
  36. package/docs/guide/ja/transmission.md +7 -5
  37. package/docs/guide/ja/troubleshooting.md +4 -2
  38. package/docs/guide/ja.md +2 -0
  39. package/docs/guide/ko/advanced.md +6 -0
  40. package/docs/guide/ko/configuration.md +27 -1
  41. package/docs/guide/ko/installation.md +2 -2
  42. package/docs/guide/ko/statistics.md +4 -0
  43. package/docs/guide/ko/transmission.md +7 -5
  44. package/docs/guide/ko/troubleshooting.md +4 -2
  45. package/docs/guide/ko.md +2 -0
  46. package/docs/guide/zh-CN/advanced.md +6 -0
  47. package/docs/guide/zh-CN/configuration.md +27 -1
  48. package/docs/guide/zh-CN/installation.md +2 -2
  49. package/docs/guide/zh-CN/statistics.md +4 -0
  50. package/docs/guide/zh-CN/transmission.md +7 -5
  51. package/docs/guide/zh-CN/troubleshooting.md +4 -2
  52. package/docs/guide/zh-CN.md +2 -0
  53. package/package.json +1 -1
@@ -0,0 +1,182 @@
1
+ /** Read-only local observations, deliberately separate from legacy report schema v1. */
2
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { parse } from 'smol-toml';
5
+ import { resolveHostPaths } from './host-paths.js';
6
+ import { validateStableRegistration, stableRuntimeLimits, stableReference } from './stable-runtime.js';
7
+ import { QuerySnapshot } from './query-snapshot.js';
8
+ import { queryAutomaticHookPolicy, effectiveTransmission } from './automatic-hook.js';
9
+ import { validateLedgerState } from './core.js';
10
+ import { isRecord } from './types.js';
11
+ import { VERSION } from './version.js';
12
+ import { CODEX_HOME_POLICY_SOURCE } from './policy-source.js';
13
+ export const DOCTOR_LEDGER_SCAN_LIMIT = 4 * 1024 * 1024;
14
+ const unknown = 'unknown';
15
+ function fail(code) { throw new Error(code); }
16
+ const version = (value) => typeof value === 'string' && /^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/.test(value) ? value : null;
17
+ const json = (bytes) => { const value = JSON.parse(bytes.toString('utf8')); if (!isRecord(value))
18
+ fail('invalid_configuration'); return value; };
19
+ const observationCode = (error) => error instanceof Error && error.message === 'concurrent_configuration_change' ? 'changed_during_observation' : error instanceof Error && ['invalid_ledger', 'invalid_outcome', 'invalid_usage'].includes(error.message) ? 'invalid_ledger' : error instanceof Error && ['stable_runtime_unverified', 'registered_node_missing', 'registered_package_missing', 'invalid_configuration', 'invalid_policy', 'invalid_policy_binding', 'missing_hook_registration', 'invalid_ledger_binding'].includes(error.message) ? error.message : 'configuration_observation_failed';
20
+ /** No lock, load, state initialization, provider or filesystem mutation. */
21
+ export function observeDoctorLedger(path, snapshot) {
22
+ const bytes = snapshot.size(path, { privateFile: true, singleLink: true });
23
+ const base = { bytes, scan_limit_bytes: DOCTOR_LEDGER_SCAN_LIMIT, write_timing: 'not_measured', counts: null };
24
+ if (bytes === null)
25
+ return { ...base, status: 'absent', history: unknown };
26
+ if (bytes > DOCTOR_LEDGER_SCAN_LIMIT)
27
+ return { ...base, status: 'scan_skipped_size_limit', history: unknown };
28
+ const state = JSON.parse(snapshot.read(path, { privateFile: true, singleLink: true, maxBytes: DOCTOR_LEDGER_SCAN_LIMIT }).toString('utf8'));
29
+ validateLedgerState(state);
30
+ const records = Object.values(state.requests);
31
+ return { ...base, status: 'validated_bounded_snapshot', counts: { total: records.length, complete: records.filter(r => r.state === 'complete').length, unknown: records.filter(r => r.state === 'unknown').length } };
32
+ }
33
+ function directNodeShape(entry) {
34
+ return typeof entry.command === 'string' && isAbsolute(entry.command) && ['node', 'node.exe'].includes(basename(entry.command).toLowerCase()) && Array.isArray(entry.args) && entry.args.length === 1 && typeof entry.args[0] === 'string' && isAbsolute(entry.args[0]) && /(?:^|[\\/])(?:dist[\\/]src[\\/]server\.js|src[\\/]server\.ts)$/.test(entry.args[0]) && !Object.hasOwn(entry, 'url');
35
+ }
36
+ function standardEntry(entry) {
37
+ return entry.command === process.execPath && Array.isArray(entry.args) && entry.args.length === 1 && typeof entry.args[0] === 'string' && isAbsolute(entry.args[0]) && /(?:^|[\\/])(?:dist[\\/]src[\\/]server\.js|src[\\/]server\.ts)$/.test(entry.args[0]) && !Object.hasOwn(entry, 'url');
38
+ }
39
+ function packageObservation(entry, snapshot) {
40
+ const server = entry.args[0], root = server.endsWith('.ts') ? dirname(dirname(server)) : dirname(dirname(dirname(server)));
41
+ // Check file kind/identity only; never execute this file or recursively follow its imports.
42
+ if (!snapshot.track(server))
43
+ return { status: 'target_missing', version: null };
44
+ const bytes = snapshot.read(join(root, 'package.json'), { maxBytes: 65536 });
45
+ if (!bytes)
46
+ return { status: 'metadata_absent', version: null };
47
+ const meta = json(bytes), v = version(meta.version);
48
+ if (meta.name !== 'aptly')
49
+ return { status: 'unrecognized_package', version: null };
50
+ return { status: v ? 'observed_numeric_release' : 'unsupported_version_metadata', version: v };
51
+ }
52
+ function hookObservation(bytes) {
53
+ if (!bytes)
54
+ return 'absent';
55
+ const config = json(bytes);
56
+ if (config.hooks !== undefined && !isRecord(config.hooks))
57
+ fail('invalid_configuration');
58
+ const pre = isRecord(config.hooks) ? config.hooks.PreToolUse : undefined;
59
+ if (pre === undefined)
60
+ return 'absent';
61
+ if (!Array.isArray(pre))
62
+ fail('invalid_configuration');
63
+ return pre.some(item => isRecord(item) && Array.isArray(item.hooks) && item.hooks.some(h => isRecord(h) && h.type === 'mcp_tool' && h.server === 'aptly' && h.tool === 'route_spawn_hook')) ? 'static_registration_present' : 'not_observed';
64
+ }
65
+ export function collectDoctor(options = {}) {
66
+ const env = options.env ?? process.env;
67
+ const clients = (options.clients ?? ['codex', 'claude']).map(client => {
68
+ const snapshot = new QuerySnapshot(), started = performance.now();
69
+ const base = { client, selected_home_source: (client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR) ? 'override' : 'default', connected_mcp_version: unknown, hook_trust: unknown, hook_execution: unknown, restart_required: unknown, retry_ticket_usage: unknown, credential_validity: unknown };
70
+ try {
71
+ const paths = resolveHostPaths(options, client), bytes = snapshot.read(paths.mcpPath, { maxBytes: 256 * 1024 });
72
+ const config = bytes ? (client === 'codex' ? parse(bytes.toString('utf8')) : json(bytes)) : {};
73
+ const servers = config[client === 'codex' ? 'mcp_servers' : 'mcpServers'];
74
+ if (servers !== undefined && !isRecord(servers))
75
+ fail('invalid_configuration');
76
+ const entry = isRecord(servers) ? servers.aptly : undefined;
77
+ if (entry === undefined) {
78
+ if (snapshot.read(join(paths.privateDir, 'setup-ownership.json'), { privateFile: true, maxBytes: 65536 }))
79
+ fail('invalid_configuration');
80
+ snapshot.verify();
81
+ return { ...base, status: 'complete', registration: 'unconfigured' };
82
+ }
83
+ if (!isRecord(entry) || (entry.env !== undefined && (!isRecord(entry.env) || Object.values(entry.env).some(v => typeof v !== 'string'))))
84
+ fail('invalid_configuration');
85
+ if (entry.env_vars !== undefined && (!Array.isArray(entry.env_vars) || entry.env_vars.length > 256 || entry.env_vars.some(v => typeof v !== 'string')))
86
+ fail('invalid_configuration');
87
+ const settings = isRecord(entry.env) ? entry.env : {}, forwarded = Array.isArray(entry.env_vars) ? entry.env_vars : [];
88
+ const permitted = (key) => client === 'claude' || forwarded.includes(key);
89
+ // A permitted passthrough is a future host binding, not evidence from this terminal.
90
+ const setting = (key) => Object.hasOwn(settings, key) ? settings[key] : undefined;
91
+ if (directNodeShape(entry)) {
92
+ if (!snapshot.track(entry.command))
93
+ fail('registered_node_missing');
94
+ if (!snapshot.track(entry.args[0]))
95
+ fail('registered_package_missing');
96
+ }
97
+ const reference = stableReference(entry, { home: options.home });
98
+ if (reference) {
99
+ snapshot.read(reference.command, { privateFile: true, maxBytes: 65536 });
100
+ snapshot.read(join(reference.runtimeRoot, 'bootstrap.cjs'), { privateFile: true, maxBytes: 65536 });
101
+ snapshot.read(join(reference.runtimeRoot, 'manifest.json'), { privateFile: true, maxBytes: stableRuntimeLimits.manifestBytes });
102
+ snapshot.read(join(reference.runtimeRoot, 'payload/package.json'), { privateFile: true, maxBytes: 65536 });
103
+ }
104
+ const stable = validateStableRegistration(entry, { home: options.home, metadataOnly: true });
105
+ const candidate = standardEntry(entry), stableVersion = stable ? version(stable.version) : null;
106
+ const target = stable ? { status: stableVersion ? 'observed_numeric_release' : 'unsupported_version_metadata', version: stableVersion } : candidate ? packageObservation(entry, snapshot) : { status: 'custom_or_remote_launcher', version: null };
107
+ const standard = !!stable || (candidate && ['observed_numeric_release', 'unsupported_version_metadata'].includes(target.status));
108
+ if (target.status === 'target_missing')
109
+ fail('registered_package_missing');
110
+ const raw = setting('APTLY_HOOK_POLICY_PATH');
111
+ let source = 'unconfigured', policyStatus = 'unconfigured', transmission = null;
112
+ if (!standard) {
113
+ source = raw === CODEX_HOME_POLICY_SOURCE ? 'codex_home' : raw !== undefined ? 'fixed' : 'unconfigured';
114
+ policyStatus = 'custom_launcher_unobserved';
115
+ }
116
+ else if (raw !== undefined) {
117
+ if (typeof raw !== 'string')
118
+ fail('invalid_policy_binding');
119
+ let policyPath;
120
+ if (raw === CODEX_HOME_POLICY_SOURCE) {
121
+ source = 'codex_home';
122
+ if (standard && (client !== 'codex' || Object.hasOwn(settings, 'CODEX_HOME') || !forwarded.includes('CODEX_HOME')))
123
+ fail('invalid_policy_binding');
124
+ policyPath = join(paths.dir, 'aptly', 'auto-policy.json');
125
+ }
126
+ else {
127
+ source = 'fixed';
128
+ if (!isAbsolute(raw))
129
+ fail('invalid_policy_binding');
130
+ policyPath = resolve(raw);
131
+ }
132
+ const loaded = queryAutomaticHookPolicy(policyPath, snapshot);
133
+ if (loaded.availability !== 'valid' || !loaded.policy)
134
+ fail('invalid_policy');
135
+ policyStatus = loaded.policy.enabled ? 'enabled' : 'disabled';
136
+ transmission = effectiveTransmission(loaded.policy);
137
+ }
138
+ else if (permitted('APTLY_HOOK_POLICY_PATH')) {
139
+ source = 'runtime_value_unobserved';
140
+ policyStatus = 'runtime_value_unobserved';
141
+ }
142
+ const hook = hookObservation(snapshot.read(paths.hooksPath, { maxBytes: 256 * 1024 }));
143
+ if (standard && policyStatus === 'enabled' && hook !== 'static_registration_present')
144
+ fail('missing_hook_registration');
145
+ const ledgerPath = setting('ROUTER_LEDGER_PATH');
146
+ let ledger = { status: 'runtime_value_unobserved', counts: null, write_timing: 'not_measured' };
147
+ if (standard && ledgerPath !== undefined) {
148
+ if (typeof ledgerPath !== 'string' || !isAbsolute(ledgerPath))
149
+ fail('invalid_ledger_binding');
150
+ try {
151
+ ledger = observeDoctorLedger(ledgerPath, snapshot);
152
+ }
153
+ catch (error) {
154
+ if (error instanceof SyntaxError)
155
+ fail('invalid_ledger');
156
+ throw error;
157
+ }
158
+ }
159
+ else if (!standard)
160
+ ledger = { status: 'custom_launcher_unobserved', counts: null, write_timing: 'not_measured' };
161
+ else if (!permitted('ROUTER_LEDGER_PATH')) {
162
+ if (setting('ROUTER_PROVIDER') === 'decisions')
163
+ fail('invalid_ledger_binding');
164
+ ledger = { status: 'not_declared', counts: null, write_timing: 'not_measured' };
165
+ }
166
+ snapshot.verify();
167
+ return { ...base, status: 'complete', ...(stable && stable.version !== VERSION ? { stable_snapshot_outdated: true, recovery: [`aptly setup --client ${client} --migrate-launcher${process.platform === 'win32' ? '' : ' --launcher stable'} --dry-run`] } : {}), registration: stable ? 'stable_runtime_registration' : standard ? 'standard_node_registration' : 'custom_or_remote_launcher', registered_package: target, policy: { source_kind: source, status: policyStatus, transmission }, hook_registration: hook, credential_reference: settings.APTLY_SECRET_BACKEND === 'os' ? 'os_reference' : Object.hasOwn(settings, 'OPENAI_API_KEY') ? 'inline_environment_present' : permitted('OPENAI_API_KEY') ? 'runtime_environment_permitted' : 'not_declared', ledger: { ...ledger, diagnostic_scan_ms: Math.max(0, performance.now() - started), timing_scope: 'full_client_observation_and_rechecks' } };
168
+ }
169
+ catch (error) {
170
+ // A changed observation takes precedence over a parse/validation failure.
171
+ try {
172
+ snapshot.verify();
173
+ }
174
+ catch (changed) {
175
+ if (changed instanceof Error && changed.message === 'concurrent_configuration_change')
176
+ error = changed;
177
+ }
178
+ return { ...base, status: 'partial', code: observationCode(error), ...(['stable_runtime_unverified', 'registered_node_missing', 'registered_package_missing'].includes(observationCode(error)) ? { recovery: [`aptly setup --client ${client} --migrate-launcher${process.platform === 'win32' ? '' : ' --launcher stable'} --dry-run`] } : {}) };
179
+ }
180
+ });
181
+ return { kind: 'aptly-doctor', schema_version: 1, status: clients.some(c => c.status === 'partial') ? 'partial' : 'complete', cli_version: VERSION, scope: 'local_configuration_snapshot', readiness: 'not_certified', clients };
182
+ }
package/dist/src/files.js CHANGED
@@ -58,7 +58,7 @@ export function readRegularFile(path, { privateFile = false, maxBytes = 65536 }
58
58
  throw new Error('unsafe_file');
59
59
  if (privateFile && process.platform === 'win32')
60
60
  assertWindowsPrivatePath(path);
61
- const buffer = Buffer.alloc(maxBytes + 1);
61
+ const buffer = Buffer.alloc(Math.min(maxBytes + 1, stat.size + 1));
62
62
  let size = 0;
63
63
  while (size < buffer.length) {
64
64
  const count = readSync(fd, buffer, size, buffer.length - size, null);
@@ -66,7 +66,7 @@ export function readRegularFile(path, { privateFile = false, maxBytes = 65536 }
66
66
  break;
67
67
  size += count;
68
68
  }
69
- if (size > maxBytes)
69
+ if (size > maxBytes || size > stat.size || fstatSync(fd).size !== stat.size)
70
70
  throw new Error('unsafe_file');
71
71
  return buffer.subarray(0, size);
72
72
  }
@@ -0,0 +1,10 @@
1
+ /** Shared CLI selection; never claims the home of a running host. */
2
+ export declare function resolveHostPaths(options: {
3
+ home?: string;
4
+ env?: NodeJS.ProcessEnv;
5
+ }, client: 'codex' | 'claude'): {
6
+ dir: string;
7
+ mcpPath: string;
8
+ hooksPath: string;
9
+ privateDir: string;
10
+ };
@@ -0,0 +1,15 @@
1
+ import { homedir } from 'node:os';
2
+ import { isAbsolute, join, resolve } from 'node:path';
3
+ import { CODEX_HOME_POLICY_SOURCE, resolvePolicySource } from './policy-source.js';
4
+ /** Shared CLI selection; never claims the home of a running host. */
5
+ export function resolveHostPaths(options, client) {
6
+ const home = resolve(options.home ?? homedir()), env = options.env ?? process.env;
7
+ const override = client === 'codex' ? env.CODEX_HOME : env.CLAUDE_CONFIG_DIR;
8
+ if (override && !isAbsolute(override))
9
+ throw new Error('relative_configuration_directory');
10
+ if (client === 'codex' && override !== undefined)
11
+ resolvePolicySource(CODEX_HOME_POLICY_SOURCE, env);
12
+ const dir = override || join(home, client === 'codex' ? '.codex' : '.claude');
13
+ const mcpPath = client === 'codex' ? join(dir, 'config.toml') : override ? join(dir, '.claude.json') : join(home, '.claude.json');
14
+ return { dir, mcpPath, hooksPath: join(dir, client === 'codex' ? 'hooks.json' : 'settings.json'), privateDir: join(dir, 'aptly') };
15
+ }
@@ -0,0 +1,17 @@
1
+ interface Options {
2
+ privateFile?: boolean;
3
+ directory?: boolean;
4
+ singleLink?: boolean;
5
+ identityOnly?: boolean;
6
+ maxBytes?: number;
7
+ }
8
+ export declare class QuerySnapshot {
9
+ private observations;
10
+ private remember;
11
+ track(path: string, options?: Options): boolean;
12
+ /** Checked size from the same observation later verified; does not read the body. */
13
+ size(path: string, options?: Options): number | null;
14
+ read(path: string, options?: Options): Buffer | null;
15
+ verify(): void;
16
+ }
17
+ export {};
@@ -0,0 +1,112 @@
1
+ /** Checked, bounded observations for read-only CLI queries; never an atomic multi-file snapshot. */
2
+ import { lstatSync, readlinkSync } from 'node:fs';
3
+ import { dirname, isAbsolute, resolve } from 'node:path';
4
+ import { assertPrivateStatePath, readRegularFile, systemAliasAllowed } from './files.js';
5
+ import { assertWindowsPrivatePath } from './windows-private.js';
6
+ function metadata(path) {
7
+ try {
8
+ const s = lstatSync(path);
9
+ if (s.isSymbolicLink() && !systemAliasAllowed(path, s, readlinkSync(path)))
10
+ throw new Error('unsafe_configuration_file');
11
+ return { dev: s.dev, ino: s.ino, mode: s.mode, uid: s.uid, gid: s.gid, nlink: s.nlink, size: s.size, mtime: s.mtimeMs, ctime: s.ctimeMs, directory: s.isDirectory() };
12
+ }
13
+ catch (error) {
14
+ if (error.code === 'ENOENT')
15
+ return null;
16
+ throw error;
17
+ }
18
+ }
19
+ function signature(value, identityOnly = false) {
20
+ if (value === null)
21
+ return 'absent';
22
+ const { dev, ino, mode, uid, gid, nlink, size, mtime, ctime, directory } = value;
23
+ return JSON.stringify(directory ? { dev, ino, mode, uid, gid, directory } : identityOnly ? { dev, ino, mode, uid, gid, nlink, directory } : { dev, ino, mode, uid, gid, nlink, size, mtime, ctime, directory });
24
+ }
25
+ export class QuerySnapshot {
26
+ observations = new Map();
27
+ remember(path, value, options = {}) {
28
+ const old = this.observations.get(path);
29
+ if (old && signature(old.metadata, old.options.identityOnly) !== signature(value, old.options.identityOnly))
30
+ throw new Error('concurrent_configuration_change');
31
+ if (!old)
32
+ this.observations.set(path, { metadata: value, options: { ...options } });
33
+ else
34
+ old.options = { ...old.options, ...options, privateFile: old.options.privateFile || options.privateFile, singleLink: old.options.singleLink || options.singleLink };
35
+ }
36
+ track(path, options = {}) {
37
+ if (typeof path !== 'string' || !isAbsolute(path))
38
+ throw new Error('unsafe_configuration_file');
39
+ path = resolve(path);
40
+ const value = metadata(path);
41
+ this.remember(path, value, options);
42
+ for (let parent = dirname(path);; parent = dirname(parent)) {
43
+ this.remember(parent, metadata(parent), { directory: true, identityOnly: true });
44
+ if (dirname(parent) === parent)
45
+ break;
46
+ }
47
+ if (value === null) {
48
+ // Missing content does not make an existing insecure private parent safe.
49
+ if (options.privateFile && !options.directory && this.observations.get(dirname(path))?.metadata !== null)
50
+ assertPrivateStatePath(path);
51
+ return false;
52
+ }
53
+ if (options.directory ? !value.directory : value.directory || (value.mode & 0o170000) !== 0o100000)
54
+ throw new Error('unsafe_configuration_file');
55
+ if (options.singleLink && !value.directory && value.nlink !== 1)
56
+ throw new Error('unsafe_configuration_file');
57
+ if (options.privateFile) {
58
+ if (options.directory) {
59
+ if (process.platform === 'win32')
60
+ assertWindowsPrivatePath(path);
61
+ else if ((value.mode & 0o077) || (process.getuid && value.uid !== process.getuid()))
62
+ throw new Error('private_directory_permissions');
63
+ }
64
+ else
65
+ assertPrivateStatePath(path);
66
+ if (!options.directory && process.platform !== 'win32' && ((value.mode & 0o077) || (process.getuid && value.uid !== process.getuid())))
67
+ throw new Error('private_file_permissions');
68
+ }
69
+ return true;
70
+ }
71
+ /** Checked size from the same observation later verified; does not read the body. */
72
+ size(path, options = {}) {
73
+ if (!this.track(path, options))
74
+ return null;
75
+ return this.observations.get(resolve(path)).metadata.size;
76
+ }
77
+ read(path, options = {}) {
78
+ if (typeof path !== 'string' || !isAbsolute(path))
79
+ throw new Error('unsafe_configuration_file');
80
+ path = resolve(path);
81
+ if (!this.track(path, options))
82
+ return null;
83
+ const bytes = readRegularFile(path, { privateFile: options.privateFile, maxBytes: options.maxBytes ?? 4 * 1024 * 1024 });
84
+ const observed = this.observations.get(path);
85
+ if (signature(observed.metadata) !== signature(metadata(path)))
86
+ throw new Error('concurrent_configuration_change');
87
+ if (observed.bytes && !observed.bytes.equals(bytes))
88
+ throw new Error('concurrent_configuration_change');
89
+ observed.bytes = bytes;
90
+ observed.options = { ...observed.options, ...options };
91
+ return bytes;
92
+ }
93
+ verify() {
94
+ for (const [path, observation] of this.observations) {
95
+ try {
96
+ if (signature(observation.metadata, observation.options.identityOnly) !== signature(metadata(path), observation.options.identityOnly))
97
+ throw new Error('concurrent_configuration_change');
98
+ if (observation.bytes) {
99
+ const bytes = readRegularFile(path, { privateFile: observation.options.privateFile, maxBytes: observation.options.maxBytes ?? 4 * 1024 * 1024 });
100
+ if (!observation.bytes.equals(bytes) || signature(observation.metadata) !== signature(metadata(path)))
101
+ throw new Error('concurrent_configuration_change');
102
+ }
103
+ }
104
+ catch (error) {
105
+ // A previously observed path becoming redirected/unsafe is an observation change.
106
+ if (error instanceof Error && ['unsafe_configuration_file', 'unsafe_path', 'unsafe_file'].includes(error.message))
107
+ throw new Error('concurrent_configuration_change');
108
+ throw error;
109
+ }
110
+ }
111
+ }
112
+ }
@@ -24,6 +24,7 @@ const observationSchema = z.object({ client: hookSchema.client.optional(), event
24
24
  const content = (result) => ({ content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
25
25
  export function createServer({ env: inputEnv = process.env } = {}) {
26
26
  const codexBound = inputEnv.APTLY_HOOK_POLICY_PATH === CODEX_HOME_POLICY_SOURCE;
27
+ const policySourceKind = codexBound ? 'codex_home' : inputEnv.APTLY_HOOK_POLICY_PATH === undefined ? 'unconfigured' : 'fixed';
27
28
  const env = { ...inputEnv, APTLY_HOOK_POLICY_PATH: resolvePolicySource(inputEnv.APTLY_HOOK_POLICY_PATH, inputEnv) };
28
29
  const { router, budget, mode, modelInfo, credentialStatus, disabledClients } = runtime(env);
29
30
  const observations = new RoutingObservations();
@@ -71,6 +72,7 @@ export function createServer({ env: inputEnv = process.env } = {}) {
71
72
  recommendation: { application: 'advisory_only', host_evidence_required: false, constraints: 'caller_declared_pins' },
72
73
  model_information: { status: modelInfo.status, refresh: 'explicit_only', account_access_verified: false }, disabled_clients: disabledClients,
73
74
  credential_status: credentialStatus,
75
+ runtime_diagnostics: { version: VERSION, policy_source_kind: policySourceKind, credential_status_observed: 'startup_snapshot', context_retries: retries.diagnostics() },
74
76
  execution_statistics: { collection: 'explicit_operator_opt_in', view: 'aptly stats', semantics: 'host_reported_model_evidence_not_user_acceptance', effective_effort: 'not_measured', usage_rollups: 'not_collected' },
75
77
  automatic_hook: { status: automatic.reason, mode: automatic.policy?.mode ?? 'disabled', transmission: automatic.policy ? effectiveTransmission(automatic.policy) : null, transmission_provenance: automatic.policy ? (automatic.policy.schema_version === 1 ? 'legacy_v1_default' : 'operator_policy_v2') : 'unavailable', host_settings_verified: false, context_tool: 'prepare_spawn_context', context_scope: 'this_process_exact_event_5_minutes', context_retry_tool: 'retry_spawn_recommendation', context_retry_limit: 1, fresh_delegation_tool: 'prepare_fresh_delegation', fresh_delegation_intent: 'caller_declared_not_verified', observation_tool: 'get_spawn_routing_observation', observation_scope: 'this_process_recent_calls', execution_observation: 'not_supported',
76
78
  guarantee: { scope: 'enabled_trusted_connected_supported_hook_only', missing_hook_detectable: false, unavailable_host_hook: 'host_controls_fallback', eligible_defaults_failure: 'deny_when_transmission_enabled', inherited_application: 'defaults_deny_advisory_feedback', caller_recovery: 'model_driven_not_guaranteed' } },
@@ -3,6 +3,7 @@ export interface SetupOptions {
3
3
  home?: string;
4
4
  env?: NodeJS.ProcessEnv;
5
5
  packageRoot?: string;
6
+ launcher?: 'stable';
6
7
  automatic?: boolean;
7
8
  clients?: Client[];
8
9
  mode?: 'defaults' | 'advisory';
@@ -73,8 +74,9 @@ export declare function prepareTransmissionReview(options?: SetupOptions & {
73
74
  candidates: TransmissionReviewCandidate[];
74
75
  apply(choice: 'keep' | TransmissionScope): SetupResult;
75
76
  };
76
- /** Read-only redacted policy state. Does not create host directories or contact a provider. */
77
+ /** Redacted policy query; aggregate status is query completion, not host readiness. */
77
78
  export declare function showTransmission(options?: SetupOptions): {
79
+ status: string;
78
80
  clients: ({
79
81
  client: Client;
80
82
  status: string;
@@ -142,7 +144,12 @@ export declare function setStatisticsCollection(enabled: boolean, options?: Setu
142
144
  }): SetupResult;
143
145
  /** Snapshot view; no runtime, credentials, provider, budget gate or state creation. */
144
146
  export declare function showStatistics(options?: SetupOptions, today?: boolean): {
147
+ status: string;
145
148
  clients: ({
149
+ client: Client;
150
+ status: string;
151
+ collection: string;
152
+ } | {
146
153
  status: string;
147
154
  scope: string;
148
155
  semantics: string;
@@ -178,10 +185,6 @@ export declare function showStatistics(options?: SetupOptions, today?: boolean):
178
185
  model_alias_scope: string;
179
186
  counts_are_lifetime: boolean;
180
187
  client: Client;
181
- } | {
182
- client: Client;
183
- status: string;
184
- collection: string;
185
188
  })[];
186
189
  };
187
190
  export {};