@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.
- package/AGENTS.md +11 -1
- package/README.md +42 -9
- package/dist/agent/adapters.js +394 -0
- package/dist/agent/api.js +232 -0
- package/dist/agent/command.js +580 -0
- package/dist/agent/daemon.js +584 -0
- package/dist/agent/hook.js +353 -0
- package/dist/agent/install.js +194 -0
- package/dist/agent/outbox.js +122 -0
- package/dist/agent/policy.js +87 -0
- package/dist/agent/store.js +243 -0
- package/dist/agent/system.js +269 -0
- package/dist/agent/text.js +90 -0
- package/dist/agent/transcript.js +107 -0
- package/dist/agent/workspaces.js +118 -0
- package/dist/files.js +4 -3
- package/dist/firebase-connect.js +32 -0
- package/dist/guide.js +4 -4
- package/dist/index.js +37 -3
- package/dist/tools.js +23 -8
- package/dist/watch.js +65 -27
- package/examples/watch-agent/README.md +7 -1
- package/examples/watch-agent/config.example.json +1 -0
- package/examples/watch-agent/listen.mjs +24 -3
- package/examples/watch-agent/test/listen.test.mjs +15 -0
- package/examples/watch-dispatcher/SPEC.md +6 -5
- package/examples/watch-dispatcher/dispatcher.mjs +13 -7
- package/examples/watch-dispatcher/test/dispatcher.test.mjs +6 -4
- package/package.json +4 -1
- package/prompts/agent-design.md +2 -2
- package/prompts/watch-agent.md +2 -2
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `odyssey agent daemon` — 상주 브리지(설계 §6.2 · §10 · §11.2).
|
|
3
|
+
*
|
|
4
|
+
* - 하트비트: 시작 때 started:true, 1분마다 lastSeenAt, 브리지 문서 pingAt 이 바뀌면 pong, 끝날 때 stopped:true.
|
|
5
|
+
* - 듣기(watch 와 같은 CLI 읽기 신원): `agent_bridge/{id}`(pingAt · keepAwake) ·
|
|
6
|
+
* `companion_turn` where leaseOwner == 'bridge:<id>' && status == 'running'(새 턴 실행 · stopRequested 면 멈춤).
|
|
7
|
+
* - 턴: 세션 문서(external)의 workspaceId → 로컬 등록 폴더, externalSessionId → 재개. 어댑터 실행 → activity 덮어쓰기 →
|
|
8
|
+
* `<턴>-out` 메시지 → settle. 위험 도구는 막고 승인 카드로 done(§15 머리), 다음 턴의 approval 로 한 번 허락해 재개.
|
|
9
|
+
* - host desktop 턴은 실행하지 않는다 — 듣는 데스크톱 세션 몫(§6.3). 그 글을 장부에 적어 두면 훅이 그 세션의 답으로 닫는다.
|
|
10
|
+
* - outbox 재전송 · 내려받은 미디어 기한 정리 · 잠자기 방지 · 잠들었다 깨면 다시 started.
|
|
11
|
+
*/
|
|
12
|
+
import { AuthRequiredError } from '../config.js';
|
|
13
|
+
import { appendFileSync, mkdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import { call, downloadMedia } from './api.js';
|
|
16
|
+
import { adapterFor } from './adapters.js';
|
|
17
|
+
import { flushOutbox, CLI_VERSION, makeClient, sendEntry } from './outbox.js';
|
|
18
|
+
import { emptyGrant, heaviestAction } from './policy.js';
|
|
19
|
+
import { cleanText, findMediaPaths } from './text.js';
|
|
20
|
+
import { hashText, normText } from './hook.js';
|
|
21
|
+
import { KeepAwake, onAcPower, wantAwake } from './system.js';
|
|
22
|
+
import { loadWorkspaces, publicWorkspaces, workspaceById } from './workspaces.js';
|
|
23
|
+
import { AgentBridgeTiming, AgentHost, STALE_TURN_MS, bridgeOwner, enqueue, loadBridges, loadLedger, paths, pruneMedia, saveBridges, updateLedger, writeJson, KEEP_AWAKE_MODES, } from './store.js';
|
|
24
|
+
/** 턴 판정 까닭(앱이 다국어로 그린다 — 모르는 값은 failed 로). 기존 CompanionTurnError 에 없는 값은 새 코드다. */
|
|
25
|
+
export const BridgeTurnError = {
|
|
26
|
+
failed: 'failed',
|
|
27
|
+
/** 만든 지 10분 넘은 요청(컴퓨터가 잠들었거나 꺼져 있었다). */
|
|
28
|
+
stale: 'stale',
|
|
29
|
+
/** 데몬이 끝나며 닫았다(컴퓨터 끔 · 로그아웃 · 손으로 멈춤). */
|
|
30
|
+
offline: 'offline',
|
|
31
|
+
/** 세션의 작업 폴더가 이 컴퓨터에 등록돼 있지 않다(등록이 풀렸다). */
|
|
32
|
+
noWorkspace: 'noWorkspace',
|
|
33
|
+
/** 데스크톱 세션인데 듣는 데스크톱 세션이 없다. */
|
|
34
|
+
noDesktopListener: 'noDesktopListener',
|
|
35
|
+
/** 에이전트가 깔려 있지 않다 · SDK 가 없다. */
|
|
36
|
+
agentMissing: 'agentMissing',
|
|
37
|
+
/** 에이전트 로그인이 풀렸다(claude /login · codex login 필요). */
|
|
38
|
+
agentAuth: 'agentAuth',
|
|
39
|
+
};
|
|
40
|
+
export function fileLogger() {
|
|
41
|
+
const dir = paths.logs();
|
|
42
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
43
|
+
const file = join(dir, 'daemon.log');
|
|
44
|
+
const write = (level, msg) => {
|
|
45
|
+
const line = `${new Date().toISOString()} ${level} ${msg}\n`;
|
|
46
|
+
try {
|
|
47
|
+
if (statSync(file).size > 5 * 1024 * 1024)
|
|
48
|
+
renameSync(file, `${file}.1`);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// 아직 없다
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
appendFileSync(file, line);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
// 로그 실패는 무시
|
|
58
|
+
}
|
|
59
|
+
if (process.stderr.isTTY || process.env.ODYSSEY_AGENT_LOG_STDERR === '1')
|
|
60
|
+
process.stderr.write(line);
|
|
61
|
+
};
|
|
62
|
+
return { info: (m) => write('INFO', m), error: (m) => write('ERROR', m) };
|
|
63
|
+
}
|
|
64
|
+
export function toMillis(v) {
|
|
65
|
+
if (!v)
|
|
66
|
+
return undefined;
|
|
67
|
+
if (typeof v === 'string') {
|
|
68
|
+
const t = Date.parse(v);
|
|
69
|
+
return Number.isFinite(t) ? t : undefined;
|
|
70
|
+
}
|
|
71
|
+
if (typeof v === 'object') {
|
|
72
|
+
const o = v;
|
|
73
|
+
if (typeof o.toMillis === 'function')
|
|
74
|
+
return o.toMillis();
|
|
75
|
+
if (typeof o.seconds === 'number')
|
|
76
|
+
return o.seconds * 1000;
|
|
77
|
+
}
|
|
78
|
+
if (v instanceof Date)
|
|
79
|
+
return v.getTime();
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
export function turnFromDoc(id, d) {
|
|
83
|
+
const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string') : []);
|
|
84
|
+
return {
|
|
85
|
+
uid: d.uid || id,
|
|
86
|
+
sessionUid: String(d.sessionUid ?? ''),
|
|
87
|
+
...(typeof d.text === 'string' ? { text: d.text } : {}),
|
|
88
|
+
...(typeof d.displayText === 'string' ? { displayText: d.displayText } : {}),
|
|
89
|
+
...(typeof d.status === 'string' ? { status: d.status } : {}),
|
|
90
|
+
...(typeof d.leaseOwner === 'string' ? { leaseOwner: d.leaseOwner } : {}),
|
|
91
|
+
stopRequested: d.stopRequested === true,
|
|
92
|
+
imageStoragePaths: strings(d.imageStoragePaths),
|
|
93
|
+
mediaIds: strings(d.mediaIds),
|
|
94
|
+
approval: d.approval && typeof d.approval === 'object' ? d.approval : null,
|
|
95
|
+
...(toMillis(d.createdAt) ? { createdAtMs: toMillis(d.createdAt) } : {}),
|
|
96
|
+
...(typeof d.workspaceId === 'string' ? { workspaceId: d.workspaceId } : {}),
|
|
97
|
+
...(d.external && typeof d.external === 'object' ? { external: d.external } : {}),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/** 쓰기 묶음을 바로 보내고, 실패하면 남은 것을 outbox 에(잃지 않게). */
|
|
101
|
+
async function sendNow(client, jobs, profile, log) {
|
|
102
|
+
const entry = { id: 'direct', createdAt: new Date().toISOString(), attempts: 0, jobs, done: 0 };
|
|
103
|
+
try {
|
|
104
|
+
await sendEntry(client, entry);
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
log.error(`보내기 실패 — outbox 에 남김: ${e.message}`);
|
|
108
|
+
enqueue(jobs.slice(entry.done), profile);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function settleJob(bridgeId, turnUid, args) {
|
|
112
|
+
return { kind: 'call', tool: 'agent_turn_update', args: { bridgeId, turnUid, ...args } };
|
|
113
|
+
}
|
|
114
|
+
/** 턴 하나를 판정까지 끌고 간다. 돌려주는 값 = 판정. */
|
|
115
|
+
export async function runTurn(turn, deps, running) {
|
|
116
|
+
const { client, bridge, log } = deps;
|
|
117
|
+
const now = deps.now?.() ?? Date.now();
|
|
118
|
+
const profile = bridge.odysseyProfile;
|
|
119
|
+
const fail = async (error, detail) => {
|
|
120
|
+
log.error(`턴 ${turn.uid} 실패(${error})${detail ? `: ${detail}` : ''}`);
|
|
121
|
+
await sendNow(client, [settleJob(bridge.bridgeId, turn.uid, { settle: 'failed', error, sessionState: 'idle' })], profile, log);
|
|
122
|
+
return 'failed';
|
|
123
|
+
};
|
|
124
|
+
if (turn.createdAtMs && now - turn.createdAtMs > STALE_TURN_MS)
|
|
125
|
+
return fail(BridgeTurnError.stale);
|
|
126
|
+
const ext = (await deps.readSession(turn.sessionUid).catch(() => null)) ?? turn.external ?? null;
|
|
127
|
+
const ledger = loadLedger();
|
|
128
|
+
const known = ledger.sessions[turn.sessionUid];
|
|
129
|
+
if (ext?.host === AgentHost.desktop || known?.host === AgentHost.desktop) {
|
|
130
|
+
// 데스크톱 갈래 — 듣는 세션이 send_message/start_session 으로 넘긴다. 훅이 그 글을 알아보고 답으로 닫게 적어 둔다.
|
|
131
|
+
if (!deps.desktopRelay)
|
|
132
|
+
return fail(BridgeTurnError.noDesktopListener);
|
|
133
|
+
updateLedger((l) => {
|
|
134
|
+
l.relayTexts = l.relayTexts ?? [];
|
|
135
|
+
l.relayTexts.push({ hash: hashText(turn.text ?? ''), len: normText(turn.text ?? '').length, turnUid: turn.uid, sessionUid: turn.sessionUid, at: new Date(now).toISOString() });
|
|
136
|
+
if (!l.turns.includes(turn.uid))
|
|
137
|
+
l.turns.push(turn.uid);
|
|
138
|
+
});
|
|
139
|
+
log.info(`턴 ${turn.uid}: 데스크톱 세션 — 듣는 세션에 맡김`);
|
|
140
|
+
return 'relayed';
|
|
141
|
+
}
|
|
142
|
+
// CLI 신원은 세션 문서를 못 읽는다(규칙) — 장부 · 턴 칸 · (등록 폴더가 하나뿐이면) 그 폴더 순으로 찾는다.
|
|
143
|
+
const registered = loadWorkspaces();
|
|
144
|
+
const workspaceId = ext?.workspaceId ?? known?.workspaceId ?? turn.workspaceId ?? (registered.length === 1 ? registered[0].id : undefined);
|
|
145
|
+
const ws = workspaceById(workspaceId);
|
|
146
|
+
if (!ws)
|
|
147
|
+
return fail(BridgeTurnError.noWorkspace, `workspaceId=${workspaceId ?? '(없음)'}`);
|
|
148
|
+
const adapter = deps.adapter ?? adapterFor(bridge.agent);
|
|
149
|
+
const origin = (ext?.origin ?? known?.origin ?? 'app') === 'local' ? 'local' : 'app';
|
|
150
|
+
let resumeId = ext?.externalSessionId ?? known?.externalSessionId;
|
|
151
|
+
// 승인 답 — 막았던 도구를 이 실행 동안 허락(위험 명령은 그 명령만).
|
|
152
|
+
const grant = emptyGrant();
|
|
153
|
+
let prompt = (turn.text ?? '').trim();
|
|
154
|
+
if (turn.approval?.turnUid) {
|
|
155
|
+
const pending = ledger.approvals[turn.approval.turnUid];
|
|
156
|
+
if (turn.approval.approved && pending) {
|
|
157
|
+
for (const t of pending.tools)
|
|
158
|
+
(t.includes(':') ? grant.keys : grant.tools).add(t);
|
|
159
|
+
if (!prompt)
|
|
160
|
+
prompt = '사용자가 앱에서 승인했습니다. 막혔던 작업을 이어서 하세요.';
|
|
161
|
+
}
|
|
162
|
+
else if (!turn.approval.approved && !prompt) {
|
|
163
|
+
prompt = '사용자가 앱에서 그 작업을 거절했습니다. 그 작업은 하지 말고, 대신 할 수 있는 것을 알려 주세요.';
|
|
164
|
+
}
|
|
165
|
+
updateLedger((l) => void delete l.approvals[turn.approval.turnUid]);
|
|
166
|
+
}
|
|
167
|
+
if (!prompt)
|
|
168
|
+
prompt = '(빈 메시지)';
|
|
169
|
+
// 앱이 보낸 미디어 → media/<세션>/ 에 받아 경로로 넘긴다.
|
|
170
|
+
const mediaPaths = [];
|
|
171
|
+
const refs = [
|
|
172
|
+
...(turn.imageStoragePaths ?? []).filter((p) => p.startsWith('agent_media/')).map((storagePath) => ({ storagePath })),
|
|
173
|
+
...(turn.mediaIds ?? []).map((mediaId) => ({ mediaId })),
|
|
174
|
+
];
|
|
175
|
+
for (const ref of refs) {
|
|
176
|
+
try {
|
|
177
|
+
mediaPaths.push(await downloadMedia(client, bridge.bridgeId, turn.sessionUid, ref, deps.server));
|
|
178
|
+
}
|
|
179
|
+
catch (e) {
|
|
180
|
+
log.error(`턴 ${turn.uid} 미디어 받기 실패: ${e.message}`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
updateLedger((l) => {
|
|
184
|
+
if (!l.turns.includes(turn.uid))
|
|
185
|
+
l.turns.push(turn.uid);
|
|
186
|
+
l.sessions[turn.sessionUid] = {
|
|
187
|
+
agent: bridge.agent, bridgeId: bridge.bridgeId, workspaceId: ws.id, origin, host: 'cli', updatedAt: new Date().toISOString(),
|
|
188
|
+
...(resumeId ? { externalSessionId: resumeId } : {}),
|
|
189
|
+
};
|
|
190
|
+
if (resumeId) {
|
|
191
|
+
l.active[resumeId] = turn.uid;
|
|
192
|
+
l.byExternal[resumeId] = turn.sessionUid;
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
// 세션 문서가 없으면 turn_update 가 거절된다 — 먼저 연다(있으면 상태만 고친다 · 멱등).
|
|
196
|
+
await call(client, 'agent_session_upsert', {
|
|
197
|
+
bridgeId: bridge.bridgeId, agent: bridge.agent, host: AgentHost.cli, sessionUid: turn.sessionUid, workspaceId: ws.id, origin, state: 'running',
|
|
198
|
+
...(resumeId ? { externalSessionId: resumeId } : {}),
|
|
199
|
+
}).catch((e) => log.error(`세션 열기: ${e.message}`));
|
|
200
|
+
await call(client, 'agent_turn_update', { bridgeId: bridge.bridgeId, turnUid: turn.uid, sessionState: 'running', activity: { step: 'think' } }).catch((e) => log.error(`activity: ${e.message}`));
|
|
201
|
+
let lastActivity = '';
|
|
202
|
+
let lastActivityAt = 0;
|
|
203
|
+
let result;
|
|
204
|
+
try {
|
|
205
|
+
result = await adapter.run({
|
|
206
|
+
turnUid: turn.uid,
|
|
207
|
+
prompt,
|
|
208
|
+
cwd: ws.path,
|
|
209
|
+
...(resumeId ? { resumeId } : {}),
|
|
210
|
+
mediaPaths,
|
|
211
|
+
policy: bridge.approval,
|
|
212
|
+
grant,
|
|
213
|
+
extraDirs: mediaPaths.length ? [paths.media(turn.sessionUid)] : [],
|
|
214
|
+
env: { ODYSSEY_AGENT_TURN: turn.uid },
|
|
215
|
+
mcp: deps.mcp ?? null,
|
|
216
|
+
signal: running.abort.signal,
|
|
217
|
+
onSessionId: (id) => {
|
|
218
|
+
resumeId = id;
|
|
219
|
+
updateLedger((l) => {
|
|
220
|
+
l.active[id] = turn.uid;
|
|
221
|
+
l.byExternal[id] = turn.sessionUid;
|
|
222
|
+
const s = l.sessions[turn.sessionUid];
|
|
223
|
+
if (s)
|
|
224
|
+
s.externalSessionId = id;
|
|
225
|
+
});
|
|
226
|
+
void sendNow(client, [
|
|
227
|
+
{ kind: 'call', tool: 'agent_session_upsert', args: { bridgeId: bridge.bridgeId, agent: bridge.agent, host: AgentHost.cli, externalSessionId: id, sessionUid: turn.sessionUid, workspaceId: ws.id, origin, state: 'running' } },
|
|
228
|
+
settleJob(bridge.bridgeId, turn.uid, { externalSessionId: id }),
|
|
229
|
+
], profile, log);
|
|
230
|
+
},
|
|
231
|
+
onActivity: (a) => {
|
|
232
|
+
const key = `${a.step}:${a.subject ?? ''}`;
|
|
233
|
+
const t = Date.now();
|
|
234
|
+
if (key === lastActivity || t - lastActivityAt < 2000)
|
|
235
|
+
return; // 덮어쓰기 한 줄 — 쓰기를 아낀다
|
|
236
|
+
lastActivity = key;
|
|
237
|
+
lastActivityAt = t;
|
|
238
|
+
void call(client, 'agent_turn_update', { bridgeId: bridge.bridgeId, turnUid: turn.uid, activity: { step: a.step, ...(a.subject ? { subject: a.subject.slice(0, 40) } : {}) } })
|
|
239
|
+
.then((r) => {
|
|
240
|
+
// 리스너가 놓쳐도 — 진행 줄 응답의 stopRequested 로 멈춘다.
|
|
241
|
+
if (r?.stopRequested && !running.abort.signal.aborted)
|
|
242
|
+
running.abort.abort();
|
|
243
|
+
})
|
|
244
|
+
.catch(() => { });
|
|
245
|
+
},
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
catch (e) {
|
|
249
|
+
result = { status: 'failed', text: '', toolSummary: { calls: 0, filesChanged: 0, commands: 0 }, blocked: [], error: e.message };
|
|
250
|
+
}
|
|
251
|
+
finally {
|
|
252
|
+
updateLedger((l) => {
|
|
253
|
+
for (const [k, v] of Object.entries(l.active))
|
|
254
|
+
if (v === turn.uid)
|
|
255
|
+
delete l.active[k];
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
return finishTurn(turn, result, { ...deps, ws: { id: ws.id, path: ws.path }, origin, running });
|
|
259
|
+
}
|
|
260
|
+
async function finishTurn(turn, r, ctx) {
|
|
261
|
+
const { client, bridge, log } = ctx;
|
|
262
|
+
const profile = bridge.odysseyProfile;
|
|
263
|
+
const messageUid = `${turn.uid}-out`;
|
|
264
|
+
const ext = r.externalSessionId ? { externalSessionId: r.externalSessionId } : {};
|
|
265
|
+
const media = r.text ? findMediaPaths(r.text, ctx.ws.path, ctx.ws.path) : [];
|
|
266
|
+
const reply = (text, extra = {}, mediaPaths = media) => ({
|
|
267
|
+
kind: 'reply',
|
|
268
|
+
bridgeId: bridge.bridgeId,
|
|
269
|
+
sessionUid: turn.sessionUid,
|
|
270
|
+
mediaPaths,
|
|
271
|
+
message: {
|
|
272
|
+
bridgeId: bridge.bridgeId, sessionUid: turn.sessionUid, messageUid, role: 'assistant', text: cleanText(text), turnUid: turn.uid,
|
|
273
|
+
...(r.toolSummary.calls > 0 ? { toolSummary: r.toolSummary } : {}), ...extra,
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
if (r.blocked.length && r.status !== 'stopped') {
|
|
277
|
+
const lines = r.blocked.map((b) => b.line);
|
|
278
|
+
const tools = [...new Set(r.blocked.map((b) => b.key))];
|
|
279
|
+
updateLedger((l) => {
|
|
280
|
+
l.approvals[turn.uid] = { sessionUid: turn.sessionUid, tools, lines, at: new Date().toISOString() };
|
|
281
|
+
});
|
|
282
|
+
// 물음 글(「이 작업을 해도 될까요? - …」)은 서버가 askApproval.lines 로 만든다 — 여기서 text 에 또 넣으면 말풍선이 두 번 선다(261122 E2E).
|
|
283
|
+
// text 엔 에이전트가 그때까지 한 말만. 출력 수 = (에이전트 말) + 물음 글 + 승인 카드.
|
|
284
|
+
const said = r.text.trim();
|
|
285
|
+
await sendNow(client, [
|
|
286
|
+
reply(said, { askApproval: { actionType: heaviestAction(r.blocked.map((b) => b.actionType)), lines }, ...blockedFreeSummary(r) }, []),
|
|
287
|
+
settleJob(bridge.bridgeId, turn.uid, { settle: 'done', approvalTools: tools, sessionState: 'awaitingApproval', outputCount: (said ? 1 : 0) + 2, ...ext }),
|
|
288
|
+
], profile, log);
|
|
289
|
+
log.info(`턴 ${turn.uid}: 승인 물음으로 끝남(${tools.join(', ')})`);
|
|
290
|
+
return 'done';
|
|
291
|
+
}
|
|
292
|
+
if (r.status === 'stopped') {
|
|
293
|
+
const error = ctx.running.shutdown ? BridgeTurnError.offline : undefined;
|
|
294
|
+
const jobs = [];
|
|
295
|
+
if (r.text.trim())
|
|
296
|
+
jobs.push(reply(r.text, {}, []));
|
|
297
|
+
jobs.push(settleJob(bridge.bridgeId, turn.uid, ctx.running.shutdown ? { settle: 'failed', error, sessionState: 'idle', ...ext } : { settle: 'stopped', sessionState: 'idle', outputCount: r.text.trim() ? 1 : 0, ...ext }));
|
|
298
|
+
await sendNow(client, jobs, profile, log);
|
|
299
|
+
return ctx.running.shutdown ? 'failed' : 'stopped';
|
|
300
|
+
}
|
|
301
|
+
if (r.status === 'failed') {
|
|
302
|
+
log.error(`턴 ${turn.uid} 에이전트 실패: ${r.error ?? ''}`);
|
|
303
|
+
const missing = /claude-agent-sdk|ENOENT|not found/i.test(r.error ?? '');
|
|
304
|
+
const auth = /authenticat|log ?in|OAuth|401/i.test(r.error ?? '');
|
|
305
|
+
const jobs = [];
|
|
306
|
+
// 로그인 오류 글은 답 말풍선으로 올리지 않는다(판정 코드로 앱이 그린다).
|
|
307
|
+
if (r.text.trim() && !auth)
|
|
308
|
+
jobs.push(reply(r.text, {}, []));
|
|
309
|
+
jobs.push(settleJob(bridge.bridgeId, turn.uid, { settle: 'failed', error: missing ? BridgeTurnError.agentMissing : auth ? BridgeTurnError.agentAuth : BridgeTurnError.failed, sessionState: 'idle', ...ext }));
|
|
310
|
+
await sendNow(client, jobs, profile, log);
|
|
311
|
+
return 'failed';
|
|
312
|
+
}
|
|
313
|
+
const text = r.text.trim() || '(답 없이 끝났어요)';
|
|
314
|
+
await sendNow(client, [
|
|
315
|
+
reply(text),
|
|
316
|
+
settleJob(bridge.bridgeId, turn.uid, { settle: 'done', sessionState: 'idle', outputCount: 1 + media.length, ...ext }),
|
|
317
|
+
], profile, log);
|
|
318
|
+
log.info(`턴 ${turn.uid}: done(도구 ${r.toolSummary.calls} · 미디어 ${media.length})`);
|
|
319
|
+
return 'done';
|
|
320
|
+
}
|
|
321
|
+
export async function runDaemon(opts = {}) {
|
|
322
|
+
const log = opts.log ?? fileLogger();
|
|
323
|
+
const file = loadBridges();
|
|
324
|
+
const all = Object.entries(file.bridges)
|
|
325
|
+
.filter(([k, b]) => b && (!opts.only || k === opts.only))
|
|
326
|
+
.map(([, b]) => b);
|
|
327
|
+
// 등록 전(하트비트가 거절된다) · 연결이 끊긴 브리지는 돌리지 않는다 — setup 을 다시 하면 풀린다.
|
|
328
|
+
for (const b of all) {
|
|
329
|
+
if (!b.registeredAt)
|
|
330
|
+
log.error(`브리지 ${b.bridgeId}: 서버 등록 전 — odyssey agent setup 을 다시`);
|
|
331
|
+
if (b.disconnectedAt)
|
|
332
|
+
log.error(`브리지 ${b.bridgeId}: 앱에서 연결이 끊김(${b.disconnectedAt}) — odyssey agent setup 을 다시`);
|
|
333
|
+
}
|
|
334
|
+
const bridges = all.filter((b) => b.registeredAt && !b.disconnectedAt);
|
|
335
|
+
if (!bridges.length) {
|
|
336
|
+
log.error('돌릴 브리지가 없다(등록 전 · 끊김) — 먼저 odyssey agent setup');
|
|
337
|
+
process.stderr.write('돌릴 브리지가 없습니다(서버 등록 전이거나 앱에서 연결이 끊김). 먼저: odyssey agent setup\n');
|
|
338
|
+
return all.length ? 0 : 2;
|
|
339
|
+
}
|
|
340
|
+
// 하나만 돈다 — pid 파일을 배타 생성으로 잡는다.
|
|
341
|
+
mkdirSync(paths.logs(), { recursive: true, mode: 0o700 });
|
|
342
|
+
try {
|
|
343
|
+
writeFileSync(paths.pid(), String(process.pid), { flag: 'wx', mode: 0o600 });
|
|
344
|
+
}
|
|
345
|
+
catch {
|
|
346
|
+
const { daemonPid } = await import('./store.js');
|
|
347
|
+
const other = daemonPid();
|
|
348
|
+
if (other && other !== process.pid) {
|
|
349
|
+
process.stderr.write(`데몬이 이미 돌고 있습니다(pid ${other}).\n`);
|
|
350
|
+
return 4;
|
|
351
|
+
}
|
|
352
|
+
writeFileSync(paths.pid(), String(process.pid), { mode: 0o600 });
|
|
353
|
+
}
|
|
354
|
+
const releasePid = () => {
|
|
355
|
+
try {
|
|
356
|
+
unlinkSync(paths.pid());
|
|
357
|
+
}
|
|
358
|
+
catch {
|
|
359
|
+
// 이미 없다
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
const running = new Map();
|
|
363
|
+
/** 이 프로세스가 판정까지 다룬 턴 — 늦게 온 스냅샷이 다시 집지 않게. */
|
|
364
|
+
const finished = new Set();
|
|
365
|
+
const keepAwake = new KeepAwake();
|
|
366
|
+
const modeOf = () => {
|
|
367
|
+
const modes = loadBridges().bridges;
|
|
368
|
+
const order = ['off', 'whileWorking', 'onPower', 'always'];
|
|
369
|
+
return Object.values(modes).reduce((m, b) => (b && order.indexOf(b.keepAwake) > order.indexOf(m) ? b.keepAwake : m), 'off');
|
|
370
|
+
};
|
|
371
|
+
const applyAwake = () => keepAwake.set(wantAwake(modeOf(), { working: running.size > 0, onPower: onAcPower() }));
|
|
372
|
+
const clients = new Map();
|
|
373
|
+
const clientOf = (profile) => {
|
|
374
|
+
const k = profile ?? '';
|
|
375
|
+
if (!clients.has(k))
|
|
376
|
+
clients.set(k, makeClient(profile));
|
|
377
|
+
return clients.get(k);
|
|
378
|
+
};
|
|
379
|
+
let onDisconnected = () => { };
|
|
380
|
+
const beat = async (b, extra = {}) => {
|
|
381
|
+
try {
|
|
382
|
+
const r = await call(clientOf(b.odysseyProfile), 'agent_bridge_heartbeat', { bridgeId: b.bridgeId, ...extra });
|
|
383
|
+
if (r?.disconnected && !extra.stopped)
|
|
384
|
+
onDisconnected(b);
|
|
385
|
+
writeJson(paths.state(), { pid: process.pid, lastHeartbeatAt: new Date().toISOString(), keepAwakeActive: keepAwake.active, runningTurns: running.size });
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
log.error(`하트비트 실패(${b.bridgeId}): ${e.message}`);
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
const unsubs = [];
|
|
392
|
+
let stopping = false;
|
|
393
|
+
// 연결 — 프로필마다 Firestore 하나.
|
|
394
|
+
const { connectFirestore } = await import('../firebase-connect.js');
|
|
395
|
+
const conns = new Map();
|
|
396
|
+
for (const b of bridges) {
|
|
397
|
+
const k = b.odysseyProfile ?? '';
|
|
398
|
+
if (!conns.has(k)) {
|
|
399
|
+
try {
|
|
400
|
+
conns.set(k, await connectFirestore(clientOf(b.odysseyProfile), `odyssey-agent-${k || 'default'}`));
|
|
401
|
+
}
|
|
402
|
+
catch (e) {
|
|
403
|
+
log.error(`Firestore 연결 실패(${k || 'default'}): ${e.message}`);
|
|
404
|
+
process.stderr.write(`연결 실패: ${e.message}\n`);
|
|
405
|
+
releasePid();
|
|
406
|
+
// 로그인이 풀린 것은 다시 띄워도 소용없다 — 0 으로 끝내 자동 시작이 되풀이하지 않게(네트워크 실패는 3 → 다시 띄움).
|
|
407
|
+
return e instanceof AuthRequiredError ? 0 : 3;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
for (const b of bridges) {
|
|
412
|
+
await beat(b, { started: true, workspaces: publicWorkspaces(), desktopRelay: file.desktopRelay === true });
|
|
413
|
+
log.info(`브리지 시작 ${b.bridgeId}(${b.agent}) cli ${CLI_VERSION}`);
|
|
414
|
+
const conn = conns.get(b.odysseyProfile ?? '');
|
|
415
|
+
const { fs, db, uid } = conn;
|
|
416
|
+
const client = clientOf(b.odysseyProfile);
|
|
417
|
+
const server = client.target.server;
|
|
418
|
+
// 브리지 문서 — 핑 · keepAwake.
|
|
419
|
+
let lastPing = 0;
|
|
420
|
+
unsubs.push(fs.onSnapshot(fs.doc(db, 'user', uid, 'agent_bridge', b.bridgeId), (snap) => {
|
|
421
|
+
const d = snap.data();
|
|
422
|
+
if (!d)
|
|
423
|
+
return;
|
|
424
|
+
const ping = toMillis(d.pingAt) ?? 0;
|
|
425
|
+
if (ping > lastPing) {
|
|
426
|
+
const first = lastPing === 0;
|
|
427
|
+
lastPing = ping;
|
|
428
|
+
// 처음 붙을 때의 옛 핑엔 답하지 않는다(하트비트가 이미 lastSeenAt 을 쓴다) — 1분 안의 것만.
|
|
429
|
+
if (!first || Date.now() - ping < 60_000)
|
|
430
|
+
void beat(b, { pong: true });
|
|
431
|
+
}
|
|
432
|
+
const ka = d.keepAwake;
|
|
433
|
+
if (typeof ka === 'string' && KEEP_AWAKE_MODES.includes(ka) && ka !== b.keepAwake) {
|
|
434
|
+
b.keepAwake = ka;
|
|
435
|
+
const f = loadBridges();
|
|
436
|
+
for (const x of Object.values(f.bridges))
|
|
437
|
+
if (x?.bridgeId === b.bridgeId)
|
|
438
|
+
x.keepAwake = b.keepAwake;
|
|
439
|
+
saveBridges(f);
|
|
440
|
+
log.info(`잠자기 방지 ${b.keepAwake}(앱에서 바꿈)`);
|
|
441
|
+
applyAwake();
|
|
442
|
+
}
|
|
443
|
+
}, (e) => log.error(`브리지 문서 듣기 오류: ${e.message}`)));
|
|
444
|
+
// 턴 — 주인이 이 브리지 · running.
|
|
445
|
+
const readSession = async (sessionUid) => {
|
|
446
|
+
try {
|
|
447
|
+
const snap = await fs.getDoc(fs.doc(db, 'user', uid, 'companion_session', sessionUid));
|
|
448
|
+
const ext = snap.data()?.external;
|
|
449
|
+
return ext && typeof ext === 'object' ? ext : null;
|
|
450
|
+
}
|
|
451
|
+
catch (e) {
|
|
452
|
+
log.error(`세션 문서 읽기 실패(${sessionUid}) — 장부로: ${e.message}`);
|
|
453
|
+
return null;
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
const mcp = b.attachOdysseyMcp ? mcpFor(client) : null;
|
|
457
|
+
const q = fs.query(fs.collection(db, 'user', uid, 'companion_turn'), fs.where('leaseOwner', '==', bridgeOwner(b.bridgeId)), fs.where('status', '==', 'running'));
|
|
458
|
+
unsubs.push(fs.onSnapshot(q, (snap) => {
|
|
459
|
+
for (const ch of snap.docChanges()) {
|
|
460
|
+
if (ch.type === 'removed')
|
|
461
|
+
continue;
|
|
462
|
+
const turn = turnFromDoc(ch.doc.id, ch.doc.data());
|
|
463
|
+
const cur = running.get(turn.uid);
|
|
464
|
+
if (cur) {
|
|
465
|
+
if (turn.stopRequested && !cur.abort.signal.aborted) {
|
|
466
|
+
log.info(`턴 ${turn.uid}: 멈춤 요청`);
|
|
467
|
+
cur.abort.abort();
|
|
468
|
+
}
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
if (stopping || finished.has(turn.uid))
|
|
472
|
+
continue;
|
|
473
|
+
const l = loadLedger();
|
|
474
|
+
if (l.turns.includes(turn.uid)) {
|
|
475
|
+
const relayed = (l.relayTexts ?? []).some((r) => r.turnUid === turn.uid) || Object.values(l.relay ?? {}).some((r) => r.turnUid === turn.uid);
|
|
476
|
+
const stale = !!turn.createdAtMs && Date.now() - turn.createdAtMs > STALE_TURN_MS;
|
|
477
|
+
// 앞선 데몬이 돌리다 죽은 턴 — 다시 돌리지 않고 닫는다. 데스크톱에 맡긴 턴은 듣는 세션 몫(오래되면 닫는다).
|
|
478
|
+
if (!relayed || stale) {
|
|
479
|
+
finished.add(turn.uid);
|
|
480
|
+
void sendNow(client, [settleJob(b.bridgeId, turn.uid, { settle: 'failed', error: relayed ? BridgeTurnError.stale : BridgeTurnError.offline, sessionState: 'idle' })], b.odysseyProfile, log);
|
|
481
|
+
}
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
if (turn.stopRequested) {
|
|
485
|
+
finished.add(turn.uid);
|
|
486
|
+
void sendNow(client, [settleJob(b.bridgeId, turn.uid, { settle: 'stopped', sessionState: 'idle', outputCount: 0 })], b.odysseyProfile, log);
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
const rt = { turnUid: turn.uid, sessionUid: turn.sessionUid, abort: new AbortController(), shutdown: false, done: Promise.resolve() };
|
|
490
|
+
running.set(turn.uid, rt);
|
|
491
|
+
applyAwake();
|
|
492
|
+
log.info(`턴 ${turn.uid} 받음(세션 ${turn.sessionUid})`);
|
|
493
|
+
rt.done = runTurn(turn, { client, bridge: b, server, log, readSession, desktopRelay: loadBridges().desktopRelay === true, mcp }, rt)
|
|
494
|
+
.catch((e) => {
|
|
495
|
+
log.error(`턴 ${turn.uid} 처리 오류: ${e.message}`);
|
|
496
|
+
})
|
|
497
|
+
.then(() => {
|
|
498
|
+
finished.add(turn.uid);
|
|
499
|
+
running.delete(turn.uid);
|
|
500
|
+
applyAwake();
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
}, (e) => log.error(`턴 듣기 오류: ${e.message}`)));
|
|
504
|
+
}
|
|
505
|
+
applyAwake();
|
|
506
|
+
// 1분 하트비트 · 잠듦 감지(타이머가 크게 밀리면 잠들었다 깬 것) · 잠자기 방지 다시 보기.
|
|
507
|
+
let lastTick = Date.now();
|
|
508
|
+
const tick = setInterval(() => {
|
|
509
|
+
const t = Date.now();
|
|
510
|
+
const slept = t - lastTick > AgentBridgeTiming.heartbeatMs * 2.5;
|
|
511
|
+
lastTick = t;
|
|
512
|
+
for (const b of bridges)
|
|
513
|
+
void beat(b, slept ? { started: true, workspaces: publicWorkspaces() } : {});
|
|
514
|
+
if (slept)
|
|
515
|
+
log.info('잠들었다 깸 — started 다시');
|
|
516
|
+
applyAwake();
|
|
517
|
+
}, AgentBridgeTiming.heartbeatMs);
|
|
518
|
+
const outboxTimer = setInterval(() => {
|
|
519
|
+
void flushOutbox((p) => clientOf(p)).then((r) => {
|
|
520
|
+
if (r.sent || r.dropped)
|
|
521
|
+
log.info(`outbox 보냄 ${r.sent} · 버림 ${r.dropped} · 남음 ${r.failed}`);
|
|
522
|
+
}).catch((e) => log.error(`outbox: ${e.message}`));
|
|
523
|
+
}, 10_000);
|
|
524
|
+
const pruneTimer = setInterval(() => pruneMedia(), 3600_000);
|
|
525
|
+
pruneMedia();
|
|
526
|
+
void flushOutbox((p) => clientOf(p)).catch(() => { });
|
|
527
|
+
return new Promise((resolve) => {
|
|
528
|
+
const stop = async (sig) => {
|
|
529
|
+
if (stopping)
|
|
530
|
+
return;
|
|
531
|
+
stopping = true;
|
|
532
|
+
log.info(`끝냄(${sig}) — 진행 턴 ${running.size}`);
|
|
533
|
+
clearInterval(tick);
|
|
534
|
+
clearInterval(outboxTimer);
|
|
535
|
+
clearInterval(pruneTimer);
|
|
536
|
+
for (const rt of running.values()) {
|
|
537
|
+
rt.shutdown = true;
|
|
538
|
+
rt.abort.abort();
|
|
539
|
+
}
|
|
540
|
+
await Promise.race([Promise.all([...running.values()].map((r) => r.done)), new Promise((r) => setTimeout(r, 15_000))]);
|
|
541
|
+
for (const b of bridges)
|
|
542
|
+
await beat(b, { stopped: true });
|
|
543
|
+
for (const u of unsubs)
|
|
544
|
+
u();
|
|
545
|
+
keepAwake.set(false);
|
|
546
|
+
releasePid();
|
|
547
|
+
resolve(0);
|
|
548
|
+
setTimeout(() => process.exit(0), 100).unref();
|
|
549
|
+
};
|
|
550
|
+
// 사용자가 앱에서 이 브리지 컴패니언을 지웠다 = 연결 끊기(설계 §4.1) — 표시하고 데몬을 멈춘다(다시 쓰려면 setup).
|
|
551
|
+
onDisconnected = (b) => {
|
|
552
|
+
log.info(`브리지 ${b.bridgeId} 연결이 끊겼다(앱에서 지움) — 멈춘다`);
|
|
553
|
+
const f = loadBridges();
|
|
554
|
+
for (const x of Object.values(f.bridges))
|
|
555
|
+
if (x?.bridgeId === b.bridgeId)
|
|
556
|
+
x.disconnectedAt = new Date().toISOString();
|
|
557
|
+
saveBridges(f);
|
|
558
|
+
void stop('disconnected');
|
|
559
|
+
};
|
|
560
|
+
process.once('SIGINT', () => void stop('SIGINT'));
|
|
561
|
+
process.once('SIGTERM', () => void stop('SIGTERM'));
|
|
562
|
+
process.once('SIGHUP', () => void stop('SIGHUP'));
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
/** 데몬이 띄우는 클로드 세션에 붙일 Odyssey MCP — API 키 · 환경 토큰만(OAuth 액세스 토큰은 수명이 짧아 세션 중 끊긴다). */
|
|
566
|
+
function mcpFor(client) {
|
|
567
|
+
const t = client.target;
|
|
568
|
+
const bearer = t.envToken ?? (t.profile?.credential.type === 'apiKey' ? t.profile.credential.apiKey : null);
|
|
569
|
+
if (!bearer)
|
|
570
|
+
return null;
|
|
571
|
+
return { url: `${t.server}/all`, bearer };
|
|
572
|
+
}
|
|
573
|
+
/** 승인 물음으로 끝난 턴의 활동 요약 — 막은 도구는 실제로 돌지 않았으니 세지 않는다(「파일 1개 수정」으로 보이던 것, 261122 E2E). */
|
|
574
|
+
function blockedFreeSummary(r) {
|
|
575
|
+
const fileBlocked = r.blocked.filter((b) => ['Write', 'Edit', 'MultiEdit', 'NotebookEdit'].includes(b.tool)).length;
|
|
576
|
+
const cmdBlocked = r.blocked.filter((b) => b.tool === 'Bash' || b.tool === 'PowerShell').length;
|
|
577
|
+
const s = {
|
|
578
|
+
calls: Math.max(0, r.toolSummary.calls - r.blocked.length),
|
|
579
|
+
filesChanged: Math.max(0, r.toolSummary.filesChanged - fileBlocked),
|
|
580
|
+
commands: Math.max(0, r.toolSummary.commands - cmdBlocked),
|
|
581
|
+
};
|
|
582
|
+
// 남은 것이 없으면 요약 칸을 빼서 「도구 0번」 줄이 서지 않게 한다(reply 가 먼저 넣은 toolSummary 를 덮는다).
|
|
583
|
+
return { toolSummary: s.calls > 0 ? s : undefined };
|
|
584
|
+
}
|