@odyssey365/cli 0.2.5 → 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,87 @@
1
+ /**
2
+ * 승인 정책(설계 §7 · §15.5) — 읽기는 자동 허용 · 파일 쓰기 · 명령은 ask(기본) 또는 auto · 위험 목록은 언제나 묻는다.
3
+ *
4
+ * 묻는 법(§15 머리): 막을 도구를 만나면 막고 턴을 `done` + `approvalTools` 로 닫으며 답에 승인 카드를 싣는다.
5
+ * 사용자가 허락하면 다음 턴의 approval 이 그 턴을 가리키고, 브리지는 막았던 도구를 그 재개 실행 동안 허락한다
6
+ * (위험 명령은 막았던 **그 명령**만 — 이름만 같은 다른 위험 명령은 다시 묻는다).
7
+ */
8
+ import { createHash } from 'node:crypto';
9
+ const READ_TOOLS = new Set([
10
+ 'Read', 'Glob', 'Grep', 'LS', 'NotebookRead', 'WebFetch', 'WebSearch', 'TodoWrite', 'TodoRead', 'Task', 'Agent',
11
+ 'BashOutput', 'KillShell', 'ToolSearch', 'ExitPlanMode', 'ListMcpResourcesTool', 'ReadMcpResourceTool', 'Skill', 'TaskOutput',
12
+ ]);
13
+ const WRITE_TOOLS = { Write: 'create', Edit: 'update', MultiEdit: 'update', NotebookEdit: 'update' };
14
+ const COMMAND_TOOLS = new Set(['Bash', 'PowerShell']);
15
+ /** 언제나 묻는 명령(§7) — git push · rm -r · 배포 · 설치 · sudo · 받아서 바로 실행. */
16
+ const DANGER = [
17
+ { re: /\bgit\s+push\b/, action: 'update' },
18
+ { re: /\bgit\s+(?:reset\s+--hard|clean\s+-[a-z]*f|branch\s+-D|push\s+--force)/, action: 'delete' },
19
+ { re: /\brm\s+(?:-[a-zA-Z]*[rf][a-zA-Z]*\s+)+/, action: 'delete' },
20
+ { re: /\b(?:firebase|vercel|netlify|fly|flyctl|wrangler|gcloud\s+\S+|serverless|sls|kubectl|helm|terraform)\s+(?:deploy|apply|publish|release)\b/, action: 'update' },
21
+ { re: /\b(?:npm|pnpm|yarn)\s+publish\b/, action: 'update' },
22
+ { re: /\b(?:npm|pnpm|yarn|bun)\s+(?:i|install|add)\b/, action: 'create' },
23
+ { re: /\b(?:pip3?|uv\s+pip|gem|cargo|brew|apt(?:-get)?|dnf|yum|pacman)\s+install\b/, action: 'create' },
24
+ { re: /\bsudo\b/, action: 'update' },
25
+ { re: /\b(?:curl|wget)\b[^|]*\|\s*(?:ba|z)?sh\b/, action: 'create' },
26
+ { re: /\bdd\s+if=|\bmkfs\b|\bshutdown\b|\breboot\b/, action: 'delete' },
27
+ ];
28
+ /** 읽기만 하는 명령(앞머리) — ask 정책이어도 묻지 않는다. */
29
+ const READ_COMMANDS = /^\s*(?:ls|pwd|cat|head|tail|wc|grep|rg|find|fd|echo|which|whoami|date|env|printenv|stat|file|tree|du|df|git\s+(?:status|diff|log|show|branch|remote|rev-parse|ls-files|blame))\b(?![^|;&]*[>])/;
30
+ function shorten(s, n = 120) {
31
+ const one = s.replace(/\s+/g, ' ').trim();
32
+ return one.length > n ? `${one.slice(0, n)}…` : one;
33
+ }
34
+ /** 승인 줄에선 절대 경로를 「…/파일이름」으로 줄인다 — 사람이 읽을 만큼만 남기고, 긴 경로가 비밀 가림에 통째로 걸려
35
+ * 「F="[가림]…」처럼 무엇을 허락하는지 안 보이던 것(261122 E2E)을 막는다. 경로는 앱에 올리지 않는다는 원칙과도 맞다. */
36
+ function shortenPaths(cmd) {
37
+ return cmd.replace(/(?:~|(?<![\w.]))(?:\/[^\s"'`;|&()<>]+){2,}/g, (m) => `…/${m.split('/').pop() ?? ''}`);
38
+ }
39
+ function maskArgs(cmd) {
40
+ return shortenPaths(cmd)
41
+ .replace(/(--?(?:token|password|passwd|secret|key|api-key|auth)[= ])\S+/gi, '$1[가림]')
42
+ .replace(/\b[A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|KEY)[A-Z0-9_]*=\S+/g, (m) => `${m.split('=')[0]}=[가림]`)
43
+ .replace(/https?:\/\/[^\s@]+@/g, 'https://[가림]@');
44
+ }
45
+ function baseName(p) {
46
+ return typeof p === 'string' ? p.split(/[\\/]/).pop() ?? p : '';
47
+ }
48
+ export function classifyTool(name, input) {
49
+ if (COMMAND_TOOLS.has(name)) {
50
+ const cmd = typeof input.command === 'string' ? input.command : '';
51
+ const masked = maskArgs(cmd);
52
+ const key = createHash('sha256').update(cmd).digest('hex').slice(0, 16);
53
+ const danger = DANGER.find((d) => d.re.test(cmd));
54
+ if (danger)
55
+ return { kind: 'danger', actionType: danger.action, line: `\`${shorten(masked)}\` 실행`, key: `${name}:${key}` };
56
+ const readOnly = cmd.split(/&&|\|\||;|\|/).every((part) => READ_COMMANDS.test(part));
57
+ return { kind: readOnly ? 'read' : 'command', actionType: readOnly ? 'read' : 'update', line: `\`${shorten(masked)}\` 실행`, key: name };
58
+ }
59
+ if (WRITE_TOOLS[name]) {
60
+ const file = baseName(input.file_path ?? input.notebook_path);
61
+ return { kind: 'write', actionType: WRITE_TOOLS[name], line: file ? `${file} ${name === 'Write' ? '쓰기' : '고치기'}` : `파일 ${name}`, key: name };
62
+ }
63
+ if (READ_TOOLS.has(name))
64
+ return { kind: 'read', actionType: 'read', line: name, key: name };
65
+ if (name.startsWith('mcp__')) {
66
+ const tool = name.split('__').pop() ?? name;
67
+ const read = /^(?:get|list|search|read|fetch|describe|query)_?/i.test(tool);
68
+ return { kind: read ? 'read' : 'write', actionType: read ? 'read' : /delete|remove/i.test(tool) ? 'delete' : /create|add|save/i.test(tool) ? 'create' : 'update', line: tool, key: name };
69
+ }
70
+ // 모르는 도구 — 쓰기로 본다(묻는 쪽이 안전하다).
71
+ return { kind: 'write', actionType: 'update', line: name, key: name };
72
+ }
73
+ export const emptyGrant = () => ({ tools: new Set(), keys: new Set() });
74
+ export function decide(c, toolName, policy, grant) {
75
+ if (c.kind === 'read')
76
+ return 'allow';
77
+ if (c.kind === 'danger')
78
+ return grant.keys.has(c.key) ? 'allow' : 'block';
79
+ if (policy === 'auto')
80
+ return 'allow';
81
+ return grant.tools.has(toolName) ? 'allow' : 'block';
82
+ }
83
+ /** 막은 것 → 승인 카드(askApproval)의 actionType — 가장 무거운 것. */
84
+ export function heaviestAction(list) {
85
+ const order = ['read', 'create', 'update', 'delete'];
86
+ return list.reduce((a, b) => (order.indexOf(b) > order.indexOf(a) ? b : a), 'read');
87
+ }
@@ -0,0 +1,243 @@
1
+ /**
2
+ * 에이전트 브리지의 로컬 상태 — `~/.odyssey/agent/`(설계 §15.5).
3
+ *
4
+ * bridges.json 에이전트별 브리지(id · 프로필 uid · 이름 · 이모지 · 승인 정책 · 잠자기 방지 · Odyssey 프로필)
5
+ * workspaces.json 등록한 작업 폴더 `{id, name, path, mirror}` — **경로는 여기에만** 있다(서버엔 id · 이름 · mirror 만)
6
+ * ledger.json 데몬이 띄운 세션 · 앱 턴 표식 · 승인 대기 — 미러링이 두 번 쓰지 않게, appOnly 폴더 거르기
7
+ * outbox/ 보낼 일(파일 하나 = 일 하나). 훅이 쓰고 데몬이 보낸다
8
+ * media/<세션>/ 앱이 보낸 사진 · 영상 내려받은 자리(30일 뒤 지운다)
9
+ * logs/ 데몬 로그
10
+ *
11
+ * 기준 폴더: ODYSSEY_AGENT_HOME → HOME/.odyssey/agent (테스트는 임시 HOME 또는 ODYSSEY_AGENT_HOME).
12
+ */
13
+ import { randomBytes } from 'node:crypto';
14
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync } from 'node:fs';
15
+ import { homedir } from 'node:os';
16
+ import { join } from 'node:path';
17
+ import { writePrivateFile } from '../config.js';
18
+ // ── 도메인 상수(domain/lib/src/shared/model/companion/companion_external_agent.dart 의 TS 판) ──
19
+ export const AgentKind = { claudeCode: 'claudeCode', codex: 'codex' };
20
+ export const AgentHost = { desktop: 'desktop', cli: 'cli' };
21
+ export const AgentOrigin = { app: 'app', local: 'local' };
22
+ export const AgentSessionState = { idle: 'idle', running: 'running', awaitingApproval: 'awaitingApproval' };
23
+ export const BRIDGE_OWNER_PREFIX = 'bridge:';
24
+ export const bridgeOwner = (bridgeId) => `${BRIDGE_OWNER_PREFIX}${bridgeId}`;
25
+ export const authorKindOf = (agent) => (agent === AgentKind.codex ? 'codex' : 'claude');
26
+ export const AgentMediaPolicy = {
27
+ storageRoot: 'agent_media',
28
+ expiryDays: 30,
29
+ imageMaxBytes: 50 * 1024 * 1024,
30
+ videoMaxBytes: 1024 * 1024 * 1024,
31
+ };
32
+ export const AgentBridgeTiming = {
33
+ heartbeatMs: 60_000,
34
+ staleAfterMs: 120_000,
35
+ };
36
+ export const KEEP_AWAKE_MODES = ['always', 'onPower', 'whileWorking', 'off'];
37
+ /** 깨어났을 때 이보다 오래된 running 턴은 받지 않고 failed(설계 §11.2). */
38
+ export const STALE_TURN_MS = 10 * 60_000;
39
+ /** 미러링 세션 id = `ag_<agent>_<externalSessionId>`(설계 §4.2 — 미러링 · 실행 어느 쪽이 먼저 써도 같은 문서). */
40
+ export function mirrorSessionUid(agent, externalSessionId) {
41
+ return `ag_${agent}_${externalSessionId}`;
42
+ }
43
+ // ── 경로 ──
44
+ export function agentHome() {
45
+ const fromEnv = process.env.ODYSSEY_AGENT_HOME;
46
+ if (fromEnv && fromEnv.trim())
47
+ return fromEnv;
48
+ return join(homedir(), '.odyssey', 'agent');
49
+ }
50
+ export const paths = {
51
+ bridges: () => join(agentHome(), 'bridges.json'),
52
+ workspaces: () => join(agentHome(), 'workspaces.json'),
53
+ ledger: () => join(agentHome(), 'ledger.json'),
54
+ outbox: () => join(agentHome(), 'outbox'),
55
+ media: (sessionUid) => (sessionUid ? join(agentHome(), 'media', safeName(sessionUid)) : join(agentHome(), 'media')),
56
+ logs: () => join(agentHome(), 'logs'),
57
+ pid: () => join(agentHome(), 'daemon.pid'),
58
+ state: () => join(agentHome(), 'daemon.json'),
59
+ };
60
+ /** 파일 이름으로 안전한 조각(세션 uid 가 경로를 빠져나가지 않게). */
61
+ export function safeName(s) {
62
+ return s.replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 120) || '_';
63
+ }
64
+ export function newId(prefix) {
65
+ return `${prefix}_${randomBytes(8).toString('hex')}`;
66
+ }
67
+ // ── JSON 파일 ──
68
+ export function readJson(path, fallback) {
69
+ try {
70
+ return JSON.parse(readFileSync(path, 'utf-8'));
71
+ }
72
+ catch {
73
+ return fallback;
74
+ }
75
+ }
76
+ export function writeJson(path, value) {
77
+ writePrivateFile(path, JSON.stringify(value, null, 2) + '\n');
78
+ }
79
+ export const agentOfShort = (s) => (s === 'codex' ? AgentKind.codex : AgentKind.claudeCode);
80
+ export const shortOfAgent = (a) => (a === AgentKind.codex ? 'codex' : 'claude');
81
+ export function loadBridges() {
82
+ const f = readJson(paths.bridges(), {});
83
+ return { version: 1, bridges: f.bridges ?? {}, ...(f.autostart !== undefined ? { autostart: f.autostart } : {}), ...(f.desktopRelay !== undefined ? { desktopRelay: f.desktopRelay } : {}) };
84
+ }
85
+ export function saveBridges(f) {
86
+ writeJson(paths.bridges(), f);
87
+ }
88
+ export function bridgeByAgent(agent) {
89
+ return loadBridges().bridges[shortOfAgent(agent)];
90
+ }
91
+ export function bridgeById(bridgeId) {
92
+ return Object.values(loadBridges().bridges).find((b) => b?.bridgeId === bridgeId);
93
+ }
94
+ const KEEP = 500;
95
+ export function loadLedger() {
96
+ const l = readJson(paths.ledger(), {});
97
+ return {
98
+ version: 1,
99
+ sessions: l.sessions ?? {},
100
+ byExternal: l.byExternal ?? {},
101
+ turns: Array.isArray(l.turns) ? l.turns : [],
102
+ active: l.active ?? {},
103
+ approvals: l.approvals ?? {},
104
+ posted: Array.isArray(l.posted) ? l.posted : [],
105
+ relayTexts: Array.isArray(l.relayTexts) ? l.relayTexts : [],
106
+ relay: l.relay ?? {},
107
+ };
108
+ }
109
+ export function saveLedger(l) {
110
+ l.turns = l.turns.slice(-KEEP);
111
+ l.posted = l.posted.slice(-KEEP * 4);
112
+ l.relayTexts = (l.relayTexts ?? []).slice(-50);
113
+ writeJson(paths.ledger(), l);
114
+ }
115
+ /** 읽고 → 고치고 → 쓴다(훅 · 데몬이 같은 파일을 만진다 — 짧게 잡는다). */
116
+ export function updateLedger(fn) {
117
+ const l = loadLedger();
118
+ const r = fn(l);
119
+ saveLedger(l);
120
+ return r;
121
+ }
122
+ export function enqueue(jobs, profile) {
123
+ const entry = { id: `${Date.now()}-${randomBytes(4).toString('hex')}`, createdAt: new Date().toISOString(), attempts: 0, jobs, done: 0, ...(profile ? { profile } : {}) };
124
+ writeOutbox(entry);
125
+ return entry;
126
+ }
127
+ export function writeOutbox(entry) {
128
+ mkdirSync(paths.outbox(), { recursive: true, mode: 0o700 });
129
+ writePrivateFile(join(paths.outbox(), `${entry.id}.json`), JSON.stringify(entry) + '\n');
130
+ }
131
+ export function listOutbox() {
132
+ let names = [];
133
+ try {
134
+ names = readdirSync(paths.outbox()).filter((n) => n.endsWith('.json')).sort();
135
+ }
136
+ catch {
137
+ return [];
138
+ }
139
+ const out = [];
140
+ for (const n of names) {
141
+ const e = readJson(join(paths.outbox(), n), null);
142
+ if (e && Array.isArray(e.jobs))
143
+ out.push(e);
144
+ }
145
+ return out;
146
+ }
147
+ export function removeOutbox(id) {
148
+ try {
149
+ unlinkSync(join(paths.outbox(), `${id}.json`));
150
+ }
151
+ catch {
152
+ // 이미 없다
153
+ }
154
+ }
155
+ /** 다른 프로세스(훅의 직접 보내기 · 데몬)가 같은 일을 동시에 잡지 않게 — 잡은 쪽만 .lock 으로 옮긴다. */
156
+ export function claimOutbox(id) {
157
+ const from = join(paths.outbox(), `${id}.json`);
158
+ try {
159
+ // rename 은 원자적이다 — 둘이 동시에 잡으면 하나만 이긴다.
160
+ renameSync(from, from + '.claimed');
161
+ return true;
162
+ }
163
+ catch {
164
+ return false;
165
+ }
166
+ }
167
+ export function releaseOutbox(entry, keep) {
168
+ const claimed = join(paths.outbox(), `${entry.id}.json.claimed`);
169
+ try {
170
+ unlinkSync(claimed);
171
+ }
172
+ catch {
173
+ // 없다
174
+ }
175
+ if (keep)
176
+ writeOutbox(entry);
177
+ }
178
+ /** 오래 잡힌 채 남은 일(보내다 죽은 프로세스) — 5분 넘으면 다시 내놓는다. */
179
+ export function recoverClaimed(now = Date.now()) {
180
+ let names = [];
181
+ try {
182
+ names = readdirSync(paths.outbox()).filter((n) => n.endsWith('.claimed'));
183
+ }
184
+ catch {
185
+ return;
186
+ }
187
+ for (const n of names) {
188
+ const p = join(paths.outbox(), n);
189
+ try {
190
+ if (now - statSync(p).mtimeMs > 5 * 60_000)
191
+ renameSync(p, p.replace(/\.claimed$/, ''));
192
+ }
193
+ catch {
194
+ // 그새 끝났다
195
+ }
196
+ }
197
+ }
198
+ /** 기한 지난 내려받은 미디어 지우기(설계 §9.4 — 데몬도 같은 기한). */
199
+ export function pruneMedia(now = Date.now()) {
200
+ const root = paths.media();
201
+ if (!existsSync(root))
202
+ return 0;
203
+ let removed = 0;
204
+ for (const dir of readdirSync(root)) {
205
+ const p = join(root, dir);
206
+ try {
207
+ if (now - statSync(p).mtimeMs > AgentMediaPolicy.expiryDays * 86_400_000) {
208
+ rmSync(p, { recursive: true, force: true });
209
+ removed++;
210
+ }
211
+ }
212
+ catch {
213
+ // 무시
214
+ }
215
+ }
216
+ return removed;
217
+ }
218
+ export function writeText(path, content) {
219
+ writePrivateFile(path, content);
220
+ }
221
+ // ── 데몬 pid ──
222
+ /** 살아 있는 데몬 pid(없으면 0). */
223
+ export function daemonPid() {
224
+ const pid = readPidFile();
225
+ if (!pid)
226
+ return 0;
227
+ try {
228
+ process.kill(pid, 0);
229
+ }
230
+ catch (e) {
231
+ if (e.code === 'ESRCH')
232
+ return 0;
233
+ }
234
+ return pid;
235
+ }
236
+ function readPidFile() {
237
+ try {
238
+ return Number.parseInt(readFileSync(paths.pid(), 'utf-8').trim(), 10) || 0;
239
+ }
240
+ catch {
241
+ return 0;
242
+ }
243
+ }
@@ -0,0 +1,269 @@
1
+ /**
2
+ * 잠자기 방지 · 자동 시작(설계 §11.2).
3
+ *
4
+ * 잠자기 방지 — 자식 프로세스를 데몬 pid 에 묶는다(데몬이 죽으면 함께 풀린다 — 남은 방지가 배터리를 먹지 않게):
5
+ * macOS caffeinate -i -w <데몬 pid>
6
+ * Linux systemd-inhibit --what=idle:sleep … 데몬 pid 를 기다리는 sh(데몬이 끝나면 sh 가 끝나 방지가 풀린다)
7
+ * Windows powershell 에서 SetThreadExecutionState(ES_CONTINUOUS|ES_SYSTEM_REQUIRED) 를 걸고 데몬 pid 를 기다린다
8
+ * 모드: always · onPower(기본 — 전원 연결 때만) · whileWorking(턴 도는 동안만) · off.
9
+ *
10
+ * 자동 시작 — 파일을 만드는 함수(테스트는 문자열로) + 설치:
11
+ * macOS ~/Library/LaunchAgents/app.odyssey365.agent.plist(RunAtLoad · 비정상 종료면 다시 띄움)
12
+ * Windows 작업 스케줄러 로그온 작업(schtasks /Create /SC ONLOGON)
13
+ * Linux ~/.config/systemd/user/odyssey-agent.service(Restart=on-failure)
14
+ */
15
+ import { spawn, spawnSync } from 'node:child_process';
16
+ import { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
17
+ import { homedir } from 'node:os';
18
+ import { dirname, join } from 'node:path';
19
+ export const LAUNCH_LABEL = 'app.odyssey365.agent';
20
+ export const WINDOWS_TASK = 'OdysseyAgent';
21
+ export const SYSTEMD_UNIT = 'odyssey-agent.service';
22
+ export function keepAwakeCommand(platform, pid) {
23
+ if (platform === 'darwin')
24
+ return { command: 'caffeinate', args: ['-i', '-w', String(pid)] };
25
+ if (platform === 'linux') {
26
+ return {
27
+ command: 'systemd-inhibit',
28
+ args: ['--what=idle:sleep', '--who=Odyssey agent', '--why=에이전트 브리지 대기', '--mode=block', 'sh', '-c', `while kill -0 ${pid} 2>/dev/null; do sleep 30; done`],
29
+ };
30
+ }
31
+ if (platform === 'win32') {
32
+ const ps = [
33
+ '$s = Add-Type -MemberDefinition \'[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint f);\' -Name P -Namespace W -PassThru;',
34
+ '$s::SetThreadExecutionState([uint32]"0x80000001") | Out-Null;',
35
+ `try { Wait-Process -Id ${pid} } catch {}`,
36
+ ].join(' ');
37
+ return { command: 'powershell.exe', args: ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', ps] };
38
+ }
39
+ return null;
40
+ }
41
+ /** 전원 연결 중인가(모르면 true — 막지 않는 쪽보다 대기를 지키는 쪽). */
42
+ export function onAcPower(platform = process.platform) {
43
+ try {
44
+ if (platform === 'darwin') {
45
+ const r = spawnSync('pmset', ['-g', 'batt'], { encoding: 'utf-8', timeout: 5000 });
46
+ if (r.status === 0)
47
+ return !/'Battery Power'/.test(r.stdout);
48
+ }
49
+ else if (platform === 'linux') {
50
+ const r = spawnSync('sh', ['-c', 'cat /sys/class/power_supply/*/online 2>/dev/null'], { encoding: 'utf-8', timeout: 5000 });
51
+ if (r.status === 0 && r.stdout.trim())
52
+ return r.stdout.split('\n').some((l) => l.trim() === '1');
53
+ }
54
+ else if (platform === 'win32') {
55
+ const r = spawnSync('powershell.exe', ['-NoProfile', '-Command', '(Get-CimInstance -ClassName BatteryStatus -Namespace root/wmi -ErrorAction SilentlyContinue).PowerOnline'], { encoding: 'utf-8', timeout: 10_000 });
56
+ if (r.status === 0 && r.stdout.trim())
57
+ return /True/i.test(r.stdout);
58
+ }
59
+ }
60
+ catch {
61
+ // 모른다
62
+ }
63
+ return true;
64
+ }
65
+ /** 지금 막아야 하나. */
66
+ export function wantAwake(mode, ctx) {
67
+ switch (mode) {
68
+ case 'always':
69
+ return true;
70
+ case 'onPower':
71
+ return ctx.onPower;
72
+ case 'whileWorking':
73
+ return ctx.working;
74
+ default:
75
+ return false;
76
+ }
77
+ }
78
+ export class KeepAwake {
79
+ pid;
80
+ platform;
81
+ spawnFn;
82
+ child = null;
83
+ constructor(pid = process.pid, platform = process.platform, spawnFn = spawn) {
84
+ this.pid = pid;
85
+ this.platform = platform;
86
+ this.spawnFn = spawnFn;
87
+ }
88
+ get active() {
89
+ return this.child !== null;
90
+ }
91
+ set(on) {
92
+ if (on && !this.child) {
93
+ const c = keepAwakeCommand(this.platform, this.pid);
94
+ if (!c)
95
+ return;
96
+ try {
97
+ const child = this.spawnFn(c.command, c.args, { stdio: 'ignore' });
98
+ child.on('error', () => {
99
+ if (this.child === child)
100
+ this.child = null;
101
+ });
102
+ child.on('exit', () => {
103
+ if (this.child === child)
104
+ this.child = null;
105
+ });
106
+ this.child = child;
107
+ }
108
+ catch {
109
+ this.child = null;
110
+ }
111
+ }
112
+ else if (!on && this.child) {
113
+ try {
114
+ this.child.kill('SIGTERM');
115
+ }
116
+ catch {
117
+ // 이미 끝났다
118
+ }
119
+ this.child = null;
120
+ }
121
+ }
122
+ }
123
+ function xml(s) {
124
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
125
+ }
126
+ export function launchAgentPlist(spec) {
127
+ const env = { PATH: process.env.PATH ?? '/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/bin:/usr/local/bin', ...spec.env };
128
+ const envXml = Object.entries(env).map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`).join('\n');
129
+ return `<?xml version="1.0" encoding="UTF-8"?>
130
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
131
+ <plist version="1.0">
132
+ <dict>
133
+ <key>Label</key>
134
+ <string>${LAUNCH_LABEL}</string>
135
+ <key>ProgramArguments</key>
136
+ <array>
137
+ <string>${xml(spec.node)}</string>
138
+ <string>${xml(spec.entry)}</string>
139
+ <string>agent</string>
140
+ <string>daemon</string>
141
+ </array>
142
+ <key>EnvironmentVariables</key>
143
+ <dict>
144
+ ${envXml}
145
+ </dict>
146
+ <key>RunAtLoad</key>
147
+ <true/>
148
+ <key>KeepAlive</key>
149
+ <dict>
150
+ <key>SuccessfulExit</key>
151
+ <false/>
152
+ </dict>
153
+ <key>ThrottleInterval</key>
154
+ <integer>30</integer>
155
+ <key>ProcessType</key>
156
+ <string>Background</string>
157
+ <key>StandardOutPath</key>
158
+ <string>${xml(join(spec.logDir, 'daemon.out.log'))}</string>
159
+ <key>StandardErrorPath</key>
160
+ <string>${xml(join(spec.logDir, 'daemon.err.log'))}</string>
161
+ </dict>
162
+ </plist>
163
+ `;
164
+ }
165
+ export function systemdUnit(spec) {
166
+ const q = (s) => `"${s.replace(/(["\\])/g, '\\$1')}"`;
167
+ const envLines = Object.entries(spec.env ?? {}).map(([k, v]) => `Environment=${q(`${k}=${v}`)}`).join('\n');
168
+ return `[Unit]
169
+ Description=Odyssey agent bridge (odyssey agent daemon)
170
+ After=network-online.target
171
+
172
+ [Service]
173
+ Type=simple
174
+ ExecStart=${q(spec.node)} ${q(spec.entry)} agent daemon
175
+ Restart=on-failure
176
+ RestartSec=30
177
+ ${envLines ? envLines + '\n' : ''}StandardOutput=append:${join(spec.logDir, 'daemon.out.log')}
178
+ StandardError=append:${join(spec.logDir, 'daemon.err.log')}
179
+
180
+ [Install]
181
+ WantedBy=default.target
182
+ `;
183
+ }
184
+ /** schtasks /Create 인자(로그온 때 · 제한된 권한). 환경변수는 작업에 못 실으니 기본 기준 폴더만 따른다. */
185
+ export function windowsTaskArgs(spec) {
186
+ const tr = `"${spec.node}" "${spec.entry}" agent daemon`;
187
+ return ['/Create', '/F', '/SC', 'ONLOGON', '/RL', 'LIMITED', '/TN', WINDOWS_TASK, '/TR', tr];
188
+ }
189
+ export function launchAgentPath(home = homedir()) {
190
+ return join(home, 'Library', 'LaunchAgents', `${LAUNCH_LABEL}.plist`);
191
+ }
192
+ export function systemdUnitPath(home = homedir()) {
193
+ return join(process.env.XDG_CONFIG_HOME ?? join(home, '.config'), 'systemd', 'user', SYSTEMD_UNIT);
194
+ }
195
+ /** 자동 시작 등록. run=false 면 파일만 쓰고 launchctl · systemctl · schtasks 를 부르지 않는다(테스트 · ODYSSEY_AGENT_DRY_SYSTEM=1). */
196
+ export function installAutostart(spec, opts = {}) {
197
+ const platform = opts.platform ?? process.platform;
198
+ const run = opts.run ?? process.env.ODYSSEY_AGENT_DRY_SYSTEM !== '1';
199
+ mkdirSync(spec.logDir, { recursive: true, mode: 0o700 });
200
+ if (platform === 'darwin') {
201
+ const path = launchAgentPath();
202
+ mkdirSync(dirname(path), { recursive: true });
203
+ writeFileSync(path, launchAgentPlist(spec), { mode: 0o644 });
204
+ if (run) {
205
+ const uid = String(process.getuid?.() ?? '');
206
+ spawnSync('launchctl', ['bootout', `gui/${uid}/${LAUNCH_LABEL}`], { stdio: 'ignore' });
207
+ const r = spawnSync('launchctl', ['bootstrap', `gui/${uid}`, path], { encoding: 'utf-8' });
208
+ if (r.status !== 0)
209
+ return { platform, path, installed: true, note: `launchctl bootstrap 실패: ${r.stderr.trim()}` };
210
+ }
211
+ return { platform, path, installed: true };
212
+ }
213
+ if (platform === 'linux') {
214
+ const path = systemdUnitPath();
215
+ mkdirSync(dirname(path), { recursive: true });
216
+ writeFileSync(path, systemdUnit(spec), { mode: 0o644 });
217
+ if (run) {
218
+ spawnSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore' });
219
+ const r = spawnSync('systemctl', ['--user', 'enable', '--now', SYSTEMD_UNIT], { encoding: 'utf-8' });
220
+ if (r.status !== 0)
221
+ return { platform, path, installed: true, note: `systemctl enable 실패: ${r.stderr.trim()}` };
222
+ }
223
+ return { platform, path, installed: true };
224
+ }
225
+ if (platform === 'win32') {
226
+ if (run) {
227
+ const r = spawnSync('schtasks', windowsTaskArgs(spec), { encoding: 'utf-8' });
228
+ if (r.status !== 0)
229
+ return { platform, installed: false, note: `schtasks 실패: ${r.stderr.trim()}` };
230
+ }
231
+ return { platform, installed: true, path: `작업 스케줄러: ${WINDOWS_TASK}` };
232
+ }
233
+ return { platform, installed: false, note: '이 운영체제는 자동 시작을 지원하지 않는다' };
234
+ }
235
+ export function uninstallAutostart(opts = {}) {
236
+ const platform = opts.platform ?? process.platform;
237
+ const run = opts.run ?? process.env.ODYSSEY_AGENT_DRY_SYSTEM !== '1';
238
+ if (platform === 'darwin') {
239
+ const path = launchAgentPath();
240
+ if (run)
241
+ spawnSync('launchctl', ['bootout', `gui/${process.getuid?.() ?? ''}/${LAUNCH_LABEL}`], { stdio: 'ignore' });
242
+ if (existsSync(path))
243
+ unlinkSync(path);
244
+ return { platform, path, installed: false };
245
+ }
246
+ if (platform === 'linux') {
247
+ const path = systemdUnitPath();
248
+ if (run)
249
+ spawnSync('systemctl', ['--user', 'disable', '--now', SYSTEMD_UNIT], { stdio: 'ignore' });
250
+ if (existsSync(path))
251
+ unlinkSync(path);
252
+ return { platform, path, installed: false };
253
+ }
254
+ if (platform === 'win32') {
255
+ if (run)
256
+ spawnSync('schtasks', ['/Delete', '/F', '/TN', WINDOWS_TASK], { stdio: 'ignore' });
257
+ return { platform, installed: false };
258
+ }
259
+ return { platform, installed: false };
260
+ }
261
+ export function autostartInstalled(platform = process.platform) {
262
+ if (platform === 'darwin')
263
+ return existsSync(launchAgentPath());
264
+ if (platform === 'linux')
265
+ return existsSync(systemdUnitPath());
266
+ if (platform === 'win32')
267
+ return spawnSync('schtasks', ['/Query', '/TN', WINDOWS_TASK], { stdio: 'ignore' }).status === 0;
268
+ return false;
269
+ }