@odyssey365/cli 0.2.4 → 0.3.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.
@@ -0,0 +1,90 @@
1
+ /**
2
+ * 올리기 전 글 다듬기(설계 §11.3) — 비밀 값 가림 · 답 상한 · 답 속 미디어 경로 찾기.
3
+ * 서버(agent_message_post)도 같은 가림 · 상한을 한다 — 여기는 디스크(outbox)에 남기기 전 한 겹 더.
4
+ */
5
+ import { existsSync, realpathSync, statSync } from 'node:fs';
6
+ import { basename, isAbsolute, resolve, sep } from 'node:path';
7
+ import { MEDIA_EXTS } from './api.js';
8
+ export const MESSAGE_MAX_CHARS = 8000;
9
+ const SECRET_PATTERNS = [
10
+ /\bsk-[A-Za-z0-9_-]{16,}/g, // OpenAI · Anthropic(sk-ant-…)
11
+ /\bAKIA[0-9A-Z]{16}\b/g, // AWS 키 id
12
+ /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g, // GitHub 토큰
13
+ /\bxox[abpr]-[A-Za-z0-9-]{10,}/g, // Slack
14
+ /\bAIza[0-9A-Za-z_-]{35}\b/g, // Google API 키
15
+ /\bod[kt]_[A-Za-z0-9_-]{16,}/g, // Odyssey API 키 · 토큰
16
+ /\boat_[A-Za-z0-9_-]{16,}/g,
17
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
18
+ ];
19
+ /** 긴 base64 — 경로(슬래시 여럿) · 한 가지 글자만 있는 긴 낱말은 빼고, 대 · 소문자 · 숫자가 섞인 것만. */
20
+ const LONG_B64 = /[A-Za-z0-9+/]{48,}={0,2}/g;
21
+ function looksLikeKey(s) {
22
+ return (s.match(/\//g)?.length ?? 0) < 3 && /[A-Z]/.test(s) && /[a-z]/.test(s) && /[0-9]/.test(s);
23
+ }
24
+ /** `.env` 줄 꼴(KEY=값) 중 이름이 비밀스러운 것. */
25
+ const ENV_LINE = /^(\s*(?:export\s+)?[A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API_KEY|APIKEY|PRIVATE_KEY|ACCESS_KEY)[A-Z0-9_]*\s*=\s*)(\S.*)$/gim;
26
+ export function redactSecrets(text) {
27
+ let out = text.replace(ENV_LINE, (_m, head) => `${head}[가림]`);
28
+ for (const re of SECRET_PATTERNS)
29
+ out = out.replace(re, '[가림]');
30
+ return out.replace(LONG_B64, (m) => (looksLikeKey(m) ? '[가림]' : m));
31
+ }
32
+ export function clampMessage(text, max = MESSAGE_MAX_CHARS) {
33
+ if (text.length <= max)
34
+ return text;
35
+ return `${text.slice(0, max)}\n…(컴퓨터에서 이어 보기)`;
36
+ }
37
+ export function cleanText(text) {
38
+ return clampMessage(redactSecrets(text));
39
+ }
40
+ /** 세션 제목 — 첫 프롬프트 앞부분. */
41
+ export function titleOf(prompt) {
42
+ const one = prompt.replace(/\s+/g, ' ').trim();
43
+ return one.length > 60 ? `${one.slice(0, 60)}…` : one;
44
+ }
45
+ /**
46
+ * 답 속의 이미지 · 영상 경로 — **작업 폴더 안**의 있는 파일만(폴더 밖 · 숨김 경로 제외, 설계 §9.2 안전망).
47
+ * 마크다운 이미지 `![](p)` · 링크 `[](p)` · 백틱 `` `p` `` · 맨 경로를 다 본다. 상대 경로는 cwd 기준.
48
+ */
49
+ export function findMediaPaths(text, cwd, workspaceRoot) {
50
+ const exts = MEDIA_EXTS.map((e) => e.slice(1)).join('|');
51
+ // 경로 앞뒤 구분자 — 마크다운 링크 · 코드 · 따옴표 · 괄호 · 공백, 그리고 강조(**굵게** · _기울임_)도(261122 E2E: 「**./clip.mov**」를 놓쳤다).
52
+ const re = new RegExp(`(?:\\]\\(|\`|["'(\\s*_]|^)((?:~|\\.{1,2})?[^\\s\`"'()<>\\[\\]*]*\\.(?:${exts}))(?=[)\`"'\\s.,;:!?*_]|$)`, 'gim');
53
+ const real = (p) => {
54
+ try {
55
+ return realpathSync(p);
56
+ }
57
+ catch {
58
+ return p;
59
+ }
60
+ };
61
+ const root = real(resolve(workspaceRoot));
62
+ const found = [];
63
+ for (const m of text.matchAll(re)) {
64
+ let p = m[1];
65
+ if (!p || /^[a-z]+:\/\//i.test(p))
66
+ continue;
67
+ if (p.startsWith('file://'))
68
+ p = p.slice(7);
69
+ if (p.startsWith('~'))
70
+ continue; // 홈 경로 = 작업 폴더 밖
71
+ const abs = real(isAbsolute(p) ? resolve(p) : resolve(cwd, p)); // 심볼릭 링크(/var → /private/var)를 풀어 비교
72
+ if (!(abs === root || abs.startsWith(root.endsWith(sep) ? root : root + sep)))
73
+ continue;
74
+ const rel = abs.slice(root.length);
75
+ if (rel.split(sep).some((part) => part.startsWith('.') && part.length > 1))
76
+ continue; // 숨김 폴더 · 파일
77
+ if (basename(abs).startsWith('.'))
78
+ continue;
79
+ try {
80
+ if (!existsSync(abs) || !statSync(abs).isFile())
81
+ continue;
82
+ }
83
+ catch {
84
+ continue;
85
+ }
86
+ if (!found.includes(abs))
87
+ found.push(abs);
88
+ }
89
+ return found;
90
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * 클로드 코드 transcript(JSONL) 읽기 — Stop 훅이 마지막 턴의 답 · 활동 요약을 뽑는다.
3
+ *
4
+ * 줄 꼴(claude 2.1.3xx 실측): `{type:'user'|'assistant'|'system'|…, isSidechain, uuid, promptId?, isMeta?, entrypoint?,
5
+ * message:{id?, role, content: string | [{type:'text'|'tool_use'|'tool_result'|'thinking'|'image', …}]}}`.
6
+ * 한 assistant 메시지(message.id)가 내용 블록마다 줄로 갈라져 온다. 서브에이전트 대화는 isSidechain:true(빼고 센다).
7
+ */
8
+ import { readFileSync } from 'node:fs';
9
+ const FILE_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
10
+ const COMMAND_TOOLS = new Set(['Bash', 'PowerShell']);
11
+ /** 진짜 사용자 프롬프트 줄인가 — 도구 결과만 있는 user 줄 · 메타(명령 안내 등)는 아니다. */
12
+ function isPrompt(l) {
13
+ if (l.type !== 'user' || l.isSidechain || l.isMeta)
14
+ return false;
15
+ const c = l.message?.content;
16
+ if (typeof c === 'string')
17
+ return c.trim().length > 0 && !c.startsWith('<local-command') && !c.startsWith('<command-');
18
+ if (!Array.isArray(c))
19
+ return false;
20
+ return c.some((b) => b.type === 'text' || b.type === 'image') && !c.some((b) => b.type === 'tool_result');
21
+ }
22
+ function promptText(l) {
23
+ const c = l.message?.content;
24
+ if (typeof c === 'string')
25
+ return c;
26
+ return (c ?? []).filter((b) => b.type === 'text').map((b) => b.text ?? '').join('\n');
27
+ }
28
+ export function parseTranscriptLines(lines) {
29
+ const parsed = [];
30
+ for (const raw of lines) {
31
+ if (!raw.trim())
32
+ continue;
33
+ try {
34
+ parsed.push(JSON.parse(raw));
35
+ }
36
+ catch {
37
+ // 쓰는 중인 마지막 줄 · 깨진 줄
38
+ }
39
+ }
40
+ let start = -1;
41
+ for (let i = parsed.length - 1; i >= 0; i--) {
42
+ if (isPrompt(parsed[i])) {
43
+ start = i;
44
+ break;
45
+ }
46
+ }
47
+ const prompt = start >= 0 ? parsed[start] : null;
48
+ const desktop = parsed.some((l) => l.entrypoint === 'claude-desktop');
49
+ const summary = { calls: 0, filesChanged: 0, commands: 0 };
50
+ const files = new Set();
51
+ let lastId = null;
52
+ const textById = new Map();
53
+ for (let i = start + 1; i < parsed.length; i++) {
54
+ const l = parsed[i];
55
+ if (l.type !== 'assistant' || l.isSidechain)
56
+ continue;
57
+ const c = l.message?.content;
58
+ if (!Array.isArray(c))
59
+ continue;
60
+ const id = l.message?.id ?? l.uuid ?? `line-${i}`;
61
+ for (const b of c) {
62
+ if (b.type === 'tool_use') {
63
+ summary.calls++;
64
+ if (b.name && FILE_TOOLS.has(b.name)) {
65
+ const p = (b.input?.file_path ?? b.input?.notebook_path ?? '');
66
+ files.add(p || `${id}-${summary.calls}`);
67
+ }
68
+ if (b.name && COMMAND_TOOLS.has(b.name))
69
+ summary.commands++;
70
+ }
71
+ else if (b.type === 'text' && b.text && b.text.trim()) {
72
+ if (!textById.has(id))
73
+ textById.set(id, []);
74
+ textById.get(id).push(b.text);
75
+ lastId = id;
76
+ }
77
+ }
78
+ }
79
+ summary.filesChanged = files.size;
80
+ const images = [];
81
+ const pc = prompt?.message?.content;
82
+ if (Array.isArray(pc)) {
83
+ for (const b of pc) {
84
+ if (b.type === 'image' && b.source?.type === 'base64' && b.source.data && b.source.media_type) {
85
+ images.push({ mime: b.source.media_type, data: b.source.data });
86
+ }
87
+ }
88
+ }
89
+ return {
90
+ prompt: prompt ? promptText(prompt) : null,
91
+ promptUuid: prompt?.uuid ?? null,
92
+ promptId: prompt?.promptId ?? null,
93
+ promptImages: images,
94
+ text: lastId ? textById.get(lastId).join('\n\n') : '',
95
+ messageId: lastId,
96
+ toolSummary: summary,
97
+ desktop,
98
+ };
99
+ }
100
+ export function readTranscript(path) {
101
+ try {
102
+ return parseTranscriptLines(readFileSync(path, 'utf-8').split('\n'));
103
+ }
104
+ catch {
105
+ return null;
106
+ }
107
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * 등록한 작업 폴더(설계 §11.6) — 등록은 컴퓨터에서만, 폴더마다 이름(필수) · 올리기 방식(all · appOnly).
3
+ * 앱 · 서버에는 id · 이름 · mirror 만 간다. 경로는 `workspaces.json` 에만 있다.
4
+ */
5
+ import { realpathSync, statSync } from 'node:fs';
6
+ import { basename, resolve, sep } from 'node:path';
7
+ import { UsageError } from '../config.js';
8
+ import { newId, paths, readJson, writeJson } from './store.js';
9
+ export function loadWorkspaces() {
10
+ const f = readJson(paths.workspaces(), {});
11
+ return Array.isArray(f.workspaces) ? f.workspaces.filter((w) => w && w.id && w.path && w.name) : [];
12
+ }
13
+ function save(list) {
14
+ writeJson(paths.workspaces(), { version: 1, workspaces: list });
15
+ }
16
+ /** 심볼릭 링크 · 상대 경로를 풀어 비교 가능한 절대 경로로. 없는 경로면 resolve 만. */
17
+ export function canonicalPath(p) {
18
+ const abs = resolve(p);
19
+ try {
20
+ return realpathSync(abs);
21
+ }
22
+ catch {
23
+ return abs;
24
+ }
25
+ }
26
+ /** 서버에 보낼 꼴 — 이름 · mirror 만. */
27
+ export function publicWorkspaces(list = loadWorkspaces()) {
28
+ return list.map((w) => ({ id: w.id, name: w.name, mirror: w.mirror }));
29
+ }
30
+ /** cwd 를 품는 가장 가까운(가장 깊은) 등록 폴더. 없으면 null — 등록 밖 세션은 미러링도 실행도 하지 않는다. */
31
+ export function findWorkspace(cwd, list = loadWorkspaces()) {
32
+ if (!cwd)
33
+ return null;
34
+ const c = canonicalPath(cwd);
35
+ let best = null;
36
+ for (const w of list) {
37
+ const root = canonicalPath(w.path);
38
+ if (c === root || c.startsWith(root.endsWith(sep) ? root : root + sep)) {
39
+ if (!best || root.length > canonicalPath(best.path).length)
40
+ best = w;
41
+ }
42
+ }
43
+ return best;
44
+ }
45
+ export function workspaceById(id, list = loadWorkspaces()) {
46
+ if (!id)
47
+ return null;
48
+ return list.find((w) => w.id === id) ?? null;
49
+ }
50
+ function findByRef(ref, list) {
51
+ const asPath = canonicalPath(ref);
52
+ return list.find((w) => w.id === ref) ?? list.find((w) => canonicalPath(w.path) === asPath) ?? list.find((w) => w.name === ref);
53
+ }
54
+ export function suggestName(path) {
55
+ return basename(canonicalPath(path)) || 'workspace';
56
+ }
57
+ export function addWorkspace(path, name, appOnly) {
58
+ const abs = canonicalPath(path);
59
+ let isDir = false;
60
+ try {
61
+ isDir = statSync(abs).isDirectory();
62
+ }
63
+ catch {
64
+ isDir = false;
65
+ }
66
+ if (!isDir)
67
+ throw new UsageError(`폴더가 아닙니다: ${abs}`);
68
+ const n = (name ?? '').trim();
69
+ if (!n)
70
+ throw new UsageError('작업 폴더에는 이름이 필요합니다(--name). 앱에는 이 이름만 보입니다.');
71
+ if (n.length > 40)
72
+ throw new UsageError('작업 폴더 이름은 40자까지입니다.');
73
+ const list = loadWorkspaces();
74
+ const existing = list.find((w) => canonicalPath(w.path) === abs);
75
+ if (existing) {
76
+ existing.name = n;
77
+ existing.mirror = appOnly ? 'appOnly' : 'all';
78
+ save(list);
79
+ return existing;
80
+ }
81
+ if (list.some((w) => w.name === n))
82
+ throw new UsageError(`같은 이름의 작업 폴더가 이미 있습니다: ${n}`);
83
+ const w = { id: newId('ws'), name: n, path: abs, mirror: appOnly ? 'appOnly' : 'all', addedAt: new Date().toISOString() };
84
+ list.push(w);
85
+ save(list);
86
+ return w;
87
+ }
88
+ export function renameWorkspace(ref, name) {
89
+ const n = name.trim();
90
+ if (!n)
91
+ throw new UsageError('새 이름이 비었습니다.');
92
+ const list = loadWorkspaces();
93
+ const w = findByRef(ref, list);
94
+ if (!w)
95
+ throw new UsageError(`등록된 작업 폴더가 아닙니다: ${ref}`);
96
+ if (list.some((x) => x !== w && x.name === n))
97
+ throw new UsageError(`같은 이름의 작업 폴더가 이미 있습니다: ${n}`);
98
+ w.name = n;
99
+ save(list);
100
+ return w;
101
+ }
102
+ export function setWorkspaceMirror(ref, appOnly) {
103
+ const list = loadWorkspaces();
104
+ const w = findByRef(ref, list);
105
+ if (!w)
106
+ throw new UsageError(`등록된 작업 폴더가 아닙니다: ${ref}`);
107
+ w.mirror = appOnly ? 'appOnly' : 'all';
108
+ save(list);
109
+ return w;
110
+ }
111
+ export function removeWorkspace(ref) {
112
+ const list = loadWorkspaces();
113
+ const w = findByRef(ref, list);
114
+ if (!w)
115
+ throw new UsageError(`등록된 작업 폴더가 아닙니다: ${ref}`);
116
+ save(list.filter((x) => x !== w));
117
+ return w;
118
+ }
package/dist/files.js CHANGED
@@ -7,9 +7,10 @@
7
7
  * 할일·메모 본문에 사진을 붙이는 운영 흐름이 이 한 단계로 열린다.
8
8
  *
9
9
  * 바꾸는 자리(앱에서 사람이 사진을 넣는 세 곳과 같다):
10
- * - `image: { file }` — 스냅샷 사진 칸(create_snapshot · update_snapshot · create_snapshot_draft).
11
- * - `uploadImages: [{ file }]` — 할일·메모 본문 끝(create_todo · update_todo · create_memo · update_memo).
12
- * - `files: ["경로", …]` — 에셋(create_asset · add_asset_images) → `uploads: [{ uploadId, index }]`.
10
+ * - `image: { file }` — 페이지 사진 칸(create_page · update_page · create_page_draft — 옛 이름 *_snapshot*).
11
+ * - `uploadImages: [{ file }]` — 할일·메모 본문 끝(create_todo · update_todo · create_memo · update_memo) · 리포트 원고 끝 삽화
12
+ * (create_report · update_report).
13
+ * - `files: ["경로", …]` — 에셋(save_asset — 옛 create_asset · add_asset_images) → `uploads: [{ uploadId, index }]`.
13
14
  * 에셋은 사진뿐 아니라 PDF·문서·소리도 담으므로, 이 자리가 있으면 주소를 `accept:'files'` 로 받는다(서버가 내용으로 판정한다).
14
15
  * 이름이 다른 키의 `file` 은 손대지 않는다 — 다른 도구의 문자열을 파일로 오인해 읽어 보내면 안 된다.
15
16
  * 상대 경로는 `--input` 파일이 있는 폴더 기준(원고 JSON 옆에 그림을 두는 흐름), 없으면 지금 폴더.
@@ -0,0 +1,32 @@
1
+ /**
2
+ * CLI 자격 → Firebase(App Check + 커스텀 토큰) → Firestore — `odyssey watch` 와 `odyssey agent daemon` 이 같이 쓴다.
3
+ * 자격 수명 · 회수 설명은 watch.ts 머리말. Firebase JS SDK 는 여기서만 동적으로 불러온다(다른 명령은 의존성 없이 뜬다).
4
+ */
5
+ import { UsageError } from './config.js';
6
+ export async function connectFirestore(client, appName) {
7
+ let session = await client.firebaseSession();
8
+ let sessionAt = Date.now();
9
+ const { initializeApp } = await import('firebase/app');
10
+ const { initializeAppCheck, CustomProvider } = await import('firebase/app-check');
11
+ const { getAuth, signInWithCustomToken } = await import('firebase/auth');
12
+ const fs = await import('firebase/firestore');
13
+ const app = initializeApp(session.firebase, appName);
14
+ initializeAppCheck(app, {
15
+ provider: new CustomProvider({
16
+ // SDK 는 토큰이 다 됐을 때만 다시 부른다. 처음 한 번은 교환에서 받은 것을 쓰고, 그 뒤는 다시 교환한다.
17
+ getToken: async () => {
18
+ if (Date.now() - sessionAt > 60_000) {
19
+ session = await client.firebaseSession();
20
+ sessionAt = Date.now();
21
+ }
22
+ return { token: session.appCheck.token, expireTimeMillis: sessionAt + session.appCheck.ttlMillis };
23
+ },
24
+ }),
25
+ isTokenAutoRefreshEnabled: false,
26
+ });
27
+ const signedIn = await signInWithCustomToken(getAuth(app), session.customToken);
28
+ if (signedIn.user.uid !== session.firebaseUid) {
29
+ throw new UsageError('Firebase 신원이 CLI 전용 세션과 일치하지 않습니다. 서버의 감시 보안 업데이트가 필요합니다.');
30
+ }
31
+ return { fs, db: fs.getFirestore(app), uid: session.uid };
32
+ }
package/dist/guide.js CHANGED
@@ -21,7 +21,7 @@
21
21
  * 이력: document/90-process/work-log/261101 Odyssey CLI 0.2.2 설계 사례집 agent-guide design 관심 스레드 안내.md
22
22
  */
23
23
  const CORE_RULES = `- **사용자의 데이터다.** 쓰기는 사용자 앱 화면·알림에 그대로 나타난다. 요청 범위를 넘는 생성·수정을 하지 않는다.
24
- - \`[쓰기·덮어씀]\` 도구와 \`delete_*\` 는 사용자가 그 변경을 분명히 원할 때만 부른다(삭제는 휴지통으로 가지만 그래도 먼저 확인).
24
+ - \`[쓰기·덮어씀]\` 도구와 \`delete_*\`(항목 지우기는 \`delete_item\` — type + id) 는 사용자가 그 변경을 분명히 원할 때만 부른다(삭제는 휴지통으로 가지만 그래도 먼저 확인).
25
25
  - 없는 UID·도구·파라미터를 추측하지 않는다 — \`odyssey search\`·\`list_*\` 로 찾는다. 이름으로 찾을 땐 \`search\` 가 먼저다.
26
26
  - 쓰기 뒤에는 \`get_*\`/\`list_*\` 로 다시 읽어 결과를 확인하고, 실제로 한 일만 보고한다.
27
27
  - 로그인(\`odyssey login\`)은 브라우저 인증이 필요한 **사람의 일**이다. 종료 코드 3 이면 사용자에게 부탁하고, 비밀번호·토큰을 직접 다루지 않는다.`;
@@ -29,7 +29,7 @@ const CORE_RULES = `- **사용자의 데이터다.** 쓰기는 사용자 앱 화
29
29
  * 관심 스레드 — 전문·짧은 절이 함께 쓰는 한 벌. 서버(functions_v2 followed-threads)의 계약을 옮긴 것이라
30
30
  * 기본 기간·한도를 바꾸면 여기도 같이 바꾼다. 전문에 없고 짧은 절에만 있던 것을 261101 에 한 곳으로 모았다.
31
31
  */
32
- const FOLLOW_RULES = `- **붙는 법** — 에이전트가 \`comment_on_item\`·\`comment_on_project\` 로 댓글을 남긴 스레드는 **자동으로** 관심 스레드가 된다. 아직 댓글을 안 단 스레드는 \`odyssey threads follow --itemType <타입> --itemUid <uid>\`(보드 카드면 \`--projectId <보드>\`)로 미리 올린다.
32
+ const FOLLOW_RULES = `- **붙는 법** — 에이전트가 \`comment_on_item\`(보드 전체 스레드는 \`itemType project\`) 로 댓글을 남긴 스레드는 **자동으로** 관심 스레드가 된다. 아직 댓글을 안 단 스레드는 \`odyssey threads follow --itemType <타입> --itemUid <uid>\`(보드 카드면 \`--projectId <보드>\`)로 미리 올린다.
33
33
  - **받는 것** — \`odyssey watch\` 가 그 방의 새 댓글을 누가 썼든 낸다(\`followed:true\`, 남의 글은 \`author:"other"\`). 내 댓글은 관심 스레드가 아니어도 늘 온다.
34
34
  - **기간** — 마지막 **에이전트 활동**(댓글·follow) 뒤 기본 14일 조용하면 빠진다. 사람 댓글로는 늘지 않는다. 사용자가 기간을 말했을 때만 \`--days N\`(1~365) — 뒤의 자동 등록도 그 기간으로 다시 센다. 만료 없이 볼 항목은 태그 감시(\`odyssey watch --tag\`).
35
35
  - **빼는 법** — 일이 끝나 더 받을 필요가 없으면 \`odyssey threads unfollow --roomUid <방>\`(또는 \`--itemType\`·\`--itemUid\`). **마지막 답글 뒤에** 뺀다 — 뺀 뒤 댓글을 달면 다시 올라온다. 할일 완료만으로는 빠지지 않는다(일부러).
@@ -81,7 +81,7 @@ export function renderAgentGuide(input) {
81
81
  | 만들고 싶은 것 | 쓰는 것 | 한 줄 |
82
82
  |---|---|---|
83
83
  | **감시 에이전트** — 앱 태그/멘션 → 일하는 세션이 직접 듣기 | \`odyssey watch-agent init <새폴더>\` → 세션이 \`odyssey agent-guide --watch-agent\` 를 읽고 듣는다 | 듣기는 **깨우기만**(오래 = 백그라운드 종료 · 잠깐 = Monitor). 답글·판단은 그 세션+MCP. 에이전트 댓글엔 반응 금지 |
84
- | **활동 기록기** — 게임/앱 세션 → 타임라인 | \`create_record\` 1회 + \`add_record_trace\`(+\`dedupeKey\`) | 종료 4만 같은 키로 재전송. JSON은 \`--input -\` |
84
+ | **활동 기록기** — 게임/앱 세션 → 타임라인 | \`save_record\`(만들기) 1회 + \`add_record_trace\`(+\`dedupeKey\`) | 종료 4만 같은 키로 재전송. JSON은 \`--input -\` |
85
85
  | **저장소 코딩 에이전트**에 Odyssey 도구 심기 | \`odyssey agent-guide --snippet\` → AGENTS.md | 시작 시 \`agent-guide\` 전문을 읽게 한다 |
86
86
  | **운영**(공지·사용법) | \`-p admin\` / \`-p support\` | 쓰기 전 \`whoami -p …\` 로 uid 확인 |
87
87
 
@@ -107,7 +107,7 @@ ${profileSection(input)}
107
107
  - 필수 파라미터가 하나뿐이면 위치 인자: \`odyssey get_todo <todoId>\`
108
108
  - 여러 값·특수 문자가 섞이면 \`--input -\` 에 JSON 객체를 넣는 편이 안전하다(셸 따옴표 문제 없음)
109
109
  - 시각은 오프셋을 붙인 ISO 8601(\`+09:00\` 또는 \`Z\`)
110
- - 같은 일을 다시 보낼 수 있는 자동화면 \`dedupeKey\` 를 준다(\`create_timeline_event\`·\`add_record_trace\` — 같은 키 = 한 번만 기록)
110
+ - 같은 일을 다시 보낼 수 있는 자동화면 \`dedupeKey\` 를 준다(\`save_timeline_event\`·\`add_record_trace\` — 같은 키 = 한 번만 기록)
111
111
 
112
112
  ## 출력과 종료 코드
113
113
 
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@
8
8
  * odyssey login # 개인 계정 → 프로필 default
9
9
  * odyssey login -p admin # 운영 계정 → 프로필 admin
10
10
  * odyssey list_todos --status inProgress
11
- * odyssey -p admin list_snapshots
11
+ * odyssey -p admin list_pages
12
12
  *
13
13
  * 도구 정의는 서버가 정본이다(tools/list). CLI 는 이름·스키마를 받아 플래그를 맞출 뿐이라
14
14
  * 서버에 도구가 늘면 CLI 배포 없이 바로 쓸 수 있다.
@@ -24,12 +24,13 @@ import { extractGlobals, parseToolArgs, takeFlag, takeIntOption } from './args.j
24
24
  import { discover, fetchUserInfo, interactiveLogin, registerClient, revokeTokenRemote } from './oauth.js';
25
25
  import { NetworkError } from './rpc.js';
26
26
  import { envServer, OdysseyClient, resolveTarget, selectedProfileName } from './session.js';
27
- import { findTool, getTools, renderToolDetail, renderToolList, toolListJson } from './tools.js';
27
+ import { findTool, getTools, isUnknownToolResult, lookupTool, normalizeToolName, renderToolDetail, renderToolList, toolListJson, unknownToolError, } from './tools.js';
28
28
  import { printToolResult, writeJson } from './output.js';
29
29
  import { collectLocalFiles, inlineImageFiles, uploadLocalFiles } from './files.js';
30
30
  import { renderAgentGuide, renderSkill, renderSnippet } from './guide.js';
31
31
  import { cmdWatch, WATCH_HELP } from './watch.js';
32
32
  import { cmdWatchAgent, WATCH_AGENT_HELP } from './watch-agent.js';
33
+ import { cmdAgent } from './agent/command.js';
33
34
  const __dirname = dirname(fileURLToPath(import.meta.url));
34
35
  const VERSION = JSON.parse(readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')).version;
35
36
  const HELP = `Odyssey CLI v${VERSION} — Odyssey 계정의 할일·메모·보드·페이지를 터미널과 AI 에이전트에서 다룬다.
@@ -58,6 +59,10 @@ AI 에이전트라면 먼저: odyssey agent-guide (사용법·로그인된 계
58
59
  follow --days N: 감시 기간(일, 1~365 · 기본 14 — 뒤의 자동 등록도 이 기간으로)
59
60
  빼기는 마지막 답글 뒤에(뺀 뒤 댓글을 달면 다시 오른다) · 할일 완료로는 안 빠진다
60
61
 
62
+ 에이전트 브리지(클로드 코드 · 코덱스 세션을 앱 컴패니언 대화로)
63
+ odyssey agent setup 첫 설정(이름 · 이모지 · 미러링 · 작업 폴더 · 승인 · 잠자기 방지 · 자동 시작)
64
+ odyssey agent status|start|stop 상태 · 데몬 켜고 끄기 · 자세히: odyssey agent help (별칭 odyssey claude · odyssey codex)
65
+
61
66
  AI 에이전트
62
67
  odyssey agent-guide 에이전트용 설명서(사용법 + 계정 + 서버 사용 지침 실시간)
63
68
  odyssey agent-guide --skill Claude Code·Codex 스킬 파일(SKILL.md) 내용
@@ -462,7 +467,9 @@ async function cmdCall(g, toolName, tokens,
462
467
  /** 명령이 미리 형을 맞춘 파라미터(threads follow --days) — 플래그 해석 뒤에 덮는다. */
463
468
  extra = {}) {
464
469
  const client = new OdysseyClient(resolveTarget(g), VERSION);
465
- const tool = await findTool(client, toolName, { refresh: g.refreshTools });
470
+ const { tool, names } = await lookupTool(client, toolName, { refresh: g.refreshTools });
471
+ if (!tool)
472
+ return cmdCallUnlisted(g, client, toolName, tokens, extra, names);
466
473
  const base = await readInputObject(g);
467
474
  const { args, positionals } = parseToolArgs(tokens, tool.inputSchema, base);
468
475
  Object.assign(args, extra);
@@ -485,6 +492,30 @@ extra = {}) {
485
492
  const result = await client.callTool(tool.name, args);
486
493
  return printToolResult(result, g.output ?? 'json', tool.name);
487
494
  }
495
+ /**
496
+ * 목록에 없는 이름 — 서버가 옛 이름(별칭)으로 받을 수 있으니 스키마 없이 그대로 보낸다(60-backend D880: 옛 이름 ·
497
+ * 옛 인자는 서버가 지금 이름으로 옮긴다). 스키마를 몰라 값은 문자열(`{` · `[` 로 시작하면 JSON)이고 위치 인자는 둘 자리를
498
+ * 모른다 — 숫자 · 참거짓은 `--json` 으로. 서버도 모르는 이름이면 예전처럼 비슷한 이름을 알려 준다.
499
+ * 이력: document/90-process/work-log/261110 MCP 도구 100 이하 지우기 저장 합치기 fetch 상세 페이지 시트 개명.md
500
+ */
501
+ async function cmdCallUnlisted(g, client, toolName, tokens, extra, names) {
502
+ const name = normalizeToolName(toolName);
503
+ const base = await readInputObject(g);
504
+ const { args, positionals } = parseToolArgs(tokens, undefined, base);
505
+ Object.assign(args, extra);
506
+ if (positionals.length) {
507
+ const hint = unknownToolError(toolName, names).message.split('\n')[0];
508
+ throw new UsageError(`${hint} — 목록에 없는 이름(옛 이름일 수 있다)은 위치 인자를 둘 자리를 모릅니다. --키 값 또는 --json 으로 주세요.` +
509
+ '\n도구 목록: odyssey tools');
510
+ }
511
+ const baseDir = g.inputFile && g.inputFile !== '-' ? dirname(resolvePath(g.inputFile)) : process.cwd();
512
+ await attachLocalFiles(client, args, baseDir);
513
+ const result = await client.callTool(name, args);
514
+ if (isUnknownToolResult(result))
515
+ throw unknownToolError(toolName, names);
516
+ process.stderr.write(`참고: ${name} 은 지금 도구 목록에 없는 이름이라 서버에 그대로 보냈습니다(옛 이름이면 서버가 지금 이름으로 옮깁니다).\n`);
517
+ return printToolResult(result, g.output ?? 'json', name);
518
+ }
488
519
  // ── 진입 ─────────────────────────────────────────────────────────────────────
489
520
  const ACCOUNT_COMMANDS = new Set(['login', 'logout', 'whoami', 'profiles', 'use', 'agent-guide', 'watch', 'watch-agent']);
490
521
  /**
@@ -520,6 +551,9 @@ async function main(argv) {
520
551
  process.stdout.write(`${WATCH_AGENT_HELP}\n`);
521
552
  return 0;
522
553
  }
554
+ if (command === 'agent' || command === 'claude' || command === 'codex') {
555
+ return cmdAgent(g, args, command === 'agent' ? undefined : command);
556
+ }
523
557
  if (g.help && command === 'threads') {
524
558
  const tool = THREADS_TOOLS[args[0] ?? 'list'];
525
559
  if (!tool)
package/dist/tools.js CHANGED
@@ -49,8 +49,8 @@ export async function getTools(client, opts = {}) {
49
49
  }
50
50
  return fetchTools(client);
51
51
  }
52
- /** 이름으로 도구를 찾는다. 케밥(list-todos)도 받는다. 캐시에 없으면 한 번 새로 받아 본다. */
53
- export async function findTool(client, rawName, opts = {}) {
52
+ /** 이름으로 도구를 찾는다. 케밥(list-todos)도 받는다. 캐시에 없으면 한 번 새로 받아 본다. 없으면 tool 은 undefined. */
53
+ export async function lookupTool(client, rawName, opts = {}) {
54
54
  const name = normalizeToolName(rawName);
55
55
  let tools = await getTools(client, opts);
56
56
  let tool = tools.find((t) => t.name === name);
@@ -58,14 +58,29 @@ export async function findTool(client, rawName, opts = {}) {
58
58
  tools = await fetchTools(client);
59
59
  tool = tools.find((t) => t.name === name);
60
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
- }
61
+ return { tool, names: tools.map((t) => t.name) };
62
+ }
63
+ /** [lookupTool] 의 없음을 오류로 — describe 처럼 스키마가 꼭 있어야 하는 자리. */
64
+ export async function findTool(client, rawName, opts = {}) {
65
+ const { tool, names } = await lookupTool(client, rawName, opts);
66
+ if (!tool)
67
+ throw unknownToolError(rawName, names);
67
68
  return tool;
68
69
  }
70
+ export function unknownToolError(rawName, names) {
71
+ const near = suggestNames(normalizeToolName(rawName), names);
72
+ return new UsageError(`알 수 없는 명령·도구 "${rawName}".` +
73
+ (near.length ? ` 혹시: ${near.join(', ')}` : '') +
74
+ '\n도구 목록: odyssey tools');
75
+ }
76
+ /**
77
+ * 서버도 모르는 이름이라는 답인가 — 목록에 없는 이름을 서버에 그대로 보냈을 때(옛 이름 별칭 시도) 가른다.
78
+ * 서버 문구: `mcp_streamable` 의 tools/call 「오류: 알 수 없는 도구 "…"」.
79
+ */
80
+ export function isUnknownToolResult(result) {
81
+ const r = result;
82
+ return r?.isError === true && (r.content?.[0]?.text ?? '').startsWith('오류: 알 수 없는 도구');
83
+ }
69
84
  export function normalizeToolName(name) {
70
85
  return name.trim().replace(/-/g, '_');
71
86
  }