@odyssey365/cli 0.2.2 → 0.2.4

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.
@@ -1,110 +1,93 @@
1
- # Odyssey 감시 에이전트 예제
1
+ # Odyssey 세션 듣기 예제
2
2
 
3
- > `@odyssey365/cli` **0.2.0+** · 감시는 CLI 로그인 프로필(브라우저 로그인 또는 API 키 `--with-key`)이 필요합니다.
3
+ > `@odyssey365/cli` **0.2.4+** · 감시는 CLI 로그인 프로필(브라우저 로그인 또는 API 키 `--with-key`)이 필요합니다.
4
4
 
5
- Odyssey에서 태그나 댓글로 맡긴 일을 Claude Code에 전달하는 실행 가능한 예제입니다.
6
- 할일·항목마다 세션 하나를 만들고, 이후 댓글은 같은 세션으로 이어 받습니다.
7
- 대기 중에는 모델을 부르지 않습니다. 컴퓨터가 켜져 있고 이 프로그램이 실행 중이어야 받습니다.
5
+ Odyssey에서 태그나 댓글로 맡긴 일을 **지금 일하고 있는 코딩 에이전트 세션**(예: Claude Code)이 직접 받는 예제입니다.
6
+ `listen.mjs`는 `odyssey watch`를 걸러 세션을 깨울 일만 한 줄 JSON으로 냅니다. 판단·작업·답글은 그 세션이 합니다.
7
+ 기다리는 동안 모델을 부르지 않습니다. 세션이 열려 있고 컴퓨터가 깨어 있을 때만 받고, 다시 켜면 밀린 것부터 받습니다.
8
+
9
+ 일하는 세션이 앱의 세션 목록에 그대로 보이고, 권한도 그 세션의 설정을 따릅니다. 따로 상주 프로그램·자동 시작·일꾼 권한 목록을 돌보지 않습니다.
8
10
 
9
11
  ## 처음 시작하기
10
12
 
11
- Node.js 20 이상, 로그인한 Odyssey CLI(브라우저 로그인 또는 앱에서 만든 API 키), 로그인한 Claude Code가 필요합니다.
13
+ Node.js 20 이상, 로그인한 Odyssey CLI, Odyssey 도구(MCP 커넥터 또는 `odyssey` CLI)를 쓰는 코딩 에이전트가 필요합니다.
12
14
 
13
15
  ```sh
14
16
  npm install -g @odyssey365/cli
15
- odyssey --version # 0.2.0+
17
+ odyssey --version # 0.2.4+
16
18
  odyssey login
17
19
  odyssey whoami
18
20
  ```
19
21
 
20
- 실제로 작업할 프로젝트 폴더에서 예제를 준비합니다. **새 폴더**를 지정하세요. 기존 폴더는 덮어쓰지 않습니다.
22
+ 작업할 프로젝트 폴더에서 예제를 **새 폴더**에 꺼냅니다. 기존 폴더는 덮어쓰지 않습니다.
21
23
 
22
24
  ```sh
23
25
  cd /path/to/my-project
24
- odyssey watch-agent init ../my-watch-agent
25
- cd ../my-watch-agent
26
+ odyssey watch-agent init ../odyssey-listen
26
27
  ```
27
28
 
28
- 생성된 `config.json`의 `workDir`은 명령을 실행한 프로젝트 폴더입니다.
29
- `odysseyBin`에는 설치한 CLI의 JS 경로를 넣으므로 전역 npm 명령의 위치를 다시 찾을 필요가 없습니다.
30
- 프로필을 고르려면 생성할 때 `-p work`를 붙입니다. 자격증명·토큰은 복사하지 않습니다.
31
-
32
- Claude Code의 Odyssey MCP도 **작업할 프로젝트 폴더에서 같은 계정으로** 연결하세요.
33
- 이미 연결했다면 다시 추가할 필요가 없습니다. 새 연결은 다음 명령으로 등록하고 Claude Code를 열어 `/mcp`에서 로그인합니다.
29
+ `config.json`의 `odysseyBin`에는 설치한 CLI의 JS 경로, `odysseyProfile`에는 고른 프로필(`-p work`)이 들어갑니다. 자격증명·토큰은 복사하지 않습니다.
30
+ 세션이 쓰는 Odyssey 도구도 **같은 계정**이어야 합니다. Claude Code라면 프로젝트 폴더에서 한 번 연결해 둡니다(이미 있으면 그대로).
34
31
 
35
32
  ```sh
36
- cd /path/to/my-project
37
33
  claude mcp add --transport http odyssey https://mcp-odyssey30-60.odyssey365.app
38
- claude
39
34
  ```
40
35
 
41
- Claude Code에서 Odyssey 계정·카테고리 등 읽기 작업을 한 번 확인한 후 예제 폴더로 돌아옵니다.
42
- CLI 로그인과 MCP 로그인은 별개입니다. `--check`는 MCP 등록을 확인하며 두 로그인 계정의 일치까지 증명하지 않습니다.
36
+ 확인은 모델을 부르지 않습니다.
43
37
 
44
38
  ```sh
45
- node dispatcher.mjs --check
46
- node dispatcher.mjs --dry-run
39
+ node ../odyssey-listen/listen.mjs --check # CLI 계정 uid — config.json 의 expectedUid 에 넣으면 다른 계정 감시를 막는다
40
+ node ../odyssey-listen/listen.mjs --dry-run # 밀린 태그 할일 중 무엇이 세션을 깨울지(상태를 쓰지 않는다)
47
41
  ```
48
42
 
