estimetry 0.1.2 → 0.3.0

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 (65) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +88 -16
  3. package/dist/application/contracts/skill-mention.js +20 -0
  4. package/dist/application/estimetry.js +2 -0
  5. package/dist/application/hooks/context-limit.js +10 -2
  6. package/dist/application/hooks/hook-context.js +12 -4
  7. package/dist/application/hooks/receive-session-hook.js +15 -4
  8. package/dist/application/hooks/session-end-import.js +6 -7
  9. package/dist/application/project/init-defaults.js +17 -4
  10. package/dist/application/project/init-project.js +4 -1
  11. package/dist/application/project/install-copy.js +8 -1
  12. package/dist/application/project/show-init-choices.js +1 -1
  13. package/dist/application/project/tool-notices.js +8 -0
  14. package/dist/application/task/import-session-logs.js +4 -1
  15. package/dist/application/task/show-calibration.js +12 -8
  16. package/dist/application/task/task-cards.js +1 -1
  17. package/dist/bootstrap/container.js +23 -6
  18. package/dist/bootstrap/hook-receiver.js +7 -14
  19. package/dist/bootstrap/main.js +1 -1
  20. package/dist/domain/calibration/applicable-coefficient.js +35 -19
  21. package/dist/domain/calibration/calibration-policy.js +39 -0
  22. package/dist/domain/calibration/calibration.js +21 -36
  23. package/dist/domain/calibration/level-parts.js +41 -0
  24. package/dist/domain/calibration/ratio-samples.js +34 -0
  25. package/dist/domain/code/code-classes.js +1 -1
  26. package/dist/domain/estimate/estimate.js +22 -5
  27. package/dist/domain/progress/progress-record-parser.js +6 -0
  28. package/dist/domain/progress/session-log.js +2 -1
  29. package/dist/domain/usage/task-usage.js +24 -7
  30. package/dist/infrastructure/persistence/records.js +1 -1
  31. package/dist/infrastructure/persistence/yaml-config-store.js +6 -5
  32. package/dist/infrastructure/persistence/yaml-estimate-reader.js +20 -12
  33. package/dist/integrations/tools/claude-code/claude-code-adapter.js +29 -48
  34. package/dist/integrations/tools/claude-code/hook-events.js +4 -0
  35. package/dist/integrations/tools/claude-code/hook-translation.js +16 -34
  36. package/dist/integrations/tools/claude-code/importer/claude-code-logs.js +1 -1
  37. package/dist/integrations/tools/claude-code/skill-file.js +7 -19
  38. package/dist/integrations/tools/codex/codex-adapter.js +161 -0
  39. package/dist/integrations/tools/codex/hook-events.js +23 -0
  40. package/dist/integrations/tools/codex/hook-translation.js +76 -0
  41. package/dist/integrations/tools/codex/hook-trust.js +69 -0
  42. package/dist/integrations/tools/codex/importer/codex-logs.js +208 -0
  43. package/dist/integrations/tools/codex/importer/rollout-parser.js +163 -0
  44. package/dist/integrations/tools/codex/sandbox-rules.js +38 -0
  45. package/dist/integrations/tools/codex/skill-file.js +22 -0
  46. package/dist/integrations/tools/codex/trust-tables.js +96 -0
  47. package/dist/integrations/tools/content/commands.js +35 -26
  48. package/dist/integrations/tools/shared/generated-file.js +26 -0
  49. package/dist/integrations/tools/shared/hook-payload.js +33 -0
  50. package/dist/integrations/tools/{claude-code → shared}/hook-settings.js +37 -22
  51. package/dist/integrations/tools/shared/instructions-block.js +39 -0
  52. package/dist/integrations/tools/shared/skills-plan.js +39 -0
  53. package/dist/interface/cli/commands/calibrate-command.js +11 -0
  54. package/dist/interface/cli/commands/hook-command.js +1 -1
  55. package/dist/interface/cli/commands/init-command.js +16 -7
  56. package/dist/interface/cli/commands/status-command.js +5 -2
  57. package/dist/interface/cli/help.js +3 -1
  58. package/dist/interface/cli/presenters/text/closing-text.js +7 -3
  59. package/dist/interface/cli/presenters/text/estimate-text.js +35 -13
  60. package/dist/interface/cli/presenters/text/notices-text.js +1 -0
  61. package/dist/interface/cli/presenters/text/task-text.js +1 -1
  62. package/dist/interface/cli/presenters/text-presenter.js +3 -3
  63. package/package.json +1 -1
  64. package/dist/integrations/tools/claude-code/claude-md.js +0 -28
  65. /package/dist/integrations/tools/{claude-code/importer → shared}/log-lines.js +0 -0
