@odyssey365/cli 0.0.0-stage → 0.1.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/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,169 @@
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
+ /** SSE 본문에서 JSON 메시지들을 꺼낸다. 이벤트 경계=빈 줄, 여러 data 줄은 \n 으로 잇는다. */
48
+ export function parseSseMessages(body) {
49
+ const out = [];
50
+ const events = body.replace(/\r\n/g, '\n').split(/\n\n+/);
51
+ for (const ev of events) {
52
+ const data = ev
53
+ .split('\n')
54
+ .filter((line) => line.startsWith('data:'))
55
+ .map((line) => line.slice(5).replace(/^ /, ''))
56
+ .join('\n');
57
+ if (!data.trim())
58
+ continue;
59
+ try {
60
+ out.push(JSON.parse(data));
61
+ }
62
+ catch {
63
+ // keep-alive 주석·깨진 조각은 건너뛴다
64
+ }
65
+ }
66
+ return out;
67
+ }
68
+ /** 응답 본문(JSON 또는 SSE)에서 id 가 맞는 JSON-RPC 응답을 고른다. */
69
+ export function pickResponse(contentType, body, id) {
70
+ let messages;
71
+ if (contentType.includes('text/event-stream')) {
72
+ messages = parseSseMessages(body);
73
+ }
74
+ else {
75
+ try {
76
+ const parsed = JSON.parse(body);
77
+ messages = Array.isArray(parsed) ? parsed : [parsed];
78
+ }
79
+ catch {
80
+ return null;
81
+ }
82
+ }
83
+ for (const m of messages) {
84
+ if (m && typeof m === 'object' && 'id' in m && m.id === id) {
85
+ return m;
86
+ }
87
+ }
88
+ return null;
89
+ }
90
+ /** 오류 응답 본문에서 사람이 읽을 메시지를 뽑는다(JSON-RPC error · OAuth error_description · 원문). */
91
+ export function errorMessageFromBody(body) {
92
+ try {
93
+ const j = JSON.parse(body);
94
+ if (j?.error?.message)
95
+ return String(j.error.message);
96
+ if (typeof j?.error_description === 'string')
97
+ return j.error_description;
98
+ if (typeof j?.error === 'string')
99
+ return j.error;
100
+ }
101
+ catch {
102
+ // 원문으로
103
+ }
104
+ return body.trim().slice(0, 500) || '(빈 응답)';
105
+ }
106
+ let nextId = 1;
107
+ /** JSON-RPC 요청 하나를 보내고 결과(result)를 돌려준다. */
108
+ export async function postRpc(opts, method, params) {
109
+ const id = nextId++;
110
+ const headers = {
111
+ 'Content-Type': 'application/json',
112
+ Accept: 'application/json, text/event-stream',
113
+ Authorization: `Bearer ${opts.bearer}`,
114
+ };
115
+ if (opts.protocolVersion !== null) {
116
+ headers['MCP-Protocol-Version'] = opts.protocolVersion ?? PREFERRED_PROTOCOL_VERSION;
117
+ }
118
+ if (opts.userAgent)
119
+ headers['User-Agent'] = opts.userAgent;
120
+ let res;
121
+ try {
122
+ res = await fetch(endpointUrl(opts.server), {
123
+ method: 'POST',
124
+ headers,
125
+ body: JSON.stringify({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) }),
126
+ signal: AbortSignal.timeout(timeoutMs()),
127
+ });
128
+ }
129
+ catch (e) {
130
+ throw new NetworkError(describeFetchError(e, opts.server));
131
+ }
132
+ const body = await res.text();
133
+ if (!res.ok) {
134
+ throw new HttpError(res.status, errorMessageFromBody(body), res.headers.get('www-authenticate') ?? undefined);
135
+ }
136
+ const msg = pickResponse(res.headers.get('content-type') ?? '', body, id);
137
+ if (!msg) {
138
+ throw new RpcError(-32700, `서버 응답을 해석할 수 없습니다: ${body.slice(0, 200)}`);
139
+ }
140
+ if (msg.error) {
141
+ throw new RpcError(msg.error.code, msg.error.message, msg.error.data);
142
+ }
143
+ return msg.result;
144
+ }
145
+ /** MCP 엔드포인트 = 서버 루트(끝 슬래시). */
146
+ export function endpointUrl(server) {
147
+ return server.replace(/\/+$/, '') + '/';
148
+ }
149
+ export function describeFetchError(e, server) {
150
+ const err = e;
151
+ if (err?.name === 'TimeoutError' || err?.name === 'AbortError') {
152
+ return `서버 응답이 ${Math.round(timeoutMs() / 1000)}초 안에 오지 않았습니다 (${server}). ODYSSEY_TIMEOUT_MS 로 늘릴 수 있습니다.`;
153
+ }
154
+ const cause = err?.cause?.code ?? err?.cause?.message ?? err?.message ?? String(e);
155
+ return `서버에 연결하지 못했습니다 (${server}): ${cause}`;
156
+ }
157
+ /** 프로토콜 버전 거절(400)인지 — 이때만 initialize 로 협상해 다시 보낸다. */
158
+ export function isProtocolVersionRejection(e) {
159
+ return e instanceof HttpError && e.status === 400 && /protocol version/i.test(e.message);
160
+ }
161
+ /** initialize 로 서버가 고른 프로토콜 버전을 받아 온다. */
162
+ export async function negotiateProtocolVersion(opts, clientVersion) {
163
+ const result = (await postRpc({ ...opts, protocolVersion: null }, 'initialize', {
164
+ protocolVersion: PREFERRED_PROTOCOL_VERSION,
165
+ capabilities: {},
166
+ clientInfo: { name: 'odyssey-cli', version: clientVersion },
167
+ }));
168
+ return result?.protocolVersion ?? PREFERRED_PROTOCOL_VERSION;
169
+ }
@@ -0,0 +1,191 @@
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, isProtocolVersionRejection, negotiateProtocolVersion, postRpc, } 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
+ /** 자격증명이 살아 있는지 가장 싸게 확인한다(MCP ping — 인증을 지나야 응답한다). */
161
+ async ping() {
162
+ await this.request('ping');
163
+ }
164
+ /** OAuth 프로필의 신원(/userinfo). 401 이면 한 번 갱신해 다시 묻는다. API 키·환경변수 토큰은 null. */
165
+ async userInfo() {
166
+ const cred = this.target.profile?.credential;
167
+ if (this.target.envToken || !cred || cred.type !== 'oauth')
168
+ return null;
169
+ const meta = await discover(this.target.server);
170
+ let info = await fetchUserInfo(this.target.server, meta, await this.bearer());
171
+ if (!info && this.canRefresh()) {
172
+ info = await fetchUserInfo(this.target.server, meta, await this.refresh());
173
+ }
174
+ return info;
175
+ }
176
+ async listTools() {
177
+ const tools = [];
178
+ let cursor;
179
+ for (let page = 0; page < 50; page++) {
180
+ const result = (await this.request('tools/list', cursor ? { cursor } : {}));
181
+ tools.push(...(result?.tools ?? []));
182
+ if (!result?.nextCursor)
183
+ break;
184
+ cursor = result.nextCursor;
185
+ }
186
+ return tools;
187
+ }
188
+ async callTool(name, args) {
189
+ return this.request('tools/call', { name, arguments: args });
190
+ }
191
+ }
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
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@odyssey365/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Odyssey CLI — 터미널과 AI 에이전트에서 Odyssey 계정(여러 개)의 할일·메모·보드·스냅샷을 다룬다",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=20"
8
+ },
9
+ "bin": {
10
+ "odyssey": "dist/index.js"
11
+ },
12
+ "files": [
13
+ "dist",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "prepublishOnly": "npm run build && npm test",
20
+ "test": "npm run build && node --test test/*.test.mjs",
21
+ "dev": "node dist/index.js"
22
+ },
23
+ "keywords": [
24
+ "odyssey",
25
+ "cli",
26
+ "mcp",
27
+ "todo",
28
+ "memo",
29
+ "claude",
30
+ "ai-agent"
31
+ ],
32
+ "license": "MIT",
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/Odyssey365App/odyssey30_60.git",
39
+ "directory": "back_end/odyssey_cli"
40
+ },
41
+ "devDependencies": {
42
+ "@types/node": "^22.0.0",
43
+ "typescript": "^5.7.3"
44
+ }
45
+ }