harness-craft 0.1.0 → 0.1.1

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/README.md CHANGED
@@ -8,13 +8,13 @@ Turn your Claude Code and Codex harness into a pixel-RPG character sheet: one se
8
8
  ## 쓰는 법
9
9
 
10
10
  ```bash
11
- npx harness-craft share --handle <내-아이디>
11
+ npx harness-craft share --name <닉네임>
12
12
  # → ./harness-sheet.html
13
13
  ```
14
14
 
15
15
  | 옵션 | 동작 |
16
16
  |---|---|
17
- | `--handle <이름>` | 시트에 보일 이름. 영문·숫자·`_.-` 39자까지. 기본 `player` |
17
+ | `--name <이름>` | 시트에 보일 이름(닉네임). 한글·이모지도 되고 32자까지. 기본 `player` |
18
18
  | `--hide <glob>` | 이름이 맞는 MCP·스킬·에이전트·플러그인·훅을 파일에서 아예 뺀다. `*` 와일드카드, 대소문자 무시, 여러 번 쓸 수 있다 |
19
19
  | `--descriptions` | 스킬·에이전트 설명을 넣는다. 기본은 뺀다 |
20
20
  | `--out <파일>` | 저장 위치. 기본 `./harness-sheet.html` |
@@ -31,10 +31,16 @@ npx harness-craft share --handle <내-아이디>
31
31
  | `~/.claude.json`, `~/.claude/settings.json` | MCP 서버 이름, 훅 이벤트, 모델, 플러그인 |
32
32
  | `~/.claude/skills`, `~/.claude/agents`, 플러그인 | 스킬·에이전트 이름(설명은 `--descriptions` 일 때만) |
33
33
  | `~/.claude/projects/**/*.jsonl` | 도구·스킬·에이전트·MCP 호출 횟수와 활동일 |
34
- | `~/.codex/config.toml`, `hooks.json`, `skills`, `sessions` | 같은 항목의 Codex 쪽 값 |
34
+ | `~/.codex/config.toml`, `hooks.json`, `AGENTS.md`(`AGENTS.override.md` 우선) | 같은 항목의 Codex 쪽 값. `enabled = false` 인 MCP·스킬·훅·플러그인은 뺀다 |
35
+ | `~/.codex/skills`(`.system` 포함), `~/.agents/skills` | Codex 스킬 이름. 시스템 스킬은 쓴 적이 있을 때만 |
36
+ | `~/.codex/plugins/cache/**/.codex-plugin/plugin.json` | Codex 플러그인 이름·버전, 플러그인 스킬·훅 |
37
+ | `~/.codex/sessions/**/*.jsonl` | 세션 수(대화형·exec), 스킬·MCP·명령 호출 횟수, 가장 많이 쓴 모델, 활동일 |
38
+ | `~/.codex/agents/*.toml`, `config.toml` 의 `[agents.*]` | Codex 커스텀 에이전트 이름·설명·모델(`developer_instructions` 는 담지 않음) |
39
+ | 위 두 도구의 날짜 | 활동일 수와 첫날·마지막 날(날짜 목록은 담지 않음) |
35
40
 
36
41
  환경변수 값, 헤더, 명령 인자, 파일 본문, 절대 경로, 대화 내용은 담지 않는다.
37
42
  `~/.codex/auth.json`, `~/.claude/.credentials.json`, sqlite 파일은 열지 않는다.
43
+ `$CODEX_HOME` 을 정해 두었으면 `~/.codex` 대신 그 폴더를 읽는다.
38
44
  MCP 서버 주소는 공개 서비스로 알려진 곳만 남기고, 공유 파일에서는 그마저 뺀다.
39
45
 
40
46
  ## 라이선스
@@ -1,8 +1,12 @@
1
1
  import { join } from 'node:path';
2
- import { definitionName, toAgent, toSkill, usageKeys } from '../definitions.js';
2
+ import { definitionName, toAgent, toSkill, usageKeys, usedBuiltinAgents } from '../definitions.js';
3
3
  import { sortByName } from '../fsutil.js';
4
4
  import { readFlatDefinitions, readSkillDefinitions } from '../items.js';
5
5
  import { numberField, recordField } from './config.js';
6
+ /** Agents that ship with Claude Code (Agent/Task `subagent_type`). Shown only when used. */
7
+ export const CLAUDE_BUILTIN_AGENTS = [
8
+ 'general-purpose', 'Explore', 'Plan', 'claude', 'statusline-setup', 'claude-code-guide',
9
+ ];
6
10
  const EMPTY_COUNTS = { skillCalls: new Map(), slashCalls: new Map(), agentCalls: new Map() };
