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
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
import { createHmac } from 'node:crypto';
|
|
2
|
+
import { closeSync, existsSync, fstatSync, lstatSync, openSync } from 'node:fs';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { isAbsolute, join } from 'node:path';
|
|
5
|
+
import { assertPrivateStatePath, readRegularFile } from './files.js';
|
|
6
|
+
import { isRecord } from './types.js';
|
|
7
|
+
export const STATISTICS_CONFIG_FILE = 'stats-config.json';
|
|
8
|
+
export const STATISTICS_KEY_FILE = 'stats-key';
|
|
9
|
+
export const STATISTICS_DATABASE_FILE = 'stats.sqlite';
|
|
10
|
+
export const STATISTICS_DB_FILE = STATISTICS_DATABASE_FILE;
|
|
11
|
+
export const STATISTICS_CONFIG_VERSION = 1;
|
|
12
|
+
const require = createRequire(import.meta.url);
|
|
13
|
+
const APP_ID = 0x41505354;
|
|
14
|
+
const CAPACITY = 10_000;
|
|
15
|
+
const hashPattern = /^[a-f0-9]{64}$/;
|
|
16
|
+
const validClient = (v) => v === 'codex' || v === 'claude';
|
|
17
|
+
const id = (v) => typeof v === 'string' && v.length > 0 && v.length <= 1024 && !v.includes('\0') && !v.includes('${');
|
|
18
|
+
const secretLike = (v) => /(?:sk-|bearer(?:[ _.:-]|$)|api[_-]?key|access[_-]?token|secret[_-]?key)/i.test(v);
|
|
19
|
+
const model = (v) => typeof v === 'string' && !secretLike(v) && /^(?:(?:gpt|claude)-[a-z0-9][a-z0-9.-]{0,79}|haiku|sonnet|opus|fable)$/.test(v);
|
|
20
|
+
const safeToken = (v) => typeof v === 'string' && !secretLike(v) && /^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,95}$/.test(v);
|
|
21
|
+
const effort = (v) => typeof v === 'string' && /^(none|minimal|low|medium|high|xhigh|max|ultra)$/.test(v);
|
|
22
|
+
const ignored = (reason) => ({ status: 'ignored', reason });
|
|
23
|
+
export function parseStatisticsConfig(value) {
|
|
24
|
+
if (!isRecord(value) || value.schema_version !== 1 || !Array.isArray(value.enabled_clients) || value.enabled_clients.length > 2 ||
|
|
25
|
+
!value.enabled_clients.every(validClient) || new Set(value.enabled_clients).size !== value.enabled_clients.length ||
|
|
26
|
+
Object.keys(value).some(k => !['schema_version', 'enabled_clients', 'codex_native_metadata', 'codex_home'].includes(k)) ||
|
|
27
|
+
(value.codex_native_metadata !== undefined && typeof value.codex_native_metadata !== 'boolean') ||
|
|
28
|
+
(value.codex_home !== undefined && (typeof value.codex_home !== 'string' || !isAbsolute(value.codex_home) || value.codex_home.includes('\0'))) ||
|
|
29
|
+
(value.codex_native_metadata === true && value.codex_home === undefined))
|
|
30
|
+
return null;
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
export function serializeStatisticsConfig(value) {
|
|
34
|
+
if (!parseStatisticsConfig(value))
|
|
35
|
+
throw new Error('statistics_config_invalid');
|
|
36
|
+
return JSON.stringify(value, null, 2) + '\n';
|
|
37
|
+
}
|
|
38
|
+
export function loadStatisticsConfig(options) {
|
|
39
|
+
try {
|
|
40
|
+
const path = join(options.stateDirectory, STATISTICS_CONFIG_FILE);
|
|
41
|
+
privateFile(path);
|
|
42
|
+
return parseStatisticsConfig(JSON.parse(readRegularFile(path, { privateFile: true, maxBytes: 8192 }).toString('utf8')));
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export function statisticsHash(key, domain, client, value) {
|
|
49
|
+
if (!hashPattern.test(key) || !id(value) || !validClient(client))
|
|
50
|
+
throw new Error('statistics_hash_invalid');
|
|
51
|
+
return createHmac('sha256', Buffer.from(key, 'hex')).update(JSON.stringify(['aptly-stats-v1', domain, client, value])).digest('hex');
|
|
52
|
+
}
|
|
53
|
+
export function loadStatisticsHash(options) {
|
|
54
|
+
try {
|
|
55
|
+
privateFile(join(options.stateDirectory, STATISTICS_KEY_FILE));
|
|
56
|
+
const key = readRegularFile(join(options.stateDirectory, STATISTICS_KEY_FILE), { privateFile: true, maxBytes: 65 }).toString('utf8');
|
|
57
|
+
if (!/^[a-f0-9]{64}\n$/.test(key))
|
|
58
|
+
return null;
|
|
59
|
+
return (domain, client, value) => statisticsHash(key.trim(), domain, client, value);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function privateFile(path, absent = false) {
|
|
66
|
+
assertPrivateStatePath(path);
|
|
67
|
+
try {
|
|
68
|
+
const stat = lstatSync(path);
|
|
69
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || (process.platform !== 'win32' && (stat.mode & 0o077)))
|
|
70
|
+
throw new Error('statistics_private_file');
|
|
71
|
+
return stat;
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (absent && isRecord(error) && error.code === 'ENOENT')
|
|
75
|
+
return;
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function checkSidecars(path) {
|
|
80
|
+
if (existsSync(path + '-wal') || existsSync(path + '-shm'))
|
|
81
|
+
throw new Error('statistics_wal_unsupported');
|
|
82
|
+
privateFile(path + '-journal', true);
|
|
83
|
+
}
|
|
84
|
+
function initialize(path) {
|
|
85
|
+
// Exclusive reservation never overwrites an existing file and has no hard-link
|
|
86
|
+
// publication window. Incomplete/crashed initialization is deliberately left
|
|
87
|
+
// unavailable for manual review; observers never remove or reinitialize it.
|
|
88
|
+
let fd;
|
|
89
|
+
try {
|
|
90
|
+
fd = openSync(path, 'wx', 0o600);
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (isRecord(error) && error.code === 'EEXIST')
|
|
94
|
+
return;
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
const reserved = fstatSync(fd);
|
|
98
|
+
closeSync(fd);
|
|
99
|
+
const before = privateFile(path);
|
|
100
|
+
if (reserved.dev !== before.dev || reserved.ino !== before.ino)
|
|
101
|
+
throw new Error('statistics_identity_changed');
|
|
102
|
+
const { DatabaseSync: Database } = require('node:sqlite');
|
|
103
|
+
const db = new Database(path);
|
|
104
|
+
try {
|
|
105
|
+
const after = privateFile(path);
|
|
106
|
+
if (before.dev !== after.dev || before.ino !== after.ino)
|
|
107
|
+
throw new Error('statistics_identity_changed');
|
|
108
|
+
db.exec(`PRAGMA busy_timeout=50; PRAGMA journal_mode=DELETE; BEGIN IMMEDIATE;
|
|
109
|
+
PRAGMA application_id=${APP_ID}; PRAGMA user_version=1;
|
|
110
|
+
CREATE TABLE delegations(id TEXT PRIMARY KEY, client TEXT NOT NULL, session TEXT, created INTEGER NOT NULL, data TEXT NOT NULL);
|
|
111
|
+
CREATE TABLE children(id TEXT PRIMARY KEY, client TEXT NOT NULL, session TEXT NOT NULL, created INTEGER NOT NULL, data TEXT NOT NULL);
|
|
112
|
+
CREATE TABLE metadata(key TEXT PRIMARY KEY, value INTEGER NOT NULL);
|
|
113
|
+
INSERT INTO metadata VALUES ('capacity_reached',0); COMMIT;`);
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
db.close();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
function connection(options, write) {
|
|
120
|
+
const path = join(options.stateDirectory, STATISTICS_DATABASE_FILE);
|
|
121
|
+
if (!write && !existsSync(path))
|
|
122
|
+
return null;
|
|
123
|
+
assertPrivateStatePath(path);
|
|
124
|
+
if (!existsSync(path)) {
|
|
125
|
+
if (!write)
|
|
126
|
+
return null;
|
|
127
|
+
initialize(path);
|
|
128
|
+
}
|
|
129
|
+
const before = privateFile(path);
|
|
130
|
+
checkSidecars(path);
|
|
131
|
+
const { DatabaseSync: Database } = require('node:sqlite');
|
|
132
|
+
const db = new Database(path, { readOnly: !write, enableDoubleQuotedStringLiterals: false });
|
|
133
|
+
try {
|
|
134
|
+
const after = privateFile(path);
|
|
135
|
+
if (before.dev !== after.dev || before.ino !== after.ino)
|
|
136
|
+
throw new Error('statistics_identity_changed');
|
|
137
|
+
db.exec('PRAGMA busy_timeout=50');
|
|
138
|
+
if (db.prepare('PRAGMA application_id').get()?.application_id !== APP_ID || db.prepare('PRAGMA user_version').get()?.user_version !== 1 ||
|
|
139
|
+
db.prepare('PRAGMA journal_mode').get()?.journal_mode !== 'delete')
|
|
140
|
+
throw new Error('statistics_database_invalid');
|
|
141
|
+
if (write)
|
|
142
|
+
db.exec('PRAGMA max_page_count=8192; PRAGMA secure_delete=ON; BEGIN IMMEDIATE');
|
|
143
|
+
return db;
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
db.close();
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function rows(db, table) {
|
|
151
|
+
return db.prepare(`SELECT * FROM ${table} ORDER BY created,id`).all().map(row => ({ ...row, data: JSON.parse(String(row.data)) }));
|
|
152
|
+
}
|
|
153
|
+
function limit(value) { if (value === undefined)
|
|
154
|
+
return CAPACITY; if (!Number.isInteger(value) || value < 1 || value > CAPACITY)
|
|
155
|
+
throw new Error('statistics_capacity_invalid'); return value; }
|
|
156
|
+
function get(db, table, key) { const row = db.prepare(`SELECT data FROM ${table} WHERE id=?`).get(key); return row ? JSON.parse(String(row.data)) : null; }
|
|
157
|
+
function save(db, table, key, client, session, data, options) {
|
|
158
|
+
if (get(db, table, key) !== null) {
|
|
159
|
+
db.prepare(`UPDATE ${table} SET data=? WHERE id=?`).run(JSON.stringify(data), key);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const cap = limit(table === 'delegations' ? options.maxDelegations : options.maxChildren);
|
|
163
|
+
if (Number(db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()?.n) >= cap) {
|
|
164
|
+
db.prepare("UPDATE metadata SET value=1 WHERE key='capacity_reached'").run();
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
db.prepare(`INSERT INTO ${table}(id,client,session,created,data) VALUES(?,?,?,?,?)`).run(key, client, session, Math.floor((options.now ?? Date.now)()), JSON.stringify(data));
|
|
168
|
+
}
|
|
169
|
+
function transact(options, client, fn) {
|
|
170
|
+
if (!loadStatisticsConfig(options)?.enabled_clients.includes(client))
|
|
171
|
+
return ignored('collection_disabled');
|
|
172
|
+
const hash = loadStatisticsHash(options);
|
|
173
|
+
if (!hash)
|
|
174
|
+
return { status: 'unavailable', reason: 'statistics_key_unavailable' };
|
|
175
|
+
let db = null;
|
|
176
|
+
try {
|
|
177
|
+
db = connection(options, true);
|
|
178
|
+
fn(db, hash);
|
|
179
|
+
db.exec('COMMIT');
|
|
180
|
+
return { status: 'recorded' };
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
if (db)
|
|
184
|
+
try {
|
|
185
|
+
db.exec('ROLLBACK');
|
|
186
|
+
}
|
|
187
|
+
catch { }
|
|
188
|
+
return { status: 'unavailable', reason: 'statistics_store_unavailable' };
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
try {
|
|
192
|
+
db?.close();
|
|
193
|
+
}
|
|
194
|
+
catch { }
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const combined = (hash, client, kind, session, value) => hash(kind, client, JSON.stringify([hash('session', client, session), hash(kind, client, value)]));
|
|
198
|
+
function expectedValue(input, hash) {
|
|
199
|
+
const e = input.expected;
|
|
200
|
+
if (!e || !safeToken(e.profileId) || !model(e.model) || (e.effort !== undefined && !effort(e.effort)) || (e.catalogVersion !== undefined && !id(e.catalogVersion)))
|
|
201
|
+
return;
|
|
202
|
+
return { profileId: e.profileId, model: e.model, ...(e.effort ? { effort: e.effort } : {}), ...(e.catalogVersion ? { catalogHash: hash('request', input.client, e.catalogVersion) } : {}) };
|
|
203
|
+
}
|
|
204
|
+
export function recordStatisticsRecommendation(options, input) {
|
|
205
|
+
if (!validClient(input.client) || !['auto', 'advisory', 'blocked', 'explicit_preserved', 'unbound'].includes(input.disposition))
|
|
206
|
+
return ignored('invalid_recommendation');
|
|
207
|
+
const bound = id(input.sessionId) && id(input.toolUseId) && input.disposition !== 'unbound';
|
|
208
|
+
if (!bound && !id(input.requestId))
|
|
209
|
+
return ignored('missing_binding');
|
|
210
|
+
return transact(options, input.client, (db, hash) => {
|
|
211
|
+
const key = bound ? combined(hash, input.client, 'tool', input.sessionId, input.toolUseId) : hash('request', input.client, input.requestId);
|
|
212
|
+
const value = get(db, 'delegations', key) ?? {};
|
|
213
|
+
const disposition = bound ? input.disposition : 'unbound';
|
|
214
|
+
const expected = expectedValue(input, hash);
|
|
215
|
+
if (['auto', 'advisory'].includes(disposition) && !expected)
|
|
216
|
+
throw new Error('statistics_expected_invalid');
|
|
217
|
+
if (value.disposition && (value.disposition !== disposition || JSON.stringify(value.expected) !== JSON.stringify(expected)))
|
|
218
|
+
value.conflict = true;
|
|
219
|
+
else {
|
|
220
|
+
value.disposition = disposition;
|
|
221
|
+
value.expected = expected;
|
|
222
|
+
}
|
|
223
|
+
save(db, 'delegations', key, input.client, bound ? hash('session', input.client, input.sessionId) : '', value, options);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
function union(values, value) { return [...new Set([...(values ?? []), value])].sort(); }
|
|
227
|
+
function modelEvidence(child, value) { if (model(value)) {
|
|
228
|
+
const next = union(child.models, value);
|
|
229
|
+
if (next.length > 16)
|
|
230
|
+
child.conflict = true;
|
|
231
|
+
else
|
|
232
|
+
child.models = next;
|
|
233
|
+
}
|
|
234
|
+
else
|
|
235
|
+
child.unknownModel = true; }
|
|
236
|
+
function toolResponse(value) {
|
|
237
|
+
if (isRecord(value))
|
|
238
|
+
return value;
|
|
239
|
+
if (typeof value === 'string' && Buffer.byteLength(value) <= 32768)
|
|
240
|
+
try {
|
|
241
|
+
const parsed = JSON.parse(value);
|
|
242
|
+
return isRecord(parsed) ? parsed : null;
|
|
243
|
+
}
|
|
244
|
+
catch { }
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
export function observeStatistics(options, input, bridge) {
|
|
248
|
+
const { client, event } = input;
|
|
249
|
+
if (!validClient(client) || !isRecord(event) || !id(event.session_id))
|
|
250
|
+
return ignored('invalid_event');
|
|
251
|
+
const session = event.session_id;
|
|
252
|
+
const name = event.hook_event_name;
|
|
253
|
+
const tool = name === 'PostToolUse';
|
|
254
|
+
if (tool && event.tool_use_id !== undefined && event.tool_call_id !== undefined && event.tool_use_id !== event.tool_call_id)
|
|
255
|
+
return ignored('conflicting_tool_binding');
|
|
256
|
+
const toolId = event.tool_use_id ?? event.tool_call_id;
|
|
257
|
+
const phase = name === 'SubagentStart' ? 'start' : name === 'SubagentStop' ? 'stop' : client === 'codex' && name === 'PostModelRequest' ? 'request' : null;
|
|
258
|
+
if (tool && (!id(toolId) || !(client === 'claude' ? event.tool_name === 'Agent' || event.tool_name === 'Task' : event.tool_name === 'collaborationspawn_agent' || event.tool_name === 'spawn_agent' || event.tool_name === 'collaboration.spawn_agent')))
|
|
259
|
+
return ignored('unsupported_tool');
|
|
260
|
+
if (!tool && (!phase || !id(event.agent_id)))
|
|
261
|
+
return ignored('unsupported_event');
|
|
262
|
+
return transact(options, client, (db, hash) => {
|
|
263
|
+
const sessionHash = hash('session', client, session);
|
|
264
|
+
if (tool) {
|
|
265
|
+
const response = toolResponse(event.tool_response);
|
|
266
|
+
const key = combined(hash, client, 'tool', session, toolId);
|
|
267
|
+
const value = get(db, 'delegations', key) ?? {};
|
|
268
|
+
value.toolObserved = true;
|
|
269
|
+
const actualChild = client === 'claude' ? response?.agentId : response?.agent_id;
|
|
270
|
+
if (id(actualChild)) {
|
|
271
|
+
const childKey = combined(hash, client, 'child', session, actualChild);
|
|
272
|
+
if (value.child && value.child !== childKey)
|
|
273
|
+
value.conflict = true;
|
|
274
|
+
else
|
|
275
|
+
value.child = childKey;
|
|
276
|
+
}
|
|
277
|
+
if (client === 'codex' && id(response?.task_name)) {
|
|
278
|
+
const path = hash('task_path', client, response.task_name);
|
|
279
|
+
if (value.path && value.path !== path)
|
|
280
|
+
value.conflict = true;
|
|
281
|
+
else
|
|
282
|
+
value.path = path;
|
|
283
|
+
}
|
|
284
|
+
// Fingerprint only allowed model/effort fields, never retain original arguments.
|
|
285
|
+
const args = isRecord(event.tool_input) ? event.tool_input : null;
|
|
286
|
+
const actualModel = args?.model;
|
|
287
|
+
const actualEffort = args?.reasoning_effort !== undefined ? args.reasoning_effort : args?.effort;
|
|
288
|
+
const conflictingEfforts = args && args.reasoning_effort !== undefined && args.effort !== undefined && args.reasoning_effort !== args.effort;
|
|
289
|
+
if (response && !conflictingEfforts && model(actualModel) && (actualEffort === undefined || effort(actualEffort)))
|
|
290
|
+
value.applied = union(value.applied, JSON.stringify([actualModel, actualEffort ?? null]));
|
|
291
|
+
else
|
|
292
|
+
value.appliedUnknown = true;
|
|
293
|
+
if ((value.applied?.length ?? 0) > 4) {
|
|
294
|
+
value.applied = value.applied.slice(0, 4);
|
|
295
|
+
value.conflict = true;
|
|
296
|
+
}
|
|
297
|
+
save(db, 'delegations', key, client, sessionHash, value, options);
|
|
298
|
+
if (client === 'claude' && value.child && response) {
|
|
299
|
+
const child = get(db, 'children', value.child) ?? {};
|
|
300
|
+
if (response.status === 'completed') {
|
|
301
|
+
child.complete = true;
|
|
302
|
+
modelEvidence(child, response.resolvedModel);
|
|
303
|
+
if (Array.isArray(response.modelsUsed)) {
|
|
304
|
+
if (response.modelsUsed.length > 16)
|
|
305
|
+
child.conflict = true;
|
|
306
|
+
for (const m of response.modelsUsed.slice(0, 16))
|
|
307
|
+
modelEvidence(child, m);
|
|
308
|
+
}
|
|
309
|
+
else if (response.modelsUsed !== undefined)
|
|
310
|
+
child.unknownModel = true;
|
|
311
|
+
}
|
|
312
|
+
else if (response.status === 'async_launched')
|
|
313
|
+
child.started = true;
|
|
314
|
+
save(db, 'children', value.child, client, sessionHash, child, options);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
const key = combined(hash, client, 'child', session, event.agent_id);
|
|
319
|
+
const value = get(db, 'children', key) ?? {};
|
|
320
|
+
if (phase === 'start')
|
|
321
|
+
value.started = true;
|
|
322
|
+
if (phase === 'stop')
|
|
323
|
+
value.stopped = true;
|
|
324
|
+
if (phase === 'request' && event.status === 'completed' && (event.error === null || event.error === undefined)) {
|
|
325
|
+
value.complete = true;
|
|
326
|
+
modelEvidence(value, event.model);
|
|
327
|
+
}
|
|
328
|
+
if (bridge && client === 'codex') {
|
|
329
|
+
if (!hashPattern.test(bridge.parentSessionHash) || !hashPattern.test(bridge.taskPathHash) || bridge.parentSessionHash !== sessionHash)
|
|
330
|
+
value.conflict = true;
|
|
331
|
+
else if (value.path && value.path !== bridge.taskPathHash)
|
|
332
|
+
value.conflict = true;
|
|
333
|
+
else
|
|
334
|
+
value.path = bridge.taskPathHash;
|
|
335
|
+
}
|
|
336
|
+
save(db, 'children', key, client, sessionHash, value, options);
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
const emptyCounts = () => ({ model_match: 0, model_mismatch: 0, model_changed: 0, unknown: 0, pending: 0, expired_pending: 0, application_unconfirmed: 0 });
|
|
341
|
+
function confirmed(d) { return !d.appliedUnknown && !!d.expected && d.applied?.length === 1 && d.applied[0] === JSON.stringify([d.expected.model, d.expected.effort ?? null]); }
|
|
342
|
+
function modelState(d, c, ambiguous, created, now) {
|
|
343
|
+
if (d.conflict || ambiguous || c?.conflict)
|
|
344
|
+
return 'unknown';
|
|
345
|
+
if (d.disposition === 'auto' && !confirmed(d))
|
|
346
|
+
return !d.toolObserved && !c ? (now - created > 86400000 ? 'expired_pending' : 'pending') : 'application_unconfirmed';
|
|
347
|
+
if (!c?.complete)
|
|
348
|
+
return c?.stopped ? 'unknown' : now - created > 86400000 ? 'expired_pending' : 'pending';
|
|
349
|
+
if ((c.models?.length ?? 0) > 1)
|
|
350
|
+
return 'model_changed';
|
|
351
|
+
if (c.unknownModel || !c.models?.length || !d.expected)
|
|
352
|
+
return 'unknown';
|
|
353
|
+
const expected = d.expected.model, actual = c.models[0];
|
|
354
|
+
// No family-prefix guessing: aliases are not versioned execution evidence.
|
|
355
|
+
if (['haiku', 'sonnet', 'opus', 'fable'].includes(expected) || ['haiku', 'sonnet', 'opus', 'fable'].includes(actual))
|
|
356
|
+
return 'unknown';
|
|
357
|
+
return expected === actual ? 'model_match' : 'model_mismatch';
|
|
358
|
+
}
|
|
359
|
+
export function readStatistics(options, filter = {}) {
|
|
360
|
+
const now = (options.now ?? Date.now)();
|
|
361
|
+
const output = { status: 'ok', scope: 'retained_records', semantics: 'retained_routing_records_not_user_acceptance_or_execution_total', observation_completeness: 'best_effort_not_full_execution_history', today_basis: 'UTC_binding_creation', filter: { client: filter.client ?? 'all', today: filter.today === true },
|
|
362
|
+
collection: { codex: false, claude: false }, capacity: { delegations: limit(options.maxDelegations), children: limit(options.maxChildren), reached: false },
|
|
363
|
+
delegations: 0, auto: emptyCounts(), advisory: emptyCounts(), blocked: 0, explicit_preserved: 0, unbound: 0,
|
|
364
|
+
effort_actual_unknown: 0, application_confirmed: 0, unknown_alias_count: 0, model_observed: 0, model_comparable: 0, model_match_denominator: 0, observation_denominator: 0,
|
|
365
|
+
usage_scope: 'not_collected', model_alias_scope: 'exact_canonical_model_ids_only', counts_are_lifetime: false };
|
|
366
|
+
const config = loadStatisticsConfig(options);
|
|
367
|
+
for (const client of config?.enabled_clients ?? [])
|
|
368
|
+
output.collection[client] = true;
|
|
369
|
+
let db = null;
|
|
370
|
+
try {
|
|
371
|
+
db = connection(options, false);
|
|
372
|
+
if (!db)
|
|
373
|
+
return output;
|
|
374
|
+
// All projection inputs must come from one SQLite snapshot. Separate implicit
|
|
375
|
+
// SELECT transactions can otherwise combine old bindings with new child facts.
|
|
376
|
+
db.exec('BEGIN');
|
|
377
|
+
output.capacity.reached = db.prepare("SELECT value FROM metadata WHERE key='capacity_reached'").get()?.value === 1;
|
|
378
|
+
const delegates = rows(db, 'delegations');
|
|
379
|
+
const children = rows(db, 'children');
|
|
380
|
+
// Index retained metadata once: a bounded store must also have bounded query work.
|
|
381
|
+
const childrenById = new Map(children.map(row => [row.id, row]));
|
|
382
|
+
const childrenByPath = new Map();
|
|
383
|
+
const delegationsByPath = new Map();
|
|
384
|
+
const delegationsByChild = new Map();
|
|
385
|
+
const pathKey = (client, session, path) => JSON.stringify([client, session, path]);
|
|
386
|
+
for (const child of children)
|
|
387
|
+
if (child.data.path) {
|
|
388
|
+
const key = pathKey(child.client, child.session, child.data.path);
|
|
389
|
+
const list = childrenByPath.get(key) ?? [];
|
|
390
|
+
list.push(child);
|
|
391
|
+
childrenByPath.set(key, list);
|
|
392
|
+
}
|
|
393
|
+
for (const row of delegates) {
|
|
394
|
+
if (row.data.path) {
|
|
395
|
+
const key = pathKey(row.client, row.session, row.data.path);
|
|
396
|
+
const set = delegationsByPath.get(key) ?? new Set();
|
|
397
|
+
set.add(row.id);
|
|
398
|
+
delegationsByPath.set(key, set);
|
|
399
|
+
}
|
|
400
|
+
if (row.data.child) {
|
|
401
|
+
const set = delegationsByChild.get(row.data.child) ?? new Set();
|
|
402
|
+
set.add(row.id);
|
|
403
|
+
delegationsByChild.set(row.data.child, set);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
const today = new Date(now).toISOString().slice(0, 10);
|
|
407
|
+
for (const row of delegates) {
|
|
408
|
+
const d = row.data;
|
|
409
|
+
if (!d.disposition || (filter.client && filter.client !== 'all' && row.client !== filter.client) || (filter.today && new Date(row.created).toISOString().slice(0, 10) !== today))
|
|
410
|
+
continue;
|
|
411
|
+
output.delegations++;
|
|
412
|
+
if (d.disposition === 'unbound' || d.disposition === 'blocked' || d.disposition === 'explicit_preserved') {
|
|
413
|
+
output[d.disposition]++;
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
const direct = d.child ? childrenById.get(d.child) : undefined;
|
|
417
|
+
const matches = d.child ? (direct && direct.client === row.client && direct.session === row.session ? [direct] : []) : d.path ? childrenByPath.get(pathKey(row.client, row.session, d.path)) ?? [] : [];
|
|
418
|
+
const child = matches.length === 1 ? matches[0] : undefined;
|
|
419
|
+
// A reused canonical path or child cannot retroactively certify either call.
|
|
420
|
+
const contenders = new Set();
|
|
421
|
+
const add = (ids) => { for (const id of ids ?? [])
|
|
422
|
+
if (id !== row.id)
|
|
423
|
+
contenders.add(id); };
|
|
424
|
+
if (d.path)
|
|
425
|
+
add(delegationsByPath.get(pathKey(row.client, row.session, d.path)));
|
|
426
|
+
if (d.child)
|
|
427
|
+
add(delegationsByChild.get(d.child));
|
|
428
|
+
if (child) {
|
|
429
|
+
add(delegationsByChild.get(child.id));
|
|
430
|
+
if (child.data.path)
|
|
431
|
+
add(delegationsByPath.get(pathKey(row.client, row.session, child.data.path)));
|
|
432
|
+
}
|
|
433
|
+
const pathConflict = !!(d.path && child?.data.path && d.path !== child.data.path);
|
|
434
|
+
const childPathAmbiguous = !!(child?.data.path && (childrenByPath.get(pathKey(row.client, row.session, child.data.path))?.length ?? 0) > 1);
|
|
435
|
+
const otherPathChild = !!(d.child && d.path && childrenByPath.get(pathKey(row.client, row.session, d.path))?.some(other => other.id !== d.child));
|
|
436
|
+
const ambiguous = matches.length > 1 || contenders.size > 0 || pathConflict || childPathAmbiguous || otherPathChild;
|
|
437
|
+
const validEvidence = !ambiguous && !d.conflict && !!child && !child.data.conflict && child.data.complete === true && !child.data.unknownModel && !!child.data.models?.length;
|
|
438
|
+
const state = modelState(d, child?.data, ambiguous, row.created, now);
|
|
439
|
+
output[d.disposition][state]++;
|
|
440
|
+
output.effort_actual_unknown++;
|
|
441
|
+
if (state === 'unknown' && validEvidence && child.data.models.length === 1 && d.expected &&
|
|
442
|
+
(d.disposition !== 'auto' || confirmed(d)) && [d.expected.model, child.data.models[0]].some(m => ['haiku', 'sonnet', 'opus', 'fable'].includes(m)))
|
|
443
|
+
output.unknown_alias_count++;
|
|
444
|
+
if (d.disposition === 'auto') {
|
|
445
|
+
output.observation_denominator++;
|
|
446
|
+
if (confirmed(d) && !d.conflict)
|
|
447
|
+
output.application_confirmed++;
|
|
448
|
+
if (validEvidence)
|
|
449
|
+
output.model_observed++;
|
|
450
|
+
if (state === 'model_match' || state === 'model_mismatch') {
|
|
451
|
+
output.model_comparable++;
|
|
452
|
+
output.model_match_denominator++;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return output;
|
|
457
|
+
}
|
|
458
|
+
catch {
|
|
459
|
+
output.status = 'unavailable';
|
|
460
|
+
return output;
|
|
461
|
+
}
|
|
462
|
+
finally {
|
|
463
|
+
try {
|
|
464
|
+
db?.exec('ROLLBACK');
|
|
465
|
+
}
|
|
466
|
+
catch { }
|
|
467
|
+
try {
|
|
468
|
+
db?.close();
|
|
469
|
+
}
|
|
470
|
+
catch { }
|
|
471
|
+
}
|
|
472
|
+
}
|
|
@@ -23,7 +23,7 @@ function newer(candidate, current) {
|
|
|
23
23
|
}
|
|
24
24
|
function eligible(o) {
|
|
25
25
|
return o.stdinIsTTY && o.stderrIsTTY && o.stdoutIsTTY !== false && !o.env.CI && o.env.APTLY_NO_UPDATE_NOTIFIER !== '1' && !!version(o.currentVersion) &&
|
|
26
|
-
['--version', 'config', 'setup', 'remove', 'set', 'report'].includes(o.command) && !o.args.some(arg => arg === '--help' || arg === '-h') && !o.args.includes('--automatic') && !(o.command === 'set' && o.args[0] === 'transmission' && o.args.includes('--show'));
|
|
26
|
+
['--version', 'config', 'setup', 'remove', 'set', 'report'].includes(o.command) && !o.args.some(arg => arg === '--help' || arg === '-h') && !o.args.includes('--automatic') && !o.args.includes('--check') && !(o.command === 'set' && o.args[0] === 'transmission' && o.args.includes('--show'));
|
|
27
27
|
}
|
|
28
28
|
function directory(path) {
|
|
29
29
|
if (!isAbsolute(path))
|
package/dist/src/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.1.
|
|
1
|
+
export declare const VERSION = "0.1.10";
|
package/dist/src/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const VERSION = '0.1.
|
|
1
|
+
export const VERSION = '0.1.10';
|
package/docs/guide/en.md
CHANGED
|
@@ -114,7 +114,9 @@ Restart MCP, then inspect `provider`, candidates, and `credential_status` with `
|
|
|
114
114
|
|
|
115
115
|
These options require Aptly 0.1.2 or later and are not in npm 0.1.1. To test from source, run `npm ci --ignore-scripts` and `npm run build`, then replace `aptly` below with `node bin/aptly.ts`.
|
|
116
116
|
|
|
117
|
-
Key setup diagnoses selected hosts before input or storage. If any host fails, it does not prompt or change any host. `--check` does not access keys or the credential store.
|
|
117
|
+
Key setup diagnoses selected hosts before input or storage. If any host fails, it does not prompt or change any host. `--check` does not access keys or the credential store.
|
|
118
|
+
|
|
119
|
+
From Aptly 0.1.9, on Linux, `--check` also checks for an executable `secret-tool` and, when a safe explicit session-bus address and `gdbus` are available, reads bus metadata without activating or accessing the credential service. Confirmed failures report `secure_store_unavailable` with `secure_store_secret_tool_missing`, `secure_store_bus_missing`, or `secure_store_service_missing` before input. `secure_store_bus_unverified`, `secure_store_probe_unavailable`, and service-present or activatable unverified codes mean readiness is unknown; a running or activatable service does not prove it is unlocked or writable. Install `secret-tool` and a Secret Service provider, and run from the intended desktop session when needed. The actual store operation can still fail. For SSH or headless sessions, supply `OPENAI_API_KEY` securely to the host MCP process when `APTLY_SECRET_BACKEND` is absent; preserve an existing authentication wrapper or environment. `credential_node_mismatch`, `credential_server_mismatch`, and `credential_runtime_unsupported` identify incompatible Node paths, server paths, and OS-store support respectively.
|
|
118
120
|
|
|
119
121
|
If only Claude failed, diagnose that host and review migration only when `launcher_migration_available` is returned:
|
|
120
122
|
|
|
@@ -127,6 +129,8 @@ aptly set env OPENAI_API_KEY --client claude
|
|
|
127
129
|
|
|
128
130
|
`--dry-run` makes no changes. Migration replaces the Node/server paths of a receipt-matching, Aptly-owned standard registration with the current build. It preserves environment settings, Hooks, policy and other hosts, accesses no credentials, and never executes the old launcher. Custom wrappers and missing or modified ownership records are rejected. Review such registrations locally; use the wrapper's secure environment or a separately reviewed standard registration. Do not edit or delete ownership records to bypass validation.
|
|
129
131
|
|
|
132
|
+
From Aptly 0.1.9, `aptly setup --check --client codex|claude|all` reads the normal setup plan without writing files or creating directories. It is a snapshot, not a check of the running host. Only `--client` can be combined with `--check`. If `hook_policy_path_conflict` appears, review the selected host configuration directory and existing policy reference locally, then select the intended host directory before retrying. Setup preserves the existing configuration and does not move or copy the policy; launcher migration does not resolve this mismatch.
|
|
133
|
+
|
|
130
134
|
If `launcher_migration_not_owned` refers to a preserved registration (`mcp_created: false`), **Aptly 0.1.3 or later** offers the explicit `--include-existing` opt-in. Install 0.1.3 or later, then run:
|
|
131
135
|
|
|
132
136
|
```sh
|
|
@@ -278,6 +282,34 @@ Setting commands support `--client codex|claude|all`, hidden input and explicit
|
|
|
278
282
|
|
|
279
283
|
New pre-HTTP budget denials are not cached. Only verifiable known-unpaid legacy default-policy denials can be reevaluated with the same ID; completed recommendations, abstentions, context outcomes and `unknown` remain protected. Budget recovery does not extend the original five-minute retry reference or process lifetime and does not remove history or permission constraints. Arbitrary historical custom-policy digests are not guessed; do not bypass conflicts/unknowns with new IDs or ledger deletion.
|
|
280
284
|
|
|
285
|
+
<a id="execution-statistics"></a>
|
|
286
|
+
|
|
287
|
+
### Execution statistics (0.1.10 or later)
|
|
288
|
+
|
|
289
|
+
Execution statistics require Aptly 0.1.10 or later. Install a supported version or upgrade following [package updates](#package-updates), then use the examples below. An existing Aptly setup is required. Collection is initially POSIX-only; Windows collection is unsupported and normal Aptly use on Windows is unaffected.
|
|
290
|
+
|
|
291
|
+
```sh
|
|
292
|
+
aptly stats
|
|
293
|
+
aptly stats --today --client codex
|
|
294
|
+
aptly stats enable --client codex
|
|
295
|
+
aptly stats enable --client codex --codex-native-metadata
|
|
296
|
+
aptly stats disable --client codex
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
The command forms are `aptly stats [--today] [--client codex|claude|all]`, `aptly stats enable [--client] [--codex-native-metadata]` and `aptly stats disable [--client]`. Collection is off by default and postinstall does not enable it. Enable installs Aptly-owned command observers recorded separately in `stats-ownership.json`; it leaves the legacy receipt, MCP, launchers, keys, budget and transmission settings intact. Restart MCP and the host after enabling; for Codex, review native Hook trust in `/hooks`.
|
|
300
|
+
|
|
301
|
+
Disable turns collection off and removes only unchanged owned observers. Modified or custom observers are preserved with a warning; data and the key remain. `remove` validates and removes stats-owned definitions but keeps the data. Independently managed collectors and custom Hooks are not adopted automatically.
|
|
302
|
+
|
|
303
|
+
Private state uses `stats.sqlite`, `stats-config.json` and `stats-key` (an HMAC secret), separately from the budget ledger. Do not share the key. Records contain no task text, transcripts, raw IDs, paths, errors or credentials. Reading stats makes no API, key or credential-store calls, initializes nothing and runs no notifier.
|
|
304
|
+
|
|
305
|
+
The projection reports `model_match`, `model_mismatch`, `model_changed`, `unknown`, `pending`, `expired_pending` and `application_unconfirmed`; advisory is separate. `blocked`, `explicit_preserved` and `unbound` are excluded from denominators. Effective effort is never measured; configured effort is not actual effort. Claude aliases `haiku`, `sonnet`, `opus` and `fable` cannot be resolved to an actual canonical model and are `unknown`; only exact canonical models are supported, and observing a model does not guarantee all aliases match. These figures do not establish user acceptance or quality.
|
|
306
|
+
|
|
307
|
+
Direct advisory, retries and fresh unbound calls without native continuity are not joined by approximate timing. `--today` uses the UTC date when the binding was first created. Capacity is fixed at 10,000 delegations and 10,000 children, with no automatic pruning. Counts cover retained records, not lifetime totals; at capacity, new identities are dropped and the reached flag is set. Missing callbacks do not prove bypass. There are no token or cost rollups, live quota or savings figures.
|
|
308
|
+
|
|
309
|
+
Codex native metadata is off unless explicitly enabled. It reads SQLite native metadata by exact child ID only: no transcripts, repairs or app-server launch. Relocated `sqlite_home`, unsupported schemas or paths, and ambiguous joins yield unknown. A SQL read may update existing SHM read marks; it writes no rows or schema and does not intentionally create sidecars.
|
|
310
|
+
|
|
311
|
+
Collection is best effort: lost, delayed or capacity-dropped events can leave an incomplete model history. `model_match` means the retained evidence matches, not that every request used that model. Disabling Codex collection, removing setup or enabling without `--codex-native-metadata` revokes native metadata access. After changing the Node or package path, disable and re-enable collection to register current commands. An unavailable or corrupt store is preserved; review it locally rather than deleting the key or assuming zero usage.
|
|
312
|
+
|
|
281
313
|
<a id="outbound-data-and-disabling-automatic-sharing"></a>
|
|
282
314
|
|
|
283
315
|
### Decisions API transmission scope
|