@odyssey365/cli 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +296 -2
- package/dist/args.js +348 -0
- package/dist/config.js +124 -0
- package/dist/files.js +58 -0
- package/dist/guide.js +113 -0
- package/dist/index.js +502 -0
- package/dist/oauth.js +258 -0
- package/dist/output.js +84 -0
- package/dist/rpc.js +176 -0
- package/dist/session.js +247 -0
- package/dist/tools.js +159 -0
- package/dist/watch-agent.js +45 -0
- package/dist/watch-events.js +78 -0
- package/dist/watch.js +181 -0
- package/examples/watch-agent/README.md +124 -0
- package/examples/watch-agent/config.example.json +20 -0
- package/examples/watch-agent/dispatcher.mjs +1443 -0
- package/examples/watch-agent/gitignore.template +6 -0
- package/examples/watch-agent/package.json +12 -0
- package/examples/watch-agent/test/dispatcher.test.mjs +763 -0
- package/examples/watch-agent/test/supervisor.test.mjs +126 -0
- package/package.json +50 -4
- package/prompts/watch-agent.md +250 -0
package/dist/session.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "어느 계정으로, 어느 서버에" 를 정하고 그 자격증명으로 JSON-RPC 를 보낸다.
|
|
3
|
+
*
|
|
4
|
+
* 계정 선택 순서:
|
|
5
|
+
* 1. --profile/-p 플래그
|
|
6
|
+
* 2. 환경변수 ODYSSEY_TOKEN(또는 ODYSSEY_API_KEY) — CI·일회성 실행. 저장하지 않는다.
|
|
7
|
+
* 3. 환경변수 ODYSSEY_PROFILE
|
|
8
|
+
* 4. 자격증명 파일의 기본 프로필(`odyssey use`) → 없으면 "default"
|
|
9
|
+
*
|
|
10
|
+
* OAuth 프로필은 만료 하루 전부터 미리 갱신하고, 그래도 401 이 오면 한 번 더 갱신해 재시도한다.
|
|
11
|
+
*/
|
|
12
|
+
import { AuthRequiredError, DEFAULT_PROFILE, DEFAULT_SERVER, UsageError, assertProfileName, loadCredentials, normalizeServer, updateCredentials, } from './config.js';
|
|
13
|
+
import { discover, fetchUserInfo, OAuthFlowError, refreshAccessToken } from './oauth.js';
|
|
14
|
+
import { HttpError, PREFERRED_PROTOCOL_VERSION, isProtocolVersionRejection, negotiateProtocolVersion, postRpc, fetchText, } from './rpc.js';
|
|
15
|
+
const REFRESH_LEEWAY_MS = 24 * 60 * 60 * 1000;
|
|
16
|
+
export function envServer() {
|
|
17
|
+
const v = process.env.ODYSSEY_MCP_URL;
|
|
18
|
+
return v && v.trim() ? normalizeServer(v) : undefined;
|
|
19
|
+
}
|
|
20
|
+
/** 이번 실행에서 쓸 프로필 이름(파일을 읽기만 한다). */
|
|
21
|
+
export function selectedProfileName(opts) {
|
|
22
|
+
if (opts.profile)
|
|
23
|
+
return opts.profile;
|
|
24
|
+
const fromEnv = process.env.ODYSSEY_PROFILE;
|
|
25
|
+
if (fromEnv && fromEnv.trim())
|
|
26
|
+
return fromEnv.trim();
|
|
27
|
+
return loadCredentials().defaultProfile ?? DEFAULT_PROFILE;
|
|
28
|
+
}
|
|
29
|
+
export function resolveTarget(opts) {
|
|
30
|
+
const envToken = (process.env.ODYSSEY_TOKEN ?? process.env.ODYSSEY_API_KEY ?? '').trim();
|
|
31
|
+
if (!opts.profile && envToken) {
|
|
32
|
+
return {
|
|
33
|
+
profileName: null,
|
|
34
|
+
server: normalizeServer(opts.server ?? envServer() ?? DEFAULT_SERVER),
|
|
35
|
+
envToken,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
const name = selectedProfileName(opts);
|
|
39
|
+
assertProfileName(name);
|
|
40
|
+
const file = loadCredentials();
|
|
41
|
+
const profile = file.profiles[name];
|
|
42
|
+
if (!profile) {
|
|
43
|
+
const names = Object.keys(file.profiles);
|
|
44
|
+
throw new AuthRequiredError(`프로필 "${name}" 에 로그인되어 있지 않습니다. 먼저: odyssey login${name === DEFAULT_PROFILE ? '' : ` -p ${name}`}` +
|
|
45
|
+
(names.length ? `\n로그인된 프로필: ${names.join(', ')}` : ''));
|
|
46
|
+
}
|
|
47
|
+
if (opts.server && normalizeServer(opts.server) !== normalizeServer(profile.server)) {
|
|
48
|
+
throw new UsageError(`프로필 "${name}" 은 ${profile.server} 에 로그인되어 있습니다. 다른 서버를 쓰려면 다른 프로필로 로그인하세요.`);
|
|
49
|
+
}
|
|
50
|
+
return { profileName: name, server: normalizeServer(profile.server), profile };
|
|
51
|
+
}
|
|
52
|
+
function loginHint(target) {
|
|
53
|
+
if (target.profileName === null)
|
|
54
|
+
return 'ODYSSEY_TOKEN 을 확인하세요.';
|
|
55
|
+
return `다시 로그인: odyssey login${target.profileName === DEFAULT_PROFILE ? '' : ` -p ${target.profileName}`}`;
|
|
56
|
+
}
|
|
57
|
+
function isExpiringSoon(cred) {
|
|
58
|
+
if (!cred.expiresAt)
|
|
59
|
+
return false;
|
|
60
|
+
const t = Date.parse(cred.expiresAt);
|
|
61
|
+
return Number.isFinite(t) && t - Date.now() < REFRESH_LEEWAY_MS;
|
|
62
|
+
}
|
|
63
|
+
export class OdysseyClient {
|
|
64
|
+
target;
|
|
65
|
+
clientVersion;
|
|
66
|
+
protocolVersion;
|
|
67
|
+
constructor(target, clientVersion) {
|
|
68
|
+
this.target = target;
|
|
69
|
+
this.clientVersion = clientVersion;
|
|
70
|
+
}
|
|
71
|
+
get userAgent() {
|
|
72
|
+
return `odyssey-cli/${this.clientVersion} (node ${process.versions.node}; ${process.platform})`;
|
|
73
|
+
}
|
|
74
|
+
/** 지금 보낼 Bearer. OAuth 면 곧 만료될 때 미리 갱신한다. */
|
|
75
|
+
async bearer() {
|
|
76
|
+
if (this.target.envToken)
|
|
77
|
+
return this.target.envToken;
|
|
78
|
+
const cred = this.target.profile.credential;
|
|
79
|
+
if (cred.type === 'apiKey')
|
|
80
|
+
return cred.apiKey;
|
|
81
|
+
if (isExpiringSoon(cred) && cred.refreshToken) {
|
|
82
|
+
return this.refresh();
|
|
83
|
+
}
|
|
84
|
+
return cred.accessToken;
|
|
85
|
+
}
|
|
86
|
+
/** 리프레시 토큰으로 새 액세스 토큰을 받아 파일에 저장한다. */
|
|
87
|
+
async refresh() {
|
|
88
|
+
const name = this.target.profileName;
|
|
89
|
+
const cred = this.target.profile.credential;
|
|
90
|
+
if (cred.type !== 'oauth' || !cred.refreshToken) {
|
|
91
|
+
throw new AuthRequiredError(`프로필 "${name}" 의 자격증명이 만료되었습니다. ${loginHint(this.target)}`);
|
|
92
|
+
}
|
|
93
|
+
let tokens;
|
|
94
|
+
try {
|
|
95
|
+
const meta = await discover(this.target.server);
|
|
96
|
+
tokens = await refreshAccessToken(this.target.server, meta, cred.clientId, cred.refreshToken);
|
|
97
|
+
}
|
|
98
|
+
catch (e) {
|
|
99
|
+
if (e instanceof OAuthFlowError) {
|
|
100
|
+
throw new AuthRequiredError(`프로필 "${name}" 의 로그인이 풀렸습니다(${e.message}). ${loginHint(this.target)}`);
|
|
101
|
+
}
|
|
102
|
+
throw e;
|
|
103
|
+
}
|
|
104
|
+
const next = {
|
|
105
|
+
...cred,
|
|
106
|
+
accessToken: tokens.access_token,
|
|
107
|
+
refreshToken: tokens.refresh_token ?? cred.refreshToken,
|
|
108
|
+
expiresAt: tokens.expires_in ? new Date(Date.now() + tokens.expires_in * 1000).toISOString() : undefined,
|
|
109
|
+
scope: tokens.scope ?? cred.scope,
|
|
110
|
+
};
|
|
111
|
+
// 다른 실행이 그 사이 파일을 바꿨을 수 있다 — 다시 읽고 이 프로필의 자격증명만 갈아 끼운다.
|
|
112
|
+
updateCredentials((file) => {
|
|
113
|
+
const p = file.profiles[name];
|
|
114
|
+
if (p) {
|
|
115
|
+
p.credential = next;
|
|
116
|
+
p.savedAt = new Date().toISOString();
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
this.target.profile.credential = next;
|
|
120
|
+
return next.accessToken;
|
|
121
|
+
}
|
|
122
|
+
canRefresh() {
|
|
123
|
+
const cred = this.target.profile?.credential;
|
|
124
|
+
return !!cred && cred.type === 'oauth' && !!cred.refreshToken;
|
|
125
|
+
}
|
|
126
|
+
/** JSON-RPC 요청. 401 이면 한 번 갱신 후 재시도, 프로토콜 버전 거절이면 협상 후 재시도. */
|
|
127
|
+
async request(method, params) {
|
|
128
|
+
const send = (bearer) => postRpc({ server: this.target.server, bearer, protocolVersion: this.protocolVersion, userAgent: this.userAgent }, method, params);
|
|
129
|
+
let bearer = await this.bearer();
|
|
130
|
+
try {
|
|
131
|
+
return await send(bearer);
|
|
132
|
+
}
|
|
133
|
+
catch (e) {
|
|
134
|
+
if (e instanceof HttpError && e.status === 401 && this.canRefresh()) {
|
|
135
|
+
bearer = await this.refresh();
|
|
136
|
+
return this.mapAuthError(() => send(bearer));
|
|
137
|
+
}
|
|
138
|
+
if (isProtocolVersionRejection(e)) {
|
|
139
|
+
this.protocolVersion = await negotiateProtocolVersion({ server: this.target.server, bearer, userAgent: this.userAgent }, this.clientVersion);
|
|
140
|
+
return this.mapAuthError(() => send(bearer));
|
|
141
|
+
}
|
|
142
|
+
throw this.toAuthError(e);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
async mapAuthError(fn) {
|
|
146
|
+
try {
|
|
147
|
+
return await fn();
|
|
148
|
+
}
|
|
149
|
+
catch (e) {
|
|
150
|
+
throw this.toAuthError(e);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
toAuthError(e) {
|
|
154
|
+
if (e instanceof HttpError && (e.status === 401 || e.status === 403)) {
|
|
155
|
+
const who = this.target.profileName === null ? '환경변수 토큰' : `프로필 "${this.target.profileName}"`;
|
|
156
|
+
return new AuthRequiredError(`${who} 인증 실패 (${e.status}): ${e.message}\n${loginHint(this.target)}`);
|
|
157
|
+
}
|
|
158
|
+
return e;
|
|
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
|
+
}
|
|
198
|
+
/** 자격증명이 살아 있는지 가장 싸게 확인한다(MCP ping — 인증을 지나야 응답한다). */
|
|
199
|
+
async ping() {
|
|
200
|
+
await this.request('ping');
|
|
201
|
+
}
|
|
202
|
+
/** OAuth 프로필의 신원(/userinfo). 401 이면 한 번 갱신해 다시 묻는다. API 키·환경변수 토큰은 null. */
|
|
203
|
+
async userInfo() {
|
|
204
|
+
const cred = this.target.profile?.credential;
|
|
205
|
+
if (this.target.envToken || !cred || cred.type !== 'oauth')
|
|
206
|
+
return null;
|
|
207
|
+
const meta = await discover(this.target.server);
|
|
208
|
+
let info = await fetchUserInfo(this.target.server, meta, await this.bearer());
|
|
209
|
+
if (!info && this.canRefresh()) {
|
|
210
|
+
info = await fetchUserInfo(this.target.server, meta, await this.refresh());
|
|
211
|
+
}
|
|
212
|
+
return info;
|
|
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
|
+
}
|
|
232
|
+
async listTools() {
|
|
233
|
+
const tools = [];
|
|
234
|
+
let cursor;
|
|
235
|
+
for (let page = 0; page < 50; page++) {
|
|
236
|
+
const result = (await this.request('tools/list', cursor ? { cursor } : {}));
|
|
237
|
+
tools.push(...(result?.tools ?? []));
|
|
238
|
+
if (!result?.nextCursor)
|
|
239
|
+
break;
|
|
240
|
+
cursor = result.nextCursor;
|
|
241
|
+
}
|
|
242
|
+
return tools;
|
|
243
|
+
}
|
|
244
|
+
async callTool(name, args) {
|
|
245
|
+
return this.request('tools/call', { name, arguments: args });
|
|
246
|
+
}
|
|
247
|
+
}
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 도구 목록 — 서버가 정본이다(`mcp_streamable` 의 allTools). CLI 는 정의를 들고 있지 않는다.
|
|
3
|
+
*
|
|
4
|
+
* 플래그 형 맞춤·describe 에 스키마가 필요해 tools/list 결과를 캐시한다. 도구 목록은 계정과
|
|
5
|
+
* 무관하므로(조건부 등록 없음) 서버 URL 하나에 캐시 하나다. 6시간이 지나거나, 캐시에 없는 도구
|
|
6
|
+
* 이름이 오거나, --refresh-tools 를 주면 다시 받는다.
|
|
7
|
+
*/
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
import { readFileSync } from 'node:fs';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { configDir, UsageError, writePrivateFile } from './config.js';
|
|
12
|
+
import { typeLabel } from './args.js';
|
|
13
|
+
const CACHE_TTL_MS = 6 * 60 * 60 * 1000;
|
|
14
|
+
function cachePath(server) {
|
|
15
|
+
const key = createHash('sha256').update(server).digest('hex').slice(0, 12);
|
|
16
|
+
return join(configDir(), 'cache', `tools-${key}.json`);
|
|
17
|
+
}
|
|
18
|
+
function readCache(server) {
|
|
19
|
+
try {
|
|
20
|
+
const c = JSON.parse(readFileSync(cachePath(server), 'utf-8'));
|
|
21
|
+
if (c.server !== server || !Array.isArray(c.tools))
|
|
22
|
+
return null;
|
|
23
|
+
return c;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function isFresh(c) {
|
|
30
|
+
const t = Date.parse(c.fetchedAt);
|
|
31
|
+
return Number.isFinite(t) && Date.now() - t < CACHE_TTL_MS;
|
|
32
|
+
}
|
|
33
|
+
export async function fetchTools(client) {
|
|
34
|
+
const tools = (await client.listTools());
|
|
35
|
+
const server = client.target.server;
|
|
36
|
+
try {
|
|
37
|
+
writePrivateFile(cachePath(server), JSON.stringify({ server, fetchedAt: new Date().toISOString(), tools }));
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// 캐시는 최적화일 뿐 — 못 써도 진행
|
|
41
|
+
}
|
|
42
|
+
return tools;
|
|
43
|
+
}
|
|
44
|
+
export async function getTools(client, opts = {}) {
|
|
45
|
+
if (!opts.refresh) {
|
|
46
|
+
const c = readCache(client.target.server);
|
|
47
|
+
if (c && isFresh(c))
|
|
48
|
+
return c.tools;
|
|
49
|
+
}
|
|
50
|
+
return fetchTools(client);
|
|
51
|
+
}
|
|
52
|
+
/** 이름으로 도구를 찾는다. 케밥(list-todos)도 받는다. 캐시에 없으면 한 번 새로 받아 본다. */
|
|
53
|
+
export async function findTool(client, rawName, opts = {}) {
|
|
54
|
+
const name = normalizeToolName(rawName);
|
|
55
|
+
let tools = await getTools(client, opts);
|
|
56
|
+
let tool = tools.find((t) => t.name === name);
|
|
57
|
+
if (!tool && !opts.refresh) {
|
|
58
|
+
tools = await fetchTools(client);
|
|
59
|
+
tool = tools.find((t) => t.name === name);
|
|
60
|
+
}
|
|
61
|
+
if (!tool) {
|
|
62
|
+
const near = suggestNames(name, tools.map((t) => t.name));
|
|
63
|
+
throw new UsageError(`알 수 없는 명령·도구 "${rawName}".` +
|
|
64
|
+
(near.length ? ` 혹시: ${near.join(', ')}` : '') +
|
|
65
|
+
'\n도구 목록: odyssey tools');
|
|
66
|
+
}
|
|
67
|
+
return tool;
|
|
68
|
+
}
|
|
69
|
+
export function normalizeToolName(name) {
|
|
70
|
+
return name.trim().replace(/-/g, '_');
|
|
71
|
+
}
|
|
72
|
+
function suggestNames(name, names) {
|
|
73
|
+
const parts = name.split('_').filter((p) => p.length > 2);
|
|
74
|
+
const scored = names
|
|
75
|
+
.map((n) => ({ n, hits: parts.filter((p) => n.includes(p)).length }))
|
|
76
|
+
.filter((x) => x.hits > 0)
|
|
77
|
+
.sort((a, b) => b.hits - a.hits);
|
|
78
|
+
return scored.slice(0, 4).map((x) => x.n);
|
|
79
|
+
}
|
|
80
|
+
export function isReadOnly(tool) {
|
|
81
|
+
return tool.annotations?.readOnlyHint === true;
|
|
82
|
+
}
|
|
83
|
+
function kindLabel(tool) {
|
|
84
|
+
if (isReadOnly(tool))
|
|
85
|
+
return '읽기';
|
|
86
|
+
if (tool.annotations?.destructiveHint)
|
|
87
|
+
return '쓰기·덮어씀';
|
|
88
|
+
return '쓰기';
|
|
89
|
+
}
|
|
90
|
+
/** 설명의 첫 문장(첫 줄)만. 목록에서 한 줄로 보이게. */
|
|
91
|
+
function firstLine(text) {
|
|
92
|
+
if (!text)
|
|
93
|
+
return '';
|
|
94
|
+
const line = text.split('\n').find((l) => l.trim()) ?? '';
|
|
95
|
+
return line.trim().length > 90 ? line.trim().slice(0, 88) + '…' : line.trim();
|
|
96
|
+
}
|
|
97
|
+
export function renderToolList(tools, filter) {
|
|
98
|
+
const f = filter?.toLowerCase();
|
|
99
|
+
const rows = tools.filter((t) => !f ||
|
|
100
|
+
t.name.includes(f) ||
|
|
101
|
+
(t.title ?? '').toLowerCase().includes(f) ||
|
|
102
|
+
(t.description ?? '').toLowerCase().includes(f));
|
|
103
|
+
if (rows.length === 0)
|
|
104
|
+
return `"${filter}" 에 맞는 도구가 없습니다.`;
|
|
105
|
+
const width = Math.max(...rows.map((t) => t.name.length));
|
|
106
|
+
return rows
|
|
107
|
+
.map((t) => `${t.name.padEnd(width)} [${kindLabel(t)}] ${t.title ? `${t.title} — ` : ''}${firstLine(t.description)}`)
|
|
108
|
+
.join('\n');
|
|
109
|
+
}
|
|
110
|
+
export function toolListJson(tools) {
|
|
111
|
+
return tools.map((t) => ({
|
|
112
|
+
name: t.name,
|
|
113
|
+
title: t.title,
|
|
114
|
+
readOnly: isReadOnly(t),
|
|
115
|
+
destructive: t.annotations?.destructiveHint === true,
|
|
116
|
+
summary: firstLine(t.description),
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
/** describe 출력 — 설명 전문 + 파라미터 표 + 예시 한 줄. */
|
|
120
|
+
export function renderToolDetail(tool) {
|
|
121
|
+
const lines = [];
|
|
122
|
+
lines.push(`${tool.name}${tool.title ? ` — ${tool.title}` : ''} [${kindLabel(tool)}]`);
|
|
123
|
+
lines.push('');
|
|
124
|
+
if (tool.description)
|
|
125
|
+
lines.push(tool.description.trim(), '');
|
|
126
|
+
const props = tool.inputSchema?.properties ?? {};
|
|
127
|
+
const required = new Set(tool.inputSchema?.required ?? []);
|
|
128
|
+
const entries = Object.entries(props);
|
|
129
|
+
if (entries.length === 0) {
|
|
130
|
+
lines.push('파라미터: 없음');
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
lines.push('파라미터:');
|
|
134
|
+
for (const [key, schema] of entries) {
|
|
135
|
+
const req = required.has(key) ? ' (필수)' : '';
|
|
136
|
+
lines.push(` --${key} <${typeLabel(schema)}>${req}`);
|
|
137
|
+
const desc = schema.description?.trim();
|
|
138
|
+
if (desc) {
|
|
139
|
+
for (const d of desc.split('\n'))
|
|
140
|
+
lines.push(` ${d}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
lines.push('', `예: ${exampleCommand(tool)}`);
|
|
145
|
+
return lines.join('\n');
|
|
146
|
+
}
|
|
147
|
+
function exampleCommand(tool) {
|
|
148
|
+
const props = tool.inputSchema?.properties ?? {};
|
|
149
|
+
const required = tool.inputSchema?.required ?? [];
|
|
150
|
+
const parts = [`odyssey ${tool.name}`];
|
|
151
|
+
if (required.length === 1) {
|
|
152
|
+
parts.push(`<${required[0]}>`);
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
for (const k of required)
|
|
156
|
+
parts.push(`--${k} <${typeLabel(props[k])}>`);
|
|
157
|
+
}
|
|
158
|
+
return parts.join(' ');
|
|
159
|
+
}
|
|
@@ -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
|
+
}
|