@odyssey365/cli 0.2.4 → 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.
@@ -0,0 +1,353 @@
1
+ /**
2
+ * `odyssey agent hook <agent> <event>` — 미러링 입구(설계 §6.1).
3
+ *
4
+ * 빨리 끝나야 한다: 할 일을 outbox 에 쓰고, 데몬이 없으면 한 번만 직접 보내 본다. 실패해도 에이전트 작업을 막지 않게
5
+ * 종료 코드는 늘 0(명령 쪽에서 보장).
6
+ *
7
+ * 거르기:
8
+ * - 등록 폴더 밖 cwd → 아무것도 안 한다. appOnly 폴더는 장부에 app 세션으로 적힌 것만.
9
+ * - 데몬이 띄운 세션(환경변수 ODYSSEY_AGENT_TURN · 프롬프트 source 'sdk' · 장부 active) → 데몬 몫이라 건너뛴다.
10
+ * - 서브에이전트 훅(agent_id) → 건너뛴다.
11
+ * - 데스크톱 갈래: 데몬이 적어 둔 앱 턴 글(relayTexts)과 같은 프롬프트면 앱의 `<턴>-in` 이 이미 있으니 다시 쓰지 않고,
12
+ * 그 세션의 다음 Stop 이 답을 `<턴>-out` 으로 쓰고 턴을 done 으로 닫는다.
13
+ */
14
+ import { createHash } from 'node:crypto';
15
+ import { closeSync, mkdirSync, openSync, readSync, statSync, writeFileSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import { spawn } from 'node:child_process';
18
+ import { readTranscript } from './transcript.js';
19
+ import { cleanText, findMediaPaths, titleOf } from './text.js';
20
+ import { findWorkspace } from './workspaces.js';
21
+ import { flushOutbox, makeClient } from './outbox.js';
22
+ import { extOfMime } from './api.js';
23
+ import { AgentHost, AgentKind, bridgeByAgent, daemonPid, enqueue, loadBridges, mirrorSessionUid, paths, updateLedger, } from './store.js';
24
+ const RELAY_TTL_MS = 30 * 60_000;
25
+ export function normText(s) {
26
+ return s.replace(/\s+/g, ' ').trim();
27
+ }
28
+ export function hashText(s) {
29
+ return createHash('sha256').update(normText(s)).digest('hex').slice(0, 24);
30
+ }
31
+ /** 사용자 말의 미러링 메시지 id — 훅(UserPromptSubmit)과 Stop(transcript)이 같은 값을 내게 세션 + 프롬프트 글로 만든다. */
32
+ export function userMessageUid(externalSessionId, prompt) {
33
+ return `ag-u-${hashText(`${externalSessionId}\n${prompt}`)}`;
34
+ }
35
+ /** 이 세션을 올려도 되나 — 등록 폴더 안 · appOnly 면 앱 세션만. */
36
+ export function mirrorAllowed(ws, ledger, sessionUid, externalSessionId) {
37
+ if (!ws)
38
+ return { ok: false, reason: 'outside-workspace' };
39
+ if (ws.mirror === 'appOnly') {
40
+ const s = ledger.sessions[sessionUid];
41
+ if (s?.origin !== 'app' && !ledger.relay?.[externalSessionId])
42
+ return { ok: false, reason: 'app-only' };
43
+ }
44
+ return { ok: true };
45
+ }
46
+ function sessionUidOf(ledger, agent, externalSessionId) {
47
+ return ledger.byExternal[externalSessionId] ?? mirrorSessionUid(agent, externalSessionId);
48
+ }
49
+ function upsertJob(b, args) {
50
+ return {
51
+ kind: 'call',
52
+ tool: 'agent_session_upsert',
53
+ args: {
54
+ bridgeId: b.bridgeId,
55
+ agent: b.agent,
56
+ host: args.host,
57
+ externalSessionId: args.externalSessionId,
58
+ sessionUid: args.sessionUid,
59
+ workspaceId: args.ws.id,
60
+ origin: args.origin,
61
+ state: args.state,
62
+ ...(args.title ? { title: args.title } : {}),
63
+ },
64
+ };
65
+ }
66
+ function replyJob(b, sessionUid, messageUid, text, toolSummary, mediaPaths, turnUid) {
67
+ return {
68
+ kind: 'reply',
69
+ bridgeId: b.bridgeId,
70
+ sessionUid,
71
+ mediaPaths,
72
+ message: {
73
+ bridgeId: b.bridgeId,
74
+ sessionUid,
75
+ messageUid,
76
+ role: 'assistant',
77
+ text: cleanText(text),
78
+ ...(toolSummary && toolSummary.calls > 0 ? { toolSummary } : {}),
79
+ ...(turnUid ? { turnUid } : {}),
80
+ },
81
+ };
82
+ }
83
+ function userJob(b, sessionUid, messageUid, text, mediaPaths = []) {
84
+ const message = { bridgeId: b.bridgeId, sessionUid, messageUid, role: 'user', text: cleanText(text) };
85
+ return mediaPaths.length ? { kind: 'reply', bridgeId: b.bridgeId, sessionUid, mediaPaths, message } : { kind: 'call', tool: 'agent_message_post', args: message };
86
+ }
87
+ /** transcript 끝 64KB 에서 데스크톱 표식(entrypoint) — UserPromptSubmit 때는 전체를 읽지 않는다. */
88
+ function tailIsDesktop(path) {
89
+ if (!path)
90
+ return false;
91
+ try {
92
+ const size = statSync(path).size;
93
+ const len = Math.min(size, 64 * 1024);
94
+ const buf = Buffer.alloc(len);
95
+ const fd = openSync(path, 'r');
96
+ try {
97
+ readSync(fd, buf, 0, len, size - len);
98
+ }
99
+ finally {
100
+ closeSync(fd);
101
+ }
102
+ return buf.toString('utf-8').includes('"entrypoint":"claude-desktop"');
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
108
+ function hostOf(env, transcriptPath) {
109
+ const ep = env.CLAUDE_CODE_ENTRYPOINT ?? '';
110
+ if (ep === 'claude-desktop' || tailIsDesktop(transcriptPath))
111
+ return AgentHost.desktop;
112
+ return AgentHost.cli;
113
+ }
114
+ /** 앱 턴(데스크톱 갈래)의 글과 같은 프롬프트인가 → 그 턴. 쓰면 지운다. */
115
+ function takeRelay(ledger, prompt, now = Date.now()) {
116
+ const list = ledger.relayTexts ?? [];
117
+ // 듣는 세션이 사진 경로 등을 뒤에 붙여 넘길 수 있다 — 앞부분(턴 글 길이만큼)으로 맞춘다.
118
+ const norm = normText(prompt);
119
+ const i = list.findIndex((r) => now - Date.parse(r.at) < RELAY_TTL_MS && hashText(r.len ? norm.slice(0, r.len) : norm) === r.hash);
120
+ if (i < 0)
121
+ return null;
122
+ const [hit] = list.splice(i, 1);
123
+ return { turnUid: hit.turnUid, sessionUid: hit.sessionUid };
124
+ }
125
+ function savePromptImages(sessionUid, images) {
126
+ if (!images.length)
127
+ return [];
128
+ const dir = paths.media(sessionUid);
129
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
130
+ return images.map((img, i) => {
131
+ const p = join(dir, `prompt-${Date.now()}-${i + 1}${extOfMime(img.mime)}`);
132
+ writeFileSync(p, Buffer.from(img.data, 'base64'), { mode: 0o600 });
133
+ return p;
134
+ });
135
+ }
136
+ export function planClaudeHook(event, input, env = process.env) {
137
+ const b = bridgeByAgent(AgentKind.claudeCode);
138
+ if (!b)
139
+ return { action: 'skip', reason: 'no-bridge' };
140
+ if (env.ODYSSEY_AGENT_TURN)
141
+ return { action: 'skip', reason: 'daemon-turn' };
142
+ if (input.agent_id)
143
+ return { action: 'skip', reason: 'subagent' };
144
+ const ext = input.session_id;
145
+ if (!ext)
146
+ return { action: 'skip', reason: 'no-session' };
147
+ const ws = findWorkspace(input.cwd);
148
+ return withProfile(b, updateLedger((ledger) => {
149
+ if (ledger.active[ext])
150
+ return { action: 'skip', reason: 'daemon-turn' };
151
+ const ev = (input.hook_event_name ?? event).replace(/[^A-Za-z]/g, '');
152
+ const lower = ev.toLowerCase();
153
+ // 데스크톱 갈래 — 앱 턴의 글이 이 세션에 들어왔다: 앱 세션에 묶는다(어느 폴더 방식이든 앱 세션이다).
154
+ if (lower === 'userpromptsubmit' && typeof input.prompt === 'string') {
155
+ const relay = takeRelay(ledger, input.prompt);
156
+ if (relay && ws) {
157
+ ledger.relay = ledger.relay ?? {};
158
+ ledger.relay[ext] = { turnUid: relay.turnUid, sessionUid: relay.sessionUid, externalSessionId: ext, at: new Date().toISOString() };
159
+ ledger.byExternal[ext] = relay.sessionUid;
160
+ ledger.sessions[relay.sessionUid] = { agent: b.agent, bridgeId: b.bridgeId, workspaceId: ws.id, externalSessionId: ext, origin: 'app', host: AgentHost.desktop, updatedAt: new Date().toISOString() };
161
+ return {
162
+ action: 'queued',
163
+ jobs: [
164
+ upsertJob(b, { sessionUid: relay.sessionUid, externalSessionId: ext, ws, host: AgentHost.desktop, origin: 'app', state: 'running' }),
165
+ { kind: 'call', tool: 'agent_turn_update', args: { bridgeId: b.bridgeId, turnUid: relay.turnUid, externalSessionId: ext, sessionState: 'running', activity: { step: 'think' } } },
166
+ ],
167
+ };
168
+ }
169
+ }
170
+ const sessionUid = sessionUidOf(ledger, b.agent, ext);
171
+ const allowed = mirrorAllowed(ws, ledger, sessionUid, ext);
172
+ if (!allowed.ok)
173
+ return { action: 'skip', reason: allowed.reason };
174
+ const known = ledger.sessions[sessionUid];
175
+ const origin = known?.origin ?? 'local';
176
+ const now = new Date().toISOString();
177
+ const remember = (host) => {
178
+ ledger.sessions[sessionUid] = { agent: b.agent, bridgeId: b.bridgeId, workspaceId: ws.id, externalSessionId: ext, origin, host: (known?.host ?? host), updatedAt: now, ...(known?.titled ? { titled: true } : {}) };
179
+ };
180
+ switch (lower) {
181
+ case 'sessionstart': {
182
+ // 빈 대화가 앱 목록에 서지 않게 — 첫 프롬프트에서 만든다. 여기선 장부만.
183
+ remember(hostOf(env, input.transcript_path));
184
+ return { action: 'skip', reason: 'recorded' };
185
+ }
186
+ case 'userpromptsubmit': {
187
+ if (input.source === 'sdk')
188
+ return { action: 'skip', reason: 'daemon-turn' };
189
+ const prompt = typeof input.prompt === 'string' ? input.prompt : '';
190
+ if (!prompt.trim())
191
+ return { action: 'skip', reason: 'empty' };
192
+ const host = known?.host ?? hostOf(env, input.transcript_path);
193
+ remember(host);
194
+ const messageUid = userMessageUid(ext, prompt);
195
+ if (ledger.posted.includes(messageUid))
196
+ return { action: 'skip', reason: 'posted' };
197
+ ledger.posted.push(messageUid);
198
+ // 제목은 한 번만 — SessionStart 가 장부에 먼저 적어도(known) 아직 안 보냈으면 싣는다.
199
+ const needTitle = !known?.titled;
200
+ ledger.sessions[sessionUid].titled = true;
201
+ return {
202
+ action: 'queued',
203
+ jobs: [
204
+ upsertJob(b, { sessionUid, externalSessionId: ext, ws: ws, host, origin, state: 'running', ...(needTitle ? { title: titleOf(prompt) } : {}) }),
205
+ userJob(b, sessionUid, messageUid, prompt),
206
+ ],
207
+ };
208
+ }
209
+ case 'stop': {
210
+ const t = input.transcript_path ? readTranscript(input.transcript_path) : null;
211
+ const text = (input.last_assistant_message ?? t?.text ?? '').trim();
212
+ const host = known?.host ?? (t?.desktop ? AgentHost.desktop : AgentHost.cli);
213
+ remember(host);
214
+ const relay = ledger.relay?.[ext];
215
+ const jobs = [];
216
+ if (relay) {
217
+ // 앱 턴 답 — `<턴>-out` 으로 쓰고 턴을 닫는다.
218
+ delete ledger.relay[ext];
219
+ const media = text ? findMediaPaths(text, input.cwd ?? ws.path, ws.path) : [];
220
+ jobs.push(upsertJob(b, { sessionUid: relay.sessionUid, externalSessionId: ext, ws: ws, host: AgentHost.desktop, origin: 'app', state: 'idle' }));
221
+ jobs.push(replyJob(b, relay.sessionUid, `${relay.turnUid}-out`, text, t?.toolSummary, media, relay.turnUid));
222
+ jobs.push({ kind: 'call', tool: 'agent_turn_update', args: { bridgeId: b.bridgeId, turnUid: relay.turnUid, externalSessionId: ext, sessionState: 'idle', settle: 'done', outputCount: 1 + media.length } });
223
+ return { action: 'queued', jobs };
224
+ }
225
+ const needTitle = !known?.titled && !!t?.prompt;
226
+ if (needTitle && ledger.sessions[sessionUid])
227
+ ledger.sessions[sessionUid].titled = true;
228
+ jobs.push(upsertJob(b, { sessionUid, externalSessionId: ext, ws: ws, host, origin, state: 'idle', ...(needTitle ? { title: titleOf(t.prompt) } : {}) }));
229
+ // UserPromptSubmit 훅이 놓친 프롬프트(훅을 나중에 깔았거나 실패) — 같은 id 라 두 번 서지 않는다.
230
+ if (t?.prompt && t.prompt.trim()) {
231
+ const uid = userMessageUid(ext, t.prompt);
232
+ const images = t.promptImages.length && !ledger.posted.includes(uid) ? savePromptImages(sessionUid, t.promptImages) : [];
233
+ if (!ledger.posted.includes(uid)) {
234
+ ledger.posted.push(uid);
235
+ jobs.push(userJob(b, sessionUid, uid, t.prompt, images));
236
+ }
237
+ }
238
+ if (text) {
239
+ const messageUid = `ag-${t?.messageId ?? hashText(`${ext}\n${text}`)}`;
240
+ if (!ledger.posted.includes(messageUid)) {
241
+ ledger.posted.push(messageUid);
242
+ jobs.push(replyJob(b, sessionUid, messageUid, text, t?.toolSummary, findMediaPaths(text, input.cwd ?? ws.path, ws.path)));
243
+ }
244
+ }
245
+ return { action: 'queued', jobs };
246
+ }
247
+ case 'sessionend': {
248
+ if (!known)
249
+ return { action: 'skip', reason: 'unknown-session' };
250
+ return { action: 'queued', jobs: [upsertJob(b, { sessionUid, externalSessionId: ext, ws: ws, host: known.host, origin, state: 'idle' })] };
251
+ }
252
+ default:
253
+ return { action: 'skip', reason: 'unknown-event' };
254
+ }
255
+ }));
256
+ }
257
+ function withProfile(b, o) {
258
+ return b.odysseyProfile ? { ...o, profile: b.odysseyProfile } : o;
259
+ }
260
+ export function parseCodexNotify(argv) {
261
+ for (let i = argv.length - 1; i >= 0; i--) {
262
+ const a = argv[i];
263
+ if (!a.trim().startsWith('{'))
264
+ continue;
265
+ try {
266
+ return JSON.parse(a);
267
+ }
268
+ catch {
269
+ return null;
270
+ }
271
+ }
272
+ return null;
273
+ }
274
+ export function planCodexNotify(n, opts) {
275
+ const env = opts.env ?? process.env;
276
+ const b = bridgeByAgent(AgentKind.codex);
277
+ if (!b)
278
+ return { action: 'skip', reason: 'no-bridge' };
279
+ if (env.ODYSSEY_AGENT_TURN)
280
+ return { action: 'skip', reason: 'daemon-turn' };
281
+ if (n.type && n.type !== 'agent-turn-complete')
282
+ return { action: 'skip', reason: 'unknown-event' };
283
+ const ext = n['thread-id'] ?? n.thread_id ?? opts.threadIdFallback?.() ?? null;
284
+ if (!ext)
285
+ return { action: 'skip', reason: 'no-thread' };
286
+ const ws = findWorkspace(n.cwd ?? opts.cwd);
287
+ return withProfile(b, updateLedger((ledger) => {
288
+ if (ledger.active[ext])
289
+ return { action: 'skip', reason: 'daemon-turn' };
290
+ const sessionUid = sessionUidOf(ledger, b.agent, ext);
291
+ const allowed = mirrorAllowed(ws, ledger, sessionUid, ext);
292
+ if (!allowed.ok)
293
+ return { action: 'skip', reason: allowed.reason };
294
+ const known = ledger.sessions[sessionUid];
295
+ const origin = known?.origin ?? 'local';
296
+ const prompt = (n['input-messages'] ?? []).filter((s) => typeof s === 'string').join('\n\n');
297
+ ledger.sessions[sessionUid] = { agent: b.agent, bridgeId: b.bridgeId, workspaceId: ws.id, externalSessionId: ext, origin, host: 'cli', updatedAt: new Date().toISOString() };
298
+ const jobs = [upsertJob(b, { sessionUid, externalSessionId: ext, ws: ws, host: AgentHost.cli, origin, state: 'idle', ...(known || !prompt ? {} : { title: titleOf(prompt) }) })];
299
+ if (prompt.trim()) {
300
+ const uid = userMessageUid(ext, prompt);
301
+ if (!ledger.posted.includes(uid)) {
302
+ ledger.posted.push(uid);
303
+ jobs.push(userJob(b, sessionUid, uid, prompt));
304
+ }
305
+ }
306
+ const text = (n['last-assistant-message'] ?? '').trim();
307
+ if (text) {
308
+ const messageUid = `ag-${n['turn-id'] ? `t-${n['turn-id']}` : hashText(`${ext}\n${text}`)}`;
309
+ if (!ledger.posted.includes(messageUid)) {
310
+ ledger.posted.push(messageUid);
311
+ jobs.push(replyJob(b, sessionUid, messageUid, text, undefined, findMediaPaths(text, n.cwd ?? opts.cwd, ws.path)));
312
+ }
313
+ }
314
+ return { action: 'queued', jobs };
315
+ }));
316
+ }
317
+ // ── 실행 ──
318
+ /** 계획을 outbox 에 쓰고, 데몬이 없으면 한 번 직접 보낸다. */
319
+ export async function commitHook(plan, ctx = {}) {
320
+ if (plan.action !== 'queued' || !plan.jobs?.length)
321
+ return plan;
322
+ const entry = enqueue(plan.jobs, plan.profile);
323
+ const env = ctx.env ?? process.env;
324
+ if (ctx.noSend || env.ODYSSEY_AGENT_NO_SEND === '1' || daemonPid())
325
+ return { ...plan, entryId: entry.id };
326
+ try {
327
+ const timeout = ctx.sendTimeoutMs ?? 8000;
328
+ const r = await Promise.race([
329
+ flushOutbox((p) => makeClient(p), new Set([entry.id])),
330
+ new Promise((res) => setTimeout(() => res(null), timeout).unref()),
331
+ ]);
332
+ if (r && r.sent > 0)
333
+ return { ...plan, action: 'sent', entryId: entry.id };
334
+ }
335
+ catch {
336
+ // 남겨 두면 데몬이 보낸다
337
+ }
338
+ return { ...plan, entryId: entry.id };
339
+ }
340
+ /** 코덱스: 원래 notify 프로그램이 있었으면 같은 인자로 이어 부른다(setup 이 저장한 chainNotify). */
341
+ export function chainCodexNotify(payload) {
342
+ const chain = loadBridges().bridges.codex?.chainNotify;
343
+ if (!Array.isArray(chain) || !chain.length)
344
+ return;
345
+ try {
346
+ const child = spawn(chain[0], [...chain.slice(1), payload], { detached: true, stdio: 'ignore' });
347
+ child.on('error', () => { });
348
+ child.unref();
349
+ }
350
+ catch {
351
+ // 원래 notify 가 사라졌다 — 무시
352
+ }
353
+ }
@@ -0,0 +1,194 @@
1
+ /**
2
+ * 미러링 설치 — 클로드 `~/.claude/settings.json` 훅 · 코덱스 `~/.codex/config.toml` notify(설계 §5 표 · §15.5).
3
+ *
4
+ * 남의 설정을 고치는 일이라 조심한다: 우리 줄만 넣고 빼며(명령에 `agent hook <agent>` 가 든 것), 다른 훅 · 키는 그대로 둔다.
5
+ * 고치기 전 원본을 `<파일>.odyssey-backup` 으로 한 번 남긴다(이미 있으면 덮지 않는다).
6
+ * 코덱스 notify 가 이미 다른 프로그램이면 덮지 않는다 — chain 을 허락받으면 그 프로그램을 우리 훅이 이어 부른다.
7
+ */
8
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { dirname, join } from 'node:path';
11
+ export const CLAUDE_HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'Stop', 'SessionEnd'];
12
+ export function claudeSettingsPath() {
13
+ const dir = process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), '.claude');
14
+ return join(dir, 'settings.json');
15
+ }
16
+ export function codexConfigPath() {
17
+ const dir = process.env.CODEX_HOME?.trim() || join(homedir(), '.codex');
18
+ return join(dir, 'config.toml');
19
+ }
20
+ function shq(s) {
21
+ return process.platform === 'win32' ? `"${s}"` : `'${s.replace(/'/g, `'\\''`)}'`;
22
+ }
23
+ export function claudeHookCommand(l, event) {
24
+ const env = l.agentHome && process.platform !== 'win32' ? `ODYSSEY_AGENT_HOME=${shq(l.agentHome)} ` : '';
25
+ return `${env}${shq(l.node)} ${shq(l.entry)} agent hook claude ${event}`;
26
+ }
27
+ const isOurs = (cmd, agent) => typeof cmd === 'string' && cmd.includes(`agent hook ${agent}`);
28
+ function backupOnce(path) {
29
+ const bak = `${path}.odyssey-backup`;
30
+ if (existsSync(path) && !existsSync(bak))
31
+ copyFileSync(path, bak);
32
+ }
33
+ /** settings 객체에 우리 훅을 넣는다(있으면 명령만 새로). 순수 함수 — 테스트용. */
34
+ export function withClaudeHooks(settings, l) {
35
+ const out = { ...settings, hooks: { ...(settings.hooks ?? {}) } };
36
+ for (const ev of CLAUDE_HOOK_EVENTS) {
37
+ const groups = (out.hooks[ev] ?? []).map((g) => ({ ...g, hooks: [...(g.hooks ?? [])] }));
38
+ const command = claudeHookCommand(l, ev);
39
+ let found = false;
40
+ for (const g of groups) {
41
+ for (const h of g.hooks) {
42
+ if (isOurs(h.command, 'claude')) {
43
+ h.command = command;
44
+ h.timeout = 15;
45
+ found = true;
46
+ }
47
+ }
48
+ }
49
+ if (!found)
50
+ groups.push({ hooks: [{ type: 'command', command, timeout: 15 }] });
51
+ out.hooks[ev] = groups;
52
+ }
53
+ return out;
54
+ }
55
+ export function withoutClaudeHooks(settings) {
56
+ if (!settings.hooks)
57
+ return settings;
58
+ const hooks = {};
59
+ for (const [ev, groups] of Object.entries(settings.hooks)) {
60
+ const kept = (groups ?? [])
61
+ .map((g) => ({ ...g, hooks: (g.hooks ?? []).filter((h) => !isOurs(h.command, 'claude')) }))
62
+ .filter((g) => g.hooks.length > 0);
63
+ if (kept.length)
64
+ hooks[ev] = kept;
65
+ }
66
+ const out = { ...settings, hooks };
67
+ if (!Object.keys(hooks).length)
68
+ delete out.hooks;
69
+ return out;
70
+ }
71
+ function readSettings(path) {
72
+ if (!existsSync(path))
73
+ return {};
74
+ const raw = readFileSync(path, 'utf-8');
75
+ if (!raw.trim())
76
+ return {};
77
+ try {
78
+ return JSON.parse(raw);
79
+ }
80
+ catch (e) {
81
+ throw new Error(`클로드 설정을 읽지 못했습니다(JSON 오류 — 고치지 않았습니다): ${path}: ${e.message}`);
82
+ }
83
+ }
84
+ export function installClaudeHooks(l) {
85
+ const path = claudeSettingsPath();
86
+ const next = withClaudeHooks(readSettings(path), l);
87
+ mkdirSync(dirname(path), { recursive: true });
88
+ backupOnce(path);
89
+ writeFileSync(path, JSON.stringify(next, null, 2) + '\n');
90
+ return path;
91
+ }
92
+ export function uninstallClaudeHooks() {
93
+ const path = claudeSettingsPath();
94
+ if (!existsSync(path))
95
+ return null;
96
+ const cur = readSettings(path);
97
+ const next = withoutClaudeHooks(cur);
98
+ if (JSON.stringify(next) !== JSON.stringify(cur))
99
+ writeFileSync(path, JSON.stringify(next, null, 2) + '\n');
100
+ return path;
101
+ }
102
+ export function claudeHooksInstalled() {
103
+ try {
104
+ const s = readSettings(claudeSettingsPath());
105
+ return CLAUDE_HOOK_EVENTS.every((ev) => (s.hooks?.[ev] ?? []).some((g) => (g.hooks ?? []).some((h) => isOurs(h.command, 'claude'))));
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ }
111
+ // ── 코덱스 config.toml ──
112
+ export function codexNotifyArgv(l) {
113
+ const base = [l.node, l.entry, 'agent', 'hook', 'codex', 'notify'];
114
+ return l.agentHome && process.platform !== 'win32' ? ['env', `ODYSSEY_AGENT_HOME=${l.agentHome}`, ...base] : base;
115
+ }
116
+ function tomlString(s) {
117
+ return JSON.stringify(s); // TOML 기본 문자열은 JSON 이스케이프와 호환된다
118
+ }
119
+ /** 최상위(첫 [표] 앞) notify = [...] 의 줄 범위와 값. 여러 줄 배열도 본다. */
120
+ export function findTopLevelNotify(toml) {
121
+ const lines = toml.split('\n');
122
+ for (let i = 0; i < lines.length; i++) {
123
+ const l = lines[i];
124
+ if (/^\s*\[/.test(l))
125
+ return null; // 첫 표 — 그 뒤는 최상위가 아니다
126
+ if (!/^\s*notify\s*=/.test(l))
127
+ continue;
128
+ let j = i;
129
+ let text = l;
130
+ const depth = (s) => (s.match(/\[/g)?.length ?? 0) - (s.match(/\]/g)?.length ?? 0);
131
+ while (depth(text) > 0 && j + 1 < lines.length)
132
+ text += '\n' + lines[++j];
133
+ const argv = [];
134
+ for (const m of text.slice(text.indexOf('=') + 1).matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)) {
135
+ argv.push(m[1] !== undefined ? JSON.parse(`"${m[1]}"`) : m[2]);
136
+ }
137
+ return { start: i, end: j, argv };
138
+ }
139
+ return null;
140
+ }
141
+ /** 우리 notify 를 넣은 새 toml. 남의 notify 가 있고 chain=false 면 바꾸지 않는다(changed:false · previous 로 알린다). */
142
+ export function withCodexNotify(toml, l, chain) {
143
+ const ours = `notify = [${codexNotifyArgv(l).map(tomlString).join(', ')}]`;
144
+ const span = findTopLevelNotify(toml);
145
+ const lines = toml.split('\n');
146
+ if (span) {
147
+ const mine = span.argv.join(' ').includes('agent hook codex');
148
+ if (!mine && !chain)
149
+ return { toml, previous: span.argv, changed: false };
150
+ lines.splice(span.start, span.end - span.start + 1, ours);
151
+ return { toml: lines.join('\n'), previous: mine ? null : span.argv, changed: true };
152
+ }
153
+ const body = toml.length && !toml.startsWith('\n') ? `${ours}\n${toml}` : `${ours}\n${toml.replace(/^\n/, '')}`;
154
+ return { toml: body, previous: null, changed: true };
155
+ }
156
+ export function withoutCodexNotify(toml, restore) {
157
+ const span = findTopLevelNotify(toml);
158
+ if (!span || !span.argv.join(' ').includes('agent hook codex'))
159
+ return toml;
160
+ const lines = toml.split('\n');
161
+ const repl = restore && restore.length ? [`notify = [${restore.map(tomlString).join(', ')}]`] : [];
162
+ lines.splice(span.start, span.end - span.start + 1, ...repl);
163
+ return lines.join('\n');
164
+ }
165
+ export function installCodexNotify(l, chain) {
166
+ const path = codexConfigPath();
167
+ const cur = existsSync(path) ? readFileSync(path, 'utf-8') : '';
168
+ const plan = withCodexNotify(cur, l, chain);
169
+ if (plan.changed) {
170
+ mkdirSync(dirname(path), { recursive: true });
171
+ backupOnce(path);
172
+ writeFileSync(path, plan.toml);
173
+ }
174
+ return { path, previous: plan.previous, changed: plan.changed };
175
+ }
176
+ export function uninstallCodexNotify(restore) {
177
+ const path = codexConfigPath();
178
+ if (!existsSync(path))
179
+ return null;
180
+ const cur = readFileSync(path, 'utf-8');
181
+ const next = withoutCodexNotify(cur, restore);
182
+ if (next !== cur)
183
+ writeFileSync(path, next);
184
+ return path;
185
+ }
186
+ export function codexNotifyInstalled() {
187
+ try {
188
+ const span = findTopLevelNotify(readFileSync(codexConfigPath(), 'utf-8'));
189
+ return !!span && span.argv.join(' ').includes('agent hook codex');
190
+ }
191
+ catch {
192
+ return false;
193
+ }
194
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * outbox 보내기 — 훅이 쓴 일을 데몬이(데몬이 없으면 훅이 한 번) 보낸다.
3
+ * 묶음 하나 = 파일 하나 = 차례대로 가야 하는 일들(세션 upsert → 메시지). 끝낸 개수(done)를 적어 다시 보낼 때 건너뛴다.
4
+ */
5
+ import { readFileSync } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { OdysseyClient, resolveTarget } from '../session.js';
9
+ import { call, ToolError, uploadMedia } from './api.js';
10
+ import { claimOutbox, listOutbox, recoverClaimed, releaseOutbox, removeOutbox, updateLedger } from './store.js';
11
+ import { AuthRequiredError, UsageError } from '../config.js';
12
+ const __dirname = dirname(fileURLToPath(import.meta.url));
13
+ export const CLI_VERSION = JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf-8')).version;
14
+ export const CLI_ENTRY = join(__dirname, '..', 'index.js');
15
+ export function makeClient(profile) {
16
+ return new OdysseyClient(resolveTarget(profile ? { profile } : {}), CLI_VERSION);
17
+ }
18
+ /** 이만큼 실패하면 버린다(하루쯤 — 데몬이 1분마다 다시 본다). */
19
+ const MAX_ATTEMPTS = 1440;
20
+ /** 묶음 하나를 보낸다. 다 보냈으면 true. 실패하면 done 까지 적고 던진다. */
21
+ export async function sendEntry(client, entry) {
22
+ for (let i = entry.done; i < entry.jobs.length; i++) {
23
+ const job = entry.jobs[i];
24
+ if (job.kind === 'call') {
25
+ await call(client, job.tool, job.args);
26
+ }
27
+ else {
28
+ const mediaIds = Array.isArray(job.message.mediaIds) ? [...job.message.mediaIds] : [];
29
+ const notes = [];
30
+ for (const p of job.mediaPaths) {
31
+ try {
32
+ const up = await uploadMedia(client, job.bridgeId, job.sessionUid, p);
33
+ if (up.mediaId)
34
+ mediaIds.push(up.mediaId);
35
+ if (up.tooLarge && !up.mediaId)
36
+ notes.push(`큰 파일이라 컴퓨터에만 있어요 — ${up.fileName} · ${formatBytes(up.bytes)}`);
37
+ }
38
+ catch (e) {
39
+ // 파일이 사라졌거나 서버가 그 파일을 거절(형식 · 하루 총량) — 메시지는 그대로 보낸다(미디어 한 장 때문에 답을 잃지 않게).
40
+ // 네트워크 실패는 던져 묶음째 다시 보낸다.
41
+ if (e.code === 'ENOENT' || e instanceof ToolError)
42
+ continue;
43
+ throw e;
44
+ }
45
+ }
46
+ const text = typeof job.message.text === 'string' ? job.message.text : '';
47
+ const message = {
48
+ ...job.message,
49
+ ...(notes.length ? { text: [text, ...notes].filter(Boolean).join('\n\n') } : {}),
50
+ ...(mediaIds.length ? { mediaIds } : {}),
51
+ };
52
+ await call(client, 'agent_message_post', message);
53
+ // 미디어를 다시 올리지 않게 — 보낸 뒤 비운다.
54
+ job.mediaPaths = [];
55
+ job.message = message;
56
+ }
57
+ entry.done = i + 1;
58
+ const posted = job.kind === 'reply' ? job.message.messageUid : job.tool === 'agent_message_post' ? job.args.messageUid : undefined;
59
+ if (typeof posted === 'string')
60
+ updateLedger((l) => void (l.posted.includes(posted) || l.posted.push(posted)));
61
+ }
62
+ }
63
+ export function formatBytes(n) {
64
+ if (n >= 1024 ** 3)
65
+ return `${(n / 1024 ** 3).toFixed(1)}GB`;
66
+ if (n >= 1024 ** 2)
67
+ return `${(n / 1024 ** 2).toFixed(1)}MB`;
68
+ return `${Math.max(1, Math.round(n / 1024))}KB`;
69
+ }
70
+ /**
71
+ * 밀린 일을 차례로 보낸다. 묶음마다 잡기(claim)로 다른 프로세스와 겹치지 않게 한다.
72
+ * clientFor: 프로필마다 클라이언트(테스트는 가짜). 로그인이 풀린 프로필은 그 묶음을 남겨 두고 건너뛴다.
73
+ */
74
+ export async function flushOutbox(clientFor, onlyIds) {
75
+ recoverClaimed();
76
+ const r = { sent: 0, failed: 0, dropped: 0 };
77
+ const clients = new Map();
78
+ for (const entry of listOutbox()) {
79
+ if (onlyIds && !onlyIds.has(entry.id))
80
+ continue;
81
+ if (!claimOutbox(entry.id))
82
+ continue;
83
+ const key = entry.profile ?? '';
84
+ if (!clients.has(key)) {
85
+ try {
86
+ clients.set(key, clientFor(entry.profile));
87
+ }
88
+ catch (e) {
89
+ clients.set(key, e);
90
+ }
91
+ }
92
+ const client = clients.get(key);
93
+ if (client instanceof Error) {
94
+ releaseOutbox(entry, true);
95
+ r.failed++;
96
+ continue;
97
+ }
98
+ try {
99
+ await sendEntry(client, entry);
100
+ releaseOutbox(entry, false);
101
+ removeOutbox(entry.id);
102
+ r.sent++;
103
+ }
104
+ catch (e) {
105
+ entry.attempts++;
106
+ // 계약 밖 입력(사용법 오류)이나 시도 소진은 버린다 — 영원히 되풀이하지 않게.
107
+ const permanent = e instanceof UsageError || entry.attempts >= MAX_ATTEMPTS;
108
+ if (permanent) {
109
+ releaseOutbox(entry, false);
110
+ removeOutbox(entry.id);
111
+ r.dropped++;
112
+ }
113
+ else {
114
+ releaseOutbox(entry, true);
115
+ r.failed++;
116
+ }
117
+ if (e instanceof AuthRequiredError)
118
+ clients.set(key, e);
119
+ }
120
+ }
121
+ return r;
122
+ }