@odyssey365/cli 0.2.1 → 0.2.3

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
@@ -20,19 +20,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';
23
- import { extractGlobals, parseToolArgs, takeFlag } from './args.js';
23
+ import { extractGlobals, parseToolArgs, takeFlag, takeIntOption } from './args.js';
24
24
  import { discover, fetchUserInfo, interactiveLogin, registerClient, revokeTokenRemote } from './oauth.js';
25
25
  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';
29
+ import { collectLocalFiles, inlineImageFiles, uploadLocalFiles } from './files.js';
30
30
  import { renderAgentGuide, renderSkill, renderSnippet } from './guide.js';
31
31
  import { cmdWatch, WATCH_HELP } from './watch.js';
32
32
  import { cmdWatchAgent, WATCH_AGENT_HELP } from './watch-agent.js';
33
33
  const __dirname = dirname(fileURLToPath(import.meta.url));
34
34
  const VERSION = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')).version;
35
- const HELP = `Odyssey CLI v${VERSION} — Odyssey 계정의 할일·메모·보드·스냅샷을 터미널과 AI 에이전트에서 다룬다.
35
+ const HELP = `Odyssey CLI v${VERSION} — Odyssey 계정의 할일·메모·보드·페이지를 터미널과 AI 에이전트에서 다룬다.
36
36
 
37
37
  AI 에이전트라면 먼저: odyssey agent-guide (사용법·로그인된 계정·서버 사용 지침)
38
38
 
