@odyssey365/cli 0.1.0 → 0.2.1

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/dist/index.js CHANGED
@@ -16,7 +16,7 @@
16
16
  * 이력: document/90-process/work-log/261010 Odyssey CLI 다계정 프로필 MCP CLI판.md
17
17
  */
18
18
  import { readFileSync } from 'node:fs';
19
- import { dirname, join } from 'node:path';
19
+ import { dirname, join, resolve as resolvePath } from 'node:path';
20
20
  import { fileURLToPath } from 'node:url';
21
21
  import { createInterface } from 'node:readline';
22
22
  import { AuthRequiredError, DEFAULT_PROFILE, DEFAULT_SERVER, UsageError, assertProfileName, credentialsPath, loadCredentials, normalizeServer, updateCredentials, } from './config.js';
@@ -26,10 +26,16 @@ import { NetworkError } from './rpc.js';
26
26
  import { envServer, OdysseyClient, resolveTarget, selectedProfileName } from './session.js';
27
27
  import { findTool, getTools, renderToolDetail, renderToolList, toolListJson } from './tools.js';
28
28
  import { printToolResult, writeJson } from './output.js';
29
+ import { inlineImageFiles } from './files.js';
30
+ import { renderAgentGuide, renderSkill, renderSnippet } from './guide.js';
31
+ import { cmdWatch, WATCH_HELP } from './watch.js';
32
+ import { cmdWatchAgent, WATCH_AGENT_HELP } from './watch-agent.js';
29
33
  const __dirname = dirname(fileURLToPath(import.meta.url));
30
34
  const VERSION = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')).version;
31
35
  const HELP = `Odyssey CLI v${VERSION} — Odyssey 계정의 할일·메모·보드·스냅샷을 터미널과 AI 에이전트에서 다룬다.
32
36
 
37
+ AI 에이전트라면 먼저: odyssey agent-guide (사용법·로그인된 계정·서버 사용 지침)
38
+
33
39
  사용법
34
40
  odyssey <도구> [--파라미터 값 ...] 도구 실행 (예: odyssey list_todos --status inProgress)
35
41
  odyssey tools [검색어] 도구 목록
@@ -43,6 +49,17 @@ const HELP = `Odyssey CLI v${VERSION} — Odyssey 계정의 할일·메모·보
43
49
  odyssey profiles 로그인된 프로필 목록
44
50
  odyssey use <이름> 기본 프로필 바꾸기
45
51
 
52
+ 실시간 감시
53
+ odyssey watch-agent init <폴더> 감시 에이전트 예제를 새 폴더에 준비(설정·검사 포함)
54
+ odyssey watch [--tag 태그 ...] 내 할일(태그)·내 댓글 변화를 한 줄에 JSON 하나씩(NDJSON) 흘린다
55
+ 자세히: odyssey watch --help
56
+
57
+ AI 에이전트
58
+ odyssey agent-guide 에이전트용 설명서(사용법 + 계정 + 서버 사용 지침 실시간)
59
+ odyssey agent-guide --skill Claude Code·Codex 스킬 파일(SKILL.md) 내용
60
+ odyssey agent-guide --snippet AGENTS.md·CLAUDE.md·GEMINI.md 에 붙일 짧은 절
61
+ odyssey agent-guide --watch-agent 감시 에이전트(watch → 세션 깨우기, 답글은 세션이)를 만들게 하는 프롬프트
62
+
46
63
  전역 옵션
47
64
  -p, --profile <이름> 이번 실행의 계정. 기본: ODYSSEY_PROFILE → odyssey use 값 → default
48
65
  -o, --output <형식> json(기본) · text(요약 텍스트) · raw(MCP 결과 전체)
@@ -298,6 +315,62 @@ function cmdUse(_g, args) {
298
315
  process.stdout.write(`✓ 기본 프로필: ${name}\n`);
299
316
  return 0;
300
317
  }
