estimetry 0.1.2 → 0.2.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 (51) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +41 -11
  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/bootstrap/container.js +23 -6
  16. package/dist/bootstrap/hook-receiver.js +7 -14
  17. package/dist/bootstrap/main.js +1 -1
  18. package/dist/domain/code/code-classes.js +1 -1
  19. package/dist/domain/progress/progress-record-parser.js +6 -0
  20. package/dist/domain/progress/session-log.js +2 -1
  21. package/dist/domain/usage/task-usage.js +24 -7
  22. package/dist/integrations/tools/claude-code/claude-code-adapter.js +29 -48
  23. package/dist/integrations/tools/claude-code/hook-events.js +4 -0
  24. package/dist/integrations/tools/claude-code/hook-translation.js +16 -34
  25. package/dist/integrations/tools/claude-code/importer/claude-code-logs.js +1 -1
  26. package/dist/integrations/tools/claude-code/skill-file.js +7 -19
  27. package/dist/integrations/tools/codex/codex-adapter.js +161 -0
  28. package/dist/integrations/tools/codex/hook-events.js +23 -0
  29. package/dist/integrations/tools/codex/hook-translation.js +76 -0
  30. package/dist/integrations/tools/codex/hook-trust.js +69 -0
  31. package/dist/integrations/tools/codex/importer/codex-logs.js +208 -0
  32. package/dist/integrations/tools/codex/importer/rollout-parser.js +163 -0
  33. package/dist/integrations/tools/codex/sandbox-rules.js +38 -0
  34. package/dist/integrations/tools/codex/skill-file.js +22 -0
  35. package/dist/integrations/tools/codex/trust-tables.js +96 -0
  36. package/dist/integrations/tools/content/commands.js +27 -20
  37. package/dist/integrations/tools/shared/generated-file.js +26 -0
  38. package/dist/integrations/tools/shared/hook-payload.js +33 -0
  39. package/dist/integrations/tools/{claude-code → shared}/hook-settings.js +37 -22
  40. package/dist/integrations/tools/shared/instructions-block.js +39 -0
  41. package/dist/integrations/tools/shared/skills-plan.js +39 -0
  42. package/dist/interface/cli/commands/hook-command.js +1 -1
  43. package/dist/interface/cli/commands/init-command.js +16 -7
  44. package/dist/interface/cli/commands/status-command.js +5 -2
  45. package/dist/interface/cli/presenters/text/closing-text.js +7 -3
  46. package/dist/interface/cli/presenters/text/notices-text.js +1 -0
  47. package/dist/interface/cli/presenters/text/task-text.js +1 -1
  48. package/dist/interface/cli/presenters/text-presenter.js +3 -3
  49. package/package.json +1 -1
  50. package/dist/integrations/tools/claude-code/claude-md.js +0 -28
  51. /package/dist/integrations/tools/{claude-code/importer → shared}/log-lines.js +0 -0
@@ -156,6 +156,9 @@ function logSession(data) {
156
156
  });
157
157
  buckets(agent['tokens'], `data.agents[${i}].tokens`);
158
158
  });
159
+ if (data['costReported'] !== undefined && typeof data['costReported'] !== 'boolean') {
160
+ throw new InvalidProgressRecord('data.costReported', 'must be true or false');
161
+ }
159
162
  list(data['cost'], 'data.cost').forEach((item, i) => {
160
163
  const total = object(item, `data.cost[${i}]`);
161
164
  moment(total, 'startTime', `data.cost[${i}].`);
@@ -175,6 +178,9 @@ function buckets(value, path) {
175
178
  for (const key of ['input', 'output', 'cacheRead', 'cacheWrite5m', 'cacheWrite1h']) {
176
179
  count(bucket, key, `${path}[${i}].`);
177
180
  }
181
+ if (bucket['cacheWrite'] !== undefined) {
182
+ count(bucket, 'cacheWrite', `${path}[${i}].`);
183
+ }
178
184
  });
179
185
  }