49
- `--check`는 모델을 부르지 않고 CLI 로그인 계정(uid)·Claude Code 설치·MCP 등록을 확인합니다.
50
- `--dry-run`은 실제 감시를 연결하지만 일꾼을 깨우거나 댓글을 쓰지 않습니다. 로그에서 `ready`와 배달 예정을 확인하고 Ctrl+C로 끕니다.
51
- 시험할 할일 하나에 `클로드 코드` 태그를 붙이거나 메모에 `@클로드코드` 댓글을 써서 배달 예정이 나오는지 보세요.
43
+ ## 세션에서 듣기
52
44
 
53
- 검사가 끝났으면 실제 모드를 켭니다.
45
+ 프로젝트 폴더의 코딩 에이전트 세션에게 이렇게 말합니다.
54
46
 
55
- ```sh
56
- node dispatcher.mjs
57
- ```
47
+ > `odyssey agent-guide --watch-agent` 를 읽고, `../odyssey-listen/listen.mjs` 로 들어.
58
48
 
59
- 시험 항목의 작은 일 하나부터 맡기세요. 일꾼이 남긴 질문에 댓글로 답하면 같은 세션으로 이어 받습니다.
60
- 처음 켤 때 태그가 달린 미시작 할일도 처리 대상입니다. 실제 모드는 댓글·항목을 읽고 수정하며 모델 사용량이 발생합니다.
61
- 기본 파일 편집 권한은 `acceptEdits`, 셸 명령은 허용한 패턴만 자동 승인합니다.
49
+ 세션은 그 문서(듣기 규칙 — 깨어나면 무엇을 읽고 어디에 답하나)를 따라 듣기를 띄웁니다. 장치는 둘입니다.
62
50
 
63
- ## 보통 바꾸는 설정
51
+ | | 백그라운드 종료(기본) | Monitor |
52
+ |---|---|---|
53
+ | 명령 | `node ../odyssey-listen/listen.mjs` 를 백그라운드로 | `node ../odyssey-listen/listen.mjs --stream` 을 Monitor 로 |
54
+ | 깨우는 것 | 이벤트를 내고 **끝나는 것** — 처리 뒤 다시 띄운다 | 이벤트 한 줄마다 알림 |
55
+ | 만료 | 없음 | 최대 30분 — 만료되면 다시 건다 |
56
+ | 맞는 때 | 하루 종일·밤새 | 잠깐 곁눈질 · 시험 |
57
+
58
+ 띄울 때마다 CLI 세션 발급이 1회 쓰입니다(하루 200). 오래 들을 땐 백그라운드 종료가 맞습니다.
59
+
60
+ 처음 켤 때 태그가 달린 미시작 할일도 일로 옵니다. `--dry-run`으로 먼저 보고, 받지 않을 것은 태그를 떼세요.
61
+ 시험은 작은 일 하나부터 — 할일에 `클로드 코드` 태그를 붙이거나, 메모에 앱에서 `@클로드코드 …` 댓글을 씁니다. 세션이 남긴 질문에 댓글로 답하면 같은 세션이 이어 받습니다.
64
62
 
65
- | 키 | 기본값·설명 |
63
+ ## 무엇이 깨우나
64
+
65
+ | 출력 `listen` | 언제 |
66
66
  |---|---|
