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.
Files changed (70) hide show
  1. package/README.en.md +10 -10
  2. package/README.ja.md +10 -10
  3. package/README.md +10 -10
  4. package/README.zh-CN.md +10 -10
  5. package/dist/bin/aptly-observe.d.ts +2 -0
  6. package/dist/bin/aptly-observe.js +66 -0
  7. package/dist/bin/aptly.js +59 -17
  8. package/dist/src/cli-help.js +18 -11
  9. package/dist/src/cli-input.d.ts +19 -1
  10. package/dist/src/cli-input.js +23 -11
  11. package/dist/src/policy-source.d.ts +3 -0
  12. package/dist/src/policy-source.js +11 -0
  13. package/dist/src/server.d.ts +1 -1
  14. package/dist/src/server.js +44 -2
  15. package/dist/src/setup.d.ts +69 -0
  16. package/dist/src/setup.js +605 -6
  17. package/dist/src/statistics-codex.d.ts +23 -0
  18. package/dist/src/statistics-codex.js +121 -0
  19. package/dist/src/statistics-policy.d.ts +2 -0
  20. package/dist/src/statistics-policy.js +20 -0
  21. package/dist/src/statistics.d.ts +90 -0
  22. package/dist/src/statistics.js +472 -0
  23. package/dist/src/transmission-review-cli.d.ts +11 -0
  24. package/dist/src/transmission-review-cli.js +35 -0
  25. package/dist/src/update-notifier.js +1 -1
  26. package/dist/src/version.d.ts +1 -1
  27. package/dist/src/version.js +1 -1
  28. package/docs/ADVISORY_USAGE.md +1 -1
  29. package/docs/DRAFT_0_1_0.md +1 -1
  30. package/docs/guide/en/advanced.md +217 -0
  31. package/docs/guide/en/benchmarks.md +32 -0
  32. package/docs/guide/en/budget.md +45 -0
  33. package/docs/guide/en/configuration.md +104 -0
  34. package/docs/guide/en/installation.md +114 -0
  35. package/docs/guide/en/routing.md +61 -0
  36. package/docs/guide/en/statistics.md +43 -0
  37. package/docs/guide/en/transmission.md +71 -0
  38. package/docs/guide/en/troubleshooting.md +99 -0
  39. package/docs/guide/en.md +80 -477
  40. package/docs/guide/ja/advanced.md +217 -0
  41. package/docs/guide/ja/benchmarks.md +32 -0
  42. package/docs/guide/ja/budget.md +45 -0
  43. package/docs/guide/ja/configuration.md +104 -0
  44. package/docs/guide/ja/installation.md +114 -0
  45. package/docs/guide/ja/routing.md +61 -0
  46. package/docs/guide/ja/statistics.md +43 -0
  47. package/docs/guide/ja/transmission.md +71 -0
  48. package/docs/guide/ja/troubleshooting.md +99 -0
  49. package/docs/guide/ja.md +80 -477
  50. package/docs/guide/ko/advanced.md +217 -0
  51. package/docs/guide/ko/benchmarks.md +32 -0
  52. package/docs/guide/ko/budget.md +45 -0
  53. package/docs/guide/ko/configuration.md +104 -0
  54. package/docs/guide/ko/installation.md +114 -0
  55. package/docs/guide/ko/routing.md +61 -0
  56. package/docs/guide/ko/statistics.md +43 -0
  57. package/docs/guide/ko/transmission.md +71 -0
  58. package/docs/guide/ko/troubleshooting.md +99 -0
  59. package/docs/guide/ko.md +80 -477
  60. package/docs/guide/zh-CN/advanced.md +217 -0
  61. package/docs/guide/zh-CN/benchmarks.md +32 -0
  62. package/docs/guide/zh-CN/budget.md +45 -0
  63. package/docs/guide/zh-CN/configuration.md +104 -0
  64. package/docs/guide/zh-CN/installation.md +114 -0
  65. package/docs/guide/zh-CN/routing.md +61 -0
  66. package/docs/guide/zh-CN/statistics.md +43 -0
  67. package/docs/guide/zh-CN/transmission.md +71 -0
  68. package/docs/guide/zh-CN/troubleshooting.md +99 -0
  69. package/docs/guide/zh-CN.md +80 -477
  70. package/package.json +3 -2
