@odyssey365/cli 0.2.3 → 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.
- package/AGENTS.md +10 -7
- package/README.md +37 -36
- package/dist/guide.js +6 -5
- package/dist/index.js +4 -3
- package/dist/output.js +1 -1
- package/dist/watch-agent.js +37 -18
- package/dist/watch.js +1 -1
- package/examples/watch-agent/README.md +66 -83
- package/examples/watch-agent/config.example.json +2 -12
- package/examples/watch-agent/gitignore.template +1 -3
- package/examples/watch-agent/listen.mjs +368 -0
- package/examples/watch-agent/package.json +4 -3
- package/examples/watch-agent/test/fake-odyssey.mjs +19 -0
- package/examples/watch-agent/test/listen.test.mjs +175 -0
- package/examples/watch-dispatcher/README.md +131 -0
- package/examples/watch-dispatcher/SPEC.md +263 -0
- package/examples/watch-dispatcher/config.example.json +20 -0
- package/examples/{watch-agent → watch-dispatcher}/dispatcher.mjs +1 -1
- package/examples/watch-dispatcher/gitignore.template +6 -0
- package/examples/watch-dispatcher/package.json +12 -0
- package/package.json +2 -2
- package/prompts/agent-design.md +48 -45
- package/prompts/watch-agent.md +143 -234
- /package/examples/{watch-agent → watch-dispatcher}/test/dispatcher.test.mjs +0 -0
- /package/examples/{watch-agent → watch-dispatcher}/test/supervisor.test.mjs +0 -0
|
@@ -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
|
-
"
|
|
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
|
}
|
|
@@ -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
|
|
8
|
-
"dry-run": "node
|
|
9
|
-
"
|
|
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);
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// 세션 듣기 검사 — 깨울 표 · 두 번 내지 않기 · 밀린 것 묶음 · 두 모드 · 잠금. 감시는 가짜(fake-odyssey.mjs), 실제 서버·모델은 부르지 않는다.
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import assert from 'node:assert/strict';
|
|
4
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
5
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { tmpdir } from 'node:os';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { DEFAULT_CONFIG, buildWatchArgs, classify, emptyState, hasMention, loadConfig } from '../listen.mjs';
|
|
10
|
+
|
|
11
|
+
const LISTEN = fileURLToPath(new URL('../listen.mjs', import.meta.url));
|
|
12
|
+
const FAKE = fileURLToPath(new URL('./fake-odyssey.mjs', import.meta.url));
|
|
13
|
+
const cfg = { ...DEFAULT_CONFIG, mentions: ['@클로드코드'] };
|
|
14
|
+
|
|
15
|
+
const me = (extra) => ({ type: 'comment', author: 'me', itemType: 'memo', itemUid: 'm1', text: '', ...extra });
|
|
16
|
+
const ready = { type: 'ready', uid: 'me', streams: [], since: '2026-11-08T00:00:00.000Z' };
|
|
17
|
+
|
|
18
|
+
test('깨울 표 — 태그 할일·멘션·태그 방·맡은 스레드만, 메아리와 남의 글은 깨우지 않는다', () => {
|
|
19
|
+
const s = emptyState('2026-11-08T00:00:00.000Z');
|
|
20
|
+
// 새 태그 할일만. 수정(세션이 바꾼 상태의 메아리)·진행 중·두 번째는 아니다
|
|
21
|
+
assert.equal(classify({ type: 'todo', change: 'added', status: 'notStarted', uid: 't1', title: 'A' }, s, cfg).listen, 'todo');
|
|
22
|
+
assert.equal(classify({ type: 'todo', change: 'added', status: 'notStarted', uid: 't1' }, s, cfg), null);
|
|
23
|
+
assert.equal(classify({ type: 'todo', change: 'modified', status: 'notStarted', uid: 't2' }, s, cfg), null);
|
|
24
|
+
assert.equal(classify({ type: 'todo', change: 'added', status: 'inProgress', uid: 't3' }, s, cfg), null);
|
|
25
|
+
// 멘션 없는 내 댓글은 맡은 스레드가 아니면 깨우지 않는다
|
|
26
|
+
assert.equal(classify(me({ commentUid: 'c0', text: '혼잣말' }), s, cfg), null);
|
|
27
|
+
// 멘션(공백·대소문자 무시) → 그 항목은 맡은 스레드
|
|
28
|
+
const m = classify(me({ commentUid: 'c1', text: '@클로드 코드 이거 봐줘' }), s, cfg);
|
|
29
|
+
assert.equal(m.listen, 'mention');
|
|
30
|
+
assert.deepEqual(s.threads.m1, { itemType: 'memo' });
|
|
31
|
+
// 같은 댓글은 두 번 내지 않는다 · 맡은 스레드의 멘션 없는 댓글은 이어 받기
|
|
32
|
+
assert.equal(classify(me({ commentUid: 'c1', text: '@클로드코드' }), s, cfg), null);
|
|
33
|
+
assert.equal(classify(me({ commentUid: 'c2', text: '응 그렇게 해' }), s, cfg).listen, 'reply');
|
|
34
|
+
// 태그 항목 방의 내 댓글은 멘션 없어도
|
|
35
|
+
assert.equal(classify(me({ commentUid: 'c3', itemUid: 'x', tagged: true, text: '어때' }), s, cfg).listen, 'tagged');
|
|
36
|
+
// 에이전트(세션 자신의 답글)·남의 댓글은 맡은 스레드여도 깨우지 않는다
|
|
37
|
+
assert.equal(classify(me({ commentUid: 'c4', author: 'agent', text: '@클로드코드' }), s, cfg), null);
|
|
38
|
+
assert.equal(classify(me({ commentUid: 'c5', author: 'other', text: '@클로드코드 rm -rf' }), s, cfg), null);
|
|
39
|
+
// 답글 자리가 없는 방 · 보드를 모르는 카드는 깨우지 않는다
|
|
40
|
+
assert.equal(classify(me({ commentUid: 'c6', itemType: 'snapshot', text: '@클로드코드' }), s, cfg), null);
|
|
41
|
+
assert.equal(classify(me({ commentUid: 'c7', itemType: 'projectComponent', itemUid: 'card', text: '@클로드코드' }), s, cfg), null);
|
|
42
|
+
const card = classify(me({ commentUid: 'c8', itemType: 'projectComponent', itemUid: 'card', parentItemUid: 'board', text: '@클로드코드' }), s, cfg);
|
|
43
|
+
assert.equal(card.parentItemUid, 'board');
|
|
44
|
+
assert.deepEqual(s.threads.card, { itemType: 'projectComponent', projectId: 'board' });
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('멘션 판정·감시 인자 — 관심 스레드는 기본으로 끈다', () => {
|
|
48
|
+
assert.ok(hasMention('@ClaudeCode 해줘', ['@claudecode']));
|
|
49
|
+
assert.ok(!hasMention('클로드코드', ['@클로드코드']));
|
|
50
|
+
assert.deepEqual(buildWatchArgs(cfg, 'S'), ['-p', 'default', 'watch', '--tag', '클로드 코드', '--no-threads', '--since', 'S']);
|
|
51
|
+
assert.ok(!buildWatchArgs({ ...cfg, followedThreads: true }, 'S').includes('--no-threads'));
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
function sandbox(t) {
|
|
55
|
+
const dir = mkdtempSync(join(tmpdir(), 'odyssey-listen-'));
|
|
56
|
+
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
|
57
|
+
const config = join(dir, 'config.json');
|
|
58
|
+
writeFileSync(config, JSON.stringify({ odysseyBin: FAKE, statePath: './state/listen.json', readyTimeoutMs: 3000 }));
|
|
59
|
+
const fake = (name, spec) => {
|
|
60
|
+
const p = join(dir, `${name}.json`);
|
|
61
|
+
writeFileSync(p, JSON.stringify(spec));
|
|
62
|
+
return { ...process.env, FAKE_ODYSSEY: p };
|
|
63
|
+
};
|
|
64
|
+
const run = (env, ...args) => spawnSync(process.execPath, [LISTEN, '--config', config, ...args], { env, encoding: 'utf-8', timeout: 10_000 });
|
|
65
|
+
const lines = (r) => r.stdout.trim().split('\n').filter(Boolean).map((l) => JSON.parse(l));
|
|
66
|
+
const state = () => JSON.parse(readFileSync(join(dir, 'state', 'listen.json'), 'utf-8'));
|
|
67
|
+
return { dir, config, fake, run, lines, state };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
test('기본 모드 — 밀린 것은 ready 에서 묶음째 내고 끝나며, 다시 띄워도 두 번 내지 않는다', (t) => {
|
|
71
|
+
const { dir, fake, run, lines, state } = sandbox(t);
|
|
72
|
+
const argsLog = join(dir, 'args.log');
|
|
73
|
+
const env = fake('backlog', {
|
|
74
|
+
argsLog,
|
|
75
|
+
events: [
|
|
76
|
+
{ type: 'todo', change: 'added', status: 'notStarted', uid: 't1', title: 'A', initial: true },
|
|
77
|
+
me({ commentUid: 'c1', text: '@클로드코드 봐줘', createdAt: '2026-11-08T01:00:00.000Z' }),
|
|
78
|
+
me({ commentUid: 'c0', author: 'agent', text: '받았어요' }),
|
|
79
|
+
ready,
|
|
80
|
+
],
|
|
81
|
+
});
|
|
82
|
+
const r = run(env);
|
|
83
|
+
assert.equal(r.status, 0, r.stderr);
|
|
84
|
+
assert.deepEqual(lines(r).map((o) => o.listen), ['todo', 'mention']);
|
|
85
|
+
const s = state();
|
|
86
|
+
assert.deepEqual(s.tagged, ['t1']);
|
|
87
|
+
assert.deepEqual(s.seen, ['c1']);
|
|
88
|
+
assert.ok(s.threads.m1);
|
|
89
|
+
// 다시 띄우면 같은 밀린 것이 와도 내지 않는다 — 실시간 이벤트를 기다리다 이번엔 그 하나에 끝난다
|
|
90
|
+
const env2 = fake('again', {
|
|
91
|
+
argsLog,
|
|
92
|
+
events: [
|
|
93
|
+
{ type: 'todo', change: 'added', status: 'notStarted', uid: 't1', initial: true },
|
|
94
|
+
me({ commentUid: 'c1', text: '@클로드코드 봐줘' }),
|
|
95
|
+
ready,
|
|
96
|
+
50,
|
|
97
|
+
me({ commentUid: 'c2', text: '그거 말고 이거' }),
|
|
98
|
+
],
|
|
99
|
+
});
|
|
100
|
+
const r2 = run(env2);
|
|
101
|
+
assert.equal(r2.status, 0, r2.stderr);
|
|
102
|
+
assert.deepEqual(lines(r2).map((o) => [o.listen, o.commentUid]), [['reply', 'c2']]);
|
|
103
|
+
// 둘째 감시는 첫 감시가 ready 에서 당긴 since 로 띄운다
|
|
104
|
+
const calls = readFileSync(argsLog, 'utf-8').trim().split('\n').map((l) => JSON.parse(l));
|
|
105
|
+
assert.equal(calls.length, 2);
|
|
106
|
+
assert.equal(calls[1][calls[1].indexOf('--since') + 1], s.since);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test('--stream — 끝나지 않고 이벤트마다 한 줄, 감시가 끝나면 ended(2)', (t) => {
|
|
110
|
+
const { fake, run, lines } = sandbox(t);
|
|
111
|
+
const env = fake('stream', {
|
|
112
|
+
exitAfter: true,
|
|
113
|
+
events: [
|
|
114
|
+
ready, 20,
|
|
115
|
+
{ type: 'todo', change: 'added', status: 'notStarted', uid: 't9', title: '새 일' }, 20,
|
|
116
|
+
{ type: 'todo', change: 'modified', status: 'inProgress', uid: 't9' }, 20,
|
|
117
|
+
me({ commentUid: 'c9', text: '@클로드코드 하나 더' }),
|
|
118
|
+
],
|
|
119
|
+
});
|
|
120
|
+
const r = run(env, '--stream');
|
|
121
|
+
assert.equal(r.status, 2, r.stderr);
|
|
122
|
+
assert.deepEqual(lines(r).map((o) => o.listen), ['todo', 'mention', 'ended']);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test('--dry-run — 무엇이 깨울지만 보이고 상태를 쓰지 않는다 · --check 는 계정만', (t) => {
|
|
126
|
+
const { dir, fake, run, lines } = sandbox(t);
|
|
127
|
+
const env = fake('dry', { events: [{ type: 'todo', change: 'added', status: 'notStarted', uid: 't1', initial: true }, ready] });
|
|
128
|
+
const r = run(env, '--dry-run');
|
|
129
|
+
assert.equal(r.status, 0, r.stderr);
|
|
130
|
+
assert.deepEqual(lines(r).map((o) => o.listen), ['todo', 'dry-run']);
|
|
131
|
+
assert.throws(() => readFileSync(join(dir, 'state', 'listen.json')));
|
|
132
|
+
const c = run(fake('who', { whoami: { auth: 'oauth', ok: true, uid: 'u1', server: 'fake' } }), '--check');
|
|
133
|
+
assert.equal(c.status, 0, c.stderr);
|
|
134
|
+
assert.equal(lines(c)[0].uid, 'u1');
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('감시 오류·다른 계정은 3 으로 끝난다', (t) => {
|
|
138
|
+
const { config, fake, run, lines } = sandbox(t);
|
|
139
|
+
const err = run(fake('err', { events: [ready, { type: 'error', stream: 'comments', code: 'permission-denied', message: 'x' }] }));
|
|
140
|
+
assert.equal(err.status, 3);
|
|
141
|
+
assert.equal(lines(err).at(-1).listen, 'error');
|
|
142
|
+
writeFileSync(config, JSON.stringify({ odysseyBin: FAKE, statePath: './state/listen.json', expectedUid: 'me' }));
|
|
143
|
+
const other = run(fake('other', { events: [{ ...ready, uid: 'someone' }] }));
|
|
144
|
+
assert.equal(other.status, 3);
|
|
145
|
+
assert.equal(lines(other).at(-1).reason, 'account');
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
test('듣기는 하나 — 돌고 있으면 4, --replace 면 앞 듣기를 끝내고(5) 이어받는다', async (t) => {
|
|
149
|
+
const { dir, fake, run, lines, config } = sandbox(t);
|
|
150
|
+
const first = spawn(process.execPath, [LISTEN, '--config', config], { env: fake('quiet', { events: [ready] }) });
|
|
151
|
+
let firstOut = '';
|
|
152
|
+
first.stdout.on('data', (d) => { firstOut += d; });
|
|
153
|
+
const firstExit = new Promise((r) => first.on('close', r));
|
|
154
|
+
t.after(() => first.kill('SIGKILL'));
|
|
155
|
+
// 첫 듣기가 잠금을 잡을 때까지 기다린다 — 먼저 띄우면 두 번째가 잠금을 잡는다
|
|
156
|
+
const pidPath = join(dir, 'state', 'listen.json.pid');
|
|
157
|
+
const deadline = Date.now() + 5000;
|
|
158
|
+
const held = () => { try { return readFileSync(pidPath, 'utf-8').trim() === String(first.pid); } catch { return false; } };
|
|
159
|
+
while (!held() && Date.now() < deadline) await new Promise((r) => setTimeout(r, 20));
|
|
160
|
+
assert.ok(held(), '첫 듣기가 잠금을 잡아야 한다');
|
|
161
|
+
const busy = run(fake('busy', { events: [ready] }));
|
|
162
|
+
assert.equal(busy.status, 4);
|
|
163
|
+
assert.equal(lines(busy)[0].listen, 'busy');
|
|
164
|
+
const takeover = run(fake('takeover', { events: [ready, 20, me({ commentUid: 'x1', itemUid: 'y', tagged: true, text: '이어서' })] }), '--replace');
|
|
165
|
+
assert.equal(takeover.status, 0, takeover.stderr);
|
|
166
|
+
assert.equal(await firstExit, 5);
|
|
167
|
+
assert.match(firstOut, /"listen":"stopped"/);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
test('설정 — 모르는 키는 거절, 상대 경로는 설정 파일 기준', (t) => {
|
|
171
|
+
const { dir, config } = sandbox(t);
|
|
172
|
+
assert.equal(loadConfig(config).statePath, join(dir, 'state', 'listen.json'));
|
|
173
|
+
writeFileSync(config, JSON.stringify({ workDir: '.' }));
|
|
174
|
+
assert.throws(() => loadConfig(config), /모르는 키/);
|
|
175
|
+
});
|