67
- | `workDir` | 일꾼이 일할 프로젝트 폴더. `./`·`../`는 config.json 기준 |
68
- | `odysseyProfile` | `default`. `odyssey profiles`에서 확인 |
69
- | `expectedUid` | 생성 시 로컬에 알려진 계정 uid. 비어 있으면 `--check`의 uid를 넣을 수 있음 |
70
- | `claudeBin` | `claude`. PATH에 없으면 실행 파일 절대 경로 |
71
- | `odysseyMcpName` | `odyssey`. 작업 폴더의 `claude mcp list`에 보이는 이름 |
72
- | `watchTag` / `mentions` | `클로드 코드` / `@클로드코드`. 댓글 멘션의 공백·대소문자는 무시 |
73
- | `turnBudgetUsd` / `dailyBudgetUsd` | 턴 $1 / 하루 $5. Claude Code의 API 환산 사용량 기준 |
74
- | `allowedTools` | 추가로 자동 승인할 패턴. 예: `Bash(npm test:*)`, `Bash(git status:*)` |
75
- | `extraRules` | 일꾼에게 매번 전할 프로젝트 규칙 |
76
- | `readyTimeoutMs` | 시작·재연결 준비 대기 120초. 실패하면 백오프 후 재시작 |
77
-
78
- 하루 예산은 턴이 끝난 뒤 합산하므로 최대 한 턴 예산만큼 넘을 수 있습니다. 구독·API 청구액과 같은 값으로 간주하지 마세요.
79
- 태그 할일과 세션이 생긴 항목의 **내 댓글**이 후속 지시입니다. 다른 사람이 쓴 댓글과 에이전트 댓글은 일꾼을 깨우지 않습니다.
80
- 에이전트 답글에는 별도 작성자 표식이 붙어 자기 답에 다시 반응하는 일을 막습니다.
81
-
82
- ## 끄기·복구·상태
83
-
84
- - **끄기:** 실행 중인 터미널에서 Ctrl+C. 일꾼이 도는 중이면 끊고 다음 실행에서 이어 받습니다.
85
- - **다시 켜기:** 같은 폴더에서 `node dispatcher.mjs`. 마지막 배달 커서·세션·예산은 `state.json`에 남습니다.
86
- - **연결 복구:** 감시 프로세스 종료·리스너 error·ready 시간 초과를 받으면 5초부터 최대 5분까지 간격을 늘려 재시작합니다. 10분간 정상 연결된 뒤 간격을 초기화합니다.
87
- - **로그:** 터미널과 `logs/dispatcher.log`. 로그에는 맡긴 내용이 들어갈 수 있으므로 공유 전에 확인하세요.
88
- - **단일 실행:** 같은 상태 파일의 실행 잠금으로 중복 실행을 막습니다. 복제한 여러 폴더로 같은 일을 동시에 감시하지 마세요.
89
- - **계정 변경:** 계정마다 별도 예제 폴더를 만드세요. 상태 파일에 이전 계정 uid가 있으면 다른 계정으로 이어 받지 않습니다.
90
- - **로그인 필요:** `odyssey login -p <프로필>`(또는 `--with-key`) 뒤 다시 실행합니다. API 키 프로필은 `odyssey whoami`에 uid가 나와야 합니다(키 신원을 아는 서버 261028+).
91
- - **세션 직접 열기:** 멈춘 상태에서 state.json의 sessionId를 찾아 작업 폴더에서 `claude --resume <id>`. 일꾼이 실행 중일 때 같은 세션을 열지 마세요.
92
- - **초기화:** config.json과 state.json을 지우기보다 별도 폴더를 만들어 시작하세요. 상태를 잃으면 미완료 작업을 다시 맡길 수 있습니다.
93
-
94
- 모의 실행의 상태·로그는 `state.dry-run.json`·`dispatcher.dry-run.log`로 분리합니다.
95
- 첫 실행 전의 댓글은 자동으로 소급하지 않습니다. 이후 꺼져 있던 동안의 댓글은 저장한 커서부터 따라잡습니다.
96
- 댓글 중복 기억은 항목당 최근 1,000건입니다. 네트워크 장애와 일꾼 중단 중 외부 작업을 정확히 한 번만 실행하는 것은 보장하지 않습니다.
97
- 재개한 일꾼은 항목·스레드를 다시 읽고 이미 한 작업을 확인합니다.
98
-
99
- ## 자동 시작은 직접 선택
100
-
101
- 이 예제는 로그인 시 자동 실행을 등록하지 않습니다. 터미널에서 확인한 뒤 macOS는 LaunchAgent, Linux는 사용자 systemd 서비스로 등록할 수 있습니다.
102
- 설정·로그·상태 파일을 둘 폴더의 절대 경로와 `command -v node`로 확인한 Node 경로를 사용하세요.
103
- PATH가 짧은 환경에서는 `claudeBin`도 절대 경로를 사용합니다. 중지할 때는 해당 서비스도 내려야 자동 재시작하지 않습니다.
104
- 컴퓨터가 잠들거나 꺼져 있으면 감시도 쉬며, 다음 시작 때 커서부터 이어 받습니다.
105
-
106
- Windows에서는 Node와 Claude Code 실행 파일 또는 JS 진입점 경로를 지정하세요. JS 파일은 현재 Node로 실행하므로 `.cmd` 셸 인용에 의존하지 않습니다.
107
- Windows·Linux 실기기에서의 전체 로그인·장기 감시는 별도 확인이 필요합니다.
67
+ | `todo` | 처음 보는 `클로드 코드` 태그 할일(미시작) |
68
+ | `mention` | 아무 항목에 단 **내** 댓글의 `@클로드코드`(공백·대소문자 무시) — 그 항목은 맡은 스레드가 된다 |
69
+ | `tagged` | 태그가 걸린 할일·메모·프로젝트·리포트 스레드의 내 댓글 |
70
+ | `reply` | 맡은 스레드의 내 댓글(멘션 없어도) |
71
+
72
+ AI 댓글(세션 자신의 답글)·다른 사람 댓글·할일 수정은 깨우지 않습니다 — 메아리와 남의 지시를 막습니다.
73
+ 상태 줄: `ended`(2) · `error`(3) · `busy`(4, 다른 듣기가 돎 — 이어받으려면 `--replace`) · `stopped`(5).
74
+
75
+ ## 보통 바꾸는 설정
76
+
77
+ | 키 | 기본 | 뜻 |
78
+ |---|---|---|
79
+ | `watchTag` | `클로드 코드` | 감시 태그 |
80
+ | `mentions` | `["@클로드코드"]` | 멘션(여럿 가능) |
81
+ | `odysseyProfile` | init 때 프로필 | `odyssey login` 프로필 |
82
+ | `expectedUid` | 빈 값 | `--check`의 uid — 넣으면 다른 계정이면 오류로 끝난다 |
83
+ | `followedThreads` | `false` | 관심 스레드(남의 답까지)도 들을지 — 지시는 내 댓글뿐이라 보통 끈다 |
84
+ | `statePath` | `./state/listen.json` | 상태(since·seen·tagged·threads). 세션을 비우거나 바꿔도 이어 듣는다 |
85
+
86
+ ## 끄기·비우기
87
+
88
+ - 끄기: 세션에서 백그라운드 작업·Monitor를 멈춥니다(중지 신호는 자식 감시까지 걷습니다). 강제 종료(SIGKILL)하면 `odyssey watch`가 남을 수 있습니다.
89
+ - 맥락 비우기: 일 하나를 마감한 직후가 좋은 때입니다. **먼저 듣기를 끄고** 비운 뒤 다시 "들어"라고 하면 상태 파일에서 이어 듣습니다.
90
+ - 상태를 처음부터: 듣기를 끄고 `state/`를 지웁니다(다음에 켤 때 밀린 태그 할일이 다시 옵니다).
108
91
 
109
92
  ## 예제 검사
110
93
 
@@ -112,17 +95,17 @@ Windows·Linux 실기기에서의 전체 로그인·장기 감시는 별도 확
112
95
  npm test
