@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/oauth.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 브라우저 로그인(OAuth 2.1 인가 코드 + PKCE, 루프백 리다이렉트 RFC 8252).
|
|
3
|
+
*
|
|
4
|
+
* 서버(`mcp_streamable`)가 claude.ai 커넥터에 쓰는 그 인증서버를 그대로 쓴다 — 서버 변경 없이 된다:
|
|
5
|
+
* - DCR(/register): 로그인마다 공개 클라이언트(none)로 새로 등록한다. 리프레시 토큰이 clientId 에
|
|
6
|
+
* 묶이므로 clientId 는 프로필 자격증명에 함께 둔다(로그인은 드물어 등록 문서가 쌓일 일이 적다).
|
|
7
|
+
* - redirect_uri: `http://127.0.0.1/callback` 으로 등록하고 실제로는 임의 포트를 쓴다
|
|
8
|
+
* (서버 redirectUriMatches 가 루프백끼리는 포트를 완화한다).
|
|
9
|
+
* - 로그인 페이지(auth.odyssey365.app)는 매번 새로 로그인시키고(세션 영속 없음) 루프백 앱에는
|
|
10
|
+
* "확인되지 않은 앱" 경고를 띄우지 않는다 — 운영 계정으로 바꿔 로그인하기 쉽다.
|
|
11
|
+
* - 스코프 `mcp openid email`: openid·email 은 /userinfo 로 "누구로 로그인했나"를 받기 위해서다.
|
|
12
|
+
*
|
|
13
|
+
* 토큰: 액세스 60일 · 리프레시 무기한(회수 시까지). 리프레시는 회전하지 않는다(같은 값 재사용).
|
|
14
|
+
*/
|
|
15
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
16
|
+
import { createServer } from 'node:http';
|
|
17
|
+
import { spawn } from 'node:child_process';
|
|
18
|
+
import { errorMessageFromBody, fetchText } from './rpc.js';
|
|
19
|
+
export const CLIENT_NAME = 'Odyssey CLI';
|
|
20
|
+
export const LOGIN_SCOPE = 'mcp openid email';
|
|
21
|
+
const REGISTERED_REDIRECT = 'http://127.0.0.1/callback';
|
|
22
|
+
const CALLBACK_PATH = '/callback';
|
|
23
|
+
/** 서버의 로그인 세션 수명(10분)과 같다 — 그 뒤엔 어차피 code 를 못 받는다. */
|
|
24
|
+
const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
|
|
25
|
+
export class OAuthFlowError extends Error {
|
|
26
|
+
oauthError;
|
|
27
|
+
constructor(message, oauthError) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.oauthError = oauthError;
|
|
30
|
+
this.name = 'OAuthFlowError';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function base64url(buf) {
|
|
34
|
+
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
35
|
+
}
|
|
36
|
+
export function createPkce() {
|
|
37
|
+
const verifier = base64url(randomBytes(32));
|
|
38
|
+
const challenge = base64url(createHash('sha256').update(verifier).digest());
|
|
39
|
+
return { verifier, challenge };
|
|
40
|
+
}
|
|
41
|
+
async function fetchJson(url, init, server) {
|
|
42
|
+
const { response: res, body } = await fetchText(url, init, server);
|
|
43
|
+
let json = null;
|
|
44
|
+
try {
|
|
45
|
+
json = JSON.parse(body);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// 비 JSON
|
|
49
|
+
}
|
|
50
|
+
return { status: res.status, body, json };
|
|
51
|
+
}
|
|
52
|
+
/** RFC 8414 메타데이터. 없으면 관례 경로로 폴백한다. */
|
|
53
|
+
export async function discover(server) {
|
|
54
|
+
const base = server.replace(/\/+$/, '');
|
|
55
|
+
const fallback = {
|
|
56
|
+
authorization_endpoint: `${base}/authorize`,
|
|
57
|
+
token_endpoint: `${base}/token`,
|
|
58
|
+
registration_endpoint: `${base}/register`,
|
|
59
|
+
userinfo_endpoint: `${base}/userinfo`,
|
|
60
|
+
};
|
|
61
|
+
const r = await fetchJson(`${base}/.well-known/oauth-authorization-server`, { method: 'GET' }, server);
|
|
62
|
+
if (r.status !== 200 || !r.json?.authorization_endpoint || !r.json?.token_endpoint)
|
|
63
|
+
return fallback;
|
|
64
|
+
return {
|
|
65
|
+
authorization_endpoint: r.json.authorization_endpoint,
|
|
66
|
+
token_endpoint: r.json.token_endpoint,
|
|
67
|
+
registration_endpoint: r.json.registration_endpoint ?? fallback.registration_endpoint,
|
|
68
|
+
userinfo_endpoint: r.json.userinfo_endpoint ?? fallback.userinfo_endpoint,
|
|
69
|
+
revocation_endpoint: r.json.revocation_endpoint,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/** RFC 7591 동적 등록 — 공개 클라이언트(PKCE). */
|
|
73
|
+
export async function registerClient(server, meta, version) {
|
|
74
|
+
if (!meta.registration_endpoint) {
|
|
75
|
+
throw new OAuthFlowError('서버가 클라이언트 등록(DCR)을 지원하지 않습니다.');
|
|
76
|
+
}
|
|
77
|
+
const r = await fetchJson(meta.registration_endpoint, {
|
|
78
|
+
method: 'POST',
|
|
79
|
+
headers: { 'Content-Type': 'application/json' },
|
|
80
|
+
body: JSON.stringify({
|
|
81
|
+
client_name: CLIENT_NAME,
|
|
82
|
+
redirect_uris: [REGISTERED_REDIRECT],
|
|
83
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
84
|
+
response_types: ['code'],
|
|
85
|
+
token_endpoint_auth_method: 'none',
|
|
86
|
+
scope: LOGIN_SCOPE,
|
|
87
|
+
software_id: 'app.odyssey365.cli',
|
|
88
|
+
software_version: version,
|
|
89
|
+
}),
|
|
90
|
+
}, server);
|
|
91
|
+
if (r.status !== 201 && r.status !== 200) {
|
|
92
|
+
throw new OAuthFlowError(`클라이언트 등록 실패 (${r.status}): ${errorMessageFromBody(r.body)}`);
|
|
93
|
+
}
|
|
94
|
+
if (typeof r.json?.client_id !== 'string') {
|
|
95
|
+
throw new OAuthFlowError('클라이언트 등록 응답에 client_id 가 없습니다.');
|
|
96
|
+
}
|
|
97
|
+
return r.json.client_id;
|
|
98
|
+
}
|
|
99
|
+
async function postToken(server, meta, form) {
|
|
100
|
+
const r = await fetchJson(meta.token_endpoint, {
|
|
101
|
+
method: 'POST',
|
|
102
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
103
|
+
body: new URLSearchParams(form).toString(),
|
|
104
|
+
}, server);
|
|
105
|
+
if (r.status !== 200 || typeof r.json?.access_token !== 'string') {
|
|
106
|
+
throw new OAuthFlowError(`토큰 발급 실패 (${r.status}): ${errorMessageFromBody(r.body)}`, typeof r.json?.error === 'string' ? r.json.error : undefined);
|
|
107
|
+
}
|
|
108
|
+
return r.json;
|
|
109
|
+
}
|
|
110
|
+
export function refreshAccessToken(server, meta, clientId, refreshToken) {
|
|
111
|
+
return postToken(server, meta, {
|
|
112
|
+
grant_type: 'refresh_token',
|
|
113
|
+
client_id: clientId,
|
|
114
|
+
refresh_token: refreshToken,
|
|
115
|
+
resource: server.replace(/\/+$/, ''),
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
export async function fetchUserInfo(server, meta, accessToken) {
|
|
119
|
+
if (!meta.userinfo_endpoint)
|
|
120
|
+
return null;
|
|
121
|
+
const r = await fetchJson(meta.userinfo_endpoint, { method: 'GET', headers: { Authorization: `Bearer ${accessToken}` } }, server);
|
|
122
|
+
if (r.status !== 200 || typeof r.json?.sub !== 'string')
|
|
123
|
+
return null;
|
|
124
|
+
return { uid: r.json.sub, ...(typeof r.json.email === 'string' ? { email: r.json.email } : {}) };
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* RFC 7009 토큰 회수. 서버가 엔드포인트를 광고하지 않으면 false(로컬 삭제만 하게 된다).
|
|
128
|
+
* 리프레시 토큰을 보내면 서버가 짝 액세스 토큰까지 함께 회수한다.
|
|
129
|
+
*/
|
|
130
|
+
export async function revokeTokenRemote(server, meta, clientId, token) {
|
|
131
|
+
if (!meta.revocation_endpoint)
|
|
132
|
+
return false;
|
|
133
|
+
const r = await fetchJson(meta.revocation_endpoint, {
|
|
134
|
+
method: 'POST',
|
|
135
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
136
|
+
body: new URLSearchParams({ token, client_id: clientId }).toString(),
|
|
137
|
+
}, server);
|
|
138
|
+
if (r.status !== 200) {
|
|
139
|
+
throw new OAuthFlowError(`토큰 회수 실패 (${r.status}): ${errorMessageFromBody(r.body)}`);
|
|
140
|
+
}
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
/** 기본 브라우저로 URL 을 연다. 실패해도 조용히 넘어간다(URL 은 이미 화면에 찍혀 있다). */
|
|
144
|
+
export function openBrowser(url) {
|
|
145
|
+
let cmd;
|
|
146
|
+
let args;
|
|
147
|
+
if (process.platform === 'darwin') {
|
|
148
|
+
cmd = 'open';
|
|
149
|
+
args = [url];
|
|
150
|
+
}
|
|
151
|
+
else if (process.platform === 'win32') {
|
|
152
|
+
// cmd /c start 는 URL 의 & 를 명령 구분자로 읽는다 — rundll32 는 셸을 거치지 않는다.
|
|
153
|
+
cmd = 'rundll32';
|
|
154
|
+
args = ['url.dll,FileProtocolHandler', url];
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
cmd = 'xdg-open';
|
|
158
|
+
args = [url];
|
|
159
|
+
}
|
|
160
|
+
try {
|
|
161
|
+
const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
|
|
162
|
+
child.on('error', () => { });
|
|
163
|
+
child.unref();
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
// 무시
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const RESULT_PAGE = (ok, message) => `<!doctype html>
|
|
170
|
+
<html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
171
|
+
<title>Odyssey CLI</title>
|
|
172
|
+
<style>
|
|
173
|
+
:root{color-scheme:light dark;--bg:#f6f6f4;--fg:#1d1d1f;--sub:#6e6e73;--accent:${ok ? '#2e7d4f' : '#b3261e'}}
|
|
174
|
+
@media (prefers-color-scheme:dark){:root{--bg:#161618;--fg:#f2f2f2;--sub:#a1a1a6;--accent:${ok ? '#6fcf97' : '#f2b8b5'}}}
|
|
175
|
+
body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--fg);font:16px/1.5 -apple-system,BlinkMacSystemFont,"Apple SD Gothic Neo","Segoe UI",sans-serif}
|
|
176
|
+
main{max-width:420px;padding:32px 16px;text-align:center}
|
|
177
|
+
h1{font-size:20px;margin:0 0 8px;color:var(--accent)}p{margin:0;color:var(--sub)}
|
|
178
|
+
</style></head><body><main><h1>${ok ? '로그인되었습니다' : '로그인하지 못했습니다'}</h1><p>${message}</p></main></body></html>`;
|
|
179
|
+
function escapeHtml(s) {
|
|
180
|
+
return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* 루프백 서버를 띄우고 → 브라우저로 인가 페이지를 연 뒤 → code 를 받아 토큰으로 바꾼다.
|
|
184
|
+
*/
|
|
185
|
+
export async function interactiveLogin(opts) {
|
|
186
|
+
const { verifier, challenge } = createPkce();
|
|
187
|
+
const state = base64url(randomBytes(16));
|
|
188
|
+
let settle;
|
|
189
|
+
const codePromise = new Promise((resolve, reject) => {
|
|
190
|
+
settle = { resolve, reject };
|
|
191
|
+
});
|
|
192
|
+
const http = createServer((req, res) => {
|
|
193
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
194
|
+
if (url.pathname !== CALLBACK_PATH) {
|
|
195
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' }).end('not found');
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const send = (ok, message) => {
|
|
199
|
+
res.writeHead(ok ? 200 : 400, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
200
|
+
res.end(RESULT_PAGE(ok, escapeHtml(message)));
|
|
201
|
+
};
|
|
202
|
+
// state 가 다르면 이 로그인의 응답이 아니다 — 무시하고 계속 기다린다(다른 탭의 잔여 리다이렉트 등).
|
|
203
|
+
if (url.searchParams.get('state') !== state) {
|
|
204
|
+
send(false, '이 로그인 요청의 응답이 아닙니다. 터미널에서 다시 시도하세요.');
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const error = url.searchParams.get('error');
|
|
208
|
+
if (error) {
|
|
209
|
+
const desc = url.searchParams.get('error_description') ?? error;
|
|
210
|
+
send(false, desc);
|
|
211
|
+
settle.reject(new OAuthFlowError(`로그인이 거절되었습니다: ${desc}`, error));
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const code = url.searchParams.get('code');
|
|
215
|
+
if (!code) {
|
|
216
|
+
send(false, '인가 코드가 없습니다.');
|
|
217
|
+
settle.reject(new OAuthFlowError('콜백에 인가 코드가 없습니다.'));
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
send(true, '이 창을 닫고 터미널로 돌아가세요.');
|
|
221
|
+
settle.resolve(code);
|
|
222
|
+
});
|
|
223
|
+
await new Promise((resolve, reject) => {
|
|
224
|
+
http.once('error', reject);
|
|
225
|
+
http.listen(0, '127.0.0.1', () => resolve());
|
|
226
|
+
});
|
|
227
|
+
const port = http.address().port;
|
|
228
|
+
const redirectUri = `http://127.0.0.1:${port}${CALLBACK_PATH}`;
|
|
229
|
+
const authUrl = new URL(opts.meta.authorization_endpoint);
|
|
230
|
+
authUrl.searchParams.set('response_type', 'code');
|
|
231
|
+
authUrl.searchParams.set('client_id', opts.clientId);
|
|
232
|
+
authUrl.searchParams.set('redirect_uri', redirectUri);
|
|
233
|
+
authUrl.searchParams.set('code_challenge', challenge);
|
|
234
|
+
authUrl.searchParams.set('code_challenge_method', 'S256');
|
|
235
|
+
authUrl.searchParams.set('state', state);
|
|
236
|
+
authUrl.searchParams.set('scope', LOGIN_SCOPE);
|
|
237
|
+
authUrl.searchParams.set('resource', opts.server.replace(/\/+$/, ''));
|
|
238
|
+
opts.onAuthorizeUrl(authUrl.toString());
|
|
239
|
+
if (opts.launchBrowser)
|
|
240
|
+
openBrowser(authUrl.toString());
|
|
241
|
+
const timer = setTimeout(() => settle.reject(new OAuthFlowError('10분 안에 로그인이 끝나지 않았습니다. 다시 시도하세요.')), LOGIN_TIMEOUT_MS);
|
|
242
|
+
try {
|
|
243
|
+
const code = await codePromise;
|
|
244
|
+
return await postToken(opts.server, opts.meta, {
|
|
245
|
+
grant_type: 'authorization_code',
|
|
246
|
+
client_id: opts.clientId,
|
|
247
|
+
code,
|
|
248
|
+
redirect_uri: redirectUri,
|
|
249
|
+
code_verifier: verifier,
|
|
250
|
+
resource: opts.server.replace(/\/+$/, ''),
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
clearTimeout(timer);
|
|
255
|
+
http.closeAllConnections?.();
|
|
256
|
+
http.close();
|
|
257
|
+
}
|
|
258
|
+
}
|
package/dist/output.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 도구 결과 출력.
|
|
3
|
+
*
|
|
4
|
+
* -o json (기본) structuredContent(서버가 내는 기계판독 결과)를 JSON 으로. 없으면 텍스트 그대로.
|
|
5
|
+
* -o text 서버 포맷터의 텍스트(OAuth 연결은 마크다운 요약)
|
|
6
|
+
* -o raw MCP CallToolResult 전체
|
|
7
|
+
*
|
|
8
|
+
* JSON 은 터미널이면 들여쓰고, 파이프(에이전트·스크립트)면 한 줄로 낸다 — 토큰을 아낀다.
|
|
9
|
+
* 이미지 블록(read_memo_image 등)은 파일로 저장하고 경로만 출력한다 — 에이전트가 그 경로를 연다.
|
|
10
|
+
* 결과가 오류(isError)면 메시지를 stderr 로 내고 종료 코드 1.
|
|
11
|
+
*/
|
|
12
|
+
import { mkdirSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import { tmpdir } from 'node:os';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
export function writeJson(value) {
|
|
16
|
+
const pretty = process.stdout.isTTY === true || process.env.ODYSSEY_PRETTY === '1';
|
|
17
|
+
process.stdout.write(JSON.stringify(value, null, pretty ? 2 : undefined) + '\n');
|
|
18
|
+
}
|
|
19
|
+
const EXT = {
|
|
20
|
+
'image/png': 'png',
|
|
21
|
+
'image/jpeg': 'jpg',
|
|
22
|
+
'image/jpg': 'jpg',
|
|
23
|
+
'image/gif': 'gif',
|
|
24
|
+
'image/webp': 'webp',
|
|
25
|
+
'image/heic': 'heic',
|
|
26
|
+
'image/svg+xml': 'svg',
|
|
27
|
+
};
|
|
28
|
+
export function outputDir() {
|
|
29
|
+
return process.env.ODYSSEY_OUTPUT_DIR?.trim() || join(tmpdir(), 'odyssey-cli');
|
|
30
|
+
}
|
|
31
|
+
function saveImage(block, toolName, index) {
|
|
32
|
+
const dir = outputDir();
|
|
33
|
+
mkdirSync(dir, { recursive: true });
|
|
34
|
+
const ext = EXT[block.mimeType ?? ''] ?? 'bin';
|
|
35
|
+
const path = join(dir, `${toolName}-${Date.now()}-${index + 1}.${ext}`);
|
|
36
|
+
writeFileSync(path, Buffer.from(block.data ?? '', 'base64'));
|
|
37
|
+
return path;
|
|
38
|
+
}
|
|
39
|
+
/** 결과를 찍고 종료 코드를 돌려준다. */
|
|
40
|
+
export function printToolResult(result, format, toolName) {
|
|
41
|
+
const r = (result ?? {});
|
|
42
|
+
const blocks = Array.isArray(r.content) ? r.content : [];
|
|
43
|
+
const texts = blocks.filter((b) => b.type === 'text').map((b) => b.text ?? '');
|
|
44
|
+
if (r.isError) {
|
|
45
|
+
if (format === 'raw')
|
|
46
|
+
writeJson(r);
|
|
47
|
+
process.stderr.write(texts.join('\n').replace(/^오류:\s*/, '') + '\n');
|
|
48
|
+
return 1;
|
|
49
|
+
}
|
|
50
|
+
if (format === 'raw') {
|
|
51
|
+
writeJson(r);
|
|
52
|
+
return 0;
|
|
53
|
+
}
|
|
54
|
+
const images = blocks
|
|
55
|
+
.map((b, i) => ({ b, i }))
|
|
56
|
+
.filter(({ b }) => b.type === 'image' && typeof b.data === 'string')
|
|
57
|
+
.map(({ b, i }) => ({ path: saveImage(b, toolName, i), mimeType: b.mimeType }));
|
|
58
|
+
if (images.length > 0) {
|
|
59
|
+
if (format === 'text') {
|
|
60
|
+
process.stdout.write([...texts, ...images.map((im) => `[이미지] ${im.path}`)].join('\n') + '\n');
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
writeJson({ text: texts, images });
|
|
64
|
+
}
|
|
65
|
+
return 0;
|
|
66
|
+
}
|
|
67
|
+
if (format === 'text') {
|
|
68
|
+
process.stdout.write(texts.join('\n') + '\n');
|
|
69
|
+
return 0;
|
|
70
|
+
}
|
|
71
|
+
if (r.structuredContent !== undefined) {
|
|
72
|
+
writeJson(r.structuredContent);
|
|
73
|
+
return 0;
|
|
74
|
+
}
|
|
75
|
+
// 구조화 결과가 없는 도구(문자열 반환) — 텍스트가 JSON 이면 JSON 으로, 아니면 그대로.
|
|
76
|
+
const joined = texts.join('\n');
|
|
77
|
+
try {
|
|
78
|
+
writeJson(JSON.parse(joined));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
process.stdout.write(joined + '\n');
|
|
82
|
+
}
|
|
83
|
+
return 0;
|
|
84
|
+
}
|
package/dist/rpc.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP Streamable HTTP 위의 JSON-RPC 한 왕복.
|
|
3
|
+
*
|
|
4
|
+
* 서버(`mcp_streamable`)는 stateless 다(sessionIdGenerator: undefined) — 세션 검사가 없어
|
|
5
|
+
* initialize 없이 tools/call 을 바로 보내도 받는다. 그래서 명령 하나 = HTTP 한 번이다
|
|
6
|
+
* (SDK Client 는 initialize·initialized 를 먼저 보내 왕복이 셋이 된다). 서버가 프로토콜 버전을
|
|
7
|
+
* 거절하면 그때만 initialize 로 버전을 협상해 다시 보낸다.
|
|
8
|
+
*
|
|
9
|
+
* 응답은 JSON 이거나 SSE(text/event-stream)다. SSE 면 data 줄을 모아 같은 id 의 응답을 고른다.
|
|
10
|
+
* 의존성 0 — Node 20+ 의 fetch 만 쓴다.
|
|
11
|
+
*/
|
|
12
|
+
/** 서버가 받아 주는 버전 중 하나. 거절되면 initialize 로 다시 고른다. */
|
|
13
|
+
export const PREFERRED_PROTOCOL_VERSION = '2025-06-18';
|
|
14
|
+
/** HTTP 단계 실패(401·403·5xx 등). body 는 서버가 준 JSON-RPC 오류 메시지 또는 원문. */
|
|
15
|
+
export class HttpError extends Error {
|
|
16
|
+
status;
|
|
17
|
+
wwwAuthenticate;
|
|
18
|
+
constructor(status, message, wwwAuthenticate) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.wwwAuthenticate = wwwAuthenticate;
|
|
22
|
+
this.name = 'HttpError';
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** JSON-RPC 오류 응답(error 필드). */
|
|
26
|
+
export class RpcError extends Error {
|
|
27
|
+
code;
|
|
28
|
+
data;
|
|
29
|
+
constructor(code, message, data) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.code = code;
|
|
32
|
+
this.data = data;
|
|
33
|
+
this.name = 'RpcError';
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** 네트워크 자체가 실패(DNS·연결·타임아웃). */
|
|
37
|
+
export class NetworkError extends Error {
|
|
38
|
+
constructor(message) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.name = 'NetworkError';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export function timeoutMs() {
|
|
44
|
+
const v = Number(process.env.ODYSSEY_TIMEOUT_MS);
|
|
45
|
+
return Number.isFinite(v) && v > 0 ? v : 120_000;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* 요청 시작부터 본문 수신 완료까지 같은 제한시간·네트워크 오류 계약을 적용한다.
|
|
49
|
+
* 헤더를 받은 뒤에도 연결 중단·타임아웃이 날 수 있으므로 본문 읽기를 함께 감싼다.
|
|
50
|
+
* 이력: document/90-process/work-log/261022 Odyssey CLI 배포 안정성 npm watch 감시 에이전트 감사.md
|
|
51
|
+
*/
|
|
52
|
+
export async function fetchText(url, init, server) {
|
|
53
|
+
try {
|
|
54
|
+
const response = await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs()) });
|
|
55
|
+
const body = await response.text();
|
|
56
|
+
return { response, body };
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
throw new NetworkError(describeFetchError(e, server));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** SSE 본문에서 JSON 메시지들을 꺼낸다. 이벤트 경계=빈 줄, 여러 data 줄은 \n 으로 잇는다. */
|
|
63
|
+
export function parseSseMessages(body) {
|
|
64
|
+
const out = [];
|
|
65
|
+
const events = body.replace(/\r\n/g, '\n').split(/\n\n+/);
|
|
66
|
+
for (const ev of events) {
|
|
67
|
+
const data = ev
|
|
68
|
+
.split('\n')
|
|
69
|
+
.filter((line) => line.startsWith('data:'))
|
|
70
|
+
.map((line) => line.slice(5).replace(/^ /, ''))
|
|
71
|
+
.join('\n');
|
|
72
|
+
if (!data.trim())
|
|
73
|
+
continue;
|
|
74
|
+
try {
|
|
75
|
+
out.push(JSON.parse(data));
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// keep-alive 주석·깨진 조각은 건너뛴다
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
/** 응답 본문(JSON 또는 SSE)에서 id 가 맞는 JSON-RPC 응답을 고른다. */
|
|
84
|
+
export function pickResponse(contentType, body, id) {
|
|
85
|
+
let messages;
|
|
86
|
+
if (contentType.includes('text/event-stream')) {
|
|
87
|
+
messages = parseSseMessages(body);
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
try {
|
|
91
|
+
const parsed = JSON.parse(body);
|
|
92
|
+
messages = Array.isArray(parsed) ? parsed : [parsed];
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
for (const m of messages) {
|
|
99
|
+
if (m && typeof m === 'object' && 'id' in m && m.id === id) {
|
|
100
|
+
return m;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
/** 오류 응답 본문에서 사람이 읽을 메시지를 뽑는다(JSON-RPC error · OAuth error_description · 원문). */
|
|
106
|
+
export function errorMessageFromBody(body) {
|
|
107
|
+
try {
|
|
108
|
+
const j = JSON.parse(body);
|
|
109
|
+
if (j?.error?.message)
|
|
110
|
+
return String(j.error.message);
|
|
111
|
+
if (typeof j?.error_description === 'string')
|
|
112
|
+
return j.error_description;
|
|
113
|
+
if (typeof j?.error === 'string')
|
|
114
|
+
return j.error;
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
// 원문으로
|
|
118
|
+
}
|
|
119
|
+
return body.trim().slice(0, 500) || '(빈 응답)';
|
|
120
|
+
}
|
|
121
|
+
let nextId = 1;
|
|
122
|
+
/** JSON-RPC 요청 하나를 보내고 결과(result)를 돌려준다. */
|
|
123
|
+
export async function postRpc(opts, method, params) {
|
|
124
|
+
const id = nextId++;
|
|
125
|
+
const headers = {
|
|
126
|
+
'Content-Type': 'application/json',
|
|
127
|
+
Accept: 'application/json, text/event-stream',
|
|
128
|
+
Authorization: `Bearer ${opts.bearer}`,
|
|
129
|
+
};
|
|
130
|
+
if (opts.protocolVersion !== null) {
|
|
131
|
+
headers['MCP-Protocol-Version'] = opts.protocolVersion ?? PREFERRED_PROTOCOL_VERSION;
|
|
132
|
+
}
|
|
133
|
+
if (opts.userAgent)
|
|
134
|
+
headers['User-Agent'] = opts.userAgent;
|
|
135
|
+
const { response: res, body } = await fetchText(endpointUrl(opts.server), {
|
|
136
|
+
method: 'POST',
|
|
137
|
+
headers,
|
|
138
|
+
body: JSON.stringify({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) }),
|
|
139
|
+
}, opts.server);
|
|
140
|
+
if (!res.ok) {
|
|
141
|
+
throw new HttpError(res.status, errorMessageFromBody(body), res.headers.get('www-authenticate') ?? undefined);
|
|
142
|
+
}
|
|
143
|
+
const msg = pickResponse(res.headers.get('content-type') ?? '', body, id);
|
|
144
|
+
if (!msg) {
|
|
145
|
+
throw new RpcError(-32700, `서버 응답을 해석할 수 없습니다: ${body.slice(0, 200)}`);
|
|
146
|
+
}
|
|
147
|
+
if (msg.error) {
|
|
148
|
+
throw new RpcError(msg.error.code, msg.error.message, msg.error.data);
|
|
149
|
+
}
|
|
150
|
+
return msg.result;
|
|
151
|
+
}
|
|
152
|
+
/** MCP 엔드포인트 = 서버 루트(끝 슬래시). */
|
|
153
|
+
export function endpointUrl(server) {
|
|
154
|
+
return server.replace(/\/+$/, '') + '/';
|
|
155
|
+
}
|
|
156
|
+
export function describeFetchError(e, server) {
|
|
157
|
+
const err = e;
|
|
158
|
+
if (err?.name === 'TimeoutError' || err?.name === 'AbortError') {
|
|
159
|
+
return `서버 응답이 ${Math.round(timeoutMs() / 1000)}초 안에 오지 않았습니다 (${server}). ODYSSEY_TIMEOUT_MS 로 늘릴 수 있습니다.`;
|
|
160
|
+
}
|
|
161
|
+
const cause = err?.cause?.code ?? err?.cause?.message ?? err?.message ?? String(e);
|
|
162
|
+
return `서버에 연결하지 못했습니다 (${server}): ${cause}`;
|
|
163
|
+
}
|
|
164
|
+
/** 프로토콜 버전 거절(400)인지 — 이때만 initialize 로 협상해 다시 보낸다. */
|
|
165
|
+
export function isProtocolVersionRejection(e) {
|
|
166
|
+
return e instanceof HttpError && e.status === 400 && /protocol version/i.test(e.message);
|
|
167
|
+
}
|
|
168
|
+
/** initialize 로 서버가 고른 프로토콜 버전을 받아 온다. */
|
|
169
|
+
export async function negotiateProtocolVersion(opts, clientVersion) {
|
|
170
|
+
const result = (await postRpc({ ...opts, protocolVersion: null }, 'initialize', {
|
|
171
|
+
protocolVersion: PREFERRED_PROTOCOL_VERSION,
|
|
172
|
+
capabilities: {},
|
|
173
|
+
clientInfo: { name: 'odyssey-cli', version: clientVersion },
|
|
174
|
+
}));
|
|
175
|
+
return result?.protocolVersion ?? PREFERRED_PROTOCOL_VERSION;
|
|
176
|
+
}
|