@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Odyssey365
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,181 @@
1
- # Temporary Holding Version
1
+ # Odyssey CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Command-line client for [Odyssey](https://product.odyssey365.app) — manage tasks, memos, boards and snapshots
4
+ > from your terminal or an AI agent, across **multiple Odyssey accounts**.
5
+
6
+ Odyssey MCP 커넥터와 **같은 서버·같은 도구**를 터미널에서 부른다. 다른 점은 계정이다 — 커넥터는 연결 하나에
7
+ 계정 하나지만, CLI 는 **호출마다 프로필(계정)을 고른다**. 개인 계정과 운영 계정을 한 세션에서 오가거나,
8
+ AI 에이전트(Claude Code 등)가 두 계정을 함께 다루게 할 때 쓴다.
9
+
10
+ ```bash
11
+ npm i -g @odyssey365/cli
12
+
13
+ odyssey login # 브라우저로 로그인 → 프로필 default
14
+ odyssey login -p work # 다른 계정 → 프로필 work
15
+
16
+ odyssey list_todos --status inProgress
17
+ odyssey -p work search "주간 회의"
18
+ odyssey get_todo <todoId>
19
+ ```
20
+
21
+ Node.js 20 이상. 런타임 의존성 없음.
22
+
23
+ ## 계정
24
+
25
+ | 명령 | 하는 일 |
26
+ |---|---|
27
+ | `odyssey login [-p 이름]` | 브라우저로 로그인해 프로필에 저장. 처음 로그인한 프로필이 기본이 된다 |
28
+ | `odyssey login -p 이름 --no-browser` | 브라우저를 열지 않고 로그인 주소만 출력 |
29
+ | `odyssey login -p 이름 --with-key` | 앱에서 발급한 API 키(`odk_…`)로 저장 — 표준입력 또는 숨김 입력 |
30
+ | `odyssey whoami [-p 이름]` | 그 프로필이 어느 계정인지 서버에 물어 확인 |
31
+ | `odyssey profiles` | 로그인된 프로필 목록(`*` = 기본) |
32
+ | `odyssey use 이름` | 기본 프로필 바꾸기 |
33
+ | `odyssey logout [-p 이름] [--all]` | 서버에서 토큰을 회수하고 로컬에서 지운다 |
34
+
35
+ 로그인은 Odyssey 의 OAuth 2.1(PKCE) 흐름이다. CLI 가 이 컴퓨터에 잠깐 루프백 주소(`127.0.0.1`)를 열고,
36
+ 브라우저 로그인이 끝나면 그 주소로 돌아온 인가 코드를 토큰으로 바꾼다. 로그인 페이지는 매번 새로 로그인하므로
37
+ 다른 계정으로 바꿔 로그인하기 쉽다.
38
+
39
+ 토큰은 `~/.odyssey/cli/credentials.json`(권한 0600)에 저장된다. 액세스 토큰은 60일이고, 만료 하루 전부터
40
+ 리프레시 토큰으로 알아서 갱신한다.
41
+
42
+ **계정 고르는 순서**: `-p/--profile` → 환경변수 `ODYSSEY_TOKEN`(저장 없이 토큰 직접) → `ODYSSEY_PROFILE`
43
+ → `odyssey use` 로 정한 기본 → `default`.
44
+
45
+ ## 도구
46
+
47
+ 도구 정의는 서버가 정본이다. 서버에 도구가 늘면 CLI 를 업데이트하지 않아도 바로 쓸 수 있다.
48
+
49
+ ```bash
50
+ odyssey tools # 전체 목록 ([읽기]/[쓰기] 표시)
51
+ odyssey tools memo # 검색
52
+ odyssey describe create_todo # 설명 전문 + 파라미터
53
+ odyssey create_todo --help # 같은 것
54
+ ```
55
+
56
+ ### 파라미터 적는 법
57
+
58
+ ```bash
59
+ odyssey create_todo --title "보고서 쓰기" --isToday --tags 업무 --tags 급함
60
+ odyssey create_todo --title "마감" --deadline.endTime 2026-10-20T18:00:00+09:00
61
+ odyssey create_todo --title "체크" --checklist '[{"title":"초안"},{"title":"검토"}]'
62
+ odyssey update_todo <todoId> --deadline null
63
+ odyssey create_memo --json '{"title":"회의록","text":"..."}'
64
+ cat input.json | odyssey create_memo --input -
65
+ ```
66
+
67
+ - 값의 형은 서버 스키마를 보고 맞춘다(`--limit 5` → 숫자).
68
+ - boolean 은 `--flag` / `--no-flag`, 배열은 반복하거나 JSON 으로, 객체 안쪽은 점 경로로.
69
+ - 필수 파라미터가 하나뿐인 도구는 위치 인자로 받는다(`odyssey get_todo <todoId>`).
70
+ - 도구 이름은 케밥으로 써도 된다(`odyssey list-todos`).
71
+
72
+ ### 출력
73
+
74
+ 결과는 stdout, 안내·오류는 stderr 로 나뉜다.
75
+
76
+ | `-o` | 내용 |
77
+ |---|---|
78
+ | `json`(기본) | 서버의 구조화 결과. 터미널이면 들여쓰고, 파이프면 한 줄 |
79
+ | `text` | 서버가 만든 요약 텍스트 |
80
+ | `raw` | MCP `CallToolResult` 전체 |
81
+
82
+ 이미지를 돌려주는 도구(`read_memo_image` 등)는 이미지를 파일로 저장하고 경로를 출력한다
83
+ (`ODYSSEY_OUTPUT_DIR`, 기본은 임시 폴더).
84
+
85
+ 종료 코드: `0` 성공 · `1` 도구 오류 · `2` 사용법 오류 · `3` 로그인 필요 · `4` 네트워크
86
+
87
+ ## AI 에이전트에서
88
+
89
+ CLI 는 비대화형으로 설계됐다(로그인만 빼고). 에이전트에게는 이렇게 알려 주면 된다:
90
+
91
+ ```
92
+ Odyssey 데이터는 `odyssey` CLI 로 다룬다. `odyssey tools` 로 도구를 찾고, `odyssey describe <도구>` 로
93
+ 파라미터를 확인한 뒤 `odyssey <도구> --파라미터 값` 으로 호출한다. 계정은 `-p <프로필>` 로 고른다.
94
+ 결과는 JSON 이다.
95
+ ```
96
+
97
+ ## 프로그램에서 쓰기 — 활동 자동 기록 (예: 게임 기록기)
98
+
99
+ 사람 없이 도는 프로그램(게임 프로세스 감시기 등)이 "언제부터 언제까지 무엇을 했다"를 남기는 법.
100
+
101
+ **1. 한 번만** — 그 PC 에서 로그인하고, 시간을 쌓을 기록을 만든다.
102
+
103
+ ```bash
104
+ odyssey login # 브라우저 로그인 한 번 — 이후 토큰은 알아서 갱신된다
105
+ odyssey create_record --title "리그 오브 레전드" --emoji 🎮 --numType time --numUnit min --tags 게임
106
+ # → {"recordId":"…"} 를 프로그램 설정에 저장
107
+ ```
108
+
109
+ **2. 세션이 끝날 때마다** — 측정값 하나 = 기록 통계(주·월 합계) + 타임라인 카드(그 구간).
110
+
111
+ ```json
112
+ {
113
+ "recordId": "<위 recordId>",
114
+ "value": 133,
115
+ "time": "2026-10-10T21:03:00+09:00",
116
+ "endTime": "2026-10-10T23:16:00+09:00",
117
+ "dedupeKey": "lol-2026-10-10T21:03:00+09:00"
118
+ }
119
+ ```
120
+
121
+ ```bash
122
+ odyssey add_record_trace --input - # 위 JSON 을 표준입력으로
123
+ ```
124
+
125
+ 기록 없이 타임라인 카드만 원하면 `create_timeline_event` 에 `title`·`startTime`·`endTime`(+`dedupeKey`)을 준다 —
126
+ 시작·끝이 둘 다 있으면 다른 내용 없이도 만들어진다.
127
+
128
+ **지켜야 할 것**
129
+
130
+ - **JSON 은 표준입력으로**(`--input -`). Windows 의 cmd 는 명령줄의 따옴표·`&`·`^`·`%` 를 제멋대로 해석한다.
131
+ - **`dedupeKey` 를 꼭 준다.** 같은 세션이면 같은 키(예: 게임 + 시작 시각). 오프라인이었거나 응답을 못 받아 다시 보내도
132
+ 측정값·카드가 한 번만 생긴다(`"deduplicated": true` 가 돌아온다).
133
+ - **시각은 오프셋을 붙인 ISO 8601**(`+09:00` 또는 `Z`). 못 읽는 시각은 거절된다.
134
+ - **종료 코드로 갈라 처리한다**: `0` 완료 · `4` 네트워크 → 쌓아 두고 같은 `dedupeKey` 로 나중에 재전송 ·
135
+ `3` 로그인 필요 → 사용자에게 알림(`odyssey login`) · `1`·`2` 입력 문제 → 재전송해도 같다, 로그로 남긴다.
136
+ - 출력(stdout)은 UTF-8 JSON 한 줄, 오류 메시지는 stderr.
137
+
138
+ **Windows 에서 부르는 법**
139
+
140
+ - 프로그램에서는 `odyssey.cmd`(npm 전역 설치가 만드는 실행 파일)를 부르거나, 셸을 거치지 않으려면
141
+ `node "%APPDATA%\npm\node_modules\@odyssey365\cli\dist\index.js"` 를 직접 부른다.
142
+ - PowerShell 에서 `odyssey` 가 "스크립트를 실행할 수 없습니다"로 막히면 실행 정책 때문이다 — `odyssey.cmd` 로 부르거나
143
+ `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`.
144
+
145
+ ```python
146
+ # Python 예 — 세션 하나 기록
147
+ import json, subprocess
148
+ payload = {"recordId": RECORD_ID, "value": minutes, "time": start_iso, "endTime": end_iso,
149
+ "dedupeKey": f"lol-{start_iso}"}
150
+ p = subprocess.run(["odyssey.cmd", "add_record_trace", "--input", "-"],
151
+ input=json.dumps(payload), capture_output=True, text=True, encoding="utf-8")
152
+ if p.returncode == 4: queue_for_retry(payload) # 네트워크 — 같은 키로 나중에
153
+ elif p.returncode == 3: notify("odyssey login 이 필요합니다")
154
+ elif p.returncode != 0: log_error(p.stderr)
155
+ ```
156
+
157
+ ## 환경변수
158
+
159
+ | 이름 | 뜻 |
160
+ |---|---|
161
+ | `ODYSSEY_PROFILE` | 기본 프로필 대신 쓸 프로필 |
162
+ | `ODYSSEY_TOKEN` | 저장 없이 쓸 토큰(`odk_` API 키 또는 `oat_` 토큰). `ODYSSEY_API_KEY` 도 받는다 |
163
+ | `ODYSSEY_MCP_URL` | 서버 주소(기본 `https://mcp-odyssey30-60.odyssey365.app`) |
164
+ | `ODYSSEY_CONFIG_DIR` | 자격증명·캐시 위치(기본 `~/.odyssey/cli`) |
165
+ | `ODYSSEY_OUTPUT_DIR` | 이미지 저장 위치 |
166
+ | `ODYSSEY_TIMEOUT_MS` | 요청 제한 시간(기본 120000) |
167
+ | `ODYSSEY_PRETTY=1` | 파이프에서도 JSON 들여쓰기 |
168
+
169
+ ## 개발
170
+
171
+ ```bash
172
+ npm install
173
+ npm test # 빌드 + 단위 테스트 + 가짜 서버 E2E(로그인 → 호출 → 토큰 갱신 → 로그아웃)
174
+ node dist/index.js --help
175
+ ```
176
+
177
+ 배포: `npm publish`(`prepublishOnly` 가 빌드·테스트를 돈다).
178
+
179
+ ## License
180
+
181
+ MIT
package/dist/args.js ADDED
@@ -0,0 +1,348 @@
1
+ /**
2
+ * 명령줄 해석 — 전역 옵션과 도구 파라미터 플래그.
3
+ *
4
+ * 도구 파라미터는 서버가 tools/list 로 내는 JSON Schema 를 보고 형을 맞춘다. 스키마 없이
5
+ * 문자열로 보내면 `--limit 5` 가 "5" 로 가고, 서버의 zod 가 "Expected number" 로 거절한다.
6
+ *
7
+ * --key value · --key=value 값
8
+ * --flag · --no-flag boolean
9
+ * --tags a --tags b 배열(반복) · --tags '["a","b"]' 도 된다
10
+ * --deadline.endTime 2026-… 객체 안쪽 필드(점 경로) · --deadline '{"endTime":"…"}' 도 된다
11
+ * --deadline null null 을 받는 필드
12
+ * --json '{…}' · --input file|- JSON 으로 한 번에(플래그가 그 위에 덮인다)
13
+ * <값> 필수 파라미터가 하나뿐이면 위치 인자로 받는다(get_todo <id>)
14
+ *
15
+ * 스키마에 없는 키는 그대로 보낸다 — 서버가 "이걸 의도했나요?" 로 고쳐 준다(D458).
16
+ */
17
+ import { UsageError } from './config.js';
18
+ /** 값 하나를 받는 전역 옵션(긴 이름 → 필드). */
19
+ const GLOBAL_WITH_VALUE = {
20
+ '-p': 'profile',
21
+ '--profile': 'profile',
22
+ '--server': 'server',
23
+ '-o': 'output',
24
+ '--output': 'output',
25
+ '--input': 'inputFile',
26
+ '--json': 'inputJson',
27
+ };
28
+ const GLOBAL_FLAGS = {
29
+ '-h': 'help',
30
+ '--help': 'help',
31
+ '-v': 'version',
32
+ '--version': 'version',
33
+ '--refresh-tools': 'refreshTools',
34
+ };
35
+ /**
36
+ * 전역 옵션을 어디에 있든 걷어 내고 나머지를 순서대로 돌려준다. `--` 뒤는 손대지 않는다
37
+ * (도구 파라미터 이름이 전역 옵션과 겹칠 때의 탈출구).
38
+ */
39
+ export function extractGlobals(argv) {
40
+ const globals = { help: false, version: false, refreshTools: false };
41
+ const rest = [];
42
+ for (let i = 0; i < argv.length; i++) {
43
+ const tok = argv[i];
44
+ if (tok === '--') {
45
+ rest.push(...argv.slice(i));
46
+ break;
47
+ }
48
+ const eq = tok.startsWith('--') ? tok.indexOf('=') : -1;
49
+ const name = eq > 0 ? tok.slice(0, eq) : tok;
50
+ if (name in GLOBAL_WITH_VALUE) {
51
+ let value;
52
+ if (eq > 0)
53
+ value = tok.slice(eq + 1);
54
+ else {
55
+ value = argv[i + 1];
56
+ i++;
57
+ }
58
+ if (value === undefined)
59
+ throw new UsageError(`${name} 에 값이 필요합니다.`);
60
+ const field = GLOBAL_WITH_VALUE[name];
61
+ if (field === 'output') {
62
+ if (value !== 'json' && value !== 'text' && value !== 'raw') {
63
+ throw new UsageError(`--output 은 json · text · raw 중 하나입니다 (받은 값: ${value}).`);
64
+ }
65
+ globals.output = value;
66
+ }
67
+ else {
68
+ globals[field] = value;
69
+ }
70
+ continue;
71
+ }
72
+ if (eq < 0 && tok in GLOBAL_FLAGS) {
73
+ globals[GLOBAL_FLAGS[tok]] = true;
74
+ continue;
75
+ }
76
+ rest.push(tok);
77
+ }
78
+ return { globals, rest };
79
+ }
80
+ /** 명령별 단순 플래그(--no-browser 등)를 걷어 낸다. */
81
+ export function takeFlag(args, ...names) {
82
+ let found = false;
83
+ for (let i = args.length - 1; i >= 0; i--) {
84
+ if (names.includes(args[i])) {
85
+ args.splice(i, 1);
86
+ found = true;
87
+ }
88
+ }
89
+ return found;
90
+ }
91
+ // ── 스키마 해석 ──────────────────────────────────────────────────────────────
92
+ /** 스키마가 받는 JSON 형 집합. anyOf/oneOf·enum·const 까지 펼친다. 비면 "아무거나". */
93
+ export function schemaTypes(schema) {
94
+ const out = new Set();
95
+ if (!schema)
96
+ return out;
97
+ const add = (t) => {
98
+ if (typeof t === 'string')
99
+ out.add(t);
100
+ };
101
+ if (Array.isArray(schema.type))
102
+ schema.type.forEach(add);
103
+ else
104
+ add(schema.type);
105
+ for (const sub of [...(schema.anyOf ?? []), ...(schema.oneOf ?? [])]) {
106
+ schemaTypes(sub).forEach((t) => out.add(t));
107
+ }
108
+ const literals = schema.enum ?? (schema.const !== undefined ? [schema.const] : []);
109
+ for (const v of literals) {
110
+ out.add(v === null ? 'null' : typeof v === 'number' ? 'number' : typeof v);
111
+ }
112
+ return out;
113
+ }
114
+ /** 배열 스키마의 원소 스키마(anyOf 안의 배열까지). */
115
+ function itemsOf(schema) {
116
+ if (!schema)
117
+ return undefined;
118
+ if (schema.items)
119
+ return schema.items;
120
+ for (const sub of [...(schema.anyOf ?? []), ...(schema.oneOf ?? [])]) {
121
+ const it = itemsOf(sub);
122
+ if (it)
123
+ return it;
124
+ }
125
+ return undefined;
126
+ }
127
+ /** 객체 스키마의 속성(anyOf 안의 객체까지). */
128
+ function propertiesOf(schema) {
129
+ if (!schema)
130
+ return undefined;
131
+ if (schema.properties)
132
+ return schema.properties;
133
+ for (const sub of [...(schema.anyOf ?? []), ...(schema.oneOf ?? [])]) {
134
+ const p = propertiesOf(sub);
135
+ if (p)
136
+ return p;
137
+ }
138
+ return undefined;
139
+ }
140
+ const NUMBER_RE = /^-?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?$/;
141
+ function parseJsonValue(raw, label) {
142
+ try {
143
+ return JSON.parse(raw);
144
+ }
145
+ catch (e) {
146
+ throw new UsageError(`${label} 의 JSON 을 읽지 못했습니다: ${e.message}`);
147
+ }
148
+ }
149
+ /** 문자열 값 하나를 스키마 형에 맞춘다. */
150
+ export function coerceValue(raw, schema, label) {
151
+ const types = schemaTypes(schema);
152
+ const t = raw.trim();
153
+ if (types.size === 0) {
154
+ // 스키마를 모르는 키 — 객체·배열 모양일 때만 JSON 으로 읽고 나머지는 문자열.
155
+ return t.startsWith('{') || t.startsWith('[') ? parseJsonValue(t, label) : raw;
156
+ }
157
+ if (types.has('null') && t === 'null')
158
+ return null;
159
+ if (types.has('object') && t.startsWith('{'))
160
+ return parseJsonValue(t, label);
161
+ if (types.has('array') && t.startsWith('['))
162
+ return parseJsonValue(t, label);
163
+ if (types.has('boolean') && /^(true|false)$/i.test(t))
164
+ return t.toLowerCase() === 'true';
165
+ if ((types.has('number') || types.has('integer')) && NUMBER_RE.test(t))
166
+ return Number(t);
167
+ if (types.has('string'))
168
+ return raw;
169
+ if (types.has('array'))
170
+ return [coerceValue(raw, itemsOf(schema), `${label}[]`)];
171
+ if (types.has('boolean'))
172
+ throw new UsageError(`${label} 은 true/false 입니다 (받은 값: ${raw}).`);
173
+ if (types.has('number') || types.has('integer')) {
174
+ throw new UsageError(`${label} 은 숫자입니다 (받은 값: ${raw}).`);
175
+ }
176
+ if (types.has('object'))
177
+ throw new UsageError(`${label} 은 JSON 객체입니다 — 예: ${label} '{"key":"value"}'`);
178
+ return raw;
179
+ }
180
+ function kebabToCamel(s) {
181
+ return s.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
182
+ }
183
+ /** 플래그 이름 → 스키마 키. 그대로 있으면 그대로, 케밥이면 카멜로 맞춰 본다. */
184
+ function resolveKey(name, props) {
185
+ if (!props || name in props)
186
+ return name;
187
+ const camel = kebabToCamel(name);
188
+ return camel in props ? camel : name;
189
+ }
190
+ /**
191
+ * 도구 플래그를 스키마에 맞춰 인자 객체로 만든다.
192
+ * `base` 는 --json/--input 으로 받은 객체 — 플래그가 그 위에 덮인다.
193
+ */
194
+ export function parseToolArgs(tokens, inputSchema, base = {}) {
195
+ const rootProps = inputSchema?.properties;
196
+ const args = structuredClone(base);
197
+ const positionals = [];
198
+ const seen = new Set();
199
+ const assign = (path, raw) => {
200
+ // 경로를 따라 스키마와 대상 객체를 함께 내려간다.
201
+ let props = rootProps;
202
+ let target = args;
203
+ const keys = [];
204
+ let schema;
205
+ for (let i = 0; i < path.length; i++) {
206
+ const key = resolveKey(path[i], props);
207
+ keys.push(key);
208
+ schema = props?.[key];
209
+ if (i < path.length - 1) {
210
+ const existing = target[key];
211
+ if (existing === undefined || existing === null || typeof existing !== 'object' || Array.isArray(existing)) {
212
+ target[key] = {};
213
+ }
214
+ target = target[key];
215
+ props = propertiesOf(schema);
216
+ }
217
+ }
218
+ const leaf = keys[keys.length - 1];
219
+ const label = `--${keys.join('.')}`;
220
+ const value = raw === true || raw === false
221
+ ? raw
222
+ : coerceValue(raw, schema, label);
223
+ const types = schemaTypes(schema);
224
+ const isArray = types.has('array');
225
+ const pathKey = keys.join('.');
226
+ if (isArray && !Array.isArray(value) && raw !== true && raw !== false) {
227
+ // 반복 지정 = 원소 추가
228
+ const prev = seen.has(pathKey) && Array.isArray(target[leaf]) ? target[leaf] : [];
229
+ target[leaf] = [...prev, coerceValue(raw, itemsOf(schema), `${label}[]`)];
230
+ }
231
+ else if (isArray && Array.isArray(value) && seen.has(pathKey) && Array.isArray(target[leaf])) {
232
+ target[leaf] = [...target[leaf], ...value];
233
+ }
234
+ else {
235
+ if (seen.has(pathKey)) {
236
+ throw new UsageError(`${label} 를 두 번 지정했습니다.`);
237
+ }
238
+ target[leaf] = value;
239
+ }
240
+ seen.add(pathKey);
241
+ };
242
+ const schemaAt = (path) => {
243
+ let props = rootProps;
244
+ let schema;
245
+ for (const seg of path) {
246
+ schema = props?.[resolveKey(seg, props)];
247
+ props = propertiesOf(schema);
248
+ }
249
+ return schema;
250
+ };
251
+ let afterDashDash = false;
252
+ for (let i = 0; i < tokens.length; i++) {
253
+ const tok = tokens[i];
254
+ if (tok === '--' && !afterDashDash) {
255
+ afterDashDash = true;
256
+ continue;
257
+ }
258
+ if (!tok.startsWith('--') || tok === '--') {
259
+ positionals.push(tok);
260
+ continue;
261
+ }
262
+ const body = tok.slice(2);
263
+ const eq = body.indexOf('=');
264
+ if (eq >= 0) {
265
+ assign(body.slice(0, eq).split('.'), body.slice(eq + 1));
266
+ continue;
267
+ }
268
+ const path = body.split('.');
269
+ const schema = schemaAt(path);
270
+ const types = schemaTypes(schema);
271
+ const next = tokens[i + 1];
272
+ const nextIsValue = next !== undefined && !next.startsWith('--');
273
+ if (types.has('boolean') && types.size <= 2) {
274
+ // boolean 은 값 없이 켜고, 다음 토큰이 true/false 일 때만 값으로 먹는다.
275
+ if (nextIsValue && /^(true|false)$/i.test(next)) {
276
+ assign(path, next);
277
+ i++;
278
+ }
279
+ else {
280
+ assign(path, true);
281
+ }
282
+ continue;
283
+ }
284
+ if (!schema && path.length === 1 && body.startsWith('no-')) {
285
+ const positive = body.slice(3).split('.');
286
+ const pSchema = schemaAt(positive);
287
+ if (schemaTypes(pSchema).has('boolean')) {
288
+ assign(positive, false);
289
+ continue;
290
+ }
291
+ }
292
+ if (nextIsValue) {
293
+ assign(path, next);
294
+ i++;
295
+ }
296
+ else if (!schema) {
297
+ // 모르는 키 + 값 없음 → 스위치로 본다(서버가 판단)
298
+ assign(path, true);
299
+ }
300
+ else {
301
+ throw new UsageError(`--${body} 에 값이 필요합니다.`);
302
+ }
303
+ }
304
+ // 위치 인자 → 필수 파라미터가 하나뿐일 때 그 자리로
305
+ if (positionals.length > 0) {
306
+ const required = (inputSchema?.required ?? []).filter((k) => !(k in args));
307
+ if (positionals.length === 1 && required.length === 1) {
308
+ assign([required[0]], positionals[0]);
309
+ positionals.length = 0;
310
+ }
311
+ }
312
+ return { args, positionals };
313
+ }
314
+ // ── 사람·에이전트용 표기 ─────────────────────────────────────────────────────
315
+ /** 파라미터 형을 짧게 적는다: string · number · a|b|c · string[] · {startTime?, endTime?} */
316
+ export function typeLabel(schema, depth = 0) {
317
+ if (!schema)
318
+ return 'any';
319
+ if (schema.enum)
320
+ return schema.enum.map((v) => String(v)).join('|');
321
+ if (schema.const !== undefined)
322
+ return JSON.stringify(schema.const);
323
+ const variants = schema.anyOf ?? schema.oneOf;
324
+ if (variants) {
325
+ return [...new Set(variants.map((v) => typeLabel(v, depth)))].join(' | ');
326
+ }
327
+ const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];
328
+ const parts = types.map((t) => {
329
+ if (t === 'array')
330
+ return `${wrapIfUnion(typeLabel(schema.items, depth + 1))}[]`;
331
+ if (t === 'object') {
332
+ const props = schema.properties;
333
+ if (!props || depth > 1)
334
+ return 'object';
335
+ const req = new Set(schema.required ?? []);
336
+ return `{${Object.entries(props)
337
+ .map(([k, v]) => `${k}${req.has(k) ? '' : '?'}: ${typeLabel(v, depth + 1)}`)
338
+ .join(', ')}}`;
339
+ }
340
+ if (t === 'integer')
341
+ return 'integer';
342
+ return t;
343
+ });
344
+ return parts.length ? parts.join(' | ') : 'any';
345
+ }
346
+ function wrapIfUnion(s) {
347
+ return s.includes(' | ') || s.includes('|') ? `(${s})` : s;
348
+ }
package/dist/config.js ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * 자격증명 저장소 — 프로필(계정) 여러 개를 한 파일에 둔다.
3
+ *
4
+ * MCP 커넥터는 연결 하나에 계정 하나라 개인 계정과 운영(admin) 계정을 오갈 수 없었다.
5
+ * CLI 는 호출마다 프로필을 고르게 해 이 문제를 푼다(`odyssey -p admin list_todos`).
6
+ *
7
+ * 위치: $ODYSSEY_CONFIG_DIR 또는 ~/.odyssey/cli/credentials.json (디렉터리 0700 · 파일 0600).
8
+ * 토큰은 평문이다 — gh·gcloud·firebase-tools 의 파일 저장 폴백과 같은 수준이다.
9
+ * 쓰기는 임시 파일 + rename 으로 원자적으로 한다(동시 실행 두 개가 반쯤 쓴 파일을 읽지 않게).
10
+ */
11
+ import { chmodSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
12
+ import { homedir } from 'node:os';
13
+ import { dirname, join } from 'node:path';
14
+ export const DEFAULT_SERVER = 'https://mcp-odyssey30-60.odyssey365.app';
15
+ export const DEFAULT_PROFILE = 'default';
16
+ /** 프로필 이름 규칙 — 파일 키·셸 인자로 안전한 범위만. */
17
+ export const PROFILE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/;
18
+ export function configDir() {
19
+ const fromEnv = process.env.ODYSSEY_CONFIG_DIR;
20
+ if (fromEnv && fromEnv.trim())
21
+ return fromEnv;
22
+ return join(homedir(), '.odyssey', 'cli');
23
+ }
24
+ export function credentialsPath() {
25
+ return join(configDir(), 'credentials.json');
26
+ }
27
+ /** 끝 슬래시를 떼어 서버 URL 을 한 모양으로 맞춘다(캐시 키·비교용). */
28
+ export function normalizeServer(url) {
29
+ return url.trim().replace(/\/+$/, '');
30
+ }
31
+ function emptyFile() {
32
+ return { version: 1, profiles: {} };
33
+ }
34
+ export function loadCredentials() {
35
+ let raw;
36
+ try {
37
+ raw = readFileSync(credentialsPath(), 'utf-8');
38
+ }
39
+ catch {
40
+ return emptyFile();
41
+ }
42
+ try {
43
+ const parsed = JSON.parse(raw);
44
+ return {
45
+ version: 1,
46
+ defaultProfile: parsed.defaultProfile,
47
+ profiles: parsed.profiles ?? {},
48
+ };
49
+ }
50
+ catch {
51
+ throw new Error(`자격증명 파일을 읽을 수 없습니다(JSON 손상): ${credentialsPath()}\n` +
52
+ '파일을 지우고 `odyssey login` 으로 다시 로그인하세요.');
53
+ }
54
+ }
55
+ export function saveCredentials(file) {
56
+ writePrivateFile(credentialsPath(), JSON.stringify(file, null, 2) + '\n');
57
+ }
58
+ /** 0600 파일을 원자적으로 쓴다. Windows 에서 chmod 는 효과가 없다(무시). */
59
+ export function writePrivateFile(path, content) {
60
+ const dir = dirname(path);
61
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
62
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
63
+ writeFileSync(tmp, content, { mode: 0o600 });
64
+ try {
65
+ chmodSync(tmp, 0o600);
66
+ }
67
+ catch {
68
+ // 권한 모델이 다른 파일시스템 — 무시
69
+ }
70
+ renameWithRetry(tmp, path);
71
+ }
72
+ /**
73
+ * Windows 는 백신·색인기·다른 odyssey 실행이 대상 파일을 잠깐 쥐고 있으면 rename 이 EPERM/EBUSY/EACCES 로
74
+ * 실패한다(교체 자체는 지원). 게임 기록기처럼 백그라운드에서 여럿이 부를 때 흔하다 — 짧게 몇 번 다시 해 본다.
75
+ */
76
+ function renameWithRetry(from, to) {
77
+ const transient = new Set(['EPERM', 'EBUSY', 'EACCES']);
78
+ for (let attempt = 0;; attempt++) {
79
+ try {
80
+ renameSync(from, to);
81
+ return;
82
+ }
83
+ catch (e) {
84
+ const code = e.code ?? '';
85
+ if (!transient.has(code) || attempt >= 9) {
86
+ try {
87
+ unlinkSync(from);
88
+ }
89
+ catch {
90
+ // 임시 파일 정리 실패는 무시
91
+ }
92
+ throw e;
93
+ }
94
+ // 동기 대기 50ms·100ms… (최대 ~2초) — 이 CLI 는 한 번 실행에 한 번 쓰므로 블로킹이 문제되지 않는다
95
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50 * (attempt + 1));
96
+ }
97
+ }
98
+ }
99
+ /** 읽고 → 고치고 → 쓴다. 고치는 함수가 반환한 값을 그대로 돌려준다. */
100
+ export function updateCredentials(mutate) {
101
+ const file = loadCredentials();
102
+ const result = mutate(file);
103
+ saveCredentials(file);
104
+ return result;
105
+ }
106
+ export function assertProfileName(name) {
107
+ if (!PROFILE_NAME_RE.test(name)) {
108
+ throw new UsageError(`프로필 이름 "${name}" 은 쓸 수 없습니다 — 영문·숫자·_·- 로 32자 이하(첫 글자는 영문·숫자).`);
109
+ }
110
+ }
111
+ /** 사용법 오류(종료 코드 2). */
112
+ export class UsageError extends Error {
113
+ constructor(message) {
114
+ super(message);
115
+ this.name = 'UsageError';
116
+ }
117
+ }
118
+ /** 로그인이 필요하거나 자격증명이 죽었다(종료 코드 3). */
119
+ export class AuthRequiredError extends Error {
120
+ constructor(message) {
121
+ super(message);
122
+ this.name = 'AuthRequiredError';
123
+ }
124
+ }