318
+ // ── 에이전트 설명서 ──────────────────────────────────────────────────────────
319
+ async function cmdAgentGuide(g, args) {
320
+ const skill = takeFlag(args, '--skill');
321
+ const snippet = takeFlag(args, '--snippet');
322
+ const watchAgent = takeFlag(args, '--watch-agent');
323
+ if (args.length || [skill, snippet, watchAgent].filter(Boolean).length > 1) {
324
+ throw new UsageError('사용법: odyssey agent-guide [--skill | --snippet | --watch-agent]');
325
+ }
326
+ // 감시 에이전트(디스패처)를 코딩 에이전트에게 만들게 하는 프롬프트 — 패키지의 prompts/watch-agent.md 그대로.
327
+ // 이력: document/90-process/work-log/261016 Odyssey CLI 감시 에이전트 만들기 프롬프트 watch-agent.md
328
+ // document/90-process/work-log/261018 컴패니언 백그라운드 끊김 이어 하기 CompanionAppPresence 감시 에이전트 A.md(A안 — 배달만)
329
+ if (watchAgent) {
330
+ process.stdout.write(readFileSync(join(__dirname, '..', 'prompts', 'watch-agent.md'), 'utf-8'));
331
+ return 0;
332
+ }
333
+ if (skill || snippet) {
334
+ process.stdout.write(skill ? renderSkill() : renderSnippet());
335
+ return 0;
336
+ }
337
+ const file = loadCredentials();
338
+ const profiles = Object.entries(file.profiles).map(([name, p]) => ({
339
+ name,
340
+ isDefault: file.defaultProfile === name,
341
+ auth: p.credential.type,
342
+ ...(p.account?.email ? { email: p.account.email } : {}),
343
+ ...(p.account?.uid ? { uid: p.account.uid } : {}),
344
+ }));
345
+ const envToken = !!(process.env.ODYSSEY_TOKEN ?? process.env.ODYSSEY_API_KEY ?? '').trim();
346
+ // 서버 사용 지침 — 로그인 전이거나 연결이 안 돼도 설명서는 낸다(그 사실을 적어서).
347
+ let server = normalizeServer(g.server ?? envServer() ?? DEFAULT_SERVER);
348
+ let instructionsFrom = null;
349
+ let serverInstructions;
350
+ let serverInstructionsError;
351
+ try {
352
+ const target = resolveTarget(g);
353
+ server = target.server;
354
+ instructionsFrom = target.profileName;
355
+ serverInstructions = (await new OdysseyClient(target, VERSION).serverInfo()).instructions;
356
+ if (!serverInstructions)
357
+ serverInstructionsError = '서버가 지침을 보내지 않았다';
358
+ }
359
+ catch (e) {
360
+ serverInstructionsError =
361
+ e instanceof AuthRequiredError ? '로그인 전' : e instanceof NetworkError ? '서버에 연결하지 못함' : e.message;
362
+ }
363
+ process.stdout.write(renderAgentGuide({
364
+ version: VERSION,
365
+ server,
366
+ profiles,
367
+ envToken,
368
+ instructionsFrom,
369
+ ...(serverInstructions ? { serverInstructions } : {}),
370
+ ...(serverInstructionsError ? { serverInstructionsError } : {}),
371
+ }));
372
+ return 0;
373
+ }
301
374
  // ── 도구 명령 ────────────────────────────────────────────────────────────────
302
375
  async function cmdTools(g, args) {
303
376
  if (args.length > 1)
@@ -341,11 +414,14 @@ async function cmdCall(g, toolName, tokens) {
341
414
  (missing.length === 1 && (tool.inputSchema?.required ?? []).length === 1 ? ' (위치 인자로도 됩니다)' : '') +
342
415
  `\n자세히: odyssey describe ${tool.name}`);
343
416
  }
417
+ // 사진 칸의 로컬 파일(image.file)을 바이트로 바꿔 싣는다 — 상대 경로는 --input 파일 옆 기준.
418
+ const baseDir = g.inputFile && g.inputFile !== '-' ? dirname(resolvePath(g.inputFile)) : process.cwd();
419
+ inlineImageFiles(args, baseDir);
344
420
  const result = await client.callTool(tool.name, args);
345
421
  return printToolResult(result, g.output ?? 'json', tool.name);
346
422
  }
347
423
  // ── 진입 ─────────────────────────────────────────────────────────────────────