@@ -0,0 +1,69 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { ourHandlers } from '../shared/hook-settings.js';
3
+ import { stateTable, withStateTables } from './trust-tables.js';
4
+ /*
5
+ * The trust Codex keeps for a hook (codex-install spec, "Одобрение хуков Codex"): in the user config,
6
+ * `[hooks.state."<hooks file>:<event in snake case>:<group>:<handler>"]` with `trusted_hash`. The hash is Codex's own
7
+ * (`hook_hash` in codex-rs/hooks/src/engine/discovery.rs): SHA-256 of the compact JSON, keys sorted, of
8
+ * `{event_name, matcher?, hooks: [the handler normalized]}`, normalized as Codex does it (`normalize_command_hook`,
9
+ * `matcher_pattern_for_event`); checked against trusts Codex 0.162.1 wrote. estimetry writes a trust only with the
10
+ * user's consent (codex-adapter.ts).
11
+ */
12
+ /** Events whose matcher Codex keeps; for the others it has none. */
13
+ const MATCHED_EVENTS = new Set([
14
+ 'PreToolUse',
15
+ 'PermissionRequest',
16
+ 'PostToolUse',
17
+ 'SessionStart',
18
+ 'SessionEnd',
19
+ 'SubagentStart',
20
+ 'SubagentStop',
21
+ 'PreCompact',
22
+ 'PostCompact',
23
+ ]);
24
+ /** Codex waits for these at most 3 seconds, and 1 when the hook names no timeout. */
25
+ const SHORT_EVENTS = new Set(['SessionEnd', 'Interrupt']);
26
+ /** The trust each hook of ours in a hooks file needs: its key and the hash Codex computes for it. */
27
+ export function hookTrusts(hooksPath, hooksText, ours) {
28
+ return ourHandlers(hooksText, ours).map((place) => ({
29
+ key: `${hooksPath}:${snakeCase(place.event)}:${place.group}:${place.handler}`,
30
+ hash: trustHash(place),
31
+ }));
32
+ }
33
+ /** Whether a hook of ours has no trust of Codex, or one of an earlier form of it. No config is no trust. */
34
+ export function untrustedHooks(config, trusts) {
35
+ return trusts.some((trust) => stateTable(config, trust.key)?.trustedHash !== trust.hash);
36
+ }
37
+ /** The config with a trust of every hook of ours, the rest of it as it was; undefined when it cannot be changed safely. */
38
+ export function withTrusts(config, trusts) {
39
+ return withStateTables(config, trusts.map((trust) => ({ key: trust.key, trustedHash: trust.hash })));
40
+ }
41
+ function trustHash(place) {
42
+ const handler = place.config;
43
+ const timeout = typeof handler['timeout'] === 'number' ? handler['timeout'] : undefined;
44
+ const normalized = {
45
+ type: 'command',
46
+ command: handler['command'],
47
+ timeout: SHORT_EVENTS.has(place.event) ? Math.min(Math.max(timeout ?? 1, 1), 3) : Math.max(timeout ?? 600, 1),
48
+ async: handler['async'] === true,
49
+ ...(typeof handler['statusMessage'] === 'string' ? { statusMessage: handler['statusMessage'] } : {}),
50
+ };
51
+ const matcher = place.matcher === undefined || !MATCHED_EVENTS.has(place.event) ? {} : { matcher: place.matcher };
52
+ const identity = { event_name: snakeCase(place.event), ...matcher, hooks: [normalized] };
53
+ return `sha256:${createHash('sha256').update(JSON.stringify(sorted(identity))).digest('hex')}`;
54
+ }
55
+ function sorted(value) {
56
+ if (Array.isArray(value)) {
57
+ return value.map(sorted);
58
+ }
59
+ if (typeof value === 'object' && value !== null) {
60
+ const record = value;
61
+ return Object.fromEntries(Object.keys(record).sort().map((key) => [key, sorted(record[key])]));
62
+ }
63
+ return value;
64
+ }
65
+ /** `PreToolUse` → `pre_tool_use`, as Codex names events in the keys of trusts. */
66
+ function snakeCase(event) {
67
+ return event.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
68
+ }
69
+ //# sourceMappingURL=hook-trust.js.map
@@ -0,0 +1,208 @@
1
+ import { closeSync, existsSync, openSync, readSync, readdirSync, statSync } from 'node:fs';
2
+ import { basename, dirname, join } from 'node:path';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { SessionLogFailure, } from '../../../../application/contracts/session-logs.js';
5
+ import { logLines } from '../../shared/log-lines.js';
6
+ import { RolloutParser } from './rollout-parser.js';
7
+ /** Day directories searched for a session without a path, newest first. */
8
+ const SEARCHED_DAYS = 62;
9
+ /** Days after the parent's in which its subagents may have started: a resumed session goes on for days. */
10
+ const SUBAGENT_DAYS = 14;
11
+ /** The first line of a rollout carries its instructions too; its `session_meta` is read up to this size. */
12
+ const META_BYTES = 256 * 1024;
13
+ /** The start of the first line, where its ids are. */
14
+ const HEAD_BYTES = 4 * 1024;
15
+ /**
16
+ * Session logs of Codex: rollouts in `<CODEX_HOME>/sessions/YYYY/MM/DD/rollout-<local time>-<thread id>.jsonl`, one
17
+ * per thread. A subagent the agent spawned writes its own, whose `session_meta` names the root session and
18
+ * `source.subagent.thread_spawn`; how the parent names it differs between versions of Codex, so the children are
19
+ * found by their own first line, in the parent's day directory and the days after it. Internal subagents (`guardian`
20
+ * reviews, `source.subagent.other`) are no work of the agent and are left out. The fingerprint is the parent's file
21
+ * alone: a subagent that works also adds to its parent. A compressed rollout (`.jsonl.zst`, older than a week) is not
22
+ * read: Node 22 has no zstd.
23
+ */
24
+ export class CodexLogs {
25
+ home;
26
+ id = 'codex';
27
+ /** `home` is `$CODEX_HOME`, else `~/.codex`. */
28
+ constructor(home) {
29
+ this.home = home;
30
+ }
31
+ fingerprint(session, path) {
32
+ try {
33
+ const main = this.locate(session, path);
34
+ return main === undefined ? undefined : { main: stat(main), agents: {} };
35
+ }
36
+ catch {
37
+ throw new SessionLogFailure('log-stat-failed');
38
+ }
39
+ }
40
+ read(request) {
41
+ const deadline = request.budgetMs === undefined ? Infinity : performance.now() + request.budgetMs;
42
+ const over = () => performance.now() > deadline;
43
+ try {
44
+ const main = this.locate(request.session, request.path, over);
45
+ if (main === undefined) {
46
+ return { status: 'not-found' };
47
+ }
48
+ const fingerprint = { main: stat(main), agents: {} };
49
+ const from = request.from <= fingerprint.main.size ? request.from : 0;
50
+ const parser = new RolloutParser(from);
51
+ if (parse(main, from, parser, over) === 'stopped') {
52
+ return { status: 'over-budget' };
53
+ }
54
+ if (from === 0 && parser.records === 0) {
55
+ return { status: 'no-data', fingerprint };
56
+ }
57
+ if (from === 0 && (!parser.sessionMeta || parser.recognized === 0)) {
58
+ return { status: 'unrecognized', fingerprint };
59
+ }
60
+ const agents = [];
61
+ for (const [agent, file] of spawnedChildren(main, request.session.value, this.home, over)) {
62
+ const child = new RolloutParser(0);
63
+ if (parse(file, 0, child, over) === 'stopped') {
64
+ return { status: 'over-budget' };
65
+ }
66
+ agents.push({ agent, ...agentOf(child) });
67
+ }
68
+ const { turns, next } = parser.result();
69
+ // No `cost`: Codex reports none, and the session counts in tokens only.
70
+ return { status: 'read', from, next, turns, agents, skipped: parser.skipped, fingerprint };
71
+ }
72
+ catch (error) {
73
+ if (error instanceof OverBudget) {
74
+ return { status: 'over-budget' };
75
+ }
76
+ if (error instanceof SessionLogFailure) {
77
+ throw error;
78
+ }
79
+ // Messages of fs and JSON errors carry paths and pieces of lines: only a code leaves.
80
+ throw new SessionLogFailure('log-read-failed');
81
+ }
82
+ }
83
+ /** @throws OverBudget past the time of the read: the search lists many directories. */
84
+ locate(session, path, over = () => false) {
85
+ if (path !== undefined && path !== '' && path.endsWith('.jsonl') && existsSync(path)) {
86
+ return path;
87
+ }
88
+ return this.find(`-${session.value}.jsonl`, this.newestDays(SEARCHED_DAYS), over);
89
+ }
90
+ find(suffix, days, over) {
91
+ for (const day of days) {
92
+ stopIf(over);
93
+ if (!existsSync(day)) {
94
+ continue;
95
+ }
96
+ const name = readdirSync(day).find((file) => file.startsWith('rollout-') && file.endsWith(suffix));
97
+ if (name !== undefined) {
98
+ return join(day, name);
99
+ }
100
+ }
101
+ return undefined;
102
+ }
103
+ /** Day directories of the sessions, newest first. */
104
+ newestDays(limit) {
105
+ const root = join(this.home, 'sessions');
106
+ const children = (dir) => (existsSync(dir) ? readdirSync(dir).filter((name) => /^\d+$/.test(name)).sort().reverse() : []);
107
+ const days = [];
108
+ for (const year of children(root)) {
109
+ for (const month of children(join(root, year))) {
110
+ for (const day of children(join(root, year, month))) {
111
+ days.push(join(root, year, month, day));
112
+ if (days.length >= limit) {
113
+ return days;
114
+ }
115
+ }
116
+ }
117
+ }
118
+ return days;
119
+ }
120
+ }
121
+ function parse(file, from, parser, over) {
122
+ const lines = logLines(file, from, over);
123
+ for (let step = lines.next();; step = lines.next()) {
124
+ if (step.done === true) {
125
+ return step.value;
126
+ }
127
+ parser.add(step.value.offset, step.value.text);
128
+ }
129
+ }
130
+ /** A subagent: its turns as stretches of work, its tokens wherever they stand. */
131
+ function agentOf(child) {
132
+ const { turns } = child.result();
133
+ const spans = turns.flatMap((turn) => (turn.start === undefined || turn.end === undefined ? [] : [[turn.start, turn.end]]));
134
+ return { spans, tokens: turns.flatMap((turn) => turn.tokens) };
135
+ }
136
+ function stat(file) {
137
+ const info = statSync(file);
138
+ return { size: info.size, mtimeMs: Math.round(info.mtimeMs) };
139
+ }
140
+ /** Subagents the agent spawned in the session: rollouts of its day and the days after whose meta names the session. */
141
+ function spawnedChildren(main, session, home, over) {
142
+ const children = [];
143
+ for (const day of daysFrom(dirname(main), home)) {
144
+ for (const name of readdirSync(day).sort()) {
145
+ stopIf(over);
146
+ if (!name.startsWith('rollout-') || !name.endsWith('.jsonl') || join(day, name) === main) {
147
+ continue;
148
+ }
149
+ const meta = sessionMeta(join(day, name), session);
150
+ const source = meta?.['source'];
151
+ const spawned = isObject(source) && isObject(source['subagent']) && 'thread_spawn' in source['subagent'];
152
+ if (meta !== undefined && meta['session_id'] === session && spawned && typeof meta['id'] === 'string') {
153
+ children.push([meta['id'], join(day, name)]);
154
+ }
155
+ }
156
+ }
157
+ return children;
158
+ }
159
+ /** The day directory of the parent and the existing ones after it, up to SUBAGENT_DAYS. */
160
+ function daysFrom(dayDir, home) {
161
+ const [year, month, day] = [basename(dirname(dirname(dayDir))), basename(dirname(dayDir)), basename(dayDir)];
162
+ const start = Date.UTC(Number(year), Number(month) - 1, Number(day));
163
+ if (Number.isNaN(start) || !dayDir.startsWith(join(home, 'sessions'))) {
164
+ return existsSync(dayDir) ? [dayDir] : []; // a rollout outside the day directories: its own directory only
165
+ }
166
+ return Array.from({ length: SUBAGENT_DAYS }, (_, i) => {
167
+ const date = new Date(start + i * 86_400_000).toISOString().slice(0, 10).split('-');
168
+ return join(home, 'sessions', ...date);
169
+ }).filter((dir) => existsSync(dir));
170
+ }
171
+ /**
172
+ * The `session_meta` payload of a rollout's first line when it names the session, else undefined. The ids come first
173
+ * in the line, so a file of another session is passed after its first few kilobytes.
174
+ */
175
+ function sessionMeta(file, session) {
176
+ const fd = openSync(file, 'r');
177
+ try {
178
+ const head = Buffer.alloc(HEAD_BYTES);
179
+ const headRead = readSync(fd, head, 0, HEAD_BYTES, 0);
180
+ if (!head.subarray(0, headRead).toString('utf8').includes(`"session_id":"${session}"`)) {
181
+ return undefined;
182
+ }
183
+ const buffer = Buffer.alloc(META_BYTES);
184
+ const read = readSync(fd, buffer, 0, META_BYTES, 0);
185
+ const text = buffer.subarray(0, read).toString('utf8');
186
+ const end = text.indexOf('\n');
187
+ const record = JSON.parse(end < 0 ? text : text.slice(0, end));
188
+ return isObject(record) && record['type'] === 'session_meta' && isObject(record['payload']) ? record['payload'] : undefined;
189
+ }
190
+ catch {
191
+ return undefined;
192
+ }
193
+ finally {
194
+ closeSync(fd);
195
+ }
196
+ }
197
+ function isObject(value) {
198
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
199
+ }
200
+ /** The read ran out of its time while searching directories; `read` turns it into `over-budget`. */
201
+ class OverBudget extends Error {
202
+ }
203
+ function stopIf(over) {
204
+ if (over()) {
205
+ throw new OverBudget();
206
+ }
207
+ }
208
+ //# sourceMappingURL=codex-logs.js.map
@@ -0,0 +1,163 @@
1
+ /*
2
+ * One rollout file of Codex (codex-session-logs spec): `{"timestamp", "type", "payload"}` per line. Only times, turn
3
+ * keys, models and token counts are read; texts of messages, reasoning, tool calls and instructions are never kept.
4
+ */
5
+ const KNOWN_TYPES = new Set([
6
+ 'session_meta',
7
+ 'response_item',
8
+ 'event_msg',
9
+ 'turn_context',
10
+ 'compacted',
11
+ 'token_usage_record',
12
+ 'inter_agent_communication',
13
+ 'inter_agent_communication_metadata',
14
+ 'world_state',
15
+ 'retained_context',
16
+ 'dynamic_tools_updated',
17
+ 'security_risk_score',
18
+ 'realtime_item',
19
+ ]);
20
+ const BUCKET_MS = 5 * 60_000;
21
+ /** A rollout gives no model before its first `turn_context`; tokens there still count. */
22
+ const UNKNOWN_MODEL = 'unknown';
23
+ export class RolloutParser {
24
+ from;
25
+ records = 0;
26
+ /** Records of a known type; a file whose records are all unknown is not a rollout. */
27
+ recognized = 0;
28
+ /** A rollout starts with `session_meta`; its absence in a file read from the start means another format. */
29
+ sessionMeta = false;
30
+ skipped = 0;
31
+ turns = [];
32
+ byKey = new Map();
33
+ responses = new Set();
34
+ model = UNKNOWN_MODEL;
35
+ usageRecords = false;
36
+ /** The running total of the last `token_count` counted. */
37
+ lastTotal;
38
+ countTokens;
39
+ constructor(from) {
40
+ this.from = from;
41
+ // Tokens before the first turn of the part read belong to a turn without times, keyed by where the read began.
42
+ this.countTokens = { key: from, tokens: new Map() };
43
+ }
44
+ add(offset, line) {
45
+ let record;
46
+ try {
47
+ const value = JSON.parse(line);
48
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
49
+ this.skipped += 1;
50
+ return;
51
+ }
52
+ record = value;
53
+ }
54
+ catch {
55
+ this.skipped += 1;
56
+ return;
57
+ }
58
+ this.records += 1;
59
+ const type = typeof record['type'] === 'string' ? record['type'] : '';
60
+ const at = Date.parse(typeof record['timestamp'] === 'string' ? record['timestamp'] : '');
61
+ const payload = isObject(record['payload']) ? record['payload'] : {};
62
+ if (!KNOWN_TYPES.has(type) || Number.isNaN(at)) {
63
+ this.skipped += 1;
64
+ return;
65
+ }
66
+ this.recognized += 1;
67
+ if (type === 'session_meta') {
68
+ this.sessionMeta = true;
69
+ }
70
+ else if (type === 'turn_context' && typeof payload['model'] === 'string' && payload['model'] !== '') {
71
+ this.model = payload['model'];
72
+ }
73
+ else if (type === 'event_msg') {
74
+ this.event(offset, at, payload);
75
+ }
76
+ else if (type === 'token_usage_record') {
77
+ this.usage(at, payload['response_id'], payload['usage']);
78
+ }
79
+ }
80
+ /** Turns from the part read, and where the next read starts: the first line of its last turn. */
81
+ result() {
82
+ const turns = [...(this.countTokens.tokens.size > 0 ? [this.countTokens] : []), ...this.turns].map((turn) => ({
83
+ key: turn.key,
84
+ ...(turn.start === undefined ? {} : { start: turn.start }),
85
+ ...(turn.end === undefined ? {} : { end: turn.end }),
86
+ tokens: [...turn.tokens.values()],
87
+ }));
88
+ return { turns, next: this.turns.at(-1)?.key ?? this.from };
89
+ }
90
+ event(offset, at, payload) {
91
+ const kind = payload['type'];
92
+ const turnId = typeof payload['turn_id'] === 'string' ? payload['turn_id'] : undefined;
93
+ if (kind === 'task_started' && turnId !== undefined) {
94
+ const turn = { key: offset, start: at, tokens: new Map() };
95
+ this.turns.push(turn);
96
+ this.byKey.set(turnId, turn);
97
+ }
98
+ else if ((kind === 'task_complete' || kind === 'turn_aborted') && turnId !== undefined) {
99
+ const turn = this.byKey.get(turnId);
100
+ if (turn !== undefined) {
101
+ turn.end = Math.max(turn.end ?? at, at);
102
+ }
103
+ }
104
+ else if (kind === 'token_count' && !this.usageRecords) {
105
+ const info = isObject(payload['info']) ? payload['info'] : undefined;
106
+ // Codex repeats the event with the same running total (rate limits, a resumed thread): no new response then.
107
+ const total = isObject(info?.['total_token_usage']) ? info['total_token_usage']['total_tokens'] : undefined;
108
+ if (typeof total === 'number' && total === this.lastTotal) {
109
+ return;
110
+ }
111
+ if (typeof total === 'number') {
112
+ this.lastTotal = total; // an event without a total does not forget the last one
113
+ }
114
+ this.count(at, info?.['last_token_usage']);
115
+ }
116
+ }
117
+ /** One response's usage, once per response; the newer record wins over the running `token_count`. */
118
+ usage(at, response, usage) {
119
+ if (!this.usageRecords) {
120
+ // A file with these records counts only them: `token_count` repeats the same responses.
121
+ this.usageRecords = true;
122
+ for (const turn of [this.countTokens, ...this.turns]) {
123
+ turn.tokens.clear();
124
+ }
125
+ }
126
+ if (typeof response === 'string') {
127
+ if (this.responses.has(response)) {
128
+ return;
129
+ }
130
+ this.responses.add(response);
131
+ }
132
+ this.count(at, usage);
133
+ }
134
+ count(at, usage) {
135
+ if (!isObject(usage)) {
136
+ return;
137
+ }
138
+ const input = number(usage['input_tokens']);
139
+ const cached = Math.min(number(usage['cached_input_tokens']), input);
140
+ const turn = this.turns.at(-1) ?? this.countTokens;
141
+ const bucketAt = Math.floor(at / BUCKET_MS) * BUCKET_MS;
142
+ const key = `${this.model}\u0000${bucketAt}`;
143
+ const before = turn.tokens.get(key);
144
+ turn.tokens.set(key, {
145
+ at: bucketAt,
146
+ model: this.model,
147
+ // OpenAI counts cached input inside the input: only the rest is new input.
148
+ input: (before?.input ?? 0) + input - cached,
149
+ output: (before?.output ?? 0) + number(usage['output_tokens']),
150
+ cacheRead: (before?.cacheRead ?? 0) + cached,
151
+ cacheWrite5m: 0,
152
+ cacheWrite1h: 0,
153
+ cacheWrite: (before?.cacheWrite ?? 0) + number(usage['cache_write_input_tokens']),
154
+ });
155
+ }
156
+ }
157
+ function number(value) {
158
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.round(value) : 0;
159
+ }
160
+ function isObject(value) {
161
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
162
+ }
163
+ //# sourceMappingURL=rollout-parser.js.map
@@ -0,0 +1,38 @@
1
+ /*
2
+ * The rule that lets the agent of Codex run the task commands of estimetry outside its sandbox, without asking
3
+ * (`prefix_rule` with `decision = "allow"`, the rules of Codex in `<config layer>/rules/`). They write to the store
4
+ * of estimetry, outside the workspace the sandbox allows. `init`, `upgrade`, `rebuild` and `hook` are left out: they
5
+ * write the files of projects and of the tools, so Codex still asks for them.
6
+ */
7
+ const MARK = '# Written by estimetry';
8
+ /** Commands of `emt` that work with tasks: the store of estimetry only. */
9
+ const TASK_COMMANDS = [
10
+ 'task',
11
+ 'start',
12
+ 'attach',
13
+ 'estimate',
14
+ 'extra',
15
+ 'manual',
16
+ 'parallel',
17
+ 'status',
18
+ 'close',
19
+ 'reopen',
20
+ 'retro',
21
+ 'renegotiate',
22
+ 'similar',
23
+ 'calibrate',
24
+ ];
25
+ export function SANDBOX_RULES(version) {
26
+ const alternatives = JSON.stringify(TASK_COMMANDS);
27
+ return [
28
+ `${MARK} ${version}: its task commands write to its own store, outside the sandbox of Codex.`,
29
+ '# `init`, `upgrade` and `rebuild` are not here: Codex still asks before them.',
30
+ ...['emt', 'estimetry'].map((bin) => `prefix_rule(pattern=["${bin}", ${alternatives}], decision="allow", justification="estimetry writes its own store")`),
31
+ '',
32
+ ].join('\n');
33
+ }
34
+ /** Whether a rules file is ours to rewrite. */
35
+ export function isOurRules(text) {
36
+ return text.startsWith(MARK);
37
+ }
38
+ //# sourceMappingURL=sandbox-rules.js.map
@@ -0,0 +1,22 @@
1
+ import { ARGUMENTS_MENTION, renderBody } from '../../../application/contracts/skill-mention.js';
2
+ import { generatedBy, stamp } from '../shared/generated-file.js';
3
+ import { codexSkillRef } from './hook-events.js';
4
+ /** Codex has no substitution of arguments: the agent finds them in the message that called the skill. */
5
+ const ARGUMENTS = '<arguments>';
6
+ /** A skill file in the format of Codex (`name`, `description`), stamped with the version and a hash of its own text. */
7
+ export function renderSkill(content, version) {
8
+ const takesArguments = content.body.includes(ARGUMENTS_MENTION);
9
+ return stamp([
10
+ '---',
11
+ `name: ${content.id}`,
12
+ `description: ${JSON.stringify(content.description)}`,
13
+ ...generatedBy(version),
14
+ '---',
15
+ '',
16
+ ...(takesArguments
17
+ ? [`\`${ARGUMENTS}\` below stands for what the user wrote after \`${codexSkillRef(content.id)}\`, if anything.`, '']
18
+ : []),
19
+ renderBody(content.body, codexSkillRef, ARGUMENTS),
20
+ ].join('\n'));
21
+ }
22
+ //# sourceMappingURL=skill-file.js.map
@@ -0,0 +1,96 @@
1
+ /*
2
+ * The tables `[hooks.state."<key>"]` of the user config of Codex, read and written by lines (codex-install spec,
3
+ * "Одобрение хуков Codex"). The rest of the file stays byte for byte: its comments, order and line endings. A file
4
+ * whose shape lines cannot handle safely — `hooks` or `state` as an inline table or a dotted key, multi-line strings,
5
+ * a table of ours defined twice — is refused: no trust is written, and the user trusts the hooks in `/hooks`.
6
+ */
7
+ const UNSAFE = [/^\s*(hooks|state)\s*=/, /^\s*(hooks\s*\.\s*)?state\s*\./, /^\s*hooks\s*\./];
8
+ /** The table of a key, if the config has it; undefined for a config lines cannot read safely too. */
9
+ export function stateTable(config, key) {
10
+ const lines = linesOf(config ?? '');
11
+ if (lines === undefined) {
12
+ return undefined;
13
+ }
14
+ const found = tablesOf(lines, key);
15
+ const [only] = found;
16
+ return only === undefined || found.length > 1 ? undefined : bodyFacts(lines.slice(only.start + 1, only.end));
17
+ }
18
+ /** The config with our tables written anew at its end, each keeping its `enabled`; undefined when it is refused. */
19
+ export function withStateTables(config, tables) {
20
+ const text = config ?? '';
21
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
22
+ let lines = linesOf(text);
23
+ if (lines === undefined) {
24
+ return undefined;
25
+ }
26
+ const written = [];
27
+ for (const table of tables) {
28
+ const found = tablesOf(lines, table.key);
29
+ if (found.length > 1) {
30
+ return undefined; // a table defined twice is no TOML: Codex itself would refuse the file
31
+ }
32
+ const [current] = found;
33
+ const enabled = current === undefined ? undefined : bodyFacts(lines.slice(current.start + 1, current.end)).enabled;
34
+ if (current !== undefined) {
35
+ lines = [...lines.slice(0, current.start), ...lines.slice(current.end)];
36
+ }
37
+ written.push([header(table.key), ...(enabled === undefined ? [] : [enabled]), `trusted_hash = "${table.trustedHash}"`].join(eol));
38
+ }
39
+ const body = lines.join(eol).replace(/(\r?\n){3,}/g, `${eol}${eol}`).replace(/(\r?\n)+$/, '');
40
+ return `${body === '' ? '' : `${body}${eol}${eol}`}${written.join(`${eol}${eol}`)}${eol}`;
41
+ }
42
+ /** The lines of a config lines can handle, or undefined. */
43
+ function linesOf(config) {
44
+ if (config.includes('"""') || config.includes("'''")) {
45
+ return undefined;
46
+ }
47
+ const lines = config === '' ? [] : config.split(/\r?\n/);
48
+ return lines.some((line) => !isComment(line) && UNSAFE.some((unsafe) => unsafe.test(line))) ? undefined : lines;
49
+ }
50
+ /** Each table of the key: its header line and the line where the next table starts. */
51
+ function tablesOf(lines, key) {
52
+ const found = [];
53
+ lines.forEach((line, start) => {
54
+ if (sameKey(headerKey(line), ['hooks', 'state', key])) {
55
+ const next = lines.findIndex((other, i) => i > start && headerKey(other) !== undefined);
56
+ found.push({ start, end: next < 0 ? lines.length : next });
57
+ }
58
+ });
59
+ return found;
60
+ }
61
+ function bodyFacts(body) {
62
+ const live = body.filter((line) => !isComment(line));
63
+ const hash = live.map((line) => /^\s*trusted_hash\s*=\s*"([^"]*)"/.exec(line)?.[1]).find((value) => value !== undefined);
64
+ const enabled = live.find((line) => /^\s*enabled\s*=/.test(line))?.trim();
65
+ return { ...(hash === undefined ? {} : { trustedHash: hash }), ...(enabled === undefined ? {} : { enabled }) };
66
+ }
67
+ /** The key of a table header line (`[a.b."c"]`, with spaces, quotes of both kinds, a comment after); not of `[[…]]`. */
68
+ function headerKey(line) {
69
+ const match = /^\s*\[(?!\[)(.*)\]\s*(#.*)?$/.exec(line);
70
+ if (match?.[1] === undefined) {
71
+ return undefined;
72
+ }
73
+ const parts = [];
74
+ const key = /\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([A-Za-z0-9_-]+))\s*(\.|$)/y;
75
+ let rest = match[1];
76
+ while (rest !== '') {
77
+ key.lastIndex = 0;
78
+ const part = key.exec(rest);
79
+ if (part === null) {
80
+ return undefined;
81
+ }
82
+ parts.push(part[1] !== undefined ? part[1].replace(/\\(["\\])/g, '$1') : (part[2] ?? part[3] ?? ''));
83
+ rest = rest.slice(part[0].length);
84
+ }
85
+ return parts;
86
+ }
87
+ function sameKey(found, wanted) {
88
+ return found !== undefined && found.length === wanted.length && found.every((part, i) => part === wanted[i]);
89
+ }
90
+ function header(key) {
91
+ return `[hooks.state."${key.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"]`;
92
+ }
93
+ function isComment(line) {
94
+ return /^\s*#/.test(line);
95
+ }
96
+ //# sourceMappingURL=trust-tables.js.map