113
96
  ```
114
97
 
115
- 실제 Odyssey와 Claude 대신 가짜 프로세스를 사용합니다. 배달·세션 재개·중복 방지·커서·FIFO·예산·오류 복구를 확인합니다.
116
- 구조를 바꾸고 싶으면 `odyssey agent-guide --watch-agent`의 프롬프트를 코딩 에이전트에 주되, 이 검사를 함께 유지하세요.
117
- 이 예제의 결정마다 이유와 다른 에이전트로 바꾸는 법(리뷰어·공유 보드 비서·정리 리포트)은 `odyssey agent-guide --design`(CLI 0.2.2+)에 있습니다.
98
+ 실제 Odyssey 대신 가짜 감시(`test/fake-odyssey.mjs`)로 깨울 표·중복 방지·밀린 것 묶음·두 모드·잠금을 확인합니다.
99
+ 구조를 바꾸거나 다른 언어로 옮길 때는 `odyssey agent-guide --watch-agent` 6절(듣기의 계약)을 지키고 이 검사를 함께 유지하세요.
100
+ 결정마다의 이유는 `odyssey agent-guide --design`에 있습니다.
101
+
102
+ ## 사람 없이 상시로 돌려야 하면
118
103
 
104
+ 세션을 띄워 둘 수 없는 환경이라면 무인 대안이 있습니다 — `odyssey watch-agent init <새 폴더> --dispatcher`.
105
+ 항목마다 헤드리스 일꾼(`claude -p`)을 띄우는 디스패처로, 일꾼 세션이 앱 목록에 보이지 않고 권한·예산을 따로 정해야 합니다.
119
106
 
120
107
  ## 댓글과 자격 회수
121
108
 
122
- `claude`·`companion`·알 수 없는 작성자 표식은 모두 AI 댓글입니다. 멘션이 있거나 이미 열린 세션이어도 일꾼에게 지시로 배달하지 않습니다.
123
- 일꾼이 답글을 단 스레드는 관심 스레드가 되어, 공유 보드의 다른 사람 댓글도 감시로 옵니다(`author: "other"`). 감시 태그가 달린 메모·프로젝트·리포트의
124
- 스레드도 같은 길로 옵니다(`tagged: true` — CLI 0.2.2+). 예제는 다른 사람 댓글을 일꾼에게 배달하지 않습니다 —
125
- 일꾼은 다음에 깨어날 때 스레드를 읽어 맥락으로만 봅니다. 내 「답글」이 일꾼 댓글을 향하는지는 감시가 `replyTo.author`로 알려 줍니다.
109
+ `claude`·`companion`·알 수 없는 작성자 표식은 모두 AI 댓글이며 세션을 깨우지 않습니다. 다른 사람(`author: "other"`) 댓글도 깨우지 않습니다.
126
110
  서버가 OAuth 연결을 회수하면 해당 CLI 신원의 데이터 접근과 Firebase 갱신을 막습니다. 일반 앱 로그인과 다른 OAuth 연결은 유지됩니다.
127
111
  API 키는 앱에서 폐기하면 새 감시만 바로 막고, 돌던 감시는 다음 토큰 재교환(길어야 1시간)에서 끝납니다.
128
- 이미 받은 데이터·진행 중인 일꾼 작업은 회수로 되돌아가지 않습니다. 감시 오류 뒤에는 예제의 재시작 간격이 적용됩니다.
@@ -1,20 +1,10 @@
1
1
  {
2
- "workDir": "./work",
3
2
  "odysseyProfile": "default",
4
3
  "odysseyBin": "odyssey",
5
- "claudeBin": "claude",
6
- "odysseyMcpName": "odyssey",
7
4
  "expectedUid": "",
8
5
  "watchTag": "클로드 코드",
9
6
  "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,
7
+ "followedThreads": false,
17
8
  "readyTimeoutMs": 120000,
18
- "statePath": "./state.json",
19
- "logPath": "./logs/dispatcher.log"
9
+ "statePath": "./state/listen.json"
20
10
  }
@@ -1,6 +1,4 @@
1
1
  config.json
2
- state*.json
3
- *.lock
2
+ state/
4
3
  *.tmp
5
- logs/
6
4
  test/.tmp/
@@ -0,0 +1,368 @@
1
+ #!/usr/bin/env node
2
+ // Odyssey 세션 듣기 — 일하는 코딩 에이전트 세션이 앱에서 맡긴 일을 직접 받는다
3
+ //
4
+ // `odyssey watch` 를 자식으로 띄워 NDJSON 을 읽고, 세션을 깨울 이벤트만 한 줄 JSON 으로 낸다.
5
+ // 판단·작업·답글은 이 출력을 받은 세션이 Odyssey MCP(또는 odyssey CLI)로 한다 — 이 스크립트는 모델을 부르지 않는다.
6
+ // 세션 규칙: odyssey agent-guide --watch-agent (저장소 back_end/odyssey_cli/prompts/watch-agent.md)
7
+ //
8
+ // 실행: node listen.mjs 깨울 이벤트가 오면 내고 끝난다(종료 0) — 세션이 백그라운드로 띄워 두고 그 종료로 깨어난다
9
+ // node listen.mjs --stream 끝나지 않고 이벤트마다 한 줄씩 — Claude Code Monitor 처럼 줄마다 알리는 장치용
10
+ // node listen.mjs --check CLI 로그인·설정만 확인(감시를 띄우지 않는다)
11
+ // node listen.mjs --dry-run 밀린 것 중 무엇이 깨울지만 보고 끝난다(상태를 쓰지 않는다)
12
+ // --replace 다른 듣기가 돌고 있으면 끝내고 이어받는다 · --config <파일>
13
+ // 종료 코드: 0 이벤트 · 2 감시가 끝남 · 3 감시 오류 · 4 다른 듣기가 돌고 있음 · 5 멈춤(이어받김·중지 신호) · 1 설정 오류
14
+ // Node 20+ · 의존성 없음.
15
+ // 이력: document/90-process/work-log/261108 Odyssey CLI 감시 안내 세션 듣기 권장 listen.mjs Monitor.md
16
+
17
+ import { spawn, spawnSync } from 'node:child_process';
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import readline from 'node:readline';
21
+ import { fileURLToPath, pathToFileURL } from 'node:url';
22
+
23
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
24
+
25
+ // ───────────────────────────── 설정 ─────────────────────────────
26
+ // 같은 폴더의 config.json(있으면) 또는 --config <파일> 의 같은 키가 이 값을 덮는다.
27
+ export const DEFAULT_CONFIG = Object.freeze({
28
+ // 감시 태그 — 이 태그가 달린 할일 = 세션이 맡은 일
29
+ watchTag: '클로드 코드',
30
+ // 멘션 — 아무 항목의 댓글에 내가 이 말을 쓰면 그 항목을 일로 맡는다(공백·대소문자 무시)
31
+ mentions: ['@클로드코드'],
32
+ // Odyssey 프로필 — `odyssey login` 으로 로그인된 프로필(브라우저 로그인 또는 --with-key API 키)
33
+ odysseyProfile: 'default',
34
+ odysseyBin: 'odyssey',
35
+ // 세션의 Odyssey MCP 와 같은 계정이어야 한다. --check 에서 나온 uid 를 넣으면 다른 계정 감시를 막는다.
36
+ expectedUid: '',
37
+ // 관심 스레드(남의 답까지 오는 방)도 들을지 — 지시는 내 댓글뿐이라 기본은 끈다(--no-threads)
38
+ followedThreads: false,
39
+ // 감시가 첫 스냅샷(ready)까지 이 안에 못 오면 오류(3)로 끝낸다 — 세션이 한 번 다시 띄운다
40
+ readyTimeoutMs: 120_000,
41
+ statePath: path.join(HERE, 'state', 'listen.json'),
42
+ });
43
+
44
+ /** config.json 을 읽어 기본값 위에 덮는다. 경로 키는 그 파일 기준 상대 경로를 허용한다. */
45
+ export function loadConfig(file) {
46
+ const cfg = { ...DEFAULT_CONFIG, mentions: [...DEFAULT_CONFIG.mentions] };
47
+ const p = file ? path.resolve(file) : path.join(HERE, 'config.json');
48
+ if (fs.existsSync(p)) {
49
+ const over = JSON.parse(fs.readFileSync(p, 'utf8'));
50
+ const base = path.dirname(p);
51
+ for (const [k, v] of Object.entries(over)) {
52
+ if (!(k in DEFAULT_CONFIG)) throw new Error(`설정에 모르는 키가 있어요: ${k}`);
53
+ cfg[k] = v;
54
+ }
55
+ for (const k of ['statePath', 'odysseyBin']) {
56
+ if (typeof over[k] === 'string' && (over[k].startsWith('./') || over[k].startsWith('../'))) {
57
+ cfg[k] = path.resolve(base, over[k]);
58
+ }
59
+ }
60
+ } else if (file) {
61
+ throw new Error(`설정 파일이 없어요: ${file}`);
62
+ }
63
+ validateConfig(cfg);
64
+ return cfg;
65
+ }
66
+
67
+ export function validateConfig(cfg) {
68
+ for (const k of ['watchTag', 'odysseyProfile', 'odysseyBin', 'statePath']) {
69
+ if (typeof cfg[k] !== 'string' || !cfg[k]) throw new Error(`설정 ${k} 가 비었어요`);
70
+ }
71
+ if (!Array.isArray(cfg.mentions) || cfg.mentions.some((x) => typeof x !== 'string')) throw new Error('설정 mentions 는 문자열 배열이어야 해요');
72
+ if (!cfg.mentions.some((m) => normalizeMention(m))) throw new Error('설정 mentions 가 비었어요');
73
+ if (typeof cfg.expectedUid !== 'string') throw new Error('설정 expectedUid 는 문자열이어야 해요');
74
+ if (typeof cfg.followedThreads !== 'boolean') throw new Error('설정 followedThreads 는 true/false 여야 해요');
75
+ if (!(Number.isFinite(cfg.readyTimeoutMs) && cfg.readyTimeoutMs > 0)) throw new Error('설정 readyTimeoutMs 는 유한한 양수여야 해요');
76
+ }
77
+
78
+ // ───────────────────────────── 깨울지 고르기 ─────────────────────────────
79
+
80
+ const SEEN_KEEP = 500; // 기억하는 댓글 uid 수(파일이 끝없이 커지지 않게)
81
+ const TAGGED_KEEP = 2000;
82
+
83
+ /** 세션이 답글을 달 수 있는 항목 종류 — comment_on_item 의 itemType + 보드 전체(comment_on_project). */
84
+ export const COMMENT_ITEM_TYPES = Object.freeze([
85
+ 'todo', 'memo', 'asset', 'event', 'routine', 'routineInstance', 'locationMap', 'record', 'companionReport', 'projectComponent', 'project',
86
+ ]);
87
+
88
+ export function normalizeMention(s) {
89
+ return String(s ?? '').replace(/\s+/g, '').toLowerCase();
90
+ }
91
+
92
+ export function hasMention(text, mentions) {
93
+ const t = normalizeMention(text);
94
+ return mentions.some((m) => {
95
+ const n = normalizeMention(m);
96
+ return n && t.includes(n);
97
+ });
98
+ }
99
+
100
+ export function emptyState(now = nowIso()) {
101
+ return { since: now, seen: [], tagged: [], threads: {} };
102
+ }
103
+
104
+ export function normalizeState(raw, now = nowIso()) {
105
+ const s = emptyState(now);
106
+ if (raw && typeof raw === 'object') {
107
+ if (typeof raw.since === 'string' && raw.since) s.since = raw.since;
108
+ if (Array.isArray(raw.seen)) s.seen = raw.seen.filter((x) => typeof x === 'string');
109
+ if (Array.isArray(raw.tagged)) s.tagged = raw.tagged.filter((x) => typeof x === 'string');
110
+ if (raw.threads && typeof raw.threads === 'object') s.threads = { ...raw.threads };
111
+ }
112
+ return s;
113
+ }
114
+
115
+ /**
116
+ * 감시 이벤트 하나를 세션에 낼 줄로 바꾼다(낼 게 아니면 null). 낼 때는 state 를 고친다 — 부르는 쪽이 내기 **전에** 저장한다.
117
+ * todo 처음 보는 태그 할일(added · notStarted). 첫 스냅샷의 밀린 것도 온다
118
+ * mention 아무 항목에 단 내 댓글의 멘션. 그 항목은 맡은 스레드(threads)에 오른다
119
+ * tagged 태그 항목 스레드의 내 댓글 — 멘션 없어도 대화창이다
120
+ * reply 맡은 스레드의 내 댓글
121
+ * 깨우지 않는 것: 에이전트 댓글(세션 자신의 답글 — 메아리) · 남의 댓글(author "other" — 지시가 아니다) · 할일 수정(세션이 바꾼 상태의 메아리).
122
+ */
123
+ export function classify(evt, state, cfg) {
124
+ if (evt?.type === 'todo') {
125
+ if (evt.change !== 'added' || evt.status !== 'notStarted') return null;
126
+ if (!evt.uid || state.tagged.includes(evt.uid)) return null;
127
+ state.tagged = [...state.tagged, evt.uid].slice(-TAGGED_KEEP);
128
+ return {
129
+ listen: 'todo', uid: evt.uid, title: evt.title ?? null, status: evt.status,
130
+ tags: Array.isArray(evt.tags) ? evt.tags : [], initial: Boolean(evt.initial),
131
+ };
132
+ }
133
+ if (evt?.type !== 'comment' || evt.author !== 'me') return null;
134
+ const { commentUid, itemUid, itemType } = evt;
135
+ if (!commentUid || !itemUid || state.seen.includes(commentUid)) return null;
136
+ if (!COMMENT_ITEM_TYPES.includes(itemType)) return null; // 답글을 달 곳이 없는 방(페이지·컬렉션 …)
137
+ if (itemType === 'projectComponent' && !evt.parentItemUid) return null; // 어느 보드의 카드인지 모르면 답글을 못 단다
138
+ const text = typeof evt.text === 'string' ? evt.text : '';
139
+ let kind;
140
+ if (hasMention(text, cfg.mentions)) {
141
+ kind = 'mention';
142
+ if (!state.threads[itemUid]) {
143
+ state.threads[itemUid] = { itemType, ...(evt.parentItemUid ? { projectId: evt.parentItemUid } : {}) };
144
+ }
145
+ } else if (evt.tagged) {
146
+ kind = 'tagged';
147
+ } else if (state.threads[itemUid]) {
148
+ kind = 'reply';
149
+ } else {
150
+ return null;
151
+ }
152
+ state.seen = [...state.seen, commentUid].slice(-SEEN_KEEP);
153
+ return {
154
+ listen: kind, itemType, itemUid, parentItemUid: evt.parentItemUid ?? null, commentUid,
155
+ replyToCommentUid: evt.replyToCommentUid ?? null, createdAt: evt.createdAt ?? null, text: text.slice(0, 800),
156
+ };
157
+ }
158
+
159
+ // ───────────────────────────── 상태·잠금 ─────────────────────────────
160
+
161
+ /** 감시 이벤트 createdAt 과 같은 모양(밀리초 + Z) — since 를 문자열로 비교한다. */
162
+ export function nowIso(d = new Date()) {
163
+ return d.toISOString();
164
+ }
165
+
166
+ export function loadState(file) {
167
+ try {
168
+ return normalizeState(JSON.parse(fs.readFileSync(file, 'utf8')));
169
+ } catch (e) {
170
+ if (e.code === 'ENOENT') return emptyState();
171
+ throw new Error(`상태 파일을 읽지 못했어요(${file}): ${e.message}`);
172
+ }
173
+ }
174
+
175
+ export function saveState(file, state) {
176
+ fs.mkdirSync(path.dirname(file), { recursive: true });
177
+ const tmp = `${file}.tmp`;
178
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 1));
179
+ fs.renameSync(tmp, file);
180
+ }
181
+
182
+ /** pid 가 살아 있는 듣기인가 — pid 재사용을 듣기로 오인하지 않게 명령줄까지 본다(ps 가 없는 곳은 살아 있음만). */
183
+ function isListener(pid) {
184
+ try {
185
+ process.kill(pid, 0);
186
+ } catch (e) {
187
+ if (e.code === 'ESRCH') return false;
188
+ }
189
+ const ps = spawnSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8' });
190
+ if (ps.error) return true;
191
+ return /listen\.mjs/.test(ps.stdout);
192
+ }
193
+
194
+ /** 듣기는 상태 파일 하나에 하나 — 둘이면 같은 이벤트로 세션 둘이 깨어난다. 잠금 파일은 배타 생성(wx)으로 잡는다. */
195
+ export async function takeLock(pidPath, replace) {
196
+ fs.mkdirSync(path.dirname(pidPath), { recursive: true });
197
+ for (let attempt = 0; attempt < 5; attempt++) {
198
+ try {
199
+ fs.writeFileSync(pidPath, String(process.pid), { flag: 'wx' });
200
+ return { busy: 0 };
201
+ } catch (e) {
202
+ if (e.code !== 'EEXIST') throw e;
203
+ }
204
+ let other = 0;
205
+ try {
206
+ other = Number.parseInt(fs.readFileSync(pidPath, 'utf8').trim(), 10) || 0;
207
+ } catch { /* 그새 풀렸다 */ }
208
+ if (other && other !== process.pid && isListener(other)) {
209
+ if (!replace) return { busy: other };
210
+ try { process.kill(other, 'SIGTERM'); } catch { /* 그새 끝났다 */ }
211
+ for (let i = 0; i < 50 && isListener(other); i++) await new Promise((r) => setTimeout(r, 100));
212
+ }
213
+ // 죽은 듣기의 잠금이거나 방금 끝낸 듣기 — 지우고 다시 잡는다
214
+ try { fs.unlinkSync(pidPath); } catch { /* 이미 없다 */ }
215
+ }
216
+ throw new Error(`듣기 잠금을 잡지 못했어요: ${pidPath}`);
217
+ }
218
+
219
+ export function releaseLock(pidPath) {
220
+ try {
221
+ if (fs.readFileSync(pidPath, 'utf8').trim() === String(process.pid)) fs.unlinkSync(pidPath);
222
+ } catch { /* 이미 없다 */ }
223
+ }
224
+
225
+ // ───────────────────────────── 자식 프로세스 ─────────────────────────────
226
+
227
+ /** JS 실행 파일은 현재 Node로 부른다. npm의 Windows 셸 shim이나 경로의 공백을 셸에 넘기지 않는다. */
228
+ export function commandOf(bin, args) {
229
+ return /\.(?:mjs|cjs|js)$/i.test(bin) ? [process.execPath, [bin, ...args]] : [bin, args];
230
+ }
231
+
232
+ export function buildWatchArgs(cfg, since) {
233
+ return ['-p', cfg.odysseyProfile, 'watch', '--tag', cfg.watchTag, ...(cfg.followedThreads ? [] : ['--no-threads']), '--since', since];
234
+ }
235
+
236
+ /** 감시를 띄우지 않고 CLI 로그인·계정만 확인한다. */
237
+ export function checkSetup(cfg) {
238
+ const [command, args] = commandOf(cfg.odysseyBin, ['-p', cfg.odysseyProfile, 'whoami']);
239
+ const who = spawnSync(command, args, { encoding: 'utf8', timeout: 30_000 });
240
+ if (who.error || who.status !== 0) throw new Error(`CLI 로그인을 확인하세요: odyssey login -p ${cfg.odysseyProfile}`);
241
+ const account = JSON.parse(who.stdout);
242
+ if (!['oauth', 'apiKey'].includes(account.auth) || account.ok !== true) throw new Error('감시는 로그인한 프로필이 필요해요: odyssey login');
243
+ if (!account.uid) throw new Error('CLI 계정을 확인하지 못했어요. odyssey whoami 로 uid 가 나오는지 확인하세요.');
244
+ if (cfg.expectedUid && account.uid !== cfg.expectedUid) throw new Error('설정 expectedUid와 CLI 계정이 달라요. 프로필을 확인하세요.');
245
+ return { uid: account.uid, server: account.server };
246
+ }
247
+
248
+ // ───────────────────────────── 듣기 ─────────────────────────────
249
+
250
+ /**
251
+ * 감시를 띄워 깨울 이벤트를 out 에 한 줄씩 낸다. 돌려주는 값 = 종료 코드.
252
+ * - 밀린 것(ready 전 첫 스냅샷)은 모았다가 ready 에서 한 번에 낸다. 흐름 여럿(내 댓글 · 태그 방)이 섞여 시간순이 아니라서
253
+ * since 는 낸 댓글 시각이 아니라 ready 에서만 "띄운 시각 − 1분"으로 당긴다(그 앞은 다 훑었다). 다시 온 것은 seen 이 거른다.
254
+ * - 낼 것은 내기 **전에** 상태에 적는다 — 다시 띄워도 두 번 내지 않는다.
255
+ * - stream 이 아니면 첫 낼 것(밀린 것은 묶음째)에서 끝낸다. dryRun 은 밀린 것만 보고 상태를 쓰지 않는다.
256
+ */
257
+ export function listen(cfg, { stream = false, dryRun = false, out = process.stdout, spawnFn = spawn, signals = process } = {}) {
258
+ const state = loadState(cfg.statePath);
259
+ if (!dryRun) saveState(cfg.statePath, state); // 처음 띄울 때 since(지금)를 박아 둔다 — 감시가 바로 끊겨도 그 뒤 댓글을 다시 받게
260
+ const started = Date.now();
261
+ const write = (obj) => out.write(`${JSON.stringify(obj)}\n`);
262
+ const [command, args] = commandOf(cfg.odysseyBin, buildWatchArgs(cfg, state.since));
263
+ const child = spawnFn(command, args, { stdio: ['ignore', 'pipe', 'inherit'] });
264
+
265
+ return new Promise((resolve) => {
266
+ let backlog = [];
267
+ let done = false;
268
+ const readyTimer = setTimeout(() => finish(3, { listen: 'error', reason: 'ready-timeout' }), cfg.readyTimeoutMs);
269
+ const onSignal = () => finish(5, { listen: 'stopped' });
270
+ const sigs = ['SIGTERM', 'SIGINT', 'SIGHUP'];
271
+ for (const s of sigs) signals.on(s, onSignal);
272
+
273
+ function finish(code, last) {
274
+ if (done) return;
275
+ done = true;
276
+ clearTimeout(readyTimer);
277
+ for (const s of sigs) signals.off(s, onSignal);
278
+ if (last) write(last);
279
+ // 자식 감시까지 걷는다 — 남으면 고아 리스너가 된다
280
+ try { child.kill('SIGTERM'); } catch { /* 이미 끝났다 */ }
281
+ resolve(code);
282
+ }
283
+
284
+ const emit = (items) => {
285
+ if (!dryRun) saveState(cfg.statePath, state);
286
+ for (const o of items) write(o);
287
+ if (!stream) finish(0);
288
+ };
289
+
290
+ const rl = readline.createInterface({ input: child.stdout });
291
+ rl.on('line', (line) => {
292
+ if (done) return;
293
+ let evt;
294
+ try { evt = JSON.parse(line); } catch { return; }
295
+ if (evt.type === 'error') return finish(3, { listen: 'error', event: evt });
296
+ if (evt.type === 'ready') {
297
+ clearTimeout(readyTimer);
298
+ if (cfg.expectedUid && evt.uid && evt.uid !== cfg.expectedUid) return finish(3, { listen: 'error', reason: 'account', uid: evt.uid });
299
+ const mark = nowIso(new Date(started - 60_000));
300
+ if (mark > state.since) state.since = mark;
301
+ const pending = backlog;
302
+ backlog = null; // 이제부터는 실시간
303
+ if (dryRun) {
304
+ for (const o of pending) write(o);
305
+ return finish(0, { listen: 'dry-run', count: pending.length });
306
+ }
307
+ if (pending.length) return emit(pending);
308
+ saveState(cfg.statePath, state);
309
+ return;
310
+ }
311
+ const o = classify(evt, state, cfg);
312
+ if (!o) return;
313
+ if (backlog) backlog.push(o);
314
+ else emit([o]);
315
+ });
316
+ child.on('error', (e) => finish(3, { listen: 'error', reason: 'spawn', message: e.message }));
317
+ child.on('close', () => setImmediate(() => finish(2, { listen: 'ended' })));
318
+ });
319
+ }
320
+
321
+ // ───────────────────────────── 실행 ─────────────────────────────
322
+
323
+ const HELP = `node listen.mjs [--stream | --check | --dry-run] [--replace] [--config <파일>]
324
+ (기본) 깨울 이벤트가 오면 한 줄 JSON 으로 내고 끝난다 — 세션이 백그라운드로 띄우고 그 종료로 깨어난다
325
+ --stream 끝나지 않고 이벤트마다 한 줄 — Claude Code Monitor 처럼 줄마다 알리는 장치용(만료되면 다시 건다)
326
+ --check CLI 로그인·설정만 확인한다
327
+ --dry-run 밀린 것 중 무엇이 깨울지만 보고 끝난다(상태를 쓰지 않는다)
328
+ --replace 다른 듣기가 돌고 있으면 끝내고 이어받는다
329
+ 종료 코드: 0 이벤트 · 2 감시가 끝남 · 3 감시 오류 · 4 다른 듣기가 돌고 있음 · 5 멈춤 · 1 설정 오류`;
330
+
331
+ async function main(argv) {
332
+ const flags = new Set(argv.filter((a) => a.startsWith('--')));
333
+ if (flags.has('--help') || argv.includes('-h')) {
334
+ process.stdout.write(`${HELP}\n`);
335
+ return 0;
336
+ }
337
+ const i = argv.indexOf('--config');
338
+ const cfg = loadConfig(i >= 0 ? argv[i + 1] : undefined);
339
+ if (flags.has('--check')) {
340
+ const r = checkSetup(cfg);
341
+ process.stdout.write(`${JSON.stringify({ listen: 'check', ok: true, ...r, statePath: cfg.statePath })}\n`);
342
+ return 0;
343
+ }
344
+ const dryRun = flags.has('--dry-run');
345
+ const pidPath = `${cfg.statePath}.pid`;
346
+ if (!dryRun) {
347
+ const lock = await takeLock(pidPath, flags.has('--replace'));
348
+ if (lock.busy) {
349
+ process.stdout.write(`${JSON.stringify({ listen: 'busy', pid: lock.busy })}\n`);
350
+ return 4;
351
+ }
352
+ }
353
+ try {
354
+ return await listen(cfg, { stream: flags.has('--stream'), dryRun });
355
+ } finally {
356
+ if (!dryRun) releaseLock(pidPath);
357
+ }
358
+ }
359
+
360
+ if (process.argv[1] && import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href) {
361
+ main(process.argv.slice(2)).then(
362
+ (code) => process.exit(code),
363
+ (e) => {
364
+ process.stderr.write(`listen: ${e.message}\n`);
365
+ process.exit(1);
366
+ },
367
+ );
368
+ }
@@ -4,9 +4,10 @@
4
4
  "type": "module",
5
5
  "engines": { "node": ">=20" },
6
6
  "scripts": {
7
- "check": "node dispatcher.mjs --check",
8
- "dry-run": "node dispatcher.mjs --dry-run",
9
- "start": "node dispatcher.mjs",
7
+ "check": "node listen.mjs --check",
8
+ "dry-run": "node listen.mjs --dry-run",
9
+ "listen": "node listen.mjs",
10
+ "stream": "node listen.mjs --stream",
10
11
  "test": "node --test test/*.test.mjs"
11
12
  }
12
13
  }
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ // 가짜 odyssey — 테스트가 FAKE_ODYSSEY 파일에 적은 대로 whoami 답·감시 이벤트를 낸다. 서버·모델은 부르지 않는다.
3
+ // { whoami?, events: [이벤트 객체 | 쉴 ms], exitAfter?: true, argsLog?: 파일 }
4
+ import fs from 'node:fs';
5
+
6
+ const args = process.argv.slice(2);
7
+ const spec = JSON.parse(fs.readFileSync(process.env.FAKE_ODYSSEY, 'utf8'));
8
+ if (spec.argsLog) fs.appendFileSync(spec.argsLog, `${JSON.stringify(args)}\n`);
9
+ if (args.includes('whoami')) {
10
+ process.stdout.write(JSON.stringify(spec.whoami ?? { auth: 'oauth', ok: true, uid: 'me', server: 'fake' }));
11
+ process.exit(0);
12
+ }
13
+ process.on('SIGTERM', () => process.exit(0));
14
+ for (const step of spec.events ?? []) {
15
+ if (typeof step === 'number') await new Promise((r) => setTimeout(r, step));
16
+ else process.stdout.write(`${JSON.stringify(step)}\n`);
17
+ }
18
+ if (spec.exitAfter) process.exit(0);
19
+ setInterval(() => {}, 1000);