@@ -51,14 +51,19 @@ AI 에이전트라면 먼저: odyssey agent-guide (사용법·로그인된 계
51
51
 
52
52
  실시간 감시
53
53
  odyssey watch-agent init <폴더> 감시 에이전트 예제를 새 폴더에 준비(설정·검사 포함)
54
- odyssey watch [--tag 태그 ...] 내 할일(태그)·내 댓글 변화를 한 줄에 JSON 하나씩(NDJSON) 흘린다
54
+ odyssey watch [--tag 태그 ...] 내 할일(태그)·내 댓글·관심 스레드 변화를 한 줄에 JSON 하나씩(NDJSON) 흘린다
55
55
  자세히: odyssey watch --help
56
+ odyssey threads [list] 관심 스레드 목록(에이전트가 댓글을 남긴 스레드는 자동으로 오른다)
57
+ odyssey threads follow|unfollow ... 관심 스레드 올리기·빼기 (--itemType · --itemUid · --projectId | --roomUid)
58
+ follow --days N: 감시 기간(일, 1~365 · 기본 14 — 뒤의 자동 등록도 이 기간으로)
59
+ 빼기는 마지막 답글 뒤에(뺀 뒤 댓글을 달면 다시 오른다) · 할일 완료로는 안 빠진다
56
60
 
57
61
  AI 에이전트
58
62
  odyssey agent-guide 에이전트용 설명서(사용법 + 계정 + 서버 사용 지침 실시간)
59
63
  odyssey agent-guide --skill Claude Code·Codex 스킬 파일(SKILL.md) 내용
60
64
  odyssey agent-guide --snippet AGENTS.md·CLAUDE.md·GEMINI.md 에 붙일 짧은 절
61
65
  odyssey agent-guide --watch-agent 감시 에이전트(watch → 세션 깨우기, 답글은 세션이)를 만들게 하는 프롬프트
66
+ odyssey agent-guide --design 에이전트 설계 사례집(감시 에이전트 해부 · 관심 스레드 · 변형 · 제안서 견본)
62
67
 
63
68
  전역 옵션
64
69
  -p, --profile <이름> 이번 실행의 계정. 기본: ODYSSEY_PROFILE → odyssey use 값 → default
@@ -160,6 +165,8 @@ async function cmdLogin(g, args) {
160
165
  credential = { type: 'apiKey', apiKey: key };
161
166
  const probe = new OdysseyClient({ profileName: name, server, profile: { server, credential, savedAt: '' } }, VERSION);
162
167
  await probe.ping();
168
+ // 키 주인 계정 — 구버전 서버는 키 신원을 몰라 비워 둔다(whoami 가 나중에 채운다).
169
+ account = (await probe.userInfo()) ?? undefined;
163
170
  }
164
171
  else {
165
172
  err(`프로필 "${name}" 로그인 — ${server}`);
@@ -250,13 +257,16 @@ async function cmdWhoami(g, args) {
250
257
  const client = new OdysseyClient(target, VERSION);
251
258
  const cred = target.profile?.credential;
252
259
  let account = target.profile?.account;
253
- if (cred?.type === 'oauth') {
254
- const info = await client.userInfo();
255
- if (!info)
256
- throw new AuthRequiredError(`프로필 "${target.profileName}" 의 로그인이 풀렸습니다. 다시 로그인: odyssey login${profileFlag(target.profileName)}`);
260
+ const info = await client.userInfo();
261
+ if (cred?.type === 'oauth' && !info) {
262
+ throw new AuthRequiredError(`프로필 "${target.profileName}" 의 로그인이 풀렸습니다. 다시 로그인: odyssey login${profileFlag(target.profileName)}`);
263
+ }
264
+ if (info) {
257
265
  account = info;
266
+ rememberAccount(target.profileName, info);
258
267
  }
259
268
  else {
269
+ // 키 신원을 모르는 구버전 서버 — 자격이 살아 있는지만 본다.
260
270
  await client.ping();
261
271
  }
262
272
  const after = target.profile?.credential;
@@ -271,6 +281,17 @@ async function cmdWhoami(g, args) {
271
281
  });
272
282
  return 0;
273
283
  }
284
+ /** whoami 가 확인한 계정을 프로필에 남긴다 — 예전에 저장한 API 키 프로필도 profiles 에 계정이 보이게. */
285
+ function rememberAccount(profileName, info) {
286
+ if (!profileName)
287
+ return;
288
+ updateCredentials((file) => {
289
+ const p = file.profiles[profileName];
290
+ if (!p || (p.account?.uid === info.uid && p.account?.email === info.email))
291
+ return;
292
+ p.account = info;
293
+ });
294
+ }
274
295
  function cmdProfiles(g, args) {
275
296
  if (args.length)
276
297
  throw new UsageError(`profiles 가 모르는 인자: ${args.join(' ')}`);
@@ -294,7 +315,10 @@ function cmdProfiles(g, args) {
294
315
  const width = Math.max(...entries.map(([n]) => n.length));
295
316
  for (const [name, p] of entries) {
296
317
  const mark = file.defaultProfile === name ? '*' : ' ';
297
- const who = p.account ? `${p.account.email ?? '(이메일 없음)'} ${p.account.uid}` : '(API 키)';
318
+ const key = p.credential.type === 'apiKey';
319
+ const who = p.account
320
+ ? `${p.account.email ?? '(이메일 없음)'} ${p.account.uid}${key ? ' (API 키)' : ''}`
321
+ : '(API 키 — 계정 확인: odyssey whoami)';
298
322
  const server = normalizeServer(p.server) === DEFAULT_SERVER ? '' : ` ${p.server}`;
299
323
  process.stdout.write(`${mark} ${name.padEnd(width)} ${who}${server}\n`);
300
324
  }
@@ -320,8 +344,15 @@ async function cmdAgentGuide(g, args) {
320
344
  const skill = takeFlag(args, '--skill');
321
345
  const snippet = takeFlag(args, '--snippet');
322
346
  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]');
347
+ const design = takeFlag(args, '--design');
348
+ if (args.length || [skill, snippet, watchAgent, design].filter(Boolean).length > 1) {
349
+ throw new UsageError('사용법: odyssey agent-guide [--skill | --snippet | --watch-agent | --design]');
350
+ }
351
+ // 설계 사례집 — 새 에이전트를 만들기 전에 읽는 결정·이유 모음(패키지의 prompts/agent-design.md 그대로).
352
+ // 이력: document/90-process/work-log/261101 Odyssey CLI 0.2.2 설계 사례집 agent-guide design 관심 스레드 안내.md
353
+ if (design) {
354
+ process.stdout.write(readFileSync(join(__dirname, '..', 'prompts', 'agent-design.md'), 'utf-8'));
355
+ return 0;
325
356
  }
326
357
  // 감시 에이전트(디스패처)를 코딩 에이전트에게 만들게 하는 프롬프트 — 패키지의 prompts/watch-agent.md 그대로.
327
358
  // 이력: document/90-process/work-log/261016 Odyssey CLI 감시 에이전트 만들기 프롬프트 watch-agent.md
@@ -396,11 +427,44 @@ async function cmdDescribe(g, args) {
396
427
  process.stdout.write(renderToolDetail(tool) + '\n');
397
428
  return 0;
398
429
  }
399
- async function cmdCall(g, toolName, tokens) {
430
+ /**
431
+ * 로컬 사진 경로를 서버 업로드 주소로 올리고 그 자리를 `{ uploadId, index }` 로 바꾼다(files.ts 머리말).
432
+ * 업로드 주소(create_upload_url)를 모르는 옛 서버면 스냅샷 사진(image.file)만 예전처럼 base64 로 싣는다.
433
+ * 이력: document/90-process/work-log/261028 MCP CLI 사진 올리기 업로드 주소 업로드 링크 create_upload_url.md
434
+ */
435
+ async function attachLocalFiles(client, args, baseDir) {
436
+ if (collectLocalFiles(args, baseDir).slots.length === 0)
437
+ return;
438
+ try {
439
+ await findTool(client, 'create_upload_url');
440
+ }
441
+ catch (e) {
442
+ if (!(e instanceof UsageError))
443
+ throw e;
444
+ inlineImageFiles(args, baseDir);
445
+ return;
446
+ }
447
+ await uploadLocalFiles(args, baseDir, {
448
+ // 사진만이면 종전 모양 그대로 보낸다 — accept 를 모르는 옛 서버도 받는다.
449
+ create: async (maxFiles, accept) => {
450
+ const r = (await client.callTool('create_upload_url', accept === 'files' ? { maxFiles, accept } : { maxFiles }));
451
+ const uploadId = r?.structuredContent?.uploadId;
452
+ if (r?.isError || typeof uploadId !== 'string') {
453
+ throw new UsageError(`업로드 주소를 받지 못했습니다: ${r?.content?.map((c) => c.text ?? '').join(' ') || '응답 없음'}`);
454
+ }
455
+ return { uploadId };
456
+ },
457
+ post: (uploadId, bytes, name) => client.postUpload(uploadId, bytes, name),
458
+ });
459
+ }
460
+ async function cmdCall(g, toolName, tokens,
461
+ /** 명령이 미리 형을 맞춘 파라미터(threads follow --days) — 플래그 해석 뒤에 덮는다. */
462
+ extra = {}) {
400
463
  const client = new OdysseyClient(resolveTarget(g), VERSION);
401
464
  const tool = await findTool(client, toolName, { refresh: g.refreshTools });
402
465
  const base = await readInputObject(g);
403
466
  const { args, positionals } = parseToolArgs(tokens, tool.inputSchema, base);
467
+ Object.assign(args, extra);
404
468
  if (positionals.length) {
405
469
  const req = tool.inputSchema?.required ?? [];
406
470
  throw new UsageError(`${tool.name} 에 위치 인자 ${positionals.map((p) => JSON.stringify(p)).join(' ')} 를 둘 자리가 없습니다.` +
@@ -414,14 +478,24 @@ async function cmdCall(g, toolName, tokens) {
414
478
  (missing.length === 1 && (tool.inputSchema?.required ?? []).length === 1 ? ' (위치 인자로도 됩니다)' : '') +
415
479
  `\n자세히: odyssey describe ${tool.name}`);
416
480
  }
417
- // 사진 칸의 로컬 파일(image.file)을 바이트로 바꿔 싣는다 — 상대 경로는 --input 파일 옆 기준.
481
+ // 로컬 사진 경로(image.file · uploadImages[].file · files)를 올려 업로드 번호로 바꾼다 — 상대 경로는 --input 파일 옆 기준.
418
482
  const baseDir = g.inputFile && g.inputFile !== '-' ? dirname(resolvePath(g.inputFile)) : process.cwd();
419
- inlineImageFiles(args, baseDir);
483
+ await attachLocalFiles(client, args, baseDir);
420
484
  const result = await client.callTool(tool.name, args);
421
485
  return printToolResult(result, g.output ?? 'json', tool.name);
422
486
  }
423
487
  // ── 진입 ─────────────────────────────────────────────────────────────────────
424
488
  const ACCOUNT_COMMANDS = new Set(['login', 'logout', 'whoami', 'profiles', 'use', 'agent-guide', 'watch', 'watch-agent']);
489
+ /**
490
+ * 관심 스레드 — 서버 도구의 짧은 이름. 도구 그대로 불러도 된다(odyssey follow_thread …).
491
+ * 이력: document/90-process/work-log/261029 Odyssey CLI 관심 스레드 followed_thread watch 자동 등록.md
492
+ */
493
+ const THREADS_TOOLS = {
494
+ list: 'list_followed_threads',
495
+ follow: 'follow_thread',
496
+ unfollow: 'unfollow_thread',
497
+ };
498
+ const THREADS_USAGE = '사용법: odyssey threads [list | follow [--days N] | unfollow] [--파라미터 값 ...]';
425
499
  async function main(argv) {
426
500
  const { globals: g, rest } = extractGlobals(argv);
427
501
  if (g.profile !== undefined)
@@ -445,6 +519,12 @@ async function main(argv) {
445
519
  process.stdout.write(`${WATCH_AGENT_HELP}\n`);
446
520
  return 0;
447
521
  }
522
+ if (g.help && command === 'threads') {
523
+ const tool = THREADS_TOOLS[args[0] ?? 'list'];
524
+ if (!tool)
525
+ throw new UsageError(THREADS_USAGE);
526
+ return cmdDescribe(g, [tool]);
527
+ }
448
528
  if (g.help) {
449
529
  // odyssey <도구> --help → 그 도구 설명
450
530
  if (!ACCOUNT_COMMANDS.has(command) && command !== 'tools' && command !== 'describe' && command !== 'call') {
@@ -470,6 +550,16 @@ async function main(argv) {
470
550
  return cmdWatch(g, args, VERSION);
471
551
  case 'watch-agent':
472
552
  return cmdWatchAgent(g, args);
553
+ case 'threads': {
554
+ const [sub = 'list', ...tokens] = args;
555
+ const tool = THREADS_TOOLS[sub];
556
+ if (!tool)
557
+ throw new UsageError(THREADS_USAGE);
558
+ // follow --days N 은 여기서 정수로 맞춰 넘긴다 — 캐시된 도구 목록(6시간)이 days 를 모르는 판이면 플래그 해석이
559
+ // "30"(문자열)로 보내 서버 zod 가 거절한다. 범위(1~365)는 서버가 본다. 이력: 261031 follow 기간 지정(D790)
560
+ const days = sub === 'follow' ? takeIntOption(tokens, '--days') : undefined;
561
+ return cmdCall(g, tool, tokens, days === undefined ? {} : { days });
562
+ }
473
563
  case 'tools':
474
564
  return cmdTools(g, args);
475
565
  case 'describe':
package/dist/session.js CHANGED
@@ -159,8 +159,8 @@ export class OdysseyClient {
159
159
  }
160
160
  /**
161
161
  * Firebase 세션 교환(`POST /cli/firebase-session`) — `odyssey watch` 가 Firestore 를 직접 감시할 때 쓴다.
162
- * CLI 로그인(OAuth) → Firebase 커스텀 토큰 + App Check 토큰 + 웹 앱 설정. 401 이면 한 번 갱신해 다시 묻는다.
163
- * API 키 프로필은 서버가 403 으로 거절한다(앱 수준 세션으로 바꿔 주지 않는다).
162
+ * CLI 자격(OAuth · API 키) → Firebase 커스텀 토큰 + App Check 토큰 + 웹 앱 설정. 401 이면 한 번 갱신해 다시 묻는다.
163
+ * API 키는 서버 261028+ 부터 받는다 — 폐기한 키는 403(새 교환만 막고, 돌던 감시는 rules 유예 1시간까지 간다).
164
164
  * 이력: document/90-process/work-log/261016 Odyssey CLI 스트림 odyssey watch 토큰 교환 Firestore 직접 감시.md
165
165
  */
166
166
  async firebaseSession() {
@@ -199,10 +199,13 @@ export class OdysseyClient {
199
199
  async ping() {
200
200
  await this.request('ping');
201
201
  }
202
- /** OAuth 프로필의 신원(/userinfo). 401 이면 한 번 갱신해 다시 묻는다. API 키·환경변수 토큰은 null. */
202
+ /**
203
+ * 이 자격의 신원(/userinfo). OAuth 는 401 이면 한 번 갱신해 다시 묻는다.
204
+ * API 키·환경변수 토큰도 묻는다 — 키 신원을 모르는 구버전 서버(261028 전)면 null.
205
+ * 이력: document/90-process/work-log/261028 Odyssey CLI API 키 감시 whoami 신원 앱 안내.md
206
+ */
203
207
  async userInfo() {
204
- const cred = this.target.profile?.credential;
205
- if (this.target.envToken || !cred || cred.type !== 'oauth')
208
+ if (!this.target.envToken && !this.target.profile)
206
209
  return null;
207
210
  const meta = await discover(this.target.server);
208
211
  let info = await fetchUserInfo(this.target.server, meta, await this.bearer());
@@ -244,4 +247,29 @@ export class OdysseyClient {
244
247
  async callTool(name, args) {
245
248
  return this.request('tools/call', { name, arguments: args });
246
249
  }
250
+ /**
251
+ * 사진 한 장을 업로드 주소(`POST /upload/{uploadId}`)로 보낸다 — 주소가 곧 자격이라 Bearer 를 싣지 않는다.
252
+ * 주소는 서버가 준 도메인이 아니라 **이 프로필의 서버**로 잡는다(로컬·스테이징 서버에서도 같은 곳으로).
253
+ * 응답의 index 가 그 주소 안 사진 번호다.
254
+ * 이력: document/90-process/work-log/261028 MCP CLI 사진 올리기 업로드 주소 업로드 링크 create_upload_url.md
255
+ */
256
+ async postUpload(uploadId, bytes, name) {
257
+ const server = this.target.server.replace(/\/+$/, '');
258
+ const { response: res, body } = await fetchText(`${server}/upload/${encodeURIComponent(uploadId)}?name=${encodeURIComponent(name)}`, {
259
+ method: 'POST',
260
+ headers: { 'Content-Type': 'application/octet-stream', 'User-Agent': this.userAgent },
261
+ body: new Uint8Array(bytes),
262
+ }, this.target.server);
263
+ let parsed = {};
264
+ try {
265
+ parsed = JSON.parse(body);
266
+ }
267
+ catch {
268
+ // 비 JSON 오류 본문 — 아래에서 상태 코드로 안내한다.
269
+ }
270
+ if (res.status === 200 && typeof parsed.index === 'number')
271
+ return parsed.index;
272
+ const reason = typeof parsed.message === 'string' ? parsed.message : String(parsed.error ?? res.status);
273
+ throw new HttpError(res.status, `올리기 실패(${res.status}) ${name}: ${reason}`);
274
+ }
247
275
  }
@@ -12,7 +12,146 @@
12
12
  *
13
13
  * 이력: document/90-process/work-log/261016 Odyssey CLI 스트림 odyssey watch 토큰 교환 Firestore 직접 감시.md
14
14
  * 이력: document/90-process/work-log/261018 감시 에이전트 멘션 깨우기 @클로드코드 launchd 상시 실행.md
15
+ *
16
+ * 관심 스레드(`user/{uid}/followed_thread/{room}`) — 에이전트가 말한 방. 그 방의 새 댓글은 누가 썼든
17
+ * followed:true 로 나가고(남이 쓴 것은 author 'other'), 답글이면 원 댓글의 작성자를 replyTo 에 싣는다.
18
+ * 이력: document/90-process/work-log/261029 Odyssey CLI 관심 스레드 followed_thread watch 자동 등록.md
19
+ *
20
+ * 태그 항목의 방 — `--tag` 가 걸린 내 할일·메모·프로젝트(+그 보드의 카드)·리포트의 댓글방. 태그가 곧 관심 표시라
21
+ * 등록·만료가 없고, 태그를 떼면 바로 빠진다. 그 방의 댓글은 tagged:true 로 나간다.
22
+ * 이력: document/90-process/work-log/261029 Odyssey CLI 감시 태그 항목 스레드 할일 메모 프로젝트 리포트 itemTags.md
23
+ */
24
+ /** 한 감시가 귀를 대는 관심 스레드 수 상한 — 방마다 리스너 하나라서. */
25
+ export const FOLLOWED_LISTEN_LIMIT = 100;
26
+ function millisOf(v) {
27
+ const iso = toIso(v);
28
+ return iso ? Date.parse(iso) : null;
29
+ }
30
+ /** 지금 귀를 댈 관심 스레드 — 만료 안 된 것 중 최근 에이전트 활동 순으로 [limit] 개. */
31
+ export function activeFollowedRooms(docs, now, limit = FOLLOWED_LISTEN_LIMIT) {
32
+ return [...docs.entries()]
33
+ .filter(([, d]) => (millisOf(d.expiresAt) ?? 0) > now)
34
+ .sort(([, a], [, b]) => (millisOf(b.lastAgentAt) ?? 0) - (millisOf(a.lastAgentAt) ?? 0))
35
+ .slice(0, limit)
36
+ .map(([id]) => id);
37
+ }
38
+ export function threadEvent(change, id, d, initial, reason) {
39
+ return {
40
+ type: 'thread',
41
+ change,
42
+ initial,
43
+ roomUid: str(d.roomUid) ?? id,
44
+ itemType: str(d.itemType),
45
+ itemUid: str(d.itemUid),
46
+ itemOwnerUid: str(d.itemOwnerUid),
47
+ parentItemUid: str(d.parentItemUid),
48
+ source: d.source === 'manual' ? 'manual' : 'auto',
49
+ expiresAt: toIso(d.expiresAt),
50
+ ...(reason ? { reason } : {}),
51
+ };
52
+ }
53
+ export const TAG_SOURCES = [
54
+ { itemType: 'todo', collection: 'todo', tagField: 'tags', rooms: [{ itemType: 'todo', keyField: 'itemUid' }] },
55
+ { itemType: 'memo', collection: 'memo', tagField: 'tags', rooms: [{ itemType: 'memo', keyField: 'itemUid' }] },
56
+ {
57
+ itemType: 'project',
58
+ collection: 'project',
59
+ tagField: 'tags',
60
+ rooms: [
61
+ { itemType: 'project', keyField: 'itemUid' },
62
+ { itemType: 'projectComponent', keyField: 'parentItemUid' },
63
+ ],
64
+ },
65
+ // 리포트의 `tags` 는 만들 때 건 **필터**라 항목 태그는 `itemTags` 에 따로 둔다(domain CompanionReportModel).
66
+ {
67
+ itemType: 'companionReport',
68
+ collection: 'companion_report',
69
+ tagField: 'itemTags',
70
+ rooms: [{ itemType: 'companionReport', keyField: 'itemUid' }],
71
+ },
72
+ ];
73
+ /** Firestore `in` 한도 — 방 찾기 쿼리 하나가 거는 항목 uid 수. */
74
+ export const ROOM_QUERY_IN_LIMIT = 30;
75
+ /** 한 감시가 귀를 대는 태그 항목 방 수 상한 — 최근 댓글 순으로 남긴다(방마다 리스너 하나). */
76
+ export const TAGGED_LISTEN_LIMIT = 200;
77
+ /** 태그 키 — 방을 그 방을 만든 항목으로 되짚는다. 보드 카드 방은 그 보드(카드 자체엔 태그가 없다). */
78
+ export function roomTagKey(room) {
79
+ const t = str(room.itemType);
80
+ if (t === 'projectComponent') {
81
+ const p = str(room.parentItemUid);
82
+ return p ? `project/${p}` : null;
83
+ }
84
+ const u = str(room.itemUid);
85
+ return t && u ? `${t}/${u}` : null;
86
+ }
87
+ /** 내 항목의 방이고 그 항목에 감시 태그가 걸려 있나. 남의 항목(공유 보드의 남의 할일)은 내 태그와 무관하다. */
88
+ export function isTaggedRoom(room, taggedKeys, ownerUid) {
89
+ if (!room || str(room.itemOwnerUid) !== ownerUid)
90
+ return false;
91
+ const key = roomTagKey(room);
92
+ return key !== null && taggedKeys.has(key);
93
+ }
94
+ /** 지금 귀를 댈 태그 항목 방 — 태그가 걸린 내 항목의 방 중 최근 댓글 순으로 [limit] 개. */
95
+ export function activeTaggedRooms(docs, taggedKeys, ownerUid, limit = TAGGED_LISTEN_LIMIT) {
96
+ const at = (d) => millisOf(d.lastMessageAt) ?? millisOf(d.updatedAt) ?? millisOf(d.createdAt) ?? 0;
97
+ return [...docs.entries()]
98
+ .filter(([, d]) => isTaggedRoom(d, taggedKeys, ownerUid))
99
+ .sort(([, a], [, b]) => at(b) - at(a))
100
+ .slice(0, limit)
101
+ .map(([id]) => id);
102
+ }
103
+ /**
104
+ * 항목 uid 를 [size] 개씩 묶은 칸 — 칸 하나가 방 찾기 쿼리 하나(`in`)다. 한 uid 가 들고 날 때 **그 칸만** 다시
105
+ * 구독하도록 남은 uid 의 자리를 지킨다(전부 다시 나누면 태그 하나 달 때마다 모든 쿼리가 새로 붙는다).
15
106
  */
107
+ export class InChunks {
108
+ size;
109
+ chunks = [];
110
+ slot = new Map();
111
+ constructor(size = ROOM_QUERY_IN_LIMIT) {
112
+ this.size = size;
113
+ }
114
+ /** [want] 로 맞추고 내용이 바뀐 칸 번호를 돌려준다(빈 칸 = 그 쿼리를 내린다). */
115
+ sync(want) {
116
+ const changed = new Set();
117
+ for (const [id, i] of [...this.slot]) {
118
+ if (want.has(id))
119
+ continue;
120
+ this.chunks[i].splice(this.chunks[i].indexOf(id), 1);
121
+ this.slot.delete(id);
122
+ changed.add(i);
123
+ }
124
+ for (const id of want) {
125
+ if (this.slot.has(id))
126
+ continue;
127
+ let i = this.chunks.findIndex((c) => c.length < this.size);
128
+ if (i < 0)
129
+ i = this.chunks.push([]) - 1;
130
+ this.chunks[i].push(id);
131
+ this.slot.set(id, i);
132
+ changed.add(i);
133
+ }
134
+ return [...changed].sort((a, b) => a - b);
135
+ }
136
+ get(i) {
137
+ return this.chunks[i] ?? [];
138
+ }
139
+ }
140
+ export function tagThreadEvent(change, roomUid, room, initial, reason) {
141
+ return {
142
+ type: 'thread',
143
+ change,
144
+ initial,
145
+ roomUid,
146
+ itemType: str(room.itemType),
147
+ itemUid: str(room.itemUid),
148
+ itemOwnerUid: str(room.itemOwnerUid),
149
+ parentItemUid: str(room.parentItemUid),
150
+ source: 'tag',
151
+ expiresAt: null,
152
+ ...(reason ? { reason } : {}),
153
+ };
154
+ }
16
155
  /** Firestore Timestamp(toDate) · {seconds,nanoseconds} · Date · ISO 문자열 → ISO. 모르면 null. */
17
156
  export function toIso(value) {
18
157
  if (value == null)
@@ -50,27 +189,35 @@ export function todoEvent(change, id, data, initial) {
50
189
  updatedAt: toIso(d.updatedAt),
51
190
  };
52
191
  }
53
- export function commentAuthor(data) {
192
+ /** [ownerUid] 를 주면 사람 댓글 중 주인 아닌 사람(senderUid 다름)을 other 로 가른다. */
193
+ export function commentAuthor(data, ownerUid) {
54
194
  const meta = data.metadata;
55
195
  // 사람 댓글에는 표식이 없다. 알 수 없는 값도 지시로 승격하지 않는다.
56
196
  // 이력: document/90-process/work-log/261022 Odyssey CLI 자격 회수 CLI 전용 신원 companion 댓글 분류.md
57
- return meta?.authorKind == null || meta.authorKind === '' ? 'me' : 'agent';
197
+ if (meta?.authorKind != null && meta.authorKind !== '')
198
+ return 'agent';
199
+ return ownerUid && typeof data.senderUid === 'string' && data.senderUid !== ownerUid ? 'other' : 'me';
58
200
  }
59
201
  /** 지운 댓글·숨긴 댓글은 이벤트로 내보내지 않는다. */
60
202
  export function isLiveComment(data) {
61
203
  return data.isDeleted !== true && data.isBlocked !== true;
62
204
  }
63
- export function commentEvent(id, data, room) {
205
+ export function commentEvent(id, data, room, extra = {}) {
206
+ const replyId = str(data.replyToMessageUid);
64
207
  return {
65
208
  type: 'comment',
66
- author: commentAuthor(data),
209
+ author: commentAuthor(data, extra.ownerUid),
67
210
  commentUid: str(data.uid) ?? id,
68
211
  roomUid: str(data.chatRoomUid),
69
212
  itemType: str(room?.itemType),
70
213
  itemUid: str(room?.itemUid),
71
214
  itemOwnerUid: str(room?.itemOwnerUid),
72
215
  parentItemUid: str(room?.parentItemUid),
73
- replyToCommentUid: str(data.replyToMessageUid),
216
+ replyToCommentUid: replyId,
217
+ replyTo: replyId ? { commentUid: replyId, author: extra.replyToAuthor ?? null } : null,
218
+ followed: extra.followed === true,
219
+ tagged: extra.tagged === true,
220
+ senderUid: str(data.senderUid),
74
221
  text: typeof data.content === 'string' ? data.content : '',
75
222
  kind: str(data.type),
76
223
  createdAt: toIso(data.createdAt),