7
11
  async function gather(userDir, plugins, sub, ctx) {
8
12
  const read = sub === 'skills' ? readSkillDefinitions : readFlatDefinitions;
@@ -46,8 +50,11 @@ export async function collectClaudeAgents(claudeDir, plugins, counts, ctx) {
46
50
  const items = await gather(join(claudeDir, 'agents'), plugins, 'agents', ctx);
47
51
  const userNames = new Set(items.filter((i) => i.source === 'user').map((i) => definitionName(i.def)));
48
52
  const agentCalls = (counts ?? EMPTY_COUNTS).agentCalls;
49
- return sortByName(items.map(({ def, source }) => {
53
+ const defined = items.map(({ def, source }) => {
50
54
  const uses = usageKeys(definitionName(def), source, userNames).reduce((sum, k) => sum + (agentCalls.get(k) ?? 0), 0);
51
55
  return toAgent(def, source, uses, ctx);
52
- }));
56
+ });
57
+ // Any defined agent (user or plugin) with a built-in's bare name takes those calls, so the built-in is not listed.
58
+ const definedNames = new Set(items.map((i) => definitionName(i.def)));
59
+ return sortByName([...defined, ...usedBuiltinAgents(CLAUDE_BUILTIN_AGENTS, definedNames, agentCalls)]);
53
60
  }
@@ -19,17 +19,17 @@ async function scanUsage(claudeDir, ctx) {
19
19
  return null;
20
20
  }
21
21
  }