348
- const ACCOUNT_COMMANDS = new Set(['login', 'logout', 'whoami', 'profiles', 'use']);
424
+ const ACCOUNT_COMMANDS = new Set(['login', 'logout', 'whoami', 'profiles', 'use', 'agent-guide', 'watch', 'watch-agent']);
349
425
  async function main(argv) {
350
426
  const { globals: g, rest } = extractGlobals(argv);
351
427
  if (g.profile !== undefined)
@@ -361,6 +437,14 @@ async function main(argv) {
361
437
  process.stdout.write(HELP);
362
438
  return command || g.help ? 0 : 2;
363
439
  }
440
+ if (g.help && command === 'watch') {
441
+ process.stdout.write(`${WATCH_HELP}\n`);
442
+ return 0;
443
+ }
444
+ if (g.help && command === 'watch-agent') {
445
+ process.stdout.write(`${WATCH_AGENT_HELP}\n`);
446
+ return 0;
447
+ }
364
448
  if (g.help) {
365
449
  // odyssey <도구> --help → 그 도구 설명
366
450
  if (!ACCOUNT_COMMANDS.has(command) && command !== 'tools' && command !== 'describe' && command !== 'call') {
@@ -380,6 +464,12 @@ async function main(argv) {
380
464
  return cmdProfiles(g, args);
381
465
  case 'use':
382
466
  return cmdUse(g, args);
467
+ case 'agent-guide':
468
+ return cmdAgentGuide(g, args);
469
+ case 'watch':
470
+ return cmdWatch(g, args, VERSION);
471
+ case 'watch-agent':
472
+ return cmdWatchAgent(g, args);
383
473
  case 'tools':
384
474
  return cmdTools(g, args);
385
475
  case 'describe':
package/dist/oauth.js CHANGED
@@ -15,7 +15,7 @@
15
15
  import { createHash, randomBytes } from 'node:crypto';
16
16
  import { createServer } from 'node:http';
17
17
  import { spawn } from 'node:child_process';
18
- import { errorMessageFromBody, describeFetchError, NetworkError, timeoutMs } from './rpc.js';
18
+ import { errorMessageFromBody, fetchText } from './rpc.js';
19
19
  export const CLIENT_NAME = 'Odyssey CLI';
20
20
  export const LOGIN_SCOPE = 'mcp openid email';
21
21
  const REGISTERED_REDIRECT = 'http://127.0.0.1/callback';
@@ -39,14 +39,7 @@ export function createPkce() {
39
39
  return { verifier, challenge };
40
40
  }
41
41
  async function fetchJson(url, init, server) {
42
- let res;
43
- try {
44
- res = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs()) });
45
- }
46
- catch (e) {
47
- throw new NetworkError(describeFetchError(e, server));
48
- }
49
- const body = await res.text();
42
+ const { response: res, body } = await fetchText(url, init, server);
50
43
  let json = null;
51
44
  try {
52
45
  json = JSON.parse(body);
package/dist/rpc.js CHANGED
@@ -44,6 +44,21 @@ export function timeoutMs() {
44
44
  const v = Number(process.env.ODYSSEY_TIMEOUT_MS);
45
45
  return Number.isFinite(v) && v > 0 ? v : 120_000;
46
46
  }
47
+ /**
48
+ * 요청 시작부터 본문 수신 완료까지 같은 제한시간·네트워크 오류 계약을 적용한다.
49
+ * 헤더를 받은 뒤에도 연결 중단·타임아웃이 날 수 있으므로 본문 읽기를 함께 감싼다.
50
+ * 이력: document/90-process/work-log/261022 Odyssey CLI 배포 안정성 npm watch 감시 에이전트 감사.md
51
+ */
52
+ export async function fetchText(url, init, server) {
53
+ try {
54
+ const response = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs()) });
55
+ const body = await response.text();
56
+ return { response, body };
57
+ }
58
+ catch (e) {
59
+ throw new NetworkError(describeFetchError(e, server));
60
+ }
61
+ }
47
62
  /** SSE 본문에서 JSON 메시지들을 꺼낸다. 이벤트 경계=빈 줄, 여러 data 줄은 \n 으로 잇는다. */
48
63
  export function parseSseMessages(body) {
49
64
  const out = [];
@@ -117,19 +132,11 @@ export async function postRpc(opts, method, params) {
117
132
  }
118
133
  if (opts.userAgent)
119
134
  headers['User-Agent'] = opts.userAgent;
120
- let res;
121
- try {
122
- res = await fetch(endpointUrl(opts.server), {
123
- method: 'POST',
124
- headers,
125
- body: JSON.stringify({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) }),
126
- signal: AbortSignal.timeout(timeoutMs()),
127
- });
128
- }
129
- catch (e) {
130
- throw new NetworkError(describeFetchError(e, opts.server));
131
- }
132
- const body = await res.text();
135
+ const { response: res, body } = await fetchText(endpointUrl(opts.server), {
136
+ method: 'POST',
137
+ headers,
138
+ body: JSON.stringify({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) }),
139
+ }, opts.server);
133
140
  if (!res.ok) {
134
141
  throw new HttpError(res.status, errorMessageFromBody(body), res.headers.get('www-authenticate') ?? undefined);
135
142
  }
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
+ }