180
186
  function moment(record, key, prefix) {
@@ -22,7 +22,8 @@ export function sessionLogs(records, closed = []) {
22
22
  continue; // a write cut short: the next import reads the same stretch again
23
23
  }
24
24
  const { session, from } = first.data;
25
- const log = merged.get(session) ?? { turns: [], agents: new Map(), cost: new Map() };
25
+ const log = merged.get(session) ?? { turns: [], agents: new Map(), cost: new Map(), reportsCost: false };
26
+ log.reportsCost ||= first.data.costReported !== false;
26
27
  log.turns = [...log.turns.filter((turn) => turn.key < from), ...joinedTurns(parts.flatMap((part) => part.data.turns))];
27
28
  for (const agent of joinedAgents(parts.flatMap((part) => part.data.agents))) {
28
29
  log.agents.set(agent.agent, agent);
@@ -4,18 +4,26 @@
4
4
  * session served the task come in as arguments.
5
5
  */
6
6
  /**
7
- * Relative weight of a token of each kind, the structure of Claude prices (an
8
- * input token is 1). Fitted without residue to the totals of the studied
9
- * sessions; prices themselves are not in the code. The cost of a session stays
10
- * exact whatever the weights: they only split it between tasks.
7
+ * Relative weight of a token of each kind (an input token is 1), the structure of Claude prices, the only tool that
8
+ * reports a cost: fitted without residue to the totals of the studied sessions; prices themselves are not in the
9
+ * code. A cache write without a lifetime weighs as the short one. The cost of a session stays exact whatever the
10
+ * weights: they only split it between tasks.
11
11
  */
12
- export const TOKEN_WEIGHTS = { input: 1, output: 5, cacheRead: 0.05, cacheWrite5m: 1.25, cacheWrite1h: 2 };
12
+ export const TOKEN_WEIGHTS = {
13
+ input: 1,
14
+ output: 5,
15
+ cacheRead: 0.05,
16
+ cacheWrite5m: 1.25,
17
+ cacheWrite1h: 2,
18
+ cacheWrite: 1.25,
19
+ };
13
20
  /** Undefined when no session of the task has a log. */
14
21
  export function taskUsage(input) {
15
22
  const tokens = new Map();
16
23
  let cost = 0;
17
24
  let approximate = false;
18
25
  let withLogs = 0;
26
+ let withCost = 0;
19
27
  for (const [session, spans] of input.spans) {
20
28
  const log = input.logs.get(session);
21
29
  if (log === undefined) {
@@ -32,6 +40,10 @@ export function taskUsage(input) {
32
40
  if (own < all) {
33
41
  approximate = true;
34
42
  }
43
+ if (!log.reportsCost) {
44
+ continue; // its tokens count; its cost is not known to the tool, so it is no part of the cost
45
+ }
46
+ withCost += 1;
35
47
  const totals = [...log.cost.values()];
36
48
  if (totals.some((total) => total.unknown)) {
37
49
  cost = null;
@@ -43,7 +55,7 @@ export function taskUsage(input) {
43
55
  if (withLogs === 0) {
44
56
  return undefined;
45
57
  }
46
- return { tokens, costUSD: cost, approximate, sessions: input.spans.size, withLogs };
58
+ return { tokens, costUSD: withCost === 0 ? null : cost, approximate, sessions: input.spans.size, withLogs, withCost };
47
59
  }
48
60
  function weight(buckets) {
49
61
  return buckets.reduce((sum, b) => sum +
@@ -51,7 +63,8 @@ function weight(buckets) {
51
63
  b.output * TOKEN_WEIGHTS.output +
52
64
  b.cacheRead * TOKEN_WEIGHTS.cacheRead +
53
65
  b.cacheWrite5m * TOKEN_WEIGHTS.cacheWrite5m +
54
- b.cacheWrite1h * TOKEN_WEIGHTS.cacheWrite1h, 0);
66
+ b.cacheWrite1h * TOKEN_WEIGHTS.cacheWrite1h +
67
+ (b.cacheWrite ?? 0) * TOKEN_WEIGHTS.cacheWrite, 0);
55
68
  }
56
69
  function add(sum, bucket) {
57
70
  return {
@@ -60,6 +73,9 @@ function add(sum, bucket) {
60
73
  cacheRead: (sum?.cacheRead ?? 0) + bucket.cacheRead,
61
74
  cacheWrite5m: (sum?.cacheWrite5m ?? 0) + bucket.cacheWrite5m,
62
75
  cacheWrite1h: (sum?.cacheWrite1h ?? 0) + bucket.cacheWrite1h,
76
+ ...(sum?.cacheWrite === undefined && bucket.cacheWrite === undefined
77
+ ? {}
78
+ : { cacheWrite: (sum?.cacheWrite ?? 0) + (bucket.cacheWrite ?? 0) }),
63
79
  };
64
80
  }
65
81
  /**
@@ -81,6 +97,7 @@ export function usageSummary(usage) {
81
97
  approximate: usage.approximate,
82
98
  sessions: usage.sessions,
83
99
  withLogs: usage.withLogs,
100
+ withCost: usage.withCost,
84
101
  };
85
102
  }
86
103
  //# sourceMappingURL=task-usage.js.map
@@ -1,14 +1,19 @@
1
1
  import { join } from 'node:path';
2
- import { COMMANDS, ESTIMETRY_SKILL } from '../content/commands.js';
3
- import { withBlock, withoutBlock } from './claude-md.js';
2
+ import { COMMANDS, ESTIMATE_REMINDER_BLOCK, ESTIMETRY_SKILL } from '../content/commands.js';
4
3
  import { estimetryCommand } from '../../../application/contracts/estimetry-command.js';
5
- import { hasOurHooks, isBrokenJson, withHooks, withoutHooks } from './hook-settings.js';
6
- import { CLAUDE_CODE_HOOK_EVENTS, SYNCHRONOUS_HOOK_EVENTS } from './hook-events.js';
7
- import { ownership, renderSkill } from './skill-file.js';
4
+ import { hasOurHooks, isBrokenJson, withHooks, withoutHooks } from '../shared/hook-settings.js';
5
+ import { instructionsPlan } from '../shared/instructions-block.js';
6
+ import { nameSkills } from '../../../application/contracts/skill-mention.js';
7
+ import { skillsPlan } from '../shared/skills-plan.js';
8
+ import { CLAUDE_CODE_HOOK_EVENTS, SYNCHRONOUS_HOOK_EVENTS, claudeCodeSkillRef } from './hook-events.js';
9
+ import { renderSkill } from './skill-file.js';
8
10
  export { CLAUDE_CODE_HOOK_EVENTS } from './hook-events.js';
9
11
  const SHARED_SETTINGS = join('.claude', 'settings.json');
10
12
  const LOCAL_SETTINGS = join('.claude', 'settings.local.json');
11
13
  const SKILLS = [ESTIMETRY_SKILL, ...COMMANDS];
14
+ /** Our hooks in the settings: `estimetry hook claude-code …`, in any form `estimetryCommand` gives. */
15
+ const OURS = 'hook claude-code';
16
+ const CLAUDE_MD_BLOCK = nameSkills(ESTIMATE_REMINDER_BLOCK, claudeCodeSkillRef);
12
17
  /**
13
18
  * Claude Code: hooks in the project settings, skills (which are also its slash
14
19
  * commands) in the user's directory or, for a shared install, in the project.
@@ -19,6 +24,8 @@ export class ClaudeCodeAdapter {
19
24
  aliases = ['claude'];
20
25
  title = 'Claude Code';
21
26
  hookEvents = CLAUDE_CODE_HOOK_EVENTS;
27
+ /** Claude Code runs the hooks in its settings as they are. */
28
+ asksTrust = false;
22
29
  /** `configDir` is the user's Claude Code directory: `$CLAUDE_CONFIG_DIR` or `~/.claude`. */
23
30
  constructor(configDir) {
24
31
  this.configDir = configDir;
@@ -26,17 +33,20 @@ export class ClaudeCodeAdapter {
26
33
  state(projectRoot, files) {
27
34
  const sharedText = files.read(join(projectRoot, SHARED_SETTINGS));
28
35
  const localText = files.read(join(projectRoot, LOCAL_SETTINGS));
29
- const shared = hasOurHooks(sharedText);
36
+ const shared = hasOurHooks(sharedText, OURS);
30
37
  const broken = [
31
38
  ...(isBrokenJson(sharedText) ? [SHARED_SETTINGS] : []),
32
39
  ...(isBrokenJson(localText) ? [LOCAL_SETTINGS] : []),
33
40
  ];
34
41
  return {
35
- installed: shared || hasOurHooks(localText),
42
+ installed: shared || hasOurHooks(localText, OURS),
36
43
  shared,
37
44
  ...(broken.length === 0 ? {} : { unreadable: `${broken.join(' and ')} ${broken.length === 1 ? 'is' : 'are'} not valid JSON` }),
38
45
  };
39
46
  }
47
+ present(files) {
48
+ return files.isDirectory(this.configDir);
49
+ }
40
50
  personalFiles() {
41
51
  return [LOCAL_SETTINGS];
42
52
  }
@@ -51,18 +61,18 @@ export class ClaudeCodeAdapter {
51
61
  hooks({ projectRoot, files, shared, runner }) {
52
62
  const [target, previous] = shared ? [SHARED_SETTINGS, LOCAL_SETTINGS] : [LOCAL_SETTINGS, SHARED_SETTINGS];
53
63
  // Personal settings run this installation by its paths; settings the team commits hold no paths of this machine.
54
- const command = (event) => estimetryCommand(shared ? undefined : runner, `hook claude-code ${event}`);
64
+ const command = (event) => estimetryCommand(shared ? undefined : runner, `${OURS} ${event}`);
55
65
  const changes = [
56
66
  {
57
67
  path: join(projectRoot, target),
58
- content: withHooks(files.read(join(projectRoot, target)), { events: this.hookEvents, synchronous: SYNCHRONOUS_HOOK_EVENTS, command }, target),
68
+ content: withHooks(files.read(join(projectRoot, target)), { ours: OURS, events: this.hookEvents, synchronous: SYNCHRONOUS_HOOK_EVENTS, command }, target),
59
69
  },
60
70
  ];
61
71
  const warnings = [];
62
72
  const old = files.read(join(projectRoot, previous));
63
73
  if (old !== undefined) {
64
74
  try {
65
- const cleaned = withoutHooks(old, previous);
75
+ const cleaned = withoutHooks(old, OURS, previous);
66
76
  changes.push(cleaned === undefined
67
77
  ? { path: join(projectRoot, previous), remove: true }
68
78
  : { path: join(projectRoot, previous), content: cleaned });
@@ -75,48 +85,19 @@ export class ClaudeCodeAdapter {
75
85
  return { changes, skipped: [], warnings };
76
86
  }
77
87
  skills({ projectRoot, files, shared, force, version }) {
78
- const changes = [];
79
- const skipped = [];
80
- const projectSkills = join(projectRoot, '.claude', 'skills');
81
- const target = shared ? projectSkills : join(this.configDir, 'skills');
82
- for (const skill of SKILLS) {
83
- const path = join(target, skill.id, 'SKILL.md');
84
- const current = files.read(path);
85
- const owner = current === undefined ? 'ours' : ownership(current);
86
- if (owner === 'foreign') {
87
- skipped.push({ path, reason: 'not created by estimetry, left as it is' });
88
- }
89
- else if (owner === 'edited' && !force) {
90
- skipped.push({ path, reason: 'edited after install; run init --force to overwrite it' });
91
- }
92
- else {
93
- changes.push({ path, content: renderSkill(skill, version) });
94
- }
95
- // A personal install takes the skills out of the project; a shared one keeps the personal ones for other projects.
96
- if (!shared) {
97
- const inProject = join(projectSkills, skill.id, 'SKILL.md');
98
- const text = files.read(inProject);
99
- if (text !== undefined && ownership(text) === 'ours') {
100
- changes.push({ path: inProject, remove: true });
101
- }
102
- else if (text !== undefined && ownership(text) === 'edited') {
103
- skipped.push({ path: inProject, reason: 'edited after install, so it stays in the project' });
104
- }
105
- }
106
- }
107
- return { changes, skipped, warnings: [] };
88
+ return skillsPlan(SKILLS, {
89
+ files,
90
+ projectDir: join(projectRoot, '.claude', 'skills'),
91
+ userDir: join(this.configDir, 'skills'),
92
+ shared,
93
+ force,
94
+ render: (skill) => renderSkill(skill, version),
95
+ });
108
96
  }
109
97
  /** The reminder goes to the committed CLAUDE.md only with a shared install. */
110
98
  claudeMd({ projectRoot, files, shared }) {
111
99
  const path = join(projectRoot, 'CLAUDE.md');
112
- const current = files.read(path);
113
- if (shared) {
114
- return { changes: [{ path, content: withBlock(current) }], skipped: [], warnings: [] };
115
- }
116
- if (current === undefined) {
117
- return { changes: [], skipped: [], warnings: [] };
118
- }
119
- return { changes: [{ path, content: withoutBlock(current) }], skipped: [], warnings: [] };
100
+ return instructionsPlan(path, files.read(path), shared, CLAUDE_MD_BLOCK);
120
101
  }
121
102
  }
122
103
  //# sourceMappingURL=claude-code-adapter.js.map
@@ -15,4 +15,8 @@ export const CLAUDE_CODE_HOOK_EVENTS = [
15
15
  ];
16
16
  /** Hooks the agent must wait for: their context has to reach it in the same turn, or the session is ending. */
17
17
  export const SYNCHRONOUS_HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'SessionEnd'];
18
+ /** How Claude Code calls a skill: as a slash command. One rule for the context of hooks and the bodies of skills. */
19
+ export function claudeCodeSkillRef(id) {
20
+ return `/${id}`;
21
+ }
18
22
  //# sourceMappingURL=hook-events.js.map
@@ -1,6 +1,5 @@
1
- import { SessionId } from '../../../domain/measurement/session-id.js';
2
- import { InvalidValue } from '../../../domain/shared/domain-error.js';
3
- import { CLAUDE_CODE_HOOK_EVENTS } from './hook-events.js';
1
+ import { additionalContext, payloadText, translateHook } from '../shared/hook-payload.js';
2
+ import { CLAUDE_CODE_HOOK_EVENTS, claudeCodeSkillRef } from './hook-events.js';
4
3
  /*
5
4
  * Claude Code hook payloads → activity events (claude-code-hooks spec). Prompt
6
5
  * texts, tool inputs and outputs are read only to classify the call and never
@@ -28,39 +27,25 @@ export const claudeCodeHooks = {
28
27
  id: 'claude-code',
29
28
  aliases: ['claude'],
30
29
  hookEvents: CLAUDE_CODE_HOOK_EVENTS,
30
+ projectDirVariable: 'CLAUDE_PROJECT_DIR',
31
+ // Claude Code waits for the synchronous SessionEnd within the timeout of the hook (10 s); the spec gives the import 5 s.
32
+ sessionEndBudgetMs: 5_000,
31
33
  translate(event, payload) {
32
- if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
33
- throw new InvalidValue(`claude-code ${event}: stdin is not a JSON object`);
34
- }
35
- const p = payload;
36
- if (typeof p['session_id'] !== 'string') {
37
- throw new InvalidValue(`claude-code ${event}: session_id is missing`);
38
- }
39
- const session = SessionId.parse(p['session_id']);
40
- const cwd = typeof p['cwd'] === 'string' ? p['cwd'] : undefined;
41
- const transcript = typeof p['transcript_path'] === 'string' && p['transcript_path'] !== '' ? p['transcript_path'] : undefined;
42
- return {
43
- session,
44
- ...(cwd === undefined ? {} : { cwd }),
45
- ...(transcript === undefined ? {} : { transcript }),
46
- kind: KINDS[event] ?? 'other',
47
- events: translateEvent(event, p),
48
- };
49
- },
50
- renderContext(event, text) {
51
- return JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: text } });
34
+ return translateHook('claude-code', event, payload, KINDS, translateEvent);
52
35
  },
36
+ skillRef: claudeCodeSkillRef,
37
+ renderContext: additionalContext,
53
38
  };
54
39
  function translateEvent(event, p) {
55
- const agent = text(p['agent_id']);
40
+ const agent = payloadText(p['agent_id']);
56
41
  const onAgent = agent === undefined ? {} : { agent };
57
- const turn = agent === undefined && text(p['prompt_id']) !== undefined ? { turn: text(p['prompt_id']) } : {};
58
- const tool = text(p['tool_name']);
59
- const toolUseId = text(p['tool_use_id']);
42
+ const turn = agent === undefined && payloadText(p['prompt_id']) !== undefined ? { turn: payloadText(p['prompt_id']) } : {};
43
+ const tool = payloadText(p['tool_name']);
44
+ const toolUseId = payloadText(p['tool_use_id']);
60
45
  const call = { ...onAgent, ...(tool === undefined ? {} : { tool }), ...(toolUseId === undefined ? {} : { toolUseId }) };
61
46
  switch (event) {
62
47
  case 'SessionStart': {
63
- const source = text(p['source']);
48
+ const source = payloadText(p['source']);
64
49
  if (agent !== undefined || source === 'clear' || source === 'compact') {
65
50
  return []; // a subagent's start, or the same session going on
66
51
  }
@@ -85,7 +70,7 @@ function translateEvent(event, p) {
85
70
  ? []
86
71
  : [{ type: 'turn.awaiting-input', data: { ...onAgent, reason: 'permission', ...turn } }];
87
72
  case 'Notification': {
88
- const type = text(p['notification_type']);
73
+ const type = payloadText(p['notification_type']);
89
74
  return type !== undefined && QUESTION_NOTIFICATIONS.has(type)
90
75
  ? [{ type: 'turn.awaiting-input', data: { ...onAgent, reason: 'question', ...turn } }]
91
76
  : [];
@@ -96,7 +81,7 @@ function translateEvent(event, p) {
96
81
  const launched = tool !== undefined && SUBAGENT_TOOLS.has(tool) && typeof response === 'object' && response !== null
97
82
  ? response
98
83
  : undefined;
99
- const child = launched?.['status'] === 'async_launched' ? text(launched['agentId']) : undefined;
84
+ const child = launched?.['status'] === 'async_launched' ? payloadText(launched['agentId']) : undefined;
100
85
  return child === undefined ? [used] : [used, { type: 'agent.detached', data: { agent: child } }];
101
86
  }
102
87
  case 'PostToolUseFailure': {
@@ -106,7 +91,7 @@ function translateEvent(event, p) {
106
91
  : [used];
107
92
  }
108
93
  case 'SubagentStart': {
109
- const type = text(p['agent_type']);
94
+ const type = payloadText(p['agent_type']);
110
95
  return agent === undefined ? [] : [{ type: 'agent.started', data: { agent, ...(type === undefined ? {} : { agentType: type }) } }];
111
96
  }
112
97
  case 'SubagentStop':
@@ -119,7 +104,4 @@ function duration(p) {
119
104
  const value = typeof p['duration_ms'] === 'string' ? Number(p['duration_ms']) : p['duration_ms'];
120
105
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? { durationMs: Math.round(value) } : {};
121
106
  }
122
- function text(value) {
123
- return typeof value === 'string' && value !== '' ? value : undefined;
124
- }
125
107
  //# sourceMappingURL=hook-translation.js.map
@@ -3,7 +3,7 @@ import { basename, dirname, join } from 'node:path';
3
3
  import { performance } from 'node:perf_hooks';
4
4
  import { SessionLogFailure, } from '../../../../application/contracts/session-logs.js';
5
5
  import { AgentLogParser, MainLogParser } from './log-parser.js';
6
- import { logLines } from './log-lines.js';
6
+ import { logLines } from '../../shared/log-lines.js';
7
7
  const AGENT_FILE = /^agent-(.+)\.jsonl$/;
8
8
  /**
9
9
  * Session logs of Claude Code: `<config>/projects/<folder>/<session>.jsonl`
@@ -1,31 +1,19 @@
1
- import { createHash } from 'node:crypto';
1
+ import { renderBody } from '../../../application/contracts/skill-mention.js';
2
+ import { generatedBy, stamp } from '../shared/generated-file.js';
3
+ import { claudeCodeSkillRef } from './hook-events.js';
2
4
  const ALLOWED_TOOLS = 'Bash(emt *) Bash(estimetry *)';
3
- const HASH_LINE = /^ {2}contentHash: "[0-9a-f]*"\n/m;
4
5
  /** A skill file in Claude Code's format, stamped with the version and a hash of its own text. */
5
6
  export function renderSkill(content, version) {
6
- const unhashed = [
7
+ return stamp([
7
8
  '---',
8
9
  `name: ${content.id}`,
9
10
  `description: ${JSON.stringify(content.description)}`,
10
11
  ...(content.argumentHint === undefined ? [] : [`argument-hint: ${JSON.stringify(content.argumentHint)}`]),
11
12
  `allowed-tools: ${ALLOWED_TOOLS}`,
12
- 'metadata:',
13
- ` generatedBy: "estimetry ${version}"`,
13
+ ...generatedBy(version),
14
14
  '---',
15
15
  '',
16
- content.body,
17
- ].join('\n');
18
- return unhashed.replace(/^ {2}generatedBy: .*\n/m, (line) => `${line} contentHash: "${hashOf(unhashed)}"\n`);
19
- }
20
- /** Whose the file is: ours and untouched, ours but edited by the user, or the user's own. */
21
- export function ownership(text) {
22
- if (!/^ {2}generatedBy: "estimetry /m.test(text)) {
23
- return 'foreign';
24
- }
25
- const stamped = /^ {2}contentHash: "([0-9a-f]*)"$/m.exec(text)?.[1];
26
- return stamped !== undefined && stamped === hashOf(text.replace(HASH_LINE, '')) ? 'ours' : 'edited';
27
- }
28
- function hashOf(text) {
29
- return createHash('sha256').update(text).digest('hex').slice(0, 12);
16
+ renderBody(content.body, claudeCodeSkillRef, '$ARGUMENTS'),
17
+ ].join('\n'));
30
18
  }
31
19
  //# sourceMappingURL=skill-file.js.map
@@ -0,0 +1,161 @@
1
+ import { join } from 'node:path';
2
+ import { estimetryCommand } from '../../../application/contracts/estimetry-command.js';
3
+ import { COMMANDS, ESTIMATE_REMINDER_BLOCK, ESTIMETRY_SKILL } from '../content/commands.js';
4
+ import { HOOK_TIMEOUT_SECONDS, hasOurHooks, isBrokenJson, withHooks, withoutHooks } from '../shared/hook-settings.js';
5
+ import { instructionsPlan } from '../shared/instructions-block.js';
6
+ import { nameSkills } from '../../../application/contracts/skill-mention.js';
7
+ import { skillsPlan } from '../shared/skills-plan.js';
8
+ import { CODEX_HOOK_EVENTS, CODEX_SHORT_TIMEOUT_EVENTS, CODEX_SHORT_TIMEOUT_SECONDS, CODEX_SYNCHRONOUS_EVENTS, codexSkillRef, } from './hook-events.js';
9
+ import { hookTrusts, untrustedHooks, withTrusts } from './hook-trust.js';
10
+ import { SANDBOX_RULES, isOurRules } from './sandbox-rules.js';
11
+ import { renderSkill } from './skill-file.js';
12
+ const PROJECT_HOOKS = join('.codex', 'hooks.json');
13
+ const SKILLS = [ESTIMETRY_SKILL, ...COMMANDS];
14
+ /** Our hooks in a hooks file: `estimetry hook codex …`, in any form `estimetryCommand` gives. */
15
+ const OURS = 'hook codex';
16
+ const AGENTS_MD_BLOCK = nameSkills(ESTIMATE_REMINDER_BLOCK, codexSkillRef);
17
+ const TRUST_HINT = 'Codex runs no hook you have not trusted, so it does not measure your sessions yet: ' +
18
+ 'run `estimetry init --tools codex --trust-hooks`, or open /hooks in Codex and trust the estimetry hooks';
19
+ const CONFIG_REFUSED = 'the config.toml of Codex has a form estimetry does not change by itself (an inline or dotted hooks table, a ' +
20
+ 'multi-line string): open /hooks in Codex and trust the estimetry hooks there';
21
+ const UNTRUSTED = 'Codex has no trust of the estimetry hooks in its config.toml, so it may not run them: ' +
22
+ 'run `estimetry init --tools codex --trust-hooks`, or open /hooks in Codex and trust them';
23
+ /**
24
+ * Codex: hooks in `hooks.json` (the user's one, which serves every project, or the project's one for the team),
25
+ * skills in `.agents/skills`, the reminder in `AGENTS.md` with a shared install. Codex has no personal settings
26
+ * inside a project, so a personal install writes nothing there (design.md of codex-adapter, D3).
27
+ */
28
+ export class CodexAdapter {
29
+ dirs;
30
+ id = 'codex';
31
+ aliases = ['openai-codex'];
32
+ title = 'Codex';
33
+ hookEvents = CODEX_HOOK_EVENTS;
34
+ /** Codex runs a hook only once the user trusts it, and runs commands of the agent in a sandbox. */
35
+ asksTrust = true;
36
+ constructor(dirs) {
37
+ this.dirs = dirs;
38
+ }
39
+ state(projectRoot, files) {
40
+ const userText = files.read(this.userHooks());
41
+ const projectText = files.read(join(projectRoot, PROJECT_HOOKS));
42
+ const shared = hasOurHooks(projectText, OURS);
43
+ const installed = shared || hasOurHooks(userText, OURS);
44
+ const broken = [
45
+ ...(isBrokenJson(userText) ? [this.userHooks()] : []),
46
+ ...(isBrokenJson(projectText) ? [PROJECT_HOOKS] : []),
47
+ ];
48
+ const untrusted = installed && this.untrusted(files, shared ? join(projectRoot, PROJECT_HOOKS) : this.userHooks());
49
+ return {
50
+ installed,
51
+ shared,
52
+ ...(broken.length === 0 ? {} : { unreadable: `${broken.join(' and ')} ${broken.length === 1 ? 'is' : 'are'} not valid JSON` }),
53
+ // The user's hooks file serves every project: such an install belongs to no copy of its own.
54
+ ...(installed && !shared ? { machineWide: true } : {}),
55
+ ...(untrusted ? { notice: UNTRUSTED } : {}),
56
+ };
57
+ }
58
+ present(files) {
59
+ return files.isDirectory(this.dirs.home);
60
+ }
61
+ personalFiles() {
62
+ return [];
63
+ }
64
+ plan(context) {
65
+ const plans = [this.hooks(context), this.skills(context), this.agentsMd(context)];
66
+ return {
67
+ changes: plans.flatMap((plan) => plan.changes),
68
+ skipped: plans.flatMap((plan) => plan.skipped),
69
+ warnings: plans.flatMap((plan) => plan.warnings),
70
+ };
71
+ }
72
+ userHooks() {
73
+ return join(this.dirs.home, 'hooks.json');
74
+ }
75
+ config() {
76
+ return join(this.dirs.home, 'config.toml');
77
+ }
78
+ untrusted(files, hooksPath) {
79
+ return untrustedHooks(files.read(this.config()), hookTrusts(hooksPath, files.read(hooksPath), OURS));
80
+ }
81
+ hooks(context) {
82
+ const { projectRoot, files, shared, runner } = context;
83
+ const projectPath = join(projectRoot, PROJECT_HOOKS);
84
+ const [target, display] = shared ? [projectPath, PROJECT_HOOKS] : [this.userHooks(), this.userHooks()];
85
+ // The user's hooks run this installation by its paths; hooks the team commits hold no paths of this machine.
86
+ const command = (event) => estimetryCommand(shared ? undefined : runner, `${OURS} ${event}`);
87
+ const current = files.read(target);
88
+ const content = withHooks(current, {
89
+ ours: OURS,
90
+ events: this.hookEvents,
91
+ synchronous: CODEX_SYNCHRONOUS_EVENTS,
92
+ command,
93
+ timeout: (event) => (CODEX_SHORT_TIMEOUT_EVENTS.includes(event) ? CODEX_SHORT_TIMEOUT_SECONDS : HOOK_TIMEOUT_SECONDS),
94
+ }, display);
95
+ const trust = this.trustPlan(context, target, content);
96
+ const changes = [{ path: target, content }, ...trust.changes];
97
+ const warnings = [...trust.warnings];
98
+ if (shared) {
99
+ if (hasOurHooks(files.read(this.userHooks()), OURS)) {
100
+ warnings.push(`the estimetry hooks are also in ${this.userHooks()}, which serves every project: Codex runs both, ` +
101
+ 'so each hook runs twice here (the fact stays right). Remove them from that file if this project is enough');
102
+ }
103
+ }
104
+ else {
105
+ const old = files.read(projectPath);
106
+ if (old !== undefined && hasOurHooks(old, OURS)) {
107
+ const cleaned = withoutHooks(old, OURS, PROJECT_HOOKS);
108
+ changes.push(cleaned === undefined ? { path: projectPath, remove: true } : { path: projectPath, content: cleaned });
109
+ }
110
+ }
111
+ return { changes, skipped: trust.skipped, warnings };
112
+ }
113
+ /**
114
+ * The trust of the hooks and the rule for the task commands, with the user's consent. The consent is our rules file
115
+ * in the user's Codex directory: `trust: true` writes it, `trust: false` takes it away, and without an answer (an
116
+ * upgrade) a rules file of ours means the user agreed before, so the hooks changed now are trusted again. The rule
117
+ * is the user's own even with a shared install: one person's consent does not go into the team's repository.
118
+ */
119
+ trustPlan(context, target, content) {
120
+ const { files, version } = context;
121
+ const config = files.read(this.config());
122
+ const rules = join(this.dirs.home, 'rules', 'estimetry.rules');
123
+ const existing = files.read(rules);
124
+ const ownRules = existing !== undefined && isOurRules(existing);
125
+ const trust = context.trust ?? ownRules;
126
+ const wanted = hookTrusts(target, content, OURS);
127
+ if (!trust) {
128
+ return {
129
+ changes: context.trust === false && ownRules ? [{ path: rules, remove: true }] : [],
130
+ skipped: [],
131
+ warnings: untrustedHooks(config, wanted) ? [TRUST_HINT] : [],
132
+ };
133
+ }
134
+ const trusted = withTrusts(config, wanted);
135
+ const foreignRules = existing !== undefined && !ownRules;
136
+ return {
137
+ changes: [
138
+ ...(trusted === undefined ? [] : [{ path: this.config(), content: trusted }]),
139
+ ...(foreignRules ? [] : [{ path: rules, content: SANDBOX_RULES(version) }]),
140
+ ],
141
+ skipped: foreignRules ? [{ path: rules, reason: 'not created by estimetry, left as it is' }] : [],
142
+ warnings: trusted === undefined ? [CONFIG_REFUSED] : [],
143
+ };
144
+ }
145
+ skills({ projectRoot, files, shared, force, version }) {
146
+ return skillsPlan(SKILLS, {
147
+ files,
148
+ projectDir: join(projectRoot, '.agents', 'skills'),
149
+ userDir: this.dirs.userSkills,
150
+ shared,
151
+ force,
152
+ render: (skill) => renderSkill(skill, version),
153
+ });
154
+ }
155
+ /** The reminder goes to the committed AGENTS.md only with a shared install. */
156
+ agentsMd({ projectRoot, files, shared }) {
157
+ const path = join(projectRoot, 'AGENTS.md');
158
+ return instructionsPlan(path, files.read(path), shared, AGENTS_MD_BLOCK);
159
+ }
160
+ }
161
+ //# sourceMappingURL=codex-adapter.js.map
@@ -0,0 +1,23 @@
1
+ /** Hook events of Codex that the activity contract needs (design.md of codex-adapter, D3 and D5). */
2
+ export const CODEX_HOOK_EVENTS = [
3
+ 'SessionStart',
4
+ 'SessionEnd',
5
+ 'UserPromptSubmit',
6
+ 'Stop',
7
+ 'Interrupt',
8
+ 'PermissionRequest',
9
+ 'PreToolUse',
10
+ 'PostToolUse',
11
+ 'SubagentStart',
12
+ 'SubagentStop',
13
+ ];
14
+ /** Hooks Codex runs synchronously: their context reaches the agent in the same turn, and `SessionEnd` is always synchronous. */
15
+ export const CODEX_SYNCHRONOUS_EVENTS = ['SessionStart', 'UserPromptSubmit', 'SessionEnd'];
16
+ /** Codex waits for `SessionEnd` and `Interrupt` at most 3 seconds; other hooks get the timeout of estimetry. */
17
+ export const CODEX_SHORT_TIMEOUT_EVENTS = ['SessionEnd', 'Interrupt'];
18
+ export const CODEX_SHORT_TIMEOUT_SECONDS = 3;
19
+ /** How Codex calls a skill: `$name`. One rule for the context of hooks and the bodies of skills. */
20
+ export function codexSkillRef(id) {
21
+ return `$${id}`;
22
+ }
23
+ //# sourceMappingURL=hook-events.js.map