@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,580 @@
1
+ /**
2
+ * `odyssey agent …` 명령군(설계 §11 · §15.5) — 별칭 `odyssey claude …`(= --agent claude) · `odyssey codex …`(= --agent codex).
3
+ *
4
+ * setup [플래그] 깔린 에이전트 감지 → 이름 · 이모지 → 미러링 설치 → 작업 폴더 등록 → 승인 정책 → 잠자기 방지
5
+ * → 자동 시작 → agent_bridge_register. 대화형이 기본, --yes(또는 터미널이 아니면) 비대화형.
6
+ * setup --uninstall [--purge] 훅 · notify · 자동 시작을 걷는다(--purge 면 ~/.odyssey/agent 의 장부까지)
7
+ * status · start · stop · daemon(전경) · hook <agent> <event> · workspace add|list|rename|remove
8
+ */
9
+ import { spawn, spawnSync } from 'node:child_process';
10
+ import { mkdirSync, openSync, rmSync } from 'node:fs';
11
+ import { hostname, platform as osPlatform } from 'node:os';
12
+ import { createInterface } from 'node:readline';
13
+ import { UsageError } from '../config.js';
14
+ import { call } from './api.js';
15
+ import { claudeAdapter, codexAdapter, latestCodexThread, which } from './adapters.js';
16
+ import { runDaemon } from './daemon.js';
17
+ import { chainCodexNotify, commitHook, parseCodexNotify, planClaudeHook, planCodexNotify } from './hook.js';
18
+ import { claudeHooksInstalled, claudeSettingsPath, codexConfigPath, codexNotifyInstalled, installClaudeHooks, installCodexNotify, uninstallClaudeHooks, uninstallCodexNotify, } from './install.js';
19
+ import { CLI_ENTRY, CLI_VERSION, makeClient } from './outbox.js';
20
+ import { agentHome, agentOfShort, daemonPid, KEEP_AWAKE_MODES, listOutbox, loadBridges, newId, paths, readJson, saveBridges, } from './store.js';
21
+ import { autostartInstalled, installAutostart, LAUNCH_LABEL, uninstallAutostart } from './system.js';
22
+ import { addWorkspace, loadWorkspaces, publicWorkspaces, removeWorkspace, renameWorkspace, setWorkspaceMirror, suggestName } from './workspaces.js';
23
+ export const AGENT_HELP = `odyssey agent <명령> — 에이전트 브리지: 이 컴퓨터의 클로드 코드 · 코덱스 세션을 앱 컴패니언 대화로 보이고 앱에서 부린다
24
+ (별칭: odyssey claude <명령> = --agent claude · odyssey codex <명령> = --agent codex)
25
+
26
+ setup 대화형 첫 설정(감지 → 이름 · 이모지 → 미러링 → 작업 폴더 → 승인 → 잠자기 방지 → 자동 시작 → 등록)
27
+ --agent claude|codex (반복 가능) 설정할 에이전트. 없으면 깔린 것 전부
28
+ --name <이름> --emoji <이모지> 앱 「새 대화」 줄의 이름 · 아이콘(처음 등록 때만 — 앱에서 고친 값이 정본)
29
+ --workspace <경로> --workspace-name <이름> [--app-only] 작업 폴더(반복 가능 · 이름 필수)
30
+ --approval ask|auto 파일 쓰기 · 명령을 앱에 물을지(기본 ask · 위험 명령은 언제나 묻는다)
31
+ --keep-awake always|onPower|whileWorking|off 잠자기 방지(기본 onPower)
32
+ --autostart | --no-autostart 로그인 때 자동 시작(비대화형 기본: 안 함)
33
+ --desktop-relay 이 컴퓨터에 데스크톱 듣는 세션을 둔다(host desktop 턴을 그 세션에 맡긴다)
34
+ --chain-notify 코덱스 notify 가 이미 있으면 그 프로그램을 이어 부르게 하고 바꾼다
35
+ --no-mirror 훅 · notify 를 깔지 않는다 · --no-register 서버 등록을 건너뛴다 · --attach-mcp 데몬 세션에 Odyssey MCP
36
+ --yes 묻지 않고 기본값으로
37
+ setup --uninstall [--purge] 훅 · notify · 자동 시작을 걷는다(--purge: 로컬 장부까지 지움)
38
+ status 브리지 · 데몬 · 잠자기 방지 · 자동 시작 · 마지막 하트비트 · 밀린 보내기
39
+ start | stop 데몬 켜기 · 끄기
40
+ daemon 전경 실행(자동 시작이 부르는 것 · 로그 ~/.odyssey/agent/logs)
41
+ hook <claude|codex> <이벤트> 미러링 입구(설정이 깐다 — 손으로 부를 일 없음 · 늘 종료 0)
42
+ workspace add <경로> --name <이름> [--app-only] · list · rename <id|이름|경로> <새 이름> · remove <id|이름|경로>
43
+ mirror <id|이름|경로> all|appOnly
44
+ 로컬 상태: ${'${ODYSSEY_AGENT_HOME:-~/.odyssey/agent}'}(bridges.json · workspaces.json · ledger.json · outbox/ · media/ · logs/)`;
45
+ function out(obj) {
46
+ process.stdout.write(JSON.stringify(obj, null, process.stdout.isTTY ? 2 : undefined) + '\n');
47
+ }
48
+ function say(line) {
49
+ process.stderr.write(line + '\n');
50
+ }
51
+ /** 플래그 꺼내기(반복 가능한 값은 배열로). */
52
+ class Flags {
53
+ args;
54
+ constructor(args) {
55
+ this.args = args;
56
+ }
57
+ has(name) {
58
+ const i = this.args.indexOf(name);
59
+ if (i < 0)
60
+ return false;
61
+ this.args.splice(i, 1);
62
+ return true;
63
+ }
64
+ value(name) {
65
+ const all = this.values(name);
66
+ return all.length ? all[all.length - 1] : undefined;
67
+ }
68
+ values(name) {
69
+ const outv = [];
70
+ for (let i = 0; i < this.args.length;) {
71
+ const a = this.args[i];
72
+ if (a === name) {
73
+ const v = this.args[i + 1];
74
+ if (v === undefined || v.startsWith('--'))
75
+ throw new UsageError(`${name} 에 값이 필요합니다.`);
76
+ outv.push(v);
77
+ this.args.splice(i, 2);
78
+ }
79
+ else if (a.startsWith(`${name}=`)) {
80
+ outv.push(a.slice(name.length + 1));
81
+ this.args.splice(i, 1);
82
+ }
83
+ else
84
+ i++;
85
+ }
86
+ return outv;
87
+ }
88
+ rest() {
89
+ return this.args;
90
+ }
91
+ }
92
+ /** 노드 경로 — Homebrew 의 버전 폴더(…/Cellar/node/25.8.0/bin/node)는 업그레이드하면 사라지니 PATH 의 node 를 쓴다. */
93
+ export function stableNode() {
94
+ if (/[\\/]Cellar[\\/]/.test(process.execPath)) {
95
+ const w = which('node');
96
+ if (w)
97
+ return w;
98
+ }
99
+ return process.execPath;
100
+ }
101
+ function launcher() {
102
+ const home = process.env.ODYSSEY_AGENT_HOME?.trim();
103
+ return { node: stableNode(), entry: CLI_ENTRY, ...(home ? { agentHome: home } : {}) };
104
+ }
105
+ export function deviceName() {
106
+ return hostname().replace(/\.(local|lan|home)$/i, '') || '내 컴퓨터';
107
+ }
108
+ export const DEFAULT_EMOJI = { claude: '🧑‍💻', codex: '🛠' };
109
+ export const AGENT_LABEL = { claude: '클로드', codex: '코덱스' };
110
+ /** 지원 최소 버전 — 밑이면 setup 이 멈추고 업데이트를 안내한다(코덱스는 아직 모른다 — 확인 전). */
111
+ export const MIN_VERSION = { claude: '2.0.0' };
112
+ export function versionLess(a, b) {
113
+ const pa = a.split(/[.-]/).map((x) => Number.parseInt(x, 10) || 0);
114
+ const pb = b.split(/[.-]/).map((x) => Number.parseInt(x, 10) || 0);
115
+ for (let i = 0; i < 3; i++)
116
+ if ((pa[i] ?? 0) !== (pb[i] ?? 0))
117
+ return (pa[i] ?? 0) < (pb[i] ?? 0);
118
+ return false;
119
+ }
120
+ function makeAsker(interactive) {
121
+ if (!interactive) {
122
+ return { ask: async (_q, d) => d ?? '', yes: async (_q, d) => d, close() { } };
123
+ }
124
+ const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
125
+ const ask = (q, d) => new Promise((res) => rl.question(d ? `${q} [${d}]: ` : `${q}: `, (a) => res(a.trim() || d || '')));
126
+ return {
127
+ ask,
128
+ yes: async (q, d) => {
129
+ const a = (await ask(`${q} (${d ? 'Y/n' : 'y/N'})`)).toLowerCase();
130
+ return a ? a.startsWith('y') || a === '예' || a === '네' : d;
131
+ },
132
+ close: () => rl.close(),
133
+ };
134
+ }
135
+ export async function cmdSetup(g, args, forced) {
136
+ const f = new Flags(args);
137
+ if (f.has('--uninstall'))
138
+ return cmdUninstall(f.has('--purge'), f.rest());
139
+ const yes = f.has('--yes') || f.has('-y');
140
+ const interactive = !yes && process.stdin.isTTY === true;
141
+ const agentsFlag = f.values('--agent').map((a) => (a === 'claudeCode' ? 'claude' : a));
142
+ const nameFlag = f.value('--name');
143
+ const emojiFlag = f.value('--emoji');
144
+ const wsPaths = f.values('--workspace');
145
+ const wsNames = f.values('--workspace-name');
146
+ const appOnly = f.has('--app-only');
147
+ const approvalFlag = f.value('--approval');
148
+ const keepFlag = f.value('--keep-awake');
149
+ const autoOn = f.has('--autostart');
150
+ const autoOff = f.has('--no-autostart');
151
+ const desktopRelay = f.has('--desktop-relay');
152
+ const chainNotify = f.has('--chain-notify');
153
+ const noMirror = f.has('--no-mirror');
154
+ const noRegister = f.has('--no-register');
155
+ const attachMcp = f.has('--attach-mcp');
156
+ if (f.rest().length)
157
+ throw new UsageError(`setup 이 모르는 인자: ${f.rest().join(' ')}\n${AGENT_HELP}`);
158
+ if (approvalFlag && approvalFlag !== 'ask' && approvalFlag !== 'auto')
159
+ throw new UsageError('--approval 은 ask 또는 auto');
160
+ if (keepFlag && !KEEP_AWAKE_MODES.includes(keepFlag))
161
+ throw new UsageError(`--keep-awake 는 ${KEEP_AWAKE_MODES.join(' · ')}`);
162
+ if (wsNames.length > wsPaths.length)
163
+ throw new UsageError('--workspace-name 은 --workspace 마다 하나씩');
164
+ for (const a of agentsFlag)
165
+ if (a !== 'claude' && a !== 'codex')
166
+ throw new UsageError('--agent 는 claude 또는 codex');
167
+ const asker = makeAsker(interactive);
168
+ const notes = [];
169
+ try {
170
+ // ① 깔린 에이전트
171
+ const detected = {
172
+ claude: process.env.ODYSSEY_AGENT_FAKE_DETECT ? fakeDetect('claude') : claudeAdapter.detect(),
173
+ codex: process.env.ODYSSEY_AGENT_FAKE_DETECT ? fakeDetect('codex') : codexAdapter.detect(),
174
+ };
175
+ let chosen = forced ? [forced] : agentsFlag;
176
+ if (!chosen.length) {
177
+ const installed = ['claude', 'codex'].filter((a) => detected[a].installed);
178
+ if (!installed.length)
179
+ throw new UsageError('클로드 코드도 코덱스도 찾지 못했습니다. 먼저 설치하세요(claude · codex 명령).');
180
+ chosen = [];
181
+ for (const a of installed)
182
+ if (await asker.yes(`${AGENT_LABEL[a]}(${detected[a].version ?? '버전 모름'})를 연결할까요?`, true))
183
+ chosen.push(a);
184
+ if (!chosen.length)
185
+ throw new UsageError('연결할 에이전트를 고르지 않았습니다.');
186
+ }
187
+ for (const a of chosen) {
188
+ const d = detected[a];
189
+ if (!d.installed)
190
+ throw new UsageError(`${AGENT_LABEL[a]}를 찾지 못했습니다(${a} 명령). 설치 뒤 다시 실행하세요.`);
191
+ const min = MIN_VERSION[a];
192
+ if (min && d.version && versionLess(d.version, min))
193
+ throw new UsageError(`${AGENT_LABEL[a]} ${d.version} 은 너무 오래됐습니다 — ${min} 이상으로 업데이트하세요.`);
194
+ }
195
+ const file = loadBridges();
196
+ const device = deviceName();
197
+ // ② 이름 · 이모지
198
+ for (const a of chosen) {
199
+ const prev = file.bridges[a];
200
+ const defName = prev?.name ?? `${device} ${AGENT_LABEL[a]}`;
201
+ const name = (chosen.length === 1 && nameFlag) || (await asker.ask(`${AGENT_LABEL[a]} 이름(앱 「새 대화」 줄에 보입니다)`, nameFlag ?? defName)) || defName;
202
+ const emoji = (chosen.length === 1 && emojiFlag) || (await asker.ask(`${AGENT_LABEL[a]} 이모지`, emojiFlag ?? prev?.emoji ?? DEFAULT_EMOJI[a])) || DEFAULT_EMOJI[a];
203
+ file.bridges[a] = {
204
+ bridgeId: prev?.bridgeId ?? newId('br'),
205
+ agent: agentOfShort(a),
206
+ name,
207
+ emoji,
208
+ approval: prev?.approval ?? 'ask',
209
+ keepAwake: prev?.keepAwake ?? 'onPower',
210
+ ...(prev?.profileUid ? { profileUid: prev.profileUid } : {}),
211
+ ...(prev?.chainNotify ? { chainNotify: prev.chainNotify } : {}),
212
+ ...(detected[a].version ? { agentVersion: detected[a].version } : {}),
213
+ ...(g.profile ? { odysseyProfile: g.profile } : prev?.odysseyProfile ? { odysseyProfile: prev.odysseyProfile } : {}),
214
+ ...(attachMcp || prev?.attachOdysseyMcp ? { attachOdysseyMcp: true } : {}),
215
+ };
216
+ }
217
+ // ③ 미러링
218
+ const mirror = {};
219
+ for (const a of chosen) {
220
+ if (noMirror) {
221
+ mirror[a] = null;
222
+ continue;
223
+ }
224
+ if (a === 'claude') {
225
+ mirror[a] = installClaudeHooks(launcher());
226
+ }
227
+ else {
228
+ let r = installCodexNotify(launcher(), false);
229
+ if (!r.changed && r.previous) {
230
+ const ok = chainNotify || (await asker.yes(`코덱스 notify 가 이미 있습니다(${r.previous.join(' ')}). 그 프로그램을 이어 부르게 하고 바꿀까요?`, false));
231
+ if (ok) {
232
+ r = installCodexNotify(launcher(), true);
233
+ file.bridges.codex.chainNotify = r.previous ?? undefined;
234
+ }
235
+ else
236
+ notes.push('코덱스 notify 를 바꾸지 않아 코덱스 미러링이 꺼져 있습니다(--chain-notify 로 다시).');
237
+ }
238
+ else if (r.previous) {
239
+ file.bridges.codex.chainNotify = r.previous;
240
+ }
241
+ mirror[a] = r.changed || codexNotifyInstalled() ? r.path : null;
242
+ }
243
+ }
244
+ // ④ 작업 폴더
245
+ for (let i = 0; i < wsPaths.length; i++) {
246
+ const name = wsNames[i] ?? (interactive ? await asker.ask(`작업 폴더 이름(${wsPaths[i]})`, suggestName(wsPaths[i])) : '');
247
+ addWorkspace(wsPaths[i], name, appOnly);
248
+ }
249
+ if (interactive) {
250
+ let more = loadWorkspaces().length === 0 || (await asker.yes('작업 폴더를 더 등록할까요?', false));
251
+ while (more) {
252
+ const p = await asker.ask('작업 폴더 경로', process.cwd());
253
+ const n = await asker.ask('이 폴더의 이름(앱에는 이 이름만 갑니다)', suggestName(p));
254
+ const only = await asker.yes('앱에서 만든 대화만 올릴까요?(아니면 이 폴더의 세션을 전부 올립니다)', false);
255
+ try {
256
+ const w = addWorkspace(p, n, only);
257
+ say(`✓ 등록: ${w.name}`);
258
+ }
259
+ catch (e) {
260
+ say(`✗ ${e.message}`);
261
+ }
262
+ more = await asker.yes('하나 더?', false);
263
+ }
264
+ }
265
+ if (!loadWorkspaces().length)
266
+ throw new UsageError('작업 폴더를 하나 이상 등록해야 설정이 끝납니다: --workspace <경로> --workspace-name <이름>');
267
+ // ⑤ 승인 정책 · ⑥ 잠자기 방지
268
+ const approval = approvalFlag ?? ((await asker.yes('파일 쓰기 · 명령을 실행하기 전에 앱에서 물을까요?(위험 명령은 언제나 묻습니다)', true)) ? 'ask' : 'auto');
269
+ let keep = keepFlag;
270
+ if (!keep) {
271
+ const a = await asker.ask(`잠자기 방지(${KEEP_AWAKE_MODES.join(' · ')})`, 'onPower');
272
+ keep = KEEP_AWAKE_MODES.includes(a) ? a : 'onPower';
273
+ }
274
+ for (const a of chosen) {
275
+ file.bridges[a].approval = approval;
276
+ file.bridges[a].keepAwake = keep;
277
+ }
278
+ if (desktopRelay)
279
+ file.desktopRelay = true;
280
+ // ⑦ 자동 시작
281
+ const autostart = autoOn ? true : autoOff ? false : await asker.yes('컴퓨터에 로그인하면 자동으로 켤까요?', interactive);
282
+ file.autostart = autostart;
283
+ saveBridges(file);
284
+ // ⑧ 등록
285
+ const results = [];
286
+ for (const a of chosen) {
287
+ const b = file.bridges[a];
288
+ let registered = false;
289
+ if (!noRegister) {
290
+ try {
291
+ const r = await call(makeClient(b.odysseyProfile), 'agent_bridge_register', registerArgs(b, file.desktopRelay === true));
292
+ if (r.bridgeId)
293
+ b.bridgeId = r.bridgeId;
294
+ if (r.profileUid)
295
+ b.profileUid = r.profileUid;
296
+ // 이름 · 이모지는 처음 만들 때만 쓴다 — 이미 있으면 앱에서 고친 값이 정본이라 서버 값을 받아 적는다(로컬 장부가 거짓말하지 않게).
297
+ if (r.profileCreated === false && (r.profileName || r.profileEmoji)) {
298
+ if (r.profileName && r.profileName !== b.name)
299
+ notes.push(`${AGENT_LABEL[a]} 이름은 앱에서 정한 「${r.profileName}」을 그대로 둔다(바꾸려면 앱의 컴패니언 상세에서)`);
300
+ if (r.profileName)
301
+ b.name = r.profileName;
302
+ if (r.profileEmoji)
303
+ b.emoji = r.profileEmoji;
304
+ }
305
+ b.registeredAt = new Date().toISOString();
306
+ registered = true;
307
+ }
308
+ catch (e) {
309
+ notes.push(`${AGENT_LABEL[a]} 서버 등록 실패 — 나중에 setup 을 다시: ${e.message}`);
310
+ }
311
+ }
312
+ results.push({ agent: b.agent, bridgeId: b.bridgeId, ...(b.profileUid ? { profileUid: b.profileUid } : {}), name: b.name, emoji: b.emoji, registered, mirror: mirror[a] ?? null });
313
+ }
314
+ saveBridges(file);
315
+ if (autostart) {
316
+ const r = installAutostart({ node: stableNode(), entry: CLI_ENTRY, logDir: paths.logs(), ...(process.env.ODYSSEY_AGENT_HOME ? { env: { ODYSSEY_AGENT_HOME: process.env.ODYSSEY_AGENT_HOME } } : {}) });
317
+ if (r.note)
318
+ notes.push(r.note);
319
+ }
320
+ else {
321
+ notes.push('데몬 켜기: odyssey agent start (자동 시작은 setup --autostart)');
322
+ }
323
+ const result = { bridges: results, workspaces: publicWorkspaces(), autostart, notes };
324
+ out(result);
325
+ for (const n of notes)
326
+ say(`· ${n}`);
327
+ return 0;
328
+ }
329
+ finally {
330
+ asker.close();
331
+ }
332
+ }
333
+ function fakeDetect(a) {
334
+ const spec = process.env.ODYSSEY_AGENT_FAKE_DETECT ?? '';
335
+ const m = new RegExp(`${a}@([\\d.]+)`).exec(spec);
336
+ return m ? { installed: true, version: m[1] } : { installed: false };
337
+ }
338
+ export function registerArgs(b, desktopRelay) {
339
+ return {
340
+ bridgeId: b.bridgeId,
341
+ agent: b.agent,
342
+ deviceName: deviceName(),
343
+ platform: osPlatform(),
344
+ cliVersion: CLI_VERSION,
345
+ ...(b.agentVersion ? { agentVersion: b.agentVersion } : {}),
346
+ profileName: b.name,
347
+ profileEmoji: b.emoji,
348
+ workspaces: publicWorkspaces(),
349
+ keepAwake: b.keepAwake,
350
+ desktopRelay,
351
+ };
352
+ }
353
+ async function cmdUninstall(purge, rest) {
354
+ if (rest.length)
355
+ throw new UsageError(`setup --uninstall 이 모르는 인자: ${rest.join(' ')}`);
356
+ const file = loadBridges();
357
+ const done = [];
358
+ await stopDaemon();
359
+ const a = uninstallAutostart();
360
+ done.push(`자동 시작 해제${a.path ? `(${a.path})` : ''}`);
361
+ const c = uninstallClaudeHooks();
362
+ if (c)
363
+ done.push(`클로드 훅 제거(${c})`);
364
+ const x = uninstallCodexNotify(file.bridges.codex?.chainNotify ?? null);
365
+ if (x)
366
+ done.push(`코덱스 notify 제거(${x})`);
367
+ if (purge) {
368
+ rmSync(agentHome(), { recursive: true, force: true });
369
+ done.push(`로컬 상태 삭제(${agentHome()})`);
370
+ }
371
+ else {
372
+ file.autostart = false;
373
+ saveBridges(file);
374
+ }
375
+ out({ uninstalled: true, done, note: '앱의 브리지 컴패니언은 앱에서 지우면 연결이 끊긴다.' });
376
+ return 0;
377
+ }
378
+ // ── status · start · stop ──
379
+ export function statusReport() {
380
+ const file = loadBridges();
381
+ const pid = daemonPid();
382
+ const st = readJson(paths.state(), {});
383
+ return {
384
+ home: agentHome(),
385
+ bridges: Object.entries(file.bridges).map(([k, b]) => ({
386
+ agent: k, bridgeId: b.bridgeId, name: b.name, emoji: b.emoji, registered: !!b.registeredAt, approval: b.approval,
387
+ keepAwake: b.keepAwake, profile: b.odysseyProfile ?? null, agentVersion: b.agentVersion ?? null,
388
+ })),
389
+ daemon: { running: pid > 0, pid: pid || null, lastHeartbeatAt: st.lastHeartbeatAt ?? null, keepAwakeActive: st.keepAwakeActive ?? null, runningTurns: st.runningTurns ?? null },
390
+ autostart: { wanted: file.autostart === true, installed: autostartInstalled() },
391
+ mirror: {
392
+ claude: file.bridges.claude ? { installed: claudeHooksInstalled(), settings: claudeSettingsPath() } : null,
393
+ codex: file.bridges.codex ? { installed: codexNotifyInstalled(), config: codexConfigPath() } : null,
394
+ },
395
+ desktopRelay: file.desktopRelay === true,
396
+ workspaces: loadWorkspaces().map((w) => ({ id: w.id, name: w.name, mirror: w.mirror, path: w.path })),
397
+ outbox: listOutbox().length,
398
+ };
399
+ }
400
+ async function startDaemon() {
401
+ const pid = daemonPid();
402
+ if (pid)
403
+ return { started: false, running: true, pid };
404
+ if (process.platform === 'darwin' && autostartInstalled('darwin') && process.env.ODYSSEY_AGENT_DRY_SYSTEM !== '1') {
405
+ const r = spawnSync('launchctl', ['kickstart', `gui/${process.getuid?.() ?? ''}/${LAUNCH_LABEL}`], { encoding: 'utf-8' });
406
+ if (r.status === 0)
407
+ return { started: true, via: 'launchctl' };
408
+ }
409
+ mkdirSync(paths.logs(), { recursive: true, mode: 0o700 });
410
+ const log = openSync(`${paths.logs()}/daemon.out.log`, 'a');
411
+ const child = spawn(process.execPath, [CLI_ENTRY, 'agent', 'daemon'], { detached: true, stdio: ['ignore', log, log], env: process.env });
412
+ child.unref();
413
+ for (let i = 0; i < 30 && !daemonPid(); i++)
414
+ await new Promise((r) => setTimeout(r, 200));
415
+ return { started: daemonPid() > 0, pid: daemonPid() || child.pid, log: `${paths.logs()}/daemon.log` };
416
+ }
417
+ async function stopDaemon() {
418
+ const pid = daemonPid();
419
+ if (!pid)
420
+ return { stopped: false, running: false };
421
+ try {
422
+ process.kill(pid, 'SIGTERM');
423
+ }
424
+ catch {
425
+ return { stopped: false, running: false };
426
+ }
427
+ for (let i = 0; i < 100 && daemonPid(); i++)
428
+ await new Promise((r) => setTimeout(r, 200));
429
+ return { stopped: !daemonPid(), pid };
430
+ }
431
+ // ── workspace ──
432
+ function cmdWorkspace(args) {
433
+ const [sub, ...rest] = args;
434
+ const f = new Flags(rest);
435
+ switch (sub) {
436
+ case 'add': {
437
+ const name = f.value('--name');
438
+ const only = f.has('--app-only');
439
+ const [p, ...extra] = f.rest();
440
+ if (!p || extra.length)
441
+ throw new UsageError('사용법: odyssey agent workspace add <경로> --name <이름> [--app-only]');
442
+ const w = addWorkspace(p, name, only);
443
+ out({ added: { id: w.id, name: w.name, mirror: w.mirror, path: w.path }, note: '데몬 · 앱 목록에는 다음 하트비트(또는 setup)에서 반영' });
444
+ void syncWorkspaces();
445
+ return 0;
446
+ }
447
+ case 'list':
448
+ case undefined:
449
+ out(loadWorkspaces().map((w) => ({ id: w.id, name: w.name, mirror: w.mirror, path: w.path })));
450
+ return 0;
451
+ case 'rename': {
452
+ const [ref, name] = f.rest();
453
+ if (!ref || !name)
454
+ throw new UsageError('사용법: odyssey agent workspace rename <id|이름|경로> <새 이름>');
455
+ const w = renameWorkspace(ref, name);
456
+ out({ renamed: { id: w.id, name: w.name } });
457
+ void syncWorkspaces();
458
+ return 0;
459
+ }
460
+ case 'mirror': {
461
+ const [ref, mode] = f.rest();
462
+ if (!ref || (mode !== 'all' && mode !== 'appOnly'))
463
+ throw new UsageError('사용법: odyssey agent workspace mirror <id|이름|경로> all|appOnly');
464
+ const w = setWorkspaceMirror(ref, mode === 'appOnly');
465
+ out({ mirror: { id: w.id, name: w.name, mirror: w.mirror } });
466
+ void syncWorkspaces();
467
+ return 0;
468
+ }
469
+ case 'remove': {
470
+ const [ref] = f.rest();
471
+ if (!ref)
472
+ throw new UsageError('사용법: odyssey agent workspace remove <id|이름|경로>');
473
+ const w = removeWorkspace(ref);
474
+ out({ removed: { id: w.id, name: w.name } });
475
+ void syncWorkspaces();
476
+ return 0;
477
+ }
478
+ default:
479
+ throw new UsageError('사용법: odyssey agent workspace add|list|rename|mirror|remove');
480
+ }
481
+ }
482
+ /** 등록 폴더가 바뀌면 서버 브리지 문서의 workspaces 를 고친다(실패는 조용히 — 데몬 시작 때 다시 보낸다). */
483
+ async function syncWorkspaces() {
484
+ if (process.env.ODYSSEY_AGENT_NO_SEND === '1')
485
+ return;
486
+ for (const b of Object.values(loadBridges().bridges)) {
487
+ if (!b?.registeredAt)
488
+ continue;
489
+ try {
490
+ await call(makeClient(b.odysseyProfile), 'agent_bridge_heartbeat', { bridgeId: b.bridgeId, workspaces: publicWorkspaces() });
491
+ }
492
+ catch {
493
+ // 다음에
494
+ }
495
+ }
496
+ }
497
+ // ── hook ──
498
+ async function readStdinWithTimeout(ms) {
499
+ if (process.stdin.isTTY)
500
+ return '';
501
+ return new Promise((resolve) => {
502
+ const chunks = [];
503
+ const t = setTimeout(() => done(), ms);
504
+ const done = () => {
505
+ clearTimeout(t);
506
+ process.stdin.removeAllListeners();
507
+ process.stdin.pause();
508
+ resolve(Buffer.concat(chunks).toString('utf-8'));
509
+ };
510
+ process.stdin.on('data', (c) => chunks.push(c));
511
+ process.stdin.on('end', done);
512
+ process.stdin.on('error', done);
513
+ });
514
+ }
515
+ /** 늘 0 — 실패가 에이전트 작업을 막지 않게. 결과 한 줄은 ODYSSEY_AGENT_HOOK_DEBUG=1 일 때만 stderr 로. */
516
+ async function cmdHook(args) {
517
+ const [agent, event, ...rest] = args;
518
+ try {
519
+ let outcome;
520
+ if (agent === 'claude') {
521
+ const raw = await readStdinWithTimeout(3000);
522
+ let input = {};
523
+ try {
524
+ input = raw.trim() ? JSON.parse(raw) : {};
525
+ }
526
+ catch {
527
+ input = {};
528
+ }
529
+ outcome = await commitHook(planClaudeHook(event ?? '', input));
530
+ }
531
+ else if (agent === 'codex') {
532
+ const payloadArg = rest.length ? rest[rest.length - 1] : '';
533
+ const n = parseCodexNotify(rest);
534
+ chainCodexNotify(payloadArg);
535
+ outcome = n ? await commitHook(planCodexNotify(n, { cwd: process.cwd(), threadIdFallback: () => latestCodexThread() })) : { action: 'skip', reason: 'no-payload' };
536
+ }
537
+ else {
538
+ outcome = { action: 'skip', reason: 'unknown-agent' };
539
+ }
540
+ if (process.env.ODYSSEY_AGENT_HOOK_DEBUG === '1')
541
+ process.stderr.write(JSON.stringify(outcome) + '\n');
542
+ }
543
+ catch (e) {
544
+ if (process.env.ODYSSEY_AGENT_HOOK_DEBUG === '1')
545
+ process.stderr.write(`hook 오류: ${e.message}\n`);
546
+ }
547
+ // 직접 보내기가 남긴 소켓이 프로세스를 붙잡지 않게 — 에이전트는 훅이 끝나길 기다린다.
548
+ setTimeout(() => process.exit(0), 20).unref();
549
+ return 0;
550
+ }
551
+ // ── 진입 ──
552
+ export async function cmdAgent(g, args, forced) {
553
+ const [sub, ...rest] = args;
554
+ if (!sub || sub === 'help' || g.help) {
555
+ process.stdout.write(`${AGENT_HELP}\n`);
556
+ return sub || g.help ? 0 : 2;
557
+ }
558
+ switch (sub) {
559
+ case 'setup':
560
+ return cmdSetup(g, rest, forced);
561
+ case 'status':
562
+ out(statusReport());
563
+ return 0;
564
+ case 'start':
565
+ out(await startDaemon());
566
+ return 0;
567
+ case 'stop':
568
+ out(await stopDaemon());
569
+ return 0;
570
+ case 'daemon':
571
+ return runDaemon(forced ? { only: forced } : {});
572
+ case 'hook':
573
+ return cmdHook(forced ? [forced, ...rest] : rest);
574
+ case 'workspace':
575
+ case 'workspaces':
576
+ return cmdWorkspace(rest);
577
+ default:
578
+ throw new UsageError(`agent 가 모르는 명령: ${sub}\n${AGENT_HELP}`);
579
+ }
580
+ }