22
- /** Returns null when neither ~/.claude nor ~/.claude.json exists. */
22
+ /** source is null when neither ~/.claude nor ~/.claude.json exists. */
23
23
  export async function collectClaudeCode(ctx, options) {
24
24
  const claudeDir = join(ctx.home, '.claude');
25
25
  const [hasDir, hasJson] = await Promise.all([pathExists(claudeDir), pathExists(join(ctx.home, '.claude.json'))]);
26
26
  if (!hasDir && !hasJson)
27
- return null;
27
+ return { source: null, days: null };
28
28
  const config = await readClaudeConfig(ctx.home, ctx.diag);
29
29
  const scan = options.usage ? await scanUsage(claudeDir, ctx) : null;
30
30
  const installed = await readInstalledPlugins(claudeDir, ctx);
31
31
  const { settings, claudeJson } = config;
32
- return {
32
+ const source = {
33
33
  model: ctx.redactor.optional(stringValue(settings, 'model'), MAX_SHORT_FIELD_LENGTH),
34
34
  since: ctx.redactor.optional(stringValue(claudeJson, 'claudeCodeFirstTokenDate') ?? stringValue(claudeJson, 'firstStartTime'), MAX_SHORT_FIELD_LENGTH),
35
35
  startups: numberField(claudeJson, 'numStartups'),
@@ -42,4 +42,5 @@ export async function collectClaudeCode(ctx, options) {
42
42
  instructions: await readInstructions(join(claudeDir, 'CLAUDE.md'), ctx.diag),
43
43
  usage: scan?.usage ?? null,
44
44
  };
45
+ return { source, days: scan?.days ?? null };
45
46
  }
package/dist/cli.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { writeFile } from 'node:fs/promises';
3
3
  import { homedir } from 'node:os';
4
- import { resolve } from 'node:path';
4
+ import { join, resolve } from 'node:path';
5
5
  import { parseArgs } from 'node:util';
6
6
  import { collectProfile } from './collect.js';
7
7
  import { writeShareSheet, formatShareSummary } from './shareCommand.js';
8
- import { DEFAULT_SHARE_HANDLE, SHARE_HANDLE_PATTERN } from './shareFormat.js';
8
+ import { DEFAULT_SHARE_HANDLE, SHARE_NAME_MAX_LENGTH, validateShareName } from './shareFormat.js';
9
9
  import { formatSummary } from './summary.js';
10
10
  const DEFAULT_OUT = 'harness-profile.json';
11
11
  const DEFAULT_SHARE_OUT = 'harness-sheet.html';
12
12
  const USAGE = `사용법: harness-craft [scan] [--out <file>] [--json] [--no-usage] [--home <dir>]
13
- harness-craft share [--out <file>] [--handle <name>] [--hide <glob>]... [--descriptions] [--no-usage] [--home <dir>]
13
+ harness-craft share [--out <file>] [--name <이름>] [--hide <glob>]... [--descriptions] [--no-usage] [--home <dir>]
14
14
 
15
15
  scan (기본) — 설정과 사용 기록을 읽어 harness-profile.json 을 만든다
16
16
  --out <file> 저장 위치 (기본 ./${DEFAULT_OUT})
@@ -18,18 +18,20 @@ scan (기본) — 설정과 사용 기록을 읽어 harness-profile.json 을 만
18
18
 
19
19
  share — 혼자 열리는 캐릭터 시트 HTML 한 장을 만든다
20
20
  --out <file> 저장 위치 (기본 ./${DEFAULT_SHARE_OUT})
21
- --handle <name> 시트에 쓸 이름 (영문·숫자·_.- 39자까지, 기본 ${DEFAULT_SHARE_HANDLE})
21
+ --name <이름> 시트에 보일 이름(닉네임). 한글 가능, ${SHARE_NAME_MAX_LENGTH}자까지 (기본 ${DEFAULT_SHARE_HANDLE})
22
22
  --hide <glob> 이름이 맞는 MCP·스킬·에이전트·플러그인·명령·훅을 파일에서 뺌 (대소문자 무시, * 가능, 여러 번)
23
23
  --descriptions 설명을 파일에 넣음 (기본은 뺌)
24
24
 
25
25
  공통
26
26
  --no-usage 대화 기록 집계를 건너뜀 (usage 는 null)
27
- --home <dir> 홈 디렉터리 대신 쓸 경로 (테스트·디버그용)
27
+ --home <dir> 홈 디렉터리 대신 쓸 경로 (테스트·디버그용). 주면 $CODEX_HOME 대신 <dir>/.codex 를 읽음
28
+
29
+ Codex 설정은 $CODEX_HOME (없으면 ~/.codex) 에서 읽는다.
28
30
  `;
29
31
  class UsageError extends Error {
30
32
  }
31
33
  const SCAN_ONLY = ['json'];
32
- const SHARE_ONLY = ['handle', 'hide', 'descriptions'];
34
+ const SHARE_ONLY = ['name', 'handle', 'hide', 'descriptions'];
33
35
  function parseCli(argv) {
34
36
  const { values, positionals } = parseArgs({
35
37
  args: [...argv],
@@ -40,6 +42,8 @@ function parseCli(argv) {
40
42
  json: { type: 'boolean' },
41
43
  'no-usage': { type: 'boolean', default: false },
42
44
  home: { type: 'string' },
45
+ name: { type: 'string' },
46
+ // Old spelling of --name, kept working but no longer documented.
43
47
  handle: { type: 'string' },
44
48
  hide: { type: 'string', multiple: true },
45
49
  descriptions: { type: 'boolean' },
@@ -55,23 +59,35 @@ function parseCli(argv) {
55
59
  const foreign = (command === 'scan' ? SHARE_ONLY : SCAN_ONLY).filter((key) => values[key] !== undefined);
56
60
  if (foreign.length > 0)
57
61
  throw new UsageError(`${command} 에는 쓸 수 없는 옵션: ${foreign.map((k) => `--${k}`).join(' ')}`);
58
- const common = { usage: values['no-usage'] !== true, home: resolve(values.home ?? homedir()) };
62
+ const home = resolve(values.home ?? homedir());
63
+ const common = { usage: values['no-usage'] !== true, home, codexHome: codexHomeFor(values.home, home) };
59
64
  if (command === 'scan') {
60
65
  return { ...common, command, out: resolve(values.out ?? DEFAULT_OUT), json: values.json === true };
61
66
  }
62
- const handle = values.handle ?? DEFAULT_SHARE_HANDLE;
63
- if (!SHARE_HANDLE_PATTERN.test(handle)) {
64
- throw new UsageError(`--handle 은 영문·숫자·_.- 로 1~39자여야 합니다: ${JSON.stringify(handle)}`);
65
- }
66
67
  return {
67
68
  ...common,
68
69
  command,
69
70
  out: resolve(values.out ?? DEFAULT_SHARE_OUT),
70
- handle,
71
+ handle: shareName(values.name, values.handle),
71
72
  hide: values.hide ?? [],
72
73
  descriptions: values.descriptions === true,
73
74
  };
74
75
  }
76
+ /** --home pins everything under it (tests, debugging); otherwise $CODEX_HOME, else ~/.codex. */
77
+ function codexHomeFor(homeFlag, home) {
78
+ const env = process.env.CODEX_HOME;
79
+ return homeFlag === undefined && env !== undefined && env.trim() !== '' ? resolve(env) : join(home, '.codex');
80
+ }
81
+ /** --name, or its old alias --handle. Both at once is an error. */
82
+ function shareName(name, alias) {
83
+ if (name !== undefined && alias !== undefined)
84
+ throw new UsageError('--name 과 --handle 은 같은 옵션입니다. 하나만 쓰세요.');
85
+ const flag = alias !== undefined ? '--handle' : '--name';
86
+ const result = validateShareName(name ?? alias ?? '');
87
+ if (!result.ok)
88
+ throw new UsageError(`${flag} 값이 올바르지 않습니다: ${result.error}`);
89
+ return result.name;
90
+ }
75
91
  function progressReporter(label) {
76
92
  return (done, total) => {
77
93
  process.stderr.write(`\r${label} ${done}/${total}`);
@@ -80,7 +96,7 @@ function progressReporter(label) {
80
96
  };
81
97
  }
82
98
  async function runScan(options) {
83
- const profile = await collectProfile({ home: options.home, usage: options.usage, onProgress: progressReporter });
99
+ const profile = await collectProfile({ home: options.home, codexHome: options.codexHome, usage: options.usage, onProgress: progressReporter });
84
100
  const json = JSON.stringify(profile, null, 2) + '\n';
85
101
  if (options.json) {
86
102
  process.stdout.write(json);
@@ -93,7 +109,7 @@ async function runScan(options) {
93
109
  return 0;
94
110
  }
95
111
  async function runShare(options) {
96
- const profile = await collectProfile({ home: options.home, usage: options.usage, onProgress: progressReporter });
112
+ const profile = await collectProfile({ home: options.home, codexHome: options.codexHome, usage: options.usage, onProgress: progressReporter });
97
113
  const result = await writeShareSheet(profile, options);
98
114
  process.stderr.write(formatShareSummary(result, options.descriptions));
99
115
  return 0;
@@ -0,0 +1,107 @@
1
+ // Codex custom agents (subagents): ~/.codex/agents/*.toml and [agents.<role>] tables in config.toml (docs/collector-spec.md).
2
+ import { realpath } from 'node:fs/promises';
3
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { usedBuiltinAgents } from '../definitions.js';
5
+ import { describeError } from '../diagnostics.js';
6
+ import { isRecord, listEntries, sortByName } from '../fsutil.js';
7
+ import { stringField } from '../items.js';
8
+ import { readTomlFile } from './config.js';
9
+ const MAX_NAME_LENGTH = 120;
10
+ const MAX_SHORT_FIELD_LENGTH = 64;
11
+ const AGENT_FILE_SUFFIX = '.toml';
12
+ /** Agents that ship with Codex. Shown only when used. */
13
+ export const CODEX_BUILTIN_AGENTS = ['default', 'worker', 'explorer'];
14
+ function pick(name, description, data) {
15
+ return {
16
+ name,
17
+ description,
18
+ model: data ? stringField(data, 'model') : null,
19
+ effort: data ? stringField(data, 'model_reasoning_effort') : null,
20
+ };
21
+ }
22
+ /** `~/.codex/agents/*.toml`, one agent per file. The `name` key wins over the file name. */
23
+ async function readAgentFiles(agentsDir, ctx) {
24
+ const out = [];
25
+ for (const file of await listEntries(agentsDir, 'file', ctx.diag)) {
26
+ if (!file.endsWith(AGENT_FILE_SUFFIX))
27
+ continue;
28
+ const data = await readTomlFile(join(agentsDir, file), ctx.diag);
29
+ if (data === null)
30
+ continue;
31
+ const name = stringField(data, 'name') ?? file.slice(0, -AGENT_FILE_SUFFIX.length);
32
+ out.push(pick(name, stringField(data, 'description'), data));
33
+ }
34
+ return out;
35
+ }
36
+ function isInside(root, path) {
37
+ const rel = relative(root, path);
38
+ return rel === '' || (!isAbsolute(rel) && rel.split(sep)[0] !== '..');
39
+ }
40
+ /**
41
+ * Reads a role's config_file only when it resolves inside ~/.codex, before and after following symlinks.
42
+ * Relative paths are taken from the Codex home (where config.toml lives); `~/` is the home directory.
43
+ */
44
+ async function readRoleFile(role, value, configPath, ctx) {
45
+ const codexDir = ctx.codexHome;
46
+ const target = value.startsWith('~/') ? join(ctx.home, value.slice(2)) : resolve(codexDir, value);
47
+ const outside = `[agents.${role}] config_file 이 ~/.codex 밖을 가리켜 읽지 않음`;
48
+ if (!isInside(codexDir, target)) {
49
+ ctx.diag.warn(configPath, outside);
50
+ return null;
51
+ }
52
+ let real;
53
+ let realRoot;
54
+ try {
55
+ [real, realRoot] = await Promise.all([realpath(target), realpath(codexDir)]);
56
+ }
57
+ catch (err) {
58
+ ctx.diag.warn(configPath, `[agents.${role}] config_file 을 읽지 못함 (${describeError(err)})`);
59
+ return null;
60
+ }
61
+ if (!isInside(realRoot, real)) {
62
+ ctx.diag.warn(configPath, outside);
63
+ return null;
64
+ }
65
+ return readTomlFile(real, ctx.diag);
66
+ }
67
+ /** `[agents.<role>]` sub-tables. Scalar keys under [agents] (max_threads, enabled, …) are settings, not roles. */
68
+ async function readRoleTables(config, configPath, ctx) {
69
+ const agents = isRecord(config.agents) ? config.agents : {};
70
+ const out = [];
71
+ for (const [role, table] of Object.entries(agents)) {
72
+ if (!isRecord(table))
73
+ continue;
74
+ const file = stringField(table, 'config_file');
75
+ const data = file === null ? null : await readRoleFile(role, file, configPath, ctx);
76
+ out.push(pick(role, stringField(table, 'description') ?? (data ? stringField(data, 'description') : null), data));
77
+ }
78
+ return out;
79
+ }
80
+ function toCodexAgent(raw, uses, ctx) {
81
+ const { redactor } = ctx;
82
+ return {
83
+ name: redactor.text(raw.name, MAX_NAME_LENGTH),
84
+ description: redactor.text(raw.description ?? ''),
85
+ model: redactor.optional(raw.model, MAX_SHORT_FIELD_LENGTH),
86
+ effort: redactor.optional(raw.effort, MAX_SHORT_FIELD_LENGTH),
87
+ toolCount: null,
88
+ mcpServers: [],
89
+ source: 'user',
90
+ uses,
91
+ };
92
+ }
93
+ /**
94
+ * Custom agents (standalone files win over role tables of the same name) plus built-ins that were used.
95
+ * `roleCalls` is null without a session scan: uses are 0 and no built-in is listed.
96
+ */
97
+ export async function collectCodexAgents(config, roleCalls, ctx) {
98
+ const codexDir = ctx.codexHome;
99
+ const byName = new Map();
100
+ for (const raw of await readRoleTables(config, join(codexDir, 'config.toml'), ctx))
101
+ byName.set(raw.name, raw);
102
+ for (const raw of await readAgentFiles(join(codexDir, 'agents'), ctx))
103
+ byName.set(raw.name, raw);
104
+ const calls = roleCalls ?? new Map();
105
+ const defined = [...byName.values()].map((raw) => toCodexAgent(raw, calls.get(raw.name) ?? 0, ctx));
106
+ return sortByName([...defined, ...usedBuiltinAgents(CODEX_BUILTIN_AGENTS, new Set(byName.keys()), calls)]);
107
+ }
@@ -1,10 +1,10 @@
1
1
  import { parse } from 'smol-toml';
2
2
  import { isRecord, readTextOrNull } from '../fsutil.js';
3
- /** Parses ~/.codex/config.toml. Missing -> {}; broken -> warning + {}. */
4
- export async function readCodexConfig(path, diag) {
3
+ /** Parses one TOML file. Missing -> null silently; broken -> warning + null. */
4
+ export async function readTomlFile(path, diag) {
5
5
  const text = await readTextOrNull(path, diag);
6
6
  if (text === null)
7
- return {};
7
+ return null;
8
8
  try {
9
9
  const parsed = parse(text);
10
10
  return isRecord(parsed) ? parsed : {};
@@ -12,6 +12,10 @@ export async function readCodexConfig(path, diag) {
12
12
  catch (err) {
13
13
  const message = err instanceof Error ? err.message.split('\n')[0] ?? '' : String(err);
14
14
  diag.warn(path, `TOML 파싱 실패 (${message.slice(0, 120)})`);
15
- return {};
15
+ return null;
16
16
  }
17
17
  }
18
+ /** Parses ~/.codex/config.toml. Missing -> {}; broken -> warning + {}. */
19
+ export async function readCodexConfig(path, diag) {
20
+ return (await readTomlFile(path, diag)) ?? {};
21
+ }
@@ -0,0 +1,62 @@
1
+ // Codex hooks: hooks.json, inline [hooks.<Event>] in config.toml and enabled plugins' hooks/hooks.json (docs/collector-spec.md).
2
+ import { join } from 'node:path';
3
+ import { isRecord, readJsonOrNull } from '../fsutil.js';
4
+ import { compareHooks, parseHooks } from '../hooks.js';
5
+ /** `[hooks.state]` holds per-handler trust/enable flags, not handlers. */
6
+ const STATE_KEY = 'state';
7
+ /** `[features] hooks` (or its deprecated alias `codex_hooks`) = false turns every hook off. */
8
+ function hooksEnabled(config) {
9
+ const features = isRecord(config.features) ? config.features : {};
10
+ const flag = typeof features.hooks === 'boolean' ? features.hooks : features.codex_hooks;
11
+ return flag !== false;
12
+ }
13
+ /** PreToolUse -> pre_tool_use, as in hooks.state keys. */
14
+ function snakeEvent(event) {
15
+ return event.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase();
16
+ }
17
+ /**
18
+ * Returns a copy without handlers that `[hooks.state."<file>:<event>:<group>:<handler>"] enabled = false` turns off.
19
+ * The key format was checked against hooks.json entries; config.toml and plugin files use the same scheme as a guess.
20
+ */
21
+ export function withoutDisabled(hooks, file, state) {
22
+ if (!isRecord(hooks))
23
+ return hooks;
24
+ const disabled = (event, g, h) => {
25
+ const entry = state[`${file}:${snakeEvent(event)}:${g}:${h}`];
26
+ return isRecord(entry) && entry.enabled === false;
27
+ };
28
+ return Object.fromEntries(Object.entries(hooks).map(([event, groups]) => [
29
+ event,
30
+ Array.isArray(groups)
31
+ ? groups.map((group, g) => isRecord(group) && Array.isArray(group.hooks)
32
+ ? { ...group, hooks: group.hooks.filter((_, h) => !disabled(event, g, h)) }
33
+ : group)
34
+ : groups,
35
+ ]));
36
+ }
37
+ async function readHooksJson(path, state, ctx) {
38
+ const json = await readJsonOrNull(path, ctx.diag);
39
+ if (json === null)
40
+ return [];
41
+ if (!isRecord(json)) {
42
+ ctx.diag.warn(path, '최상위가 객체가 아님');
43
+ return [];
44
+ }
45
+ return parseHooks(withoutDisabled(json.hooks, path, state), path, ctx.redactor, ctx.diag);
46
+ }
47
+ export async function collectCodexHooks(config, plugins, ctx) {
48
+ if (!hooksEnabled(config))
49
+ return [];
50
+ const configPath = join(ctx.codexHome, 'config.toml');
51
+ const table = isRecord(config.hooks) ? config.hooks : {};
52
+ const state = isRecord(table[STATE_KEY]) ? table[STATE_KEY] : {};
53
+ const inline = Object.fromEntries(Object.entries(table).filter(([key]) => key !== STATE_KEY));
54
+ const lists = [
55
+ await readHooksJson(join(ctx.codexHome, 'hooks.json'), state, ctx),
56
+ parseHooks(withoutDisabled(inline, configPath, state), configPath, ctx.redactor, ctx.diag),
57
+ ];
58
+ for (const plugin of plugins)
59
+ if (plugin.enabled)
60
+ lists.push(await readHooksJson(plugin.hooksFile, state, ctx));
61
+ return lists.flat().sort(compareHooks);
62
+ }
@@ -1,55 +1,70 @@
1
1
  import { join } from 'node:path';
2
- import { toCommand, toSkill } from '../definitions.js';
2
+ import { toCommand } from '../definitions.js';
3
3
  import { describeError } from '../diagnostics.js';
4
- import { isRecord, pathExists, readJsonOrNull, sortByName } from '../fsutil.js';
5
- import { parseHooks } from '../hooks.js';
6
- import { countFiles, readFlatDefinitions, readInstructions, readSkillDefinitions } from '../items.js';
4
+ import { compareStrings, isRecord, pathExists, sortByName } from '../fsutil.js';
5
+ import { countFiles, readFlatDefinitions, readInstructions } from '../items.js';
7
6
  import { buildMcpServer } from '../mcp.js';
8
- import { scanCodexSessions } from '../usage/codex.js';
7
+ import { NO_EFFORT, scanCodexSessions } from '../usage/codex.js';
8
+ import { collectCodexAgents } from './agents.js';
9
9
  import { readCodexConfig } from './config.js';
10
+ import { collectCodexHooks } from './hooks.js';
11
+ import { readCodexPlugins, toCodexPlugins } from './plugins.js';
12
+ import { collectCodexSkills } from './skills.js';
10
13
  const MAX_SHORT_FIELD_LENGTH = 64;
11
- const NO_USAGE = { uses: 0, lastUsedAt: null };
12
- async function scanUsage(codexDir, ctx) {
14
+ async function scanUsage(codexHome, ctx) {
13
15
  try {
14
- return await scanCodexSessions(codexDir, ctx.diag, ctx.onProgress?.('Codex 세션 읽는 중'));
16
+ return await scanCodexSessions(codexHome, ctx.diag, ctx.onProgress?.('Codex 세션 읽는 중'));
15
17
  }
16
18
  catch (err) {
17
- ctx.diag.warn(join(codexDir, 'sessions'), `세션 집계 실패 (${describeError(err)})`);
19
+ ctx.diag.warn(join(codexHome, 'sessions'), `세션 집계 실패 (${describeError(err)})`);
18
20
  return null;
19
21
  }
20
22
  }
23
+ /** `[mcp_servers.<id>] enabled = false` servers are left out. Failed calls still count, as on the Claude side. */
21
24
  function collectMcp(config, calls, ctx) {
22
25
  const servers = isRecord(config.mcp_servers) ? config.mcp_servers : {};
23
- return sortByName(Object.entries(servers).map(([name, raw]) => buildMcpServer(name, raw, 'user', calls.get(name) ?? 0, ctx.redactor)));
26
+ return sortByName(Object.entries(servers)
27
+ .filter(([, raw]) => !(isRecord(raw) && raw.enabled === false))
28
+ .map(([name, raw]) => buildMcpServer(name, raw, 'user', calls.get(name) ?? 0, ctx.redactor)));
24
29
  }
25
- async function collectHooks(path, ctx) {
26
- const json = await readJsonOrNull(path, ctx.diag);
27
- if (json === null)
28
- return [];
29
- if (!isRecord(json)) {
30
- ctx.diag.warn(path, '최상위가 객체가 아님');
31
- return [];
32
- }
33
- return parseHooks(json.hooks, path, ctx.redactor, ctx.diag);
30
+ /** AGENTS.override.md wins when it has content, as in Codex. */
31
+ async function readCodexInstructions(ctx) {
32
+ const override = await readInstructions(join(ctx.codexHome, 'AGENTS.override.md'), ctx.diag);
33
+ return override.present && override.bytes > 0 ? override : readInstructions(join(ctx.codexHome, 'AGENTS.md'), ctx.diag);
34
34
  }
35
- /** Returns null when ~/.codex does not exist. */
36
- export async function collectCodex(ctx, options) {
37
- const codexDir = join(ctx.home, '.codex');
38
- if (!(await pathExists(codexDir)))
35
+ /** Most turns wins (ties by name); its most frequent effort comes along. null when no turn_context was seen. */
36
+ export function mostUsedModel(modelTurns) {
37
+ const total = (m) => [...m.values()].reduce((a, b) => a + b, 0);
38
+ const best = [...modelTurns].sort((a, b) => total(b[1]) - total(a[1]) || compareStrings(a[0], b[0]))[0];
39
+ if (best === undefined)
39
40
  return null;
40
- const config = await readCodexConfig(join(codexDir, 'config.toml'), ctx.diag);
41
- const scan = options.usage ? await scanUsage(codexDir, ctx) : null;
42
- const skills = await readSkillDefinitions(join(codexDir, 'skills'), ctx.diag);
43
- const prompts = await readFlatDefinitions(join(codexDir, 'prompts'), ctx.diag);
44
- return {
45
- model: ctx.redactor.optional(config.model, MAX_SHORT_FIELD_LENGTH),
46
- reasoningEffort: ctx.redactor.optional(config.model_reasoning_effort, MAX_SHORT_FIELD_LENGTH),
41
+ const effort = [...best[1]].filter(([e]) => e !== NO_EFFORT).sort((a, b) => b[1] - a[1] || compareStrings(a[0], b[0]))[0];
42
+ return { model: best[0], effort: effort?.[0] ?? null };
43
+ }
44
+ /** source is null when the Codex home ($CODEX_HOME or ~/.codex) does not exist. */
45
+ export async function collectCodex(ctx, options) {
46
+ const { codexHome } = ctx;
47
+ if (!(await pathExists(codexHome)))
48
+ return { source: null, days: null };
49
+ const config = await readCodexConfig(join(codexHome, 'config.toml'), ctx.diag);
50
+ const scan = options.usage ? await scanUsage(codexHome, ctx) : null;
51
+ const plugins = await readCodexPlugins(config, ctx);
52
+ const { skills, pluginUses } = await collectCodexSkills(config, plugins, scan?.skillRefs ?? null, ctx);
53
+ const prompts = await readFlatDefinitions(join(codexHome, 'prompts'), ctx.diag);
54
+ // What the user ran in interactive sessions beats the configured default; exec and subagent turns are a fallback.
55
+ const used = scan ? (mostUsedModel(scan.interactiveModelTurns) ?? mostUsedModel(scan.modelTurns)) : null;
56
+ const source = {
57
+ model: ctx.redactor.optional(used?.model ?? config.model, MAX_SHORT_FIELD_LENGTH),
58
+ reasoningEffort: ctx.redactor.optional(used?.effort ?? config.model_reasoning_effort, MAX_SHORT_FIELD_LENGTH),
47
59
  mcpServers: collectMcp(config, scan?.mcpCalls ?? new Map(), ctx),
48
- skills: sortByName(skills.map((def) => toSkill(def, 'user', NO_USAGE, ctx))),
49
- hooks: await collectHooks(join(codexDir, 'hooks.json'), ctx),
60
+ skills,
61
+ hooks: await collectCodexHooks(config, plugins, ctx),
50
62
  commands: sortByName(prompts.map((def) => toCommand(def, ctx))),
51
- instructions: await readInstructions(join(codexDir, 'AGENTS.md'), ctx.diag),
52
- rulesFiles: await countFiles(join(codexDir, 'rules'), ctx.diag),
63
+ instructions: await readCodexInstructions(ctx),
64
+ rulesFiles: await countFiles(join(codexHome, 'rules'), ctx.diag),
65
+ agents: await collectCodexAgents(config, scan?.roleCalls ?? null, ctx),
66
+ plugins: toCodexPlugins(plugins, pluginUses, ctx),
53
67
  usage: scan?.usage ?? null,
54
68
  };
69
+ return { source, days: scan?.days ?? null };
55
70
  }
@@ -0,0 +1,87 @@
1
+ // Codex plugins: <codexHome>/plugins/cache/<marketplace>/<plugin>/<version>/.codex-plugin/plugin.json (docs/collector-spec.md).
2
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
3
+ import { basename, isRecord, listEntries, readJsonOrNull, sortByName } from '../fsutil.js';
4
+ const MAX_FIELD_LENGTH = 120;
5
+ const MANIFEST = join('.codex-plugin', 'plugin.json');
6
+ const DEFAULT_SKILLS_DIR = 'skills';
7
+ const HOOKS_FILE = join('hooks', 'hooks.json');
8
+ /** Marketplaces that ship with Codex. Their plugins are treated as built-in: shown only when used. */
9
+ const BUNDLED_MARKETPLACE_PREFIX = 'openai-';
10
+ /** `[plugins._default]` sets the default for plugins without their own entry. */
11
+ const DEFAULT_PLUGIN_KEY = '_default';
12
+ function isInside(root, path) {
13
+ const rel = relative(root, path);
14
+ return rel === '' || (!isAbsolute(rel) && rel.split(sep)[0] !== '..');
15
+ }
16
+ /** Numeric-aware version order: 0.1.10 > 0.1.9. Non-numeric parts compare as strings. */
17
+ export function compareVersions(a, b) {
18
+ const pa = a.split(/[.+-]/);
19
+ const pb = b.split(/[.+-]/);
20
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
21
+ const x = pa[i] ?? '';
22
+ const y = pb[i] ?? '';
23
+ const nx = /^\d+$/.test(x) ? Number(x) : NaN;
24
+ const ny = /^\d+$/.test(y) ? Number(y) : NaN;
25
+ const diff = Number.isNaN(nx) || Number.isNaN(ny) ? (x < y ? -1 : x > y ? 1 : 0) : nx - ny;
26
+ if (diff !== 0)
27
+ return diff;
28
+ }
29
+ return 0;
30
+ }
31
+ /** `[plugins."<name>@<marketplace>"].enabled`, else `[plugins._default].enabled`, else enabled. */
32
+ function isEnabled(config, key) {
33
+ const plugins = isRecord(config.plugins) ? config.plugins : {};
34
+ for (const entry of [plugins[key], plugins[DEFAULT_PLUGIN_KEY]]) {
35
+ if (isRecord(entry) && typeof entry.enabled === 'boolean')
36
+ return entry.enabled;
37
+ }
38
+ return true;
39
+ }
40
+ async function readInstall(marketplace, dir, config, ctx) {
41
+ // Dot entries (install staging, temp dirs) are skipped by listEntries.
42
+ const versions = (await listEntries(dir, 'dir', ctx.diag)).sort(compareVersions);
43
+ const newest = versions[versions.length - 1];
44
+ if (newest === undefined)
45
+ return null;
46
+ const root = join(dir, newest);
47
+ const manifest = await readJsonOrNull(join(root, MANIFEST), ctx.diag);
48
+ if (manifest === null)
49
+ return null;
50
+ const data = isRecord(manifest) ? manifest : {};
51
+ const name = typeof data.name === 'string' && data.name.trim() ? data.name.trim() : basename(dir);
52
+ const skillsDir = resolve(root, typeof data.skills === 'string' ? data.skills : DEFAULT_SKILLS_DIR);
53
+ if (!isInside(root, skillsDir))
54
+ ctx.diag.warn(join(root, MANIFEST), 'skills 경로가 플러그인 밖이라 읽지 않음');
55
+ return {
56
+ name,
57
+ marketplace,
58
+ version: typeof data.version === 'string' ? data.version : newest,
59
+ enabled: isEnabled(config, `${name}@${marketplace}`),
60
+ bundled: marketplace.startsWith(BUNDLED_MARKETPLACE_PREFIX),
61
+ skillsDir: isInside(root, skillsDir) ? skillsDir : null,
62
+ hooksFile: join(root, HOOKS_FILE),
63
+ };
64
+ }
65
+ export async function readCodexPlugins(config, ctx) {
66
+ const cache = join(ctx.codexHome, 'plugins', 'cache');
67
+ const out = [];
68
+ for (const marketplace of await listEntries(cache, 'dir', ctx.diag)) {
69
+ for (const plugin of await listEntries(join(cache, marketplace), 'dir', ctx.diag)) {
70
+ const install = await readInstall(marketplace, join(cache, marketplace, plugin), config, ctx);
71
+ if (install)
72
+ out.push(install);
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+ /** uses = sum of the plugin's skill uses (keyed by plugin name). Disabled plugins are listed with 0; bundled ones only when used. */
78
+ export function toCodexPlugins(installs, skillUses, ctx) {
79
+ const used = (p) => (p.enabled ? (skillUses.get(p.name) ?? 0) : 0);
80
+ return sortByName(installs.filter((p) => !p.bundled || used(p) > 0).map((p) => ({
81
+ name: ctx.redactor.text(p.name, MAX_FIELD_LENGTH),
82
+ marketplace: ctx.redactor.text(p.marketplace, MAX_FIELD_LENGTH),
83
+ version: ctx.redactor.optional(p.version, MAX_FIELD_LENGTH),
84
+ enabled: p.enabled,
85
+ uses: used(p),
86
+ })));
87
+ }