@@ -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,2 @@
1
+ /** Metadata-only policy reader; deliberately has no provider or credential dependency. */
2
+ export declare function statisticsState(path: unknown): string | null;
@@ -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
+ }
@@ -0,0 +1,90 @@
1
+ import { type Client } from './types.ts';
2
+ export declare const STATISTICS_CONFIG_FILE = "stats-config.json";
3
+ export declare const STATISTICS_KEY_FILE = "stats-key";
4
+ export declare const STATISTICS_DATABASE_FILE = "stats.sqlite";
5
+ export declare const STATISTICS_DB_FILE = "stats.sqlite";
6
+ export declare const STATISTICS_CONFIG_VERSION = 1;
7
+ export interface StatisticsConfig {
8
+ schema_version: 1;
9
+ enabled_clients: Client[];
10
+ codex_native_metadata?: boolean;
11
+ codex_home?: string;
12
+ }
13
+ export interface StatisticsOptions {
14
+ stateDirectory: string;
15
+ now?: () => number;
16
+ maxDelegations?: number;
17
+ maxChildren?: number;
18
+ }
19
+ export type StatisticsHash = (domain: 'session' | 'tool' | 'child' | 'task_path' | 'request', client: Client, value: string) => string;
20
+ export interface StatisticsBridge {
21
+ parentSessionHash: string;
22
+ taskPathHash: string;
23
+ }
24
+ export interface StatisticsRecommendation {
25
+ client: Client;
26
+ sessionId?: string;
27
+ toolUseId?: string;
28
+ requestId?: string;
29
+ disposition: 'auto' | 'advisory' | 'blocked' | 'explicit_preserved' | 'unbound';
30
+ expected?: {
31
+ profileId: string;
32
+ model: string;
33
+ effort?: string;
34
+ catalogVersion?: string;
35
+ };
36
+ }
37
+ export type StatisticsResult = {
38
+ status: 'recorded' | 'ignored' | 'unavailable';
39
+ reason?: string;
40
+ };
41
+ export declare function parseStatisticsConfig(value: unknown): StatisticsConfig | null;
42
+ export declare function serializeStatisticsConfig(value: StatisticsConfig): string;
43
+ export declare function loadStatisticsConfig(options: StatisticsOptions): StatisticsConfig | null;
44
+ export declare function statisticsHash(key: string, domain: Parameters<StatisticsHash>[0], client: Client, value: string): string;
45
+ export declare function loadStatisticsHash(options: StatisticsOptions): StatisticsHash | null;
46
+ export declare function recordStatisticsRecommendation(options: StatisticsOptions, input: StatisticsRecommendation): StatisticsResult;
47
+ export declare function observeStatistics(options: StatisticsOptions, input: {
48
+ client: Client;
49
+ event: unknown;
50
+ }, bridge?: StatisticsBridge): StatisticsResult;
51
+ export type ModelState = 'model_match' | 'model_mismatch' | 'model_changed' | 'unknown' | 'pending' | 'expired_pending' | 'application_unconfirmed';
52
+ export declare function readStatistics(options: StatisticsOptions, filter?: {
53
+ client?: Client | 'all';
54
+ today?: boolean;
55
+ }): {
56
+ status: string;
57
+ scope: string;
58
+ semantics: string;
59
+ observation_completeness: string;
60
+ today_basis: string;
61
+ filter: {
62
+ client: "all" | Client;
63
+ today: boolean;
64
+ };
65
+ collection: {
66
+ codex: boolean;
67
+ claude: boolean;
68
+ };
69
+ capacity: {
70
+ delegations: number;
71
+ children: number;
72
+ reached: boolean;
73
+ };
74
+ delegations: number;
75
+ auto: Record<ModelState, number>;
76
+ advisory: Record<ModelState, number>;
77
+ blocked: number;
78
+ explicit_preserved: number;
79
+ unbound: number;
80
+ effort_actual_unknown: number;
81
+ application_confirmed: number;
82
+ unknown_alias_count: number;
83
+ model_observed: number;
84
+ model_comparable: number;
85
+ model_match_denominator: number;
86
+ observation_denominator: number;
87
+ usage_scope: string;
88
+ model_alias_scope: string;
89
+ counts_are_lifetime: boolean;
90
+ };