@odyssey365/cli 0.1.0 → 0.2.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/README.md +128 -12
- package/dist/files.js +58 -0
- package/dist/guide.js +113 -0
- package/dist/index.js +92 -2
- package/dist/oauth.js +2 -9
- package/dist/rpc.js +20 -13
- package/dist/session.js +57 -1
- package/dist/watch-agent.js +45 -0
- package/dist/watch-events.js +78 -0
- package/dist/watch.js +181 -0
- package/examples/watch-agent/README.md +124 -0
- package/examples/watch-agent/config.example.json +20 -0
- package/examples/watch-agent/dispatcher.mjs +1443 -0
- package/examples/watch-agent/gitignore.template +6 -0
- package/examples/watch-agent/package.json +12 -0
- package/examples/watch-agent/test/dispatcher.test.mjs +763 -0
- package/examples/watch-agent/test/supervisor.test.mjs +126 -0
- package/package.json +10 -3
- package/prompts/watch-agent.md +250 -0
package/dist/session.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { AuthRequiredError, DEFAULT_PROFILE, DEFAULT_SERVER, UsageError, assertProfileName, loadCredentials, normalizeServer, updateCredentials, } from './config.js';
|
|
13
13
|
import { discover, fetchUserInfo, OAuthFlowError, refreshAccessToken } from './oauth.js';
|
|
14
|
-
import { HttpError, isProtocolVersionRejection, negotiateProtocolVersion, postRpc, } from './rpc.js';
|
|
14
|
+
import { HttpError, PREFERRED_PROTOCOL_VERSION, isProtocolVersionRejection, negotiateProtocolVersion, postRpc, fetchText, } from './rpc.js';
|
|
15
15
|
const REFRESH_LEEWAY_MS = 24 * 60 * 60 * 1000;
|
|
16
16
|
export function envServer() {
|
|
17
17
|
const v = process.env.ODYSSEY_MCP_URL;
|
|
@@ -157,6 +157,44 @@ export class OdysseyClient {
|
|
|
157
157
|
}
|
|
158
158
|
return e;
|
|
159
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Firebase 세션 교환(`POST /cli/firebase-session`) — `odyssey watch` 가 Firestore 를 직접 감시할 때 쓴다.
|
|
162
|
+
* CLI 로그인(OAuth) → Firebase 커스텀 토큰 + App Check 토큰 + 웹 앱 설정. 401 이면 한 번 갱신해 다시 묻는다.
|
|
163
|
+
* API 키 프로필은 서버가 403 으로 거절한다(앱 수준 세션으로 바꿔 주지 않는다).
|
|
164
|
+
* 이력: document/90-process/work-log/261016 Odyssey CLI 스트림 odyssey watch 토큰 교환 Firestore 직접 감시.md
|
|
165
|
+
*/
|
|
166
|
+
async firebaseSession() {
|
|
167
|
+
const send = async (bearer) => {
|
|
168
|
+
const { response: res, body: text } = await fetchText(`${this.target.server}/cli/firebase-session`, {
|
|
169
|
+
method: 'POST',
|
|
170
|
+
headers: { Authorization: `Bearer ${bearer}`, 'User-Agent': this.userAgent },
|
|
171
|
+
}, this.target.server);
|
|
172
|
+
let body = {};
|
|
173
|
+
try {
|
|
174
|
+
body = JSON.parse(text);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
// HTTP 오류가 비 JSON 본문을 돌려줘도 아래에서 상태 코드로 안내한다.
|
|
178
|
+
}
|
|
179
|
+
return { status: res.status, body };
|
|
180
|
+
};
|
|
181
|
+
let r = await send(await this.bearer());
|
|
182
|
+
if (r.status === 401 && this.canRefresh())
|
|
183
|
+
r = await send(await this.refresh());
|
|
184
|
+
if (r.status === 200) {
|
|
185
|
+
// 구버전 서버의 실제 사용자 uid 세션으로 조용히 돌아가지 않는다.
|
|
186
|
+
if (typeof r.body.uid !== 'string' || !r.body.uid
|
|
187
|
+
|| typeof r.body.firebaseUid !== 'string' || !/^odyssey-cli:[a-f0-9]{64}$/.test(r.body.firebaseUid)) {
|
|
188
|
+
throw new HttpError(502, '서버가 CLI 전용 Firebase 신원을 지원하지 않습니다. 서버의 감시 보안 업데이트가 필요합니다.');
|
|
189
|
+
}
|
|
190
|
+
return r.body;
|
|
191
|
+
}
|
|
192
|
+
const reason = typeof r.body.message === 'string' ? r.body.message : String(r.body.error ?? r.status);
|
|
193
|
+
if (r.status === 401 || r.status === 403) {
|
|
194
|
+
throw new AuthRequiredError(`세션 교환 거절(${r.status}): ${reason}\n${loginHint(this.target)}`);
|
|
195
|
+
}
|
|
196
|
+
throw new HttpError(r.status, `세션 교환 실패(${r.status}): ${reason}`);
|
|
197
|
+
}
|
|
160
198
|
/** 자격증명이 살아 있는지 가장 싸게 확인한다(MCP ping — 인증을 지나야 응답한다). */
|
|
161
199
|
async ping() {
|
|
162
200
|
await this.request('ping');
|
|
@@ -173,6 +211,24 @@ export class OdysseyClient {
|
|
|
173
211
|
}
|
|
174
212
|
return info;
|
|
175
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* 서버가 initialize 응답에 싣는 사용 지침(MCP `instructions`).
|
|
216
|
+
* 평소 호출은 initialize 를 건너뛰어(한 왕복) 이걸 받지 못한다 — MCP 커넥터 사용자는 연결 때 받는 지침을
|
|
217
|
+
* CLI 사용자는 못 받았다. `odyssey agent-guide` 가 이걸로 따로 묻는다.
|
|
218
|
+
* 이력: document/90-process/work-log/261010 Odyssey CLI agent-guide 에이전트 설명서 서버 지침.md
|
|
219
|
+
*/
|
|
220
|
+
async serverInfo() {
|
|
221
|
+
const result = (await this.request('initialize', {
|
|
222
|
+
protocolVersion: PREFERRED_PROTOCOL_VERSION,
|
|
223
|
+
capabilities: {},
|
|
224
|
+
clientInfo: { name: 'odyssey-cli', version: this.clientVersion },
|
|
225
|
+
}));
|
|
226
|
+
return {
|
|
227
|
+
...(typeof result?.instructions === 'string' ? { instructions: result.instructions } : {}),
|
|
228
|
+
...(result?.serverInfo?.name ? { name: result.serverInfo.name } : {}),
|
|
229
|
+
...(result?.serverInfo?.version ? { version: result.serverInfo.version } : {}),
|
|
230
|
+
};
|
|
231
|
+
}
|
|
176
232
|
async listTools() {
|
|
177
233
|
const tools = [];
|
|
178
234
|
let cursor;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** 배포 패키지에 든 감시 예제를 새 폴더에 꺼낸다. 기존 파일·로그인·상시 실행 설정은 바꾸지 않는다. */
|
|
2
|
+
// 이력: document/90-process/work-log/261022 Odyssey CLI 배포 안정성 npm watch 감시 에이전트 감사.md
|
|
3
|
+
import { constants, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { loadCredentials, UsageError } from './config.js';
|
|
7
|
+
import { selectedProfileName } from './session.js';
|
|
8
|
+
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
9
|
+
const EXAMPLE = join(ROOT, 'examples', 'watch-agent');
|
|
10
|
+
const FILES = ['dispatcher.mjs', 'README.md', 'package.json', 'config.example.json',
|
|
11
|
+
'test/dispatcher.test.mjs', 'test/supervisor.test.mjs'];
|
|
12
|
+
export const WATCH_AGENT_HELP = `odyssey watch-agent init <새 폴더> [-p 프로필]
|
|
13
|
+
감시 에이전트 예제·설정·검사를 새 폴더에 준비한다. 기존 폴더는 덮어쓰지 않는다.
|
|
14
|
+
config.json의 workDir·프로필·MCP 이름·예산을 확인한 뒤:
|
|
15
|
+
node dispatcher.mjs --check 설치·CLI 로그인·MCP 등록 확인(모델 호출 없음)
|
|
16
|
+
node dispatcher.mjs --dry-run 배달 예정만 확인(일꾼·댓글 쓰기 없음)
|
|
17
|
+
node dispatcher.mjs 감시 시작. Ctrl+C로 중지
|
|
18
|
+
이 명령은 로그인·자동 시작 등록·배포를 수행하지 않는다.`;
|
|
19
|
+
export function cmdWatchAgent(g, args) {
|
|
20
|
+
if (args.length !== 2 || args[0] !== 'init' || !args[1])
|
|
21
|
+
throw new UsageError(WATCH_AGENT_HELP);
|
|
22
|
+
const destination = resolve(args[1]);
|
|
23
|
+
if (existsSync(destination))
|
|
24
|
+
throw new UsageError(`이미 있는 폴더는 덮어쓰지 않습니다: ${destination}`);
|
|
25
|
+
const profile = selectedProfileName(g);
|
|
26
|
+
const account = loadCredentials().profiles[profile]?.account;
|
|
27
|
+
const config = JSON.parse(readFileSync(join(EXAMPLE, 'config.example.json'), 'utf-8'));
|
|
28
|
+
config.workDir = process.cwd();
|
|
29
|
+
config.odysseyProfile = profile;
|
|
30
|
+
config.odysseyBin = join(ROOT, 'dist', 'index.js');
|
|
31
|
+
config.expectedUid = account?.uid ?? '';
|
|
32
|
+
mkdirSync(dirname(destination), { recursive: true });
|
|
33
|
+
// mkdir는 이미 있는 폴더를 원자적으로 거절한다. 복사도 배타적으로 써서 기존 파일을 지키도록 한다.
|
|
34
|
+
mkdirSync(destination, { mode: 0o700 });
|
|
35
|
+
for (const file of FILES) {
|
|
36
|
+
const target = join(destination, file);
|
|
37
|
+
mkdirSync(dirname(target), { recursive: true, mode: 0o700 });
|
|
38
|
+
copyFileSync(join(EXAMPLE, file), target, constants.COPYFILE_EXCL);
|
|
39
|
+
}
|
|
40
|
+
writeFileSync(join(destination, '.gitignore'), readFileSync(join(EXAMPLE, 'gitignore.template')), { flag: 'wx' });
|
|
41
|
+
writeFileSync(join(destination, 'config.json'), JSON.stringify(config, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
42
|
+
process.stdout.write(`감시 예제를 준비했습니다: ${destination}\n` +
|
|
43
|
+
'config.json의 작업 폴더·프로필·MCP 이름·예산을 확인하고, 그 폴더에서 node dispatcher.mjs --check를 실행하세요.\n');
|
|
44
|
+
return 0;
|
|
45
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `odyssey watch` 가 내보내는 이벤트(NDJSON 한 줄 = 하나) — Firestore 문서를 이벤트로 바꾸는 순수 함수.
|
|
3
|
+
*
|
|
4
|
+
* Firebase SDK 를 부르지 않아 단위 테스트한다. 문서 모양은 앱과 같다:
|
|
5
|
+
* - 할일 `user/{uid}/todo/{id}` — titleIcon.title · status · tags · updatedAt
|
|
6
|
+
* - 댓글 `shared/communication/chat/{room}/messages/{id}` — senderUid · content · createdAt · chatRoomUid · metadata.authorKind
|
|
7
|
+
* - 방 `shared/communication/chat/{room}` — itemType · itemUid · itemOwnerUid · parentItemUid(보드 카드면 그 보드)
|
|
8
|
+
*
|
|
9
|
+
* 에이전트(MCP `comment_on_item`) 댓글도 senderUid 가 그 사용자라 같은 쿼리로 온다. 둘을 가르는 건
|
|
10
|
+
* `metadata.authorKind` 표식이다(claude·companion·앞으로 추가될 작성자 포함).
|
|
11
|
+
* 이걸 놓치면 감시 위의 에이전트가 AI 댓글을 사람의 지시로 받아 다시 실행한다.
|
|
12
|
+
*
|
|
13
|
+
* 이력: document/90-process/work-log/261016 Odyssey CLI 스트림 odyssey watch 토큰 교환 Firestore 직접 감시.md
|
|
14
|
+
* 이력: document/90-process/work-log/261018 감시 에이전트 멘션 깨우기 @클로드코드 launchd 상시 실행.md
|
|
15
|
+
*/
|
|
16
|
+
/** Firestore Timestamp(toDate) · {seconds,nanoseconds} · Date · ISO 문자열 → ISO. 모르면 null. */
|
|
17
|
+
export function toIso(value) {
|
|
18
|
+
if (value == null)
|
|
19
|
+
return null;
|
|
20
|
+
if (value instanceof Date)
|
|
21
|
+
return Number.isNaN(value.getTime()) ? null : value.toISOString();
|
|
22
|
+
if (typeof value === 'string') {
|
|
23
|
+
const d = new Date(value);
|
|
24
|
+
return Number.isNaN(d.getTime()) ? null : d.toISOString();
|
|
25
|
+
}
|
|
26
|
+
if (typeof value === 'object') {
|
|
27
|
+
const v = value;
|
|
28
|
+
if (typeof v.toDate === 'function')
|
|
29
|
+
return toIso(v.toDate());
|
|
30
|
+
const seconds = v.seconds ?? v._seconds;
|
|
31
|
+
if (typeof seconds === 'number')
|
|
32
|
+
return new Date(seconds * 1000 + Math.floor((v.nanoseconds ?? 0) / 1e6)).toISOString();
|
|
33
|
+
}
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
function str(value) {
|
|
37
|
+
return typeof value === 'string' && value.length ? value : null;
|
|
38
|
+
}
|
|
39
|
+
export function todoEvent(change, id, data, initial) {
|
|
40
|
+
const d = data ?? {};
|
|
41
|
+
const titleIcon = d.titleIcon;
|
|
42
|
+
return {
|
|
43
|
+
type: 'todo',
|
|
44
|
+
change,
|
|
45
|
+
initial,
|
|
46
|
+
uid: str(d.uid) ?? id,
|
|
47
|
+
title: str(titleIcon?.title),
|
|
48
|
+
status: str(d.status),
|
|
49
|
+
tags: Array.isArray(d.tags) ? d.tags.filter((t) => typeof t === 'string') : [],
|
|
50
|
+
updatedAt: toIso(d.updatedAt),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
export function commentAuthor(data) {
|
|
54
|
+
const meta = data.metadata;
|
|
55
|
+
// 사람 댓글에는 표식이 없다. 알 수 없는 값도 지시로 승격하지 않는다.
|
|
56
|
+
// 이력: document/90-process/work-log/261022 Odyssey CLI 자격 회수 CLI 전용 신원 companion 댓글 분류.md
|
|
57
|
+
return meta?.authorKind == null || meta.authorKind === '' ? 'me' : 'agent';
|
|
58
|
+
}
|
|
59
|
+
/** 지운 댓글·숨긴 댓글은 이벤트로 내보내지 않는다. */
|
|
60
|
+
export function isLiveComment(data) {
|
|
61
|
+
return data.isDeleted !== true && data.isBlocked !== true;
|
|
62
|
+
}
|
|
63
|
+
export function commentEvent(id, data, room) {
|
|
64
|
+
return {
|
|
65
|
+
type: 'comment',
|
|
66
|
+
author: commentAuthor(data),
|
|
67
|
+
commentUid: str(data.uid) ?? id,
|
|
68
|
+
roomUid: str(data.chatRoomUid),
|
|
69
|
+
itemType: str(room?.itemType),
|
|
70
|
+
itemUid: str(room?.itemUid),
|
|
71
|
+
itemOwnerUid: str(room?.itemOwnerUid),
|
|
72
|
+
parentItemUid: str(room?.parentItemUid),
|
|
73
|
+
replyToCommentUid: str(data.replyToMessageUid),
|
|
74
|
+
text: typeof data.content === 'string' ? data.content : '',
|
|
75
|
+
kind: str(data.type),
|
|
76
|
+
createdAt: toIso(data.createdAt),
|
|
77
|
+
};
|
|
78
|
+
}
|
package/dist/watch.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `odyssey watch` — 내 계정의 변화를 실시간으로 받아 NDJSON(한 줄 = 이벤트 하나)으로 stdout 에 흘린다.
|
|
3
|
+
*
|
|
4
|
+
* 그 위에 프로그램(예: Claude Code 디스패처)이 붙는다 — `odyssey watch --tag "클로드 코드" | 디스패처`.
|
|
5
|
+
*
|
|
6
|
+
* ## 어떻게 듣나
|
|
7
|
+
* MCP 서버는 무상태 함수라 밀어 줄 수 없다. 그래서 CLI 로그인(OAuth)을 서버에서 Firebase 커스텀 토큰 +
|
|
8
|
+
* App Check 토큰으로 바꿔(`/cli/firebase-session`) **Firestore 리스너를 직접** 붙인다. CLI 전용 신원으로 감시에 필요한 읽기만 허용한다.
|
|
9
|
+
* - 할일: `user/{uid}/todo` 중 태그가 하나라도 맞는 것(`--tag`, 최대 30개) — 처음 스냅샷은 initial:true(밀린 일).
|
|
10
|
+
* - 내 댓글: 컬렉션 그룹 `messages` 에서 senderUid == 나 · createdAt > 커서(기본 = 켠 시각).
|
|
11
|
+
* AI 댓글(metadata.authorKind 표식)은 기본으로 뺀다(`--include-agent`).
|
|
12
|
+
*
|
|
13
|
+
* ## 자격 수명
|
|
14
|
+
* App Check 토큰(1시간)이 다 되면 SDK 가 provider 를 다시 부르고, provider 는 서버에서 다시 교환한다.
|
|
15
|
+
* 회수는 App Check 수명에 기대지 않는다 — rules 가 연결 원장을 확인해 회수 뒤 추가 데이터 접근을 거절한다.
|
|
16
|
+
* 서버는 연결 전용 Firebase uid 의 갱신도 회수한다(사용자의 일반 앱 로그인과 분리).
|
|
17
|
+
* 이력: document/90-process/work-log/261022 Odyssey CLI 자격 회수 CLI 전용 신원 companion 댓글 분류.md
|
|
18
|
+
* Firebase 로그인 상태는 메모리에만 둔다(디스크에 refresh 토큰을 남기지 않는다).
|
|
19
|
+
*
|
|
20
|
+
* Firebase JS SDK 는 이 명령에서만 불러온다(동적 import) — 다른 명령은 의존성 없이 그대로 뜬다.
|
|
21
|
+
*
|
|
22
|
+
* 이력: document/90-process/work-log/261016 Odyssey CLI 스트림 odyssey watch 토큰 교환 Firestore 직접 감시.md
|
|
23
|
+
*/
|
|
24
|
+
import { UsageError } from './config.js';
|
|
25
|
+
import { OdysseyClient, resolveTarget } from './session.js';
|
|
26
|
+
import { commentEvent, isLiveComment, todoEvent } from './watch-events.js';
|
|
27
|
+
export const WATCH_HELP = `odyssey watch [--tag 태그 ...] [--no-comments] [--include-agent] [--since ISO]
|
|
28
|
+
내 계정의 변화를 실시간으로 받아 한 줄에 JSON 하나씩(NDJSON) stdout 으로 낸다. 끄려면 Ctrl+C.
|
|
29
|
+
--tag <태그> 이 태그(하나라도)가 달린 할일의 추가·수정·삭제(반복 가능, 최대 30). 없으면 할일은 안 본다
|
|
30
|
+
--no-comments 내 댓글은 보지 않는다
|
|
31
|
+
--include-agent AI(MCP·컴패니언)가 단 댓글도 낸다(기본은 내가 쓴 것만)
|
|
32
|
+
--since <ISO> 이 시각 뒤의 댓글부터(기본: 지금). 밀린 댓글을 다시 받을 때
|
|
33
|
+
이벤트: {"type":"ready"} · {"type":"todo",...} · {"type":"comment",...} · {"type":"error",...}
|
|
34
|
+
OAuth 로그인 프로필만 된다(API 키는 거절).`;
|
|
35
|
+
export function parseWatchArgs(args, now = new Date()) {
|
|
36
|
+
const o = { tags: [], comments: true, includeAgent: false, since: now };
|
|
37
|
+
for (let i = 0; i < args.length; i++) {
|
|
38
|
+
const a = args[i];
|
|
39
|
+
const [flag, inline] = a.startsWith('--') && a.includes('=') ? [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)] : [a, undefined];
|
|
40
|
+
const value = () => {
|
|
41
|
+
const v = inline ?? args[++i];
|
|
42
|
+
if (v === undefined || (inline === undefined && v.startsWith('--')))
|
|
43
|
+
throw new UsageError(`${flag} 에 값이 필요합니다.`);
|
|
44
|
+
return v;
|
|
45
|
+
};
|
|
46
|
+
switch (flag) {
|
|
47
|
+
case '--tag':
|
|
48
|
+
o.tags.push(value());
|
|
49
|
+
break;
|
|
50
|
+
case '--no-comments':
|
|
51
|
+
o.comments = false;
|
|
52
|
+
break;
|
|
53
|
+
case '--include-agent':
|
|
54
|
+
o.includeAgent = true;
|
|
55
|
+
break;
|
|
56
|
+
case '--since': {
|
|
57
|
+
const raw = value();
|
|
58
|
+
const d = new Date(raw);
|
|
59
|
+
if (Number.isNaN(d.getTime()))
|
|
60
|
+
throw new UsageError(`--since 는 ISO 시각이어야 합니다: ${raw}`);
|
|
61
|
+
o.since = d;
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
default:
|
|
65
|
+
throw new UsageError(`watch 가 모르는 인자: ${a}\n${WATCH_HELP}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (o.tags.length > 30)
|
|
69
|
+
throw new UsageError('--tag 는 30개까지입니다(Firestore array-contains-any 한도).');
|
|
70
|
+
if (!o.tags.length && !o.comments)
|
|
71
|
+
throw new UsageError('볼 것이 없습니다 — --tag 를 주거나 --no-comments 를 빼세요.');
|
|
72
|
+
return o;
|
|
73
|
+
}
|
|
74
|
+
function emit(event) {
|
|
75
|
+
process.stdout.write(`${JSON.stringify(event)}\n`);
|
|
76
|
+
}
|
|
77
|
+
export async function cmdWatch(g, args, version) {
|
|
78
|
+
const opts = parseWatchArgs(args);
|
|
79
|
+
const target = resolveTarget(g);
|
|
80
|
+
const client = new OdysseyClient(target, version);
|
|
81
|
+
let session = await client.firebaseSession();
|
|
82
|
+
let sessionAt = Date.now();
|
|
83
|
+
const { initializeApp } = await import('firebase/app');
|
|
84
|
+
const { initializeAppCheck, CustomProvider } = await import('firebase/app-check');
|
|
85
|
+
const { getAuth, signInWithCustomToken } = await import('firebase/auth');
|
|
86
|
+
const fs = await import('firebase/firestore');
|
|
87
|
+
const app = initializeApp(session.firebase, `odyssey-cli-${target.profileName ?? 'env'}`);
|
|
88
|
+
initializeAppCheck(app, {
|
|
89
|
+
provider: new CustomProvider({
|
|
90
|
+
// SDK 는 토큰이 다 됐을 때만 다시 부른다. 처음 한 번은 교환에서 받은 것을 쓰고, 그 뒤는 다시 교환한다.
|
|
91
|
+
getToken: async () => {
|
|
92
|
+
if (Date.now() - sessionAt > 60_000) {
|
|
93
|
+
session = await client.firebaseSession();
|
|
94
|
+
sessionAt = Date.now();
|
|
95
|
+
}
|
|
96
|
+
return { token: session.appCheck.token, expireTimeMillis: sessionAt + session.appCheck.ttlMillis };
|
|
97
|
+
},
|
|
98
|
+
}),
|
|
99
|
+
isTokenAutoRefreshEnabled: false,
|
|
100
|
+
});
|
|
101
|
+
const signedIn = await signInWithCustomToken(getAuth(app), session.customToken);
|
|
102
|
+
if (signedIn.user.uid !== session.firebaseUid) {
|
|
103
|
+
throw new UsageError('Firebase 신원이 CLI 전용 세션과 일치하지 않습니다. 서버의 감시 보안 업데이트가 필요합니다.');
|
|
104
|
+
}
|
|
105
|
+
const db = fs.getFirestore(app);
|
|
106
|
+
const uid = session.uid;
|
|
107
|
+
const unsubs = [];
|
|
108
|
+
const streams = [];
|
|
109
|
+
const pending = new Set();
|
|
110
|
+
const ready = () => {
|
|
111
|
+
if (pending.size === 0)
|
|
112
|
+
emit({ type: 'ready', uid, streams, since: opts.since.toISOString() });
|
|
113
|
+
};
|
|
114
|
+
if (opts.tags.length) {
|
|
115
|
+
streams.push('todos');
|
|
116
|
+
pending.add('todos');
|
|
117
|
+
let first = true;
|
|
118
|
+
const q = fs.query(fs.collection(db, 'user', uid, 'todo'), fs.where('tags', 'array-contains-any', opts.tags));
|
|
119
|
+
unsubs.push(fs.onSnapshot(q, (snap) => {
|
|
120
|
+
for (const ch of snap.docChanges())
|
|
121
|
+
emit(todoEvent(ch.type, ch.doc.id, ch.doc.data(), first));
|
|
122
|
+
if (first) {
|
|
123
|
+
first = false;
|
|
124
|
+
pending.delete('todos');
|
|
125
|
+
ready();
|
|
126
|
+
}
|
|
127
|
+
}, (e) => emit({ type: 'error', stream: 'todos', code: e.code ?? null, message: e.message })));
|
|
128
|
+
}
|
|
129
|
+
if (opts.comments) {
|
|
130
|
+
streams.push('comments');
|
|
131
|
+
pending.add('comments');
|
|
132
|
+
const rooms = new Map();
|
|
133
|
+
const roomOf = async (roomUid) => {
|
|
134
|
+
if (!roomUid)
|
|
135
|
+
return null;
|
|
136
|
+
if (rooms.has(roomUid))
|
|
137
|
+
return rooms.get(roomUid);
|
|
138
|
+
let room = null;
|
|
139
|
+
try {
|
|
140
|
+
const snap = await fs.getDoc(fs.doc(db, 'shared', 'communication', 'chat', roomUid));
|
|
141
|
+
room = snap.exists() ? snap.data() : null;
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
room = null; // 방을 못 읽어도(나간 공유 보드 등) 댓글은 낸다 — 항목 칸만 빈다.
|
|
145
|
+
}
|
|
146
|
+
rooms.set(roomUid, room);
|
|
147
|
+
return room;
|
|
148
|
+
};
|
|
149
|
+
let first = true;
|
|
150
|
+
const q = fs.query(fs.collectionGroup(db, 'messages'), fs.where('senderUid', '==', uid), fs.where('createdAt', '>', fs.Timestamp.fromDate(opts.since)), fs.orderBy('createdAt'));
|
|
151
|
+
unsubs.push(fs.onSnapshot(q, async (snap) => {
|
|
152
|
+
for (const ch of snap.docChanges()) {
|
|
153
|
+
if (ch.type !== 'added')
|
|
154
|
+
continue;
|
|
155
|
+
const data = ch.doc.data();
|
|
156
|
+
if (!isLiveComment(data))
|
|
157
|
+
continue;
|
|
158
|
+
const ev = commentEvent(ch.doc.id, data, await roomOf(data.chatRoomUid));
|
|
159
|
+
if (ev.author === 'agent' && !opts.includeAgent)
|
|
160
|
+
continue;
|
|
161
|
+
emit(ev);
|
|
162
|
+
}
|
|
163
|
+
if (first) {
|
|
164
|
+
first = false;
|
|
165
|
+
pending.delete('comments');
|
|
166
|
+
ready();
|
|
167
|
+
}
|
|
168
|
+
}, (e) => emit({ type: 'error', stream: 'comments', code: e.code ?? null, message: e.message })));
|
|
169
|
+
}
|
|
170
|
+
return new Promise((resolve) => {
|
|
171
|
+
const stop = () => {
|
|
172
|
+
for (const u of unsubs)
|
|
173
|
+
u();
|
|
174
|
+
resolve(0);
|
|
175
|
+
// 리스너·gRPC 소켓이 이벤트 루프를 붙잡는다 — 다 뗐으면 바로 끝낸다.
|
|
176
|
+
setTimeout(() => process.exit(0), 50).unref();
|
|
177
|
+
};
|
|
178
|
+
process.once('SIGINT', stop);
|
|
179
|
+
process.once('SIGTERM', stop);
|
|
180
|
+
});
|
|
181
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# Odyssey 감시 에이전트 예제
|
|
2
|
+
|
|
3
|
+
> 0.2.0 보안 후보: 감시는 CLI 전용 Firebase 신원을 요구합니다. Functions·규칙의 동반 업데이트 전에는 감시가 시작되지 않습니다. 이 저장소 후보는 아직 배포하지 않았습니다.
|
|
4
|
+
|
|
5
|
+
Odyssey에서 태그나 댓글로 맡긴 일을 Claude Code에 전달하는 실행 가능한 예제입니다.
|
|
6
|
+
할일·항목마다 세션 하나를 만들고, 이후 댓글은 같은 세션으로 이어 받습니다.
|
|
7
|
+
대기 중에는 모델을 부르지 않습니다. 컴퓨터가 켜져 있고 이 프로그램이 실행 중이어야 받습니다.
|
|
8
|
+
|
|
9
|
+
## 처음 시작하기
|
|
10
|
+
|
|
11
|
+
Node.js 20 이상, OAuth 로그인한 Odyssey CLI, 로그인한 Claude Code가 필요합니다.
|
|
12
|
+
배포 전 후보를 받았다면 제공된 `.tgz`로 설치합니다. 공개된 0.1.0에는 이 예제가 없습니다.
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install -g /path/to/odyssey365-cli-0.2.0.tgz
|
|
16
|
+
odyssey --version
|
|
17
|
+
odyssey login
|
|
18
|
+
odyssey whoami
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
실제로 작업할 프로젝트 폴더에서 예제를 준비합니다. **새 폴더**를 지정하세요. 기존 폴더는 덮어쓰지 않습니다.
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
cd /path/to/my-project
|
|
25
|
+
odyssey watch-agent init ../my-watch-agent
|
|
26
|
+
cd ../my-watch-agent
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
생성된 `config.json`의 `workDir`은 명령을 실행한 프로젝트 폴더입니다.
|
|
30
|
+
`odysseyBin`에는 설치한 CLI의 JS 경로를 넣으므로 전역 npm 명령의 위치를 다시 찾을 필요가 없습니다.
|
|
31
|
+
프로필을 고르려면 생성할 때 `-p work`를 붙입니다. 자격증명·토큰은 복사하지 않습니다.
|
|
32
|
+
|
|
33
|
+
Claude Code의 Odyssey MCP도 **작업할 프로젝트 폴더에서 같은 계정으로** 연결하세요.
|
|
34
|
+
이미 연결했다면 다시 추가할 필요가 없습니다. 새 연결은 다음 명령으로 등록하고 Claude Code를 열어 `/mcp`에서 로그인합니다.
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
cd /path/to/my-project
|
|
38
|
+
claude mcp add --transport http odyssey https://mcp-odyssey30-60.odyssey365.app
|
|
39
|
+
claude
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Claude Code에서 Odyssey 계정·카테고리 등 읽기 작업을 한 번 확인한 후 예제 폴더로 돌아옵니다.
|
|
43
|
+
CLI 로그인과 MCP 로그인은 별개입니다. `--check`는 MCP 등록을 확인하며 두 로그인 계정의 일치까지 증명하지 않습니다.
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
node dispatcher.mjs --check
|
|
47
|
+
node dispatcher.mjs --dry-run
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`--check`는 모델을 부르지 않고 CLI OAuth 인증·Claude Code 설치·MCP 등록을 확인합니다.
|
|
51
|
+
`--dry-run`은 실제 감시를 연결하지만 일꾼을 깨우거나 댓글을 쓰지 않습니다. 로그에서 `ready`와 배달 예정을 확인하고 Ctrl+C로 끕니다.
|
|
52
|
+
시험할 할일 하나에 `클로드 코드` 태그를 붙이거나 메모에 `@클로드코드` 댓글을 써서 배달 예정이 나오는지 보세요.
|
|
53
|
+
|
|
54
|
+
검사가 끝났으면 실제 모드를 켭니다.
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
node dispatcher.mjs
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
시험 항목의 작은 일 하나부터 맡기세요. 일꾼이 남긴 질문에 댓글로 답하면 같은 세션으로 이어 받습니다.
|
|
61
|
+
처음 켤 때 태그가 달린 미시작 할일도 처리 대상입니다. 실제 모드는 댓글·항목을 읽고 수정하며 모델 사용량이 발생합니다.
|
|
62
|
+
기본 파일 편집 권한은 `acceptEdits`, 셸 명령은 허용한 패턴만 자동 승인합니다.
|
|
63
|
+
|
|
64
|
+
## 보통 바꾸는 설정
|
|
65
|
+
|
|
66
|
+
| 키 | 기본값·설명 |
|
|
67
|
+
|---|---|
|
|
68
|
+
| `workDir` | 일꾼이 일할 프로젝트 폴더. `./`·`../`는 config.json 기준 |
|
|
69
|
+
| `odysseyProfile` | `default`. `odyssey profiles`에서 확인 |
|
|
70
|
+
| `expectedUid` | 생성 시 로컬에 알려진 계정 uid. 비어 있으면 `--check`의 uid를 넣을 수 있음 |
|
|
71
|
+
| `claudeBin` | `claude`. PATH에 없으면 실행 파일 절대 경로 |
|
|
72
|
+
| `odysseyMcpName` | `odyssey`. 작업 폴더의 `claude mcp list`에 보이는 이름 |
|
|
73
|
+
| `watchTag` / `mentions` | `클로드 코드` / `@클로드코드`. 댓글 멘션의 공백·대소문자는 무시 |
|
|
74
|
+
| `turnBudgetUsd` / `dailyBudgetUsd` | 턴 $1 / 하루 $5. Claude Code의 API 환산 사용량 기준 |
|
|
75
|
+
| `allowedTools` | 추가로 자동 승인할 패턴. 예: `Bash(npm test:*)`, `Bash(git status:*)` |
|
|
76
|
+
| `extraRules` | 일꾼에게 매번 전할 프로젝트 규칙 |
|
|
77
|
+
| `readyTimeoutMs` | 시작·재연결 준비 대기 120초. 실패하면 백오프 후 재시작 |
|
|
78
|
+
|
|
79
|
+
하루 예산은 턴이 끝난 뒤 합산하므로 최대 한 턴 예산만큼 넘을 수 있습니다. 구독·API 청구액과 같은 값으로 간주하지 마세요.
|
|
80
|
+
태그 할일과 세션이 생긴 항목의 **내 댓글**이 후속 지시입니다. 다른 사람이 쓴 댓글과 에이전트 댓글은 일꾼을 깨우지 않습니다.
|
|
81
|
+
에이전트 답글에는 별도 작성자 표식이 붙어 자기 답에 다시 반응하는 일을 막습니다.
|
|
82
|
+
|
|
83
|
+
## 끄기·복구·상태
|
|
84
|
+
|
|
85
|
+
- **끄기:** 실행 중인 터미널에서 Ctrl+C. 일꾼이 도는 중이면 끊고 다음 실행에서 이어 받습니다.
|
|
86
|
+
- **다시 켜기:** 같은 폴더에서 `node dispatcher.mjs`. 마지막 배달 커서·세션·예산은 `state.json`에 남습니다.
|
|
87
|
+
- **연결 복구:** 감시 프로세스 종료·리스너 error·ready 시간 초과를 받으면 5초부터 최대 5분까지 간격을 늘려 재시작합니다. 10분간 정상 연결된 뒤 간격을 초기화합니다.
|
|
88
|
+
- **로그:** 터미널과 `logs/dispatcher.log`. 로그에는 맡긴 내용이 들어갈 수 있으므로 공유 전에 확인하세요.
|
|
89
|
+
- **단일 실행:** 같은 상태 파일의 실행 잠금으로 중복 실행을 막습니다. 복제한 여러 폴더로 같은 일을 동시에 감시하지 마세요.
|
|
90
|
+
- **계정 변경:** 계정마다 별도 예제 폴더를 만드세요. 상태 파일에 이전 계정 uid가 있으면 다른 계정으로 이어 받지 않습니다.
|
|
91
|
+
- **로그인 필요:** `odyssey login -p <프로필>` 뒤 다시 실행합니다. API 키 로그인은 watch에 사용할 수 없습니다.
|
|
92
|
+
- **세션 직접 열기:** 멈춘 상태에서 state.json의 sessionId를 찾아 작업 폴더에서 `claude --resume <id>`. 일꾼이 실행 중일 때 같은 세션을 열지 마세요.
|
|
93
|
+
- **초기화:** config.json과 state.json을 지우기보다 별도 폴더를 만들어 시작하세요. 상태를 잃으면 미완료 작업을 다시 맡길 수 있습니다.
|
|
94
|
+
|
|
95
|
+
모의 실행의 상태·로그는 `state.dry-run.json`·`dispatcher.dry-run.log`로 분리합니다.
|
|
96
|
+
첫 실행 전의 댓글은 자동으로 소급하지 않습니다. 이후 꺼져 있던 동안의 댓글은 저장한 커서부터 따라잡습니다.
|
|
97
|
+
댓글 중복 기억은 항목당 최근 1,000건입니다. 네트워크 장애와 일꾼 중단 중 외부 작업을 정확히 한 번만 실행하는 것은 보장하지 않습니다.
|
|
98
|
+
재개한 일꾼은 항목·스레드를 다시 읽고 이미 한 작업을 확인합니다.
|
|
99
|
+
|
|
100
|
+
## 자동 시작은 직접 선택
|
|
101
|
+
|
|
102
|
+
이 예제는 로그인 시 자동 실행을 등록하지 않습니다. 터미널에서 확인한 뒤 macOS는 LaunchAgent, Linux는 사용자 systemd 서비스로 등록할 수 있습니다.
|
|
103
|
+
설정·로그·상태 파일을 둘 폴더의 절대 경로와 `command -v node`로 확인한 Node 경로를 사용하세요.
|
|
104
|
+
PATH가 짧은 환경에서는 `claudeBin`도 절대 경로를 사용합니다. 중지할 때는 해당 서비스도 내려야 자동 재시작하지 않습니다.
|
|
105
|
+
컴퓨터가 잠들거나 꺼져 있으면 감시도 쉬며, 다음 시작 때 커서부터 이어 받습니다.
|
|
106
|
+
|
|
107
|
+
Windows에서는 Node와 Claude Code 실행 파일 또는 JS 진입점 경로를 지정하세요. JS 파일은 현재 Node로 실행하므로 `.cmd` 셸 인용에 의존하지 않습니다.
|
|
108
|
+
Windows·Linux 실기기에서의 전체 로그인·장기 감시는 별도 확인이 필요합니다.
|
|
109
|
+
|
|
110
|
+
## 예제 검사
|
|
111
|
+
|
|
112
|
+
```sh
|
|
113
|
+
npm test
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
실제 Odyssey와 Claude 대신 가짜 프로세스를 사용합니다. 배달·세션 재개·중복 방지·커서·FIFO·예산·오류 복구를 확인합니다.
|
|
117
|
+
구조를 바꾸고 싶으면 `odyssey agent-guide --watch-agent`의 프롬프트를 코딩 에이전트에 주되, 이 검사를 함께 유지하세요.
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
## 댓글과 자격 회수
|
|
121
|
+
|
|
122
|
+
`claude`·`companion`·알 수 없는 작성자 표식은 모두 AI 댓글입니다. 멘션이 있거나 이미 열린 세션이어도 일꾼에게 지시로 배달하지 않습니다.
|
|
123
|
+
서버가 OAuth 연결을 회수하면 해당 CLI 신원의 데이터 접근과 Firebase 갱신을 막습니다. 일반 앱 로그인과 다른 OAuth 연결은 유지됩니다.
|
|
124
|
+
이미 받은 데이터·진행 중인 일꾼 작업은 회수로 되돌아가지 않습니다. 감시 오류 뒤에는 예제의 재시작 간격이 적용됩니다.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"workDir": "./work",
|
|
3
|
+
"odysseyProfile": "default",
|
|
4
|
+
"odysseyBin": "odyssey",
|
|
5
|
+
"claudeBin": "claude",
|
|
6
|
+
"odysseyMcpName": "odyssey",
|
|
7
|
+
"expectedUid": "",
|
|
8
|
+
"watchTag": "클로드 코드",
|
|
9
|
+
"mentions": ["@클로드코드"],
|
|
10
|
+
"mentionAck": "👀 받았어요.",
|
|
11
|
+
"permissionMode": "acceptEdits",
|
|
12
|
+
"allowedTools": [],
|
|
13
|
+
"disallowedTools": ["Bash(git push:*)", "Bash(firebase deploy:*)", "Bash(npm publish:*)"],
|
|
14
|
+
"extraRules": [],
|
|
15
|
+
"turnBudgetUsd": 1,
|
|
16
|
+
"dailyBudgetUsd": 5,
|
|
17
|
+
"readyTimeoutMs": 120000,
|
|
18
|
+
"statePath": "./state.json",
|
|
19
|
+
"logPath": "./logs/dispatcher.log"
|
|
20